Skip to content

Instantly share code, notes, and snippets.

@kashmervil
Last active August 29, 2015 14:09
Show Gist options
  • Select an option

  • Save kashmervil/cffb95b5359ece58640b to your computer and use it in GitHub Desktop.

Select an option

Save kashmervil/cffb95b5359ece58640b to your computer and use it in GitHub Desktop.
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