I’ve wrote a little program to generate numbers that have 2 conditions:
- has all digits from 1 tot 9 so a number like 123456789
- the number must be divisible by the last digit
for example 442 because 4 % 2 == 0 and 4 % 4 == 0
This is my backtrack algorithm:
static void backTrack(int value)
{
//Check if the number has all 9 digits, that it is dividable
if(isNine(value) && isDiv(value))
{
//System.out.println(value);
System.out.println("Found solution.");
System.out.println(aantal);
aantal++;
}
else
{
if(howMany(value) >= 9)
return;
for(int i = 1; i < 10; i++)
{
value = value * 10 + i;
if(value % i == 0 && howMany(value) <= 9)
{
//System.out.println(value);
backTrack(value);
}
value = value / 10;
}
}
}
//Gives length of integer for example 124 must give 3, 13 gives 2
static int howMany(int value)
{
int test = value % 10;
value = value / 10;
int teller = 0;
while(test != 0)
{
teller++;
test = value % 10;
value = value / 10;
}
return teller;
}
//Checks if the number is dividable by the last digit of the number and keeps recursive doing this for the whole number so 442 = YES 235 = NO
static boolean isDiv(int value)
{
int test = value % 10;
value = value / 10;
while(test != 0)
{
if(value % test == 0)
{
test = value % 10;
value = value / 10;
}
else
return false;
}
return true;
}
//Checks if the number has all digits from 1 to 9
static boolean isNine(int value)
{
boolean values[] = new boolean[10];
int test = value % 10;
int counter = 0;
for(int i = 1; i < values.length; i++)
values[i] = false;
while( test != 0)
{
if(values[test])
return false;
else
{
values[test] = true;
value = value /10;
test = value % 10;
}
}
for(int i = 1; i < values.length; i++)
{
if(values[i])
counter++;
}
if(counter == 9)
return true;
else
return false;
}
It never comes to a solution, I tested all subfunctions and those are working great.
Is there something wrong with my backtracking scheme? The System.out.println(aantal) is just a var to count how many solutions I’ve found.
I start with backtrack(0);
1 Answer