I'm a novice without any knowledge of algorithm optimization. I'm trying to write a code that counts the number of paths on a 20x20 grid, or lattice, from its top-left corner to its bottom-right one, only being able to move down and to the right. For example, the number of paths on a 2x2 grid would be 6:
My (very not optimal) idea is: any sequence of 2*20 moves such that I move down as many times as I move to the right, will get me to the final point. So I would generate any possible sequence of down and right moves, and then count those that respect that criteria.
I wanted to represent this sequence with a 40-bits binary number, where 0s and 1s represent the two possible moves.
I code in C and didn't find a way to deal with binary numbers, so I use an array of 40 ints.
So by starting from int n = {0,0,...,0}
I check that number of zeros = number of ones, if so I increase a counter. I then "sum 1" to this array as I would do to a binary number, and I repeat until I get to {1,1,...,1}.
The code takes 7 seconds for 13x13 grids, up to 8 minutes for a 16x16 grid, and I'd need weeks to run it for a 20x20 grid. Is there any way that this code can be speeded up? Or is this an overall silly strategy to solve the problem? The code is the following:
#include <stdio.h>
#include <stdlib.h>
int ispath(int* n, int siz){
//returns 1 if n has number of 1s = number of 0s, returns 0 otherwise
int n0,n1;
n0=0; n1=0;
for(int i=0;i<siz;i++){
if(n[i]==0) n0++;
else n1++;
}
if(n1==n0) return 1;
else return 0;
}
int risen(int* n,int siz){
//"sums" 1 to the binary number represented by n
//returns just to break from function
for(int i =siz-1;i>=0;i--){
if(n[i]==0){
n[i]=1; return 1;
}else n[i]=0;
}
}
int sumn(int* n, int siz){
int sum=0;
//sum elements of n, to check when n=11...1 and stop the while loop in main
for(int i =0;i<siz;i++) sum+=n[i];
return sum;
}
int main(){
int n[] = {0,0,0,0};//NXN lattice requires n with 2N starting zeros. This n represents 2x2 lattice
int sizen = sizeof(n)/sizeof(n[0]);
long long cnt = 0;
while(sumn(n,sizen)<sizen){
if(ispath(n,sizen)){
cnt++;
}
risen(n,sizen);
}
printf("Number of paths: %lli",cnt);
}