## Largest product in a grid (problem 11)

Posted: 12/07/2013 in Project Euler
Tags: , , , , , ,

Problem 11 of PE’s website says:

In the 20×20 grid below, four numbers along a diagonal line have been marked in red. What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?

I provided a general solution in C. My program allocates dynamically any type of matrix, with any size you want, with any length of adjacent numbers you want the program to analize (this is the only extra data you provide as a parameter of the program from the CLI). It also provides some error management (i.e. if both sizes of the grid are less than the length of the adjacent numbers you want to find the product).

My program works this way:

1. Open your command line interpreter and execute the program providing the length of adjacent numbers you want to evaluate. For example, in this problem it is 4, therefore:

$name_of_program 4 2. Now the program is waiting so that the user provides a matrix to the standard input (the program accepts any size!) and press Enter. In order that the program “catches” that you are done, it is to say, that the EOF of stdin is reached, press CTRL-D (but before of this, don’t forget to press Enter, this step is important). 3. It stores the grid in a new (temporal) file. At this point the width (= the amount of numbers of each line) and the height (= the number of lines of the file) of the grid are calculated and a new grid with that right size is created. 4. All the data stored in the file is saved in the grid. 5. All the required calculations inside the grid are performed. 6. The result is printed out on the standard output and the temporal file created by the program is removed from your computer. Here is the C code: #include <stdio.h> #include <stdlib.h> int **newGrid (unsigned int rows, unsigned int columns); /* It returns a pointer to a 2D (rows x columns) matrix. */ void freeGrid (int **grid, unsigned int columns); /* It frees the memory used for grid. */ void recordStdinToFileOpen (FILE * file); /* Entering user's input is stored in a (temporal) file. */ unsigned int countElementsForGrid (FILE * file, int index_of_array); /* After the grid is saved in a file, this function returns the width and the height of the matrix, depending on whether the value of the "index_of_array" argument is 0 or 1, respectively. */ void recordFileOpenToGrid (FILE * from_file, int **grid, unsigned int width, unsigned int height); /* This functions enters the file we are using to allocate dinamically the data and save it in a grid whose size has been previously calculated. */ unsigned long int getLargestProduct (int **grid, unsigned int width, unsigned int height, unsigned int adjacent); /* This function carries out the largest product of any "adjacent" length of adjacent numbers of the "grid" argument, whose size is "width"x"height", and returns the result. For this problem in particular, adjacent = 4, height = 20, width = 20. */ unsigned long int doTheStuff (FILE * file, unsigned int adjacent); /* It gathers all the functions above and returns the return value of the getLargestProduct() function. */ unsigned long int openFileForGrid (unsigned int adjacent); /* It opens a temporal file, does all the stuff described above, and returns the result of doTheSuff() function. When all the work is done, it removes physically that temporal file of your computer. */ int **newGrid (unsigned int rows, unsigned int columns){ int **grid = NULL; unsigned int j = 0; grid = (int **) malloc (columns * sizeof (int *)); for (j = 0; j < columns; j++){ grid[j] = (int *) malloc (rows * sizeof (int)); } return grid; } void freeGrid (int **grid, unsigned int columns){ int j = 0; for (j = 0; j < columns; j++){ free (grid[j]); } free (grid); } void recordStdinToFileOpen (FILE * file){ int num; fseek (file, 0L, SEEK_SET); while (!feof (stdin)){ fscanf (stdin, "%d", &num); if (!feof (stdin)){ fprintf (file, "%d ", num); if (getchar () == '\n'){ fprintf (file, "\n"); } } } } unsigned int countElementsForGrid (FILE * file, int index_of_array){ unsigned int result = 0; unsigned int i = 0, j = 0; /* During the execution time, press Enter after you paste your grid */ unsigned int measures = {i, j}; int first_line_done = 0; int c; fseek (file, 0L, SEEK_SET); while ((c = fgetc (file)) != EOF){ if ((c == ' ') && first_line_done == 0){ i++; } if (c == '\n'){ j++; first_line_done = 1; } else { continue; } } measures = i; measures = j; result = measures[index_of_array]; return result; } void recordFileOpenToGrid (FILE * from_file, int **grid, unsigned int width, unsigned int height){ int i = 0, j = 0; fseek (from_file, 0L, SEEK_SET); for (j = 0; j < height; j++){ for (i = 0; i < width; i++){ fscanf (from_file, "%d", &grid[j][i]); } } } unsigned long int getLargestProduct (int **grid, unsigned int width, unsigned int height, unsigned int adjacent){ unsigned long int result = 1L; unsigned long int i = 0L, j = 0L, i_temp = i, j_temp = j; unsigned long int max = 1L; for (j = 0L; j < height; j++){ for (i = 0L; i < width; i++){ i_temp = i; j_temp = j; if (width - i_temp >= adjacent){ /* Move left-to-right (horitzontally) */ for (i_temp = i; i_temp < adjacent + i; i_temp++){ result *= (unsigned int) grid[j][i_temp]; } if (result >= max) max = result; result = 1L; } if (height - j >= adjacent){ /* Move up-to-down (vertically) */ for (j_temp = j; j_temp < adjacent + j; j_temp++){ result *= (unsigned int) grid[j_temp][i]; } if (result >= max) max = result; result = 1L; } if ((height - j >= adjacent) && (width - i_temp >= adjacent)){ /* Move up-to-down diagonally (\) */ for (j_temp = j, i_temp = i; (j_temp < adjacent + j) && (i_temp < adjacent + i); j_temp++, i_temp++){ result *= (unsigned int) grid[j_temp][i_temp]; } if (result >= max) max = result; result = 1L; } if ((height - j >= adjacent) && (i_temp >= adjacent - 1)){ /* Move up-to-down diagonally (/) */ for (j_temp = j, i_temp = i; (j_temp < adjacent + j) && (i_temp + 1 > i - adjacent + 1); j_temp++, i_temp--){ result *= (unsigned int) grid [j_temp][i_temp]; } if (result >= max) max = result; result = 1L; } } } result = max; return result; } unsigned long int doTheStuff (FILE * file, unsigned int adjacent){ unsigned long int result = 1; unsigned int width = 0, height = 0; int **grid; recordStdinToFileOpen (file); width = countElementsForGrid (file, 0); height = countElementsForGrid (file, 1); if ((adjacent > width) && (adjacent > height)){ fprintf (stderr, "Error: the parameter must be equal or less than, at least, one side of the grid.\n"); exit (1); } grid = newGrid (width, height); recordFileOpenToGrid (file, grid, width, height); result = getLargestProduct (grid, width, height, adjacent); freeGrid (grid, height); return result; } unsigned long int openFileForGrid (unsigned int adjacent){ unsigned long int escape = 0L; FILE * temp_file; temp_file = fopen ("temp.txt", "w+"); if (temp_file != NULL){ escape = doTheStuff (temp_file, adjacent); } else{ fprintf (stderr, "Error: There were a problem when opening a new file.\n"); exit (1); } fclose (temp_file); system ("rm -r temp.txt"); /* Windows users: replace "rm -r temp.txt" by "DEL temp.txt". */ return escape; } int main (int argc, char *argv[]){ char * endptr; const unsigned int adjacent = (unsigned int) strtol (argv, &endptr, 10); unsigned long int result; if (argc < 2 || (int) adjacent <= 0){ fprintf (stderr, "Error: A positive integer as parameter is required.\n"); exit (1); } result = openFileForGrid (adjacent); fprintf (stdout, "\n%lu\n", result); return 0; }  I’m going to show you some examples of its use: $ (gcc -Wall -Wconversion -g prob11.c) && ./a.out 2
1 2
3 4

12
$(gcc -Wall -Wconversion -g prob11.c) && ./a.out 3 1 2 9 1 8 4 9 3 3 7 7 7 648$ (gcc -Wall -Wconversion -g prob11.c) && ./a.out 2
1 6 7 2 3

42


Examples of bad inputs:

$(gcc -Wall -Wconversion -g prob11.c) && ./a.out 5 3 5 5 3 Error: the parameter must be equal or less than, at least, one side of the grid. $ (gcc -Wall -Wconversion -g prob11.c) && ./a.out -1 Error: A positive integer as parameter is required.

In particular, for this problem:

## Largest palindrome product (problem 4)

Posted: 18/06/2013 in Project Euler
Tags: , , , ,

I’m actually working out the problems proposed in Project Euler’s website and I thought that it could be useful for many people if I post here my solutions for some of them.

The problem 4 says:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.

 

Find the largest palindrome made from the product of two 3-digit numbers.

I just generalized this problem by writing out a modular program, in C, that finds the largest Palindrome for any number of digits given in the command line.

The program may seem larger than necessary, but that’s because I used some general functions I defined a while ago for other purposes, so they work fine with any (valid) input (so at the far end that made me easier to structure the program 🙂 ).

#include <stdio.h>
#include <stdlib.h>

double exponenciar (double base, int exponent);
/* Returns the result of (base ^ exponent) */

int calculaXifres (int n);
/* Returns the number of digits of the number "n". */

long int aIntegerstoInteger (long int array_de_integers[],
int longitud);
/* Maps each element of the array of integers
"array_de_integers", of "longitud" elements,
to each digit of an integer, and returns it back.
For instance,

aIntegerstoInteger ({2, 1, 5}, 3)

will return 215. I will only use this function once,
just for making easier the inversion of a number. */

long int invertirNumero (long int num);
/* Returns the number "num" inverted */

long int maxValueNdigits (int num_digits);
/* Returns the maximum value that a number with
"num_digits" digits can reach. For example,
maxValueNdigits (4) would return 9999. */

long int largestPalindrome (int num_digits);
/* Returns the answer of this problem when
num_digits = 3. */

double exponenciar (double base, int exponent){

double retorna;

if (exponent == 0){
retorna = 1;
} else {
retorna = base * exponenciar (base, exponent - 1);
}

return retorna;
}

int calculaXifres (int n){

int quocient = n;
int comptador = 0;

while (quocient > 0){
quocient = quocient / 10;
comptador++;
}

return comptador;
}

long int aIntegerstoInteger (long int array_de_integers[],
int longitud){

int num_elements = longitud;
int i = 0;
long int integer = 0;

for (i = 0; i < num_elements; i++){
integer += array_de_integers[i] *
(int) exponenciar (10, num_elements - (i + 1));
}

return integer;
}

long int invertirNumero (long int num){

int longitud = calculaXifres (num);
long int num_invertit[longitud];
long int numero_invertit;
int i = 0;

for (i = 0; i < longitud; i++){
num_invertit[i] = num % 10;
num = num / 10;
}

numero_invertit = aIntegerstoInteger (num_invertit, longitud);

return numero_invertit;
}

long int maxValueNdigits (int num_digits){

int i = 0;
long int max_value = 0;

for (i = 0; i < num_digits; i++){
max_value = max_value + (int) exponenciar (10, i);
}

max_value = 9*max_value;

return max_value;
}

long int largestPalindrome (int num_digits){

long int starting = (long int) exponenciar (10, num_digits - 1);
long int ending = maxValueNdigits(num_digits);
long int i = starting;
long int j = i;
long int largest_palindrome = 0L;

for (i = starting; i <= ending; i++){
for (j = starting; j <= ending; j++){
if (i * j == invertirNumero (i * j) &&
i * j >= largest_palindrome){
largest_palindrome = i * j;
}
}
}

return largest_palindrome;
}

int main (int argc, char *argv[]){

int num_digits = atoi (argv);

printf ("%ld\n", largestPalindrome (num_digits));

return 0;
}


Time to compile and to execute the program:

\$ (gcc -Wall -Wconversion prob4.c) && ./a.out 3 906609

And the three-digit factors are 993 and 913, it is to say, $993 \times 913 = 906609$.