Saturday, January 5, 2013

A grid where rows, columns and diagonals are equal

My son showed me trick where I chose a number between 20 and 99 (inclusive) and he would then create a 4-by-4 grid of numbers where all the numbers would equal that number.
I thought I would write the algorithm. I thought it might be interesting for him to see how how a computer program worked. I thought C# would be easy so I used Mono on the mac.


[Main.cs]


using System;

namespace AllWaysAddUp
{
class MainClass
{
private static NumberGrid _numberGrid;

public static void Main (string[] args)
{

Console.WriteLine ("Enter a number between 20 and 99 and this will calculate"+ '\n'
                  "a grid of 4 rows and 4 columns where all the rows, columns"+ '\n' +
                  "and diagonals all add up to that number"+ '\n' + '\n'+
                  "Enter a number between 20 and 99...");

string s = Console.ReadLine();
int i;

if(!int.TryParse(s, out i))
Console.WriteLine("You did not enter a number");
else {
if( i < 20 || i > 99)
Console.WriteLine("Number not in range. Number must be between 20 and 99.");
else {
_numberGrid = new NumberGrid();
_numberGrid.calculate(i);

PrintNumberGrid();
}
}
Console.ReadLine();
}

private static void PrintNumberGrid()
{
for (int row = 0; row < 4; row++) {
Console.WriteLine();
for (int col = 0; col < 4; col++) {
int num = _numberGrid.GetCell(row, col);
Console.Write (" {0}" + '\t', num.ToString());
}
}
}
}
}


[NumberGrid]


using System;

namespace AllWaysAddUp
{
public class NumberGrid
{
private int[,] _grid;

// Array format: {row0 col0, row0 col1, row0 col2, row0 col3 }
//               {row1 col0, row1 col1, row1 col2, row1 col3 }
//               {row2 col0, row2 col1, row2 col2, row2 col3 }
//               {row3 col0, row3 col1, row3 col2, row3 col3 }
public NumberGrid ()
{
_grid =  new int [4,4] {{-1, 1, 12, 7} , {11, 8, -1, 2} ,{5, 10, 3,-1} ,{4,-1, 6, 9}} ;
}

public int GetCell(int rowNumber, int columnNumber)
{
return _grid[rowNumber, columnNumber];
}

public void calculate(int number)
{
_grid[0,0] = number -20;
_grid[1,2] = _grid[0,0] - 1;
_grid[3,1] = _grid[0,0] + 1;
_grid[2,3] = _grid[3,1] + 1;
}
}
}









No comments:

Post a Comment