ABCDE Problem

Problem proposed by Kamal Jain:


Solution can be implemented with a simple backtracking, with a bit of pruning during the Check. Not the most efficient solution due to the string operations, but did the trick, and the answer is:

09754,14754,15078,15080,15104,20078,20080,20104

Gemini 2.5 Flash as the clear winner. Code is down below, cheers.

List<string> solutions = new List<string>();
Combination("", 5, ref solutions);

for(int i=0;i<solutions.Count;i++)
    Console.Write("{0}{1}", solutions[i], i < solutions.Count - 1 ? ',' : ' ');

void Combination(string current,
                 int MAX,
                 ref List<string> retVal)
{
    if(current.Length == MAX)
    {
        if(Check(current, MAX, 20320))
            retVal.Add(current);
        return;
    }

    for(int i=0;i<10;i++)
        Combination(current + i.ToString(), MAX, ref retVal);
}

bool Check(string str,
           int MAX,
           int target)
{
    int sum = 0;
    for (int i = 0; i < MAX; i++)
    {
        sum += Int32.Parse(str.Substring(i));
        if (sum > target) return false;
    }
    return sum == target;
}


Comments

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Shortest Bridge – A BFS Story (with a Twist)

Classic Dynamic Programming IX