Re: Tuesday puzzle
Here is the code in C#. Should not be hard to convert to C, C++, Java etc.
using System;
namespace NumberGenerator
{
class Program
{
// recursive function to generate a 9 digit number such that:
// 1) each digit is unique
// 2) each left justified substring is divisible by the number of digits in it
//
// We start with an empty 'baseString' at level 1.
// At each level, we attempt to append a digit to the baseString such that it meets the constraints.
// If we are successful in adding a digit, we call the function recursively to try the next level.
// If we succeed in adding a digit at level 9, we are done!
//
static bool generate(int level, string baseString)
{
for (int digit = 1; digit <= 9; digit++) // Test each of the nine possible digits at each level
{
if (!baseString.Contains(digit.ToString())) // Make sure digit has not been used already
{
string newBaseString = baseString + digit.ToString(); // append the new digit
int newBaseInteger = int.Parse(newBaseString); // convert the newBaseString to an integer for testing
if (newBaseInteger % level == 0) // Check that the newBaseNumber is evenly divisible by 'level'
{
if (level == 9) // We have 9 digits. We are done!
{
Console.WriteLine("Answer: " + newBaseString); // Print result
Console.WriteLine(newBaseString + " / " + level + " = " + (newBaseInteger / level)); // Show work at each level
return true;
}
if (generate(level + 1, newBaseString)) // not done yet. Make a recursive call to generate the next level
{
Console.WriteLine(newBaseString + " / " + level + " = " + (newBaseInteger / level)); // Show work at each level
return true;
}
}
}
}
return false; // no valid solution with this baseString
}
static void Main(string[] args)
{
generate(1, ""); // Call at level one with an empty string
Console.ReadLine(); // wait for CR to exit.
}
}
}