Dynamic Programming - CrazyNumbers - Techie Me
We are interested in finding the count of all N digit crazy numbers. Let us define a crazy number. A crazy number is a number where the magnitude of its consecutive digits differ by 1.
We are interested in finding the count of all N digit crazy numbers. Let us define a crazy number. A crazy number is a number where the magnitude of its consecutive digits differ by 1.
For e.g.: Here is a list of all 2 digit crazy numbers:
The total number of 2 digit crazy numbers is 17. You can notice that in all the numbers the digits differ only by 1.
Here are few points to justify my claim of using dynamic programming
- The above image shows that every three digit crazy number is derived from a two digit crazy number by adding a third digit.
- The third digit can be either 1 greater than the last digit or 1 lesser than the last digit of the two digit number.
- This means each two digit crazy number will derive exactly 2 three digit numbers.
- However, the two digit number ending in 9 will only result in one three digit number.
- Also, the two digit number ending in 0 will produce only one three digit number.
public static void main(String[] args) {
int N = 40;
long A[][] = new long[N][12];
for (int i = 0; i < N; i++) {
A[i][0] = 0;
A[i][11] = 0;
}
A[0][1] = 1;
A[0][2] = 1;
A[0][3] = 2;
A[0][4] = 2;
A[0][5] = 2;
A[0][6] = 2;
A[0][7] = 2;
A[0][8] = 2;
A[0][9] = 2;
A[0][10] = 1;
for (int i = 1; i < N; i++) {
for (int j = 1; j <= 10; j++) {
A[i][j] = A[i - 1][j - 1] + A[i - 1][j + 1];
}
}
long sum = 0;
for (int i = 1; i <= 10; i++) {
sum += A[N - 2][i];
}
System.out.println(sum);
}
https://www.hackerearth.com/practice/algorithms/dynamic-programming/2-dimensional/practice-problems/algorithm/crazy-numbers-1/editorial/
This is a simple dynamic programming question. We will take two states dp(i,j) where "i" denotes the number of digits in the number and "j" denotes the last digit of that number. So basically, dp(i,j) will give us the count of all "i" digit numbers ending with digit "j". Here, our base case will be dp(i,j) = 1 for all numbers having a single digit.
Now our approach for this question would be something like this.
Now our approach for this question would be something like this.
if(j == 0) dp(i,j) = dp(i-1,j+1)
else dp(i,j) = dp(i-1,j+1) + dp(i-1,j-1)
Now our ans for numbers with "i" digits would be sum of dp(i,j) where "j" is from 1 to 9.
int main()
{
//f_in("in11.txt");
//f_out("out11.txt");
long long i,j;
for(i=0;i<=9;i++)
{
a[1][i]=1;
}
for(i=2;i<1000001;i++)
{
for(j=0;j<=9;j++)
{
if(j==0)
{
a[i][j]=a[i-1][j+1]%M;
}
else
{
a[i][j]=((a[i-1][j-1])%M+(a[i-1][j+1])%M)%M;
}
}
}
long long t,n;
cin>>t;
while(t--)
{
cin>>n;
long long sum=0;
if(n==1)
{
cout<<"10"<<endl;
}
else
{
for(i=1;i<=9;i++)
{
sum=(sum%M+a[n][i]%M)%M;
}
cout<<sum<<endl;
}
}
return 0;
}