Last active
August 29, 2015 14:09
-
-
Save kashmervil/cffb95b5359ece58640b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Different | |
| { | |
| class Program | |
| { | |
| private static bool AllDifferent(IEnumerable<int> xs) | |
| { | |
| return AllDifferentHelper(xs, x => false); | |
| } | |
| private static bool AllDifferentLoop(IEnumerable<int> xs) | |
| { | |
| Func<int,bool> func = x => false; | |
| while (true) | |
| { | |
| if (!xs.Any()) return true; | |
| var current = xs.First(); | |
| if (func(current)) return false; | |
| xs = xs.Skip(1); | |
| var func1 = func; | |
| func = x => (x == current) || func1(x); | |
| } | |
| } | |
| private static bool AllDifferentHelper(IEnumerable<int> xs, Func<int, bool> func) | |
| { | |
| if (!xs.Any()) return true; | |
| var current = xs.First(); | |
| return !func(current) && AllDifferentHelper(xs.Skip(1), x => (x == current) || func(x)); | |
| } | |
| static void Main() | |
| { | |
| var list1 = new List<int> {1, 3, 5, 6, 7, 9, 11}; | |
| var list3 = new List<int> {1, 1}; | |
| Console.WriteLine(AllDifferent(list1)); | |
| Console.WriteLine(AllDifferent(list3)); | |
| Console.WriteLine(AllDifferentLoop(list1)); | |
| Console.WriteLine(AllDifferentLoop(list3)); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment