Program.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. namespace D24._1
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. if (args.Length < 1) throw new ArgumentException();
  11. if (File.Exists(args[0]) == false) throw new FileNotFoundException();
  12. int[] presentsWeight = File.ReadAllLines(args[0]).Select(i => int.Parse(i)).ToArray();
  13. var sum = presentsWeight.Sum();
  14. var p1 = Test(presentsWeight, sum / 3);
  15. var p2 = Test(presentsWeight, sum / 4);
  16. Console.WriteLine($"The part1 answer is : {p1}");
  17. Console.WriteLine($"The part2 answer is : {p2}");
  18. }
  19. static double? Test(int[] presentsWeight, int weight, double quantumE = 1, int totalWeight = 0, int i = 0 )
  20. {
  21. if (totalWeight == weight)
  22. return quantumE;
  23. if (i >= presentsWeight.Length || totalWeight > weight)
  24. return null;
  25. var take = Test(presentsWeight, weight, quantumE * presentsWeight[i], totalWeight + presentsWeight[i], i + 1);
  26. var ignore = Test(presentsWeight, weight, quantumE, totalWeight, i + 1);
  27. if (take == null) return ignore;
  28. if (ignore == null) return take;
  29. return Math.Min(take.GetValueOrDefault(0), ignore.GetValueOrDefault(0));
  30. }
  31. }
  32. }