Snippets

Cameron Presley C# Constraint Solver

Created by Cameron Presley last modified
// Recommend running this in LINQPad
void Main()
{
	var numbers = Enumerable.Range(0, 10000).ToList();
	var constraints = new List<IConstraint>{new MustBeFourDigitsLongConstraint(), new MustBeEvenConstraint(), new PalindromeConstraint()};
	
	var constraintSolver = new ConstraintSolver();
	var result = constraintSolver.FindValues(constraints, numbers.ToList());
	
	result.Dump();
}

public interface IConstraint
{
	bool FollowsConstraint(int value);
}

class MustBeFourDigitsLongConstraint : IConstraint
{
	public bool FollowsConstraint(int value)
	{
		return value.ToString().Length == 4;
	}
}

class MustBeEvenConstraint : IConstraint
{
	public bool FollowsConstraint(int value)
	{
		return value % 2 == 0;
	}
}

class FirstDigitMustEqualLastDigitConstraint : IConstraint
{
	public bool FollowsConstraint(int value)
	{
		var valueString = value.ToString();
		return valueString[0] == valueString[valueString.Length-1];
	}
}

class ConstraintSolver
{
	public List<int> FindValues(List<IConstraint> constraints, List<int> values)
	{
		if (constraints == null) throw new ArgumentNullException("constraints");
		if (values == null) throw new ArgumentNullException("values");
		
		var result = values;
		foreach (var constraint in constraints)
		{
			result = result.Where(x => constraint.FollowsConstraint(x)).ToList();
		}
		return result;
	}
}

Comments (0)