Created
August 23, 2016 23:16
-
-
Save Sidneys1/81e5e48095ac9cc63a50debecb6f5bf6 to your computer and use it in GitHub Desktop.
SumIt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace SumIt { | |
internal static class Program { | |
private static void Main() { | |
var nums = new List<string[]> { new[] { "+-1", "+1" } }; | |
for (var i = 2; i < 10; i++) | |
nums.Add(new[] {$"{i}", $"+-{i}", $"+{i}"}); | |
var solutions = M(nums) | |
.Select(o => string.Join("", o)) | |
.Select(o=>new { | |
expr = o.TrimStart('+').Replace("+-", " - ").Replace("+", " + "), | |
res = o.Split(new[] { '+' }, StringSplitOptions.RemoveEmptyEntries).Sum(int.Parse) | |
}).ToArray(); | |
for (var i = 0; i <= 100; i++) { | |
var right = solutions.Where(o => o.res == i).ToList(); | |
Console.WriteLine($"Solving for {i}, there are {right.Count:N0} correct. {solutions.Length - right.Count:N0} incorrect."); | |
foreach (var solution in right) | |
Console.WriteLine($"\t{solution.expr}"); | |
} | |
Console.ReadLine(); | |
} | |
public static IEnumerable<IEnumerable<string>> M(List<string[]> list) { | |
var m = list.GetRange(1, list.Count - 1); | |
if (list.Count == 1) | |
foreach (var s in list[0]) | |
yield return new[] {s}; | |
else | |
foreach (var enumerable in M(m).Select(sublist => sublist as IList<string> ?? sublist.ToList())) | |
foreach (var s in list[0]) | |
yield return Prepend(s, enumerable); | |
} | |
private static IEnumerable<T> Prepend<T>(T first, IEnumerable<T> rest) { | |
yield return first; | |
foreach (var item in rest) | |
yield return item; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment