Finding the column total in an array - c#

I have an 1-dimensional array with random elements, got through a m*n grid. I want to find out the row total and column total, present in it.
Here is how the 1 dimensional array is:
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
I want to treat it like :
01 02 03 04 05
06 07 08 09 10
11 12 13 14 15
16 17 18 19 20
Now i want to find the reo total and column total.
Row total is done as follows:
for (int i = 0; i < totalRows; i++)
{
for (int j = 0; j < totalColumns; j++)
{
rowTotal[i] += numbers[temp + j];
}
temp += totalColumns;
}
I am trying to do the same with Column.
Here is the code:
for (int i = 0; i < totalColumns; i++)
{
tempk = 0;
for (int j = 0; j < totalRows; j++)
{
blockTotal[i] += numbers[i+j+tempk];
tempk += totalColumns;
}
}
Am not able to get the column total, as intended. Please Help.

You can get both in the same loop
for (int i = 0; i < totalRows; i++)
{
for (int j = 0; j < totalColumns; j++)
{
rowTotal[i] += numbers[i * totalColumns + j];
blockTotal[j] += numbers[i * totalColumns + j];
}
}

The easiest thing to do is to write a little method that translates a "logical" (row, col) address to an index:
int numberAt(int row, int col)
{
return numbers[row * totalColumns + col];
}
int[] colTotals = new int[totalColumns];
int[] rowTotals = new int[totalRows];
for (int row = 0; row < totalRows; ++row)
{
for (int col = 0; col < totalColumns; ++col)
{
int number = numberAt(row, col);
rowTotals[row] += number;
colTotals[col] += number;
}
}
Edit in response to question in comments below:
Here's a complete compilable example that demonstrates it working on a non-square array:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
class Program
{
// Array will 4x3 (rows x cols):
//
// 1 2 3 | 6
// 4 5 6 | 15
// 7 8 9 | 24
// 10 11 12 | 33
// ---------
// 22 26 30
int[] numbers = Enumerable.Range(1, 12).ToArray();
int totalColumns = 3;
int totalRows = 4;
int numberAt(int row, int col)
{
return numbers[row * totalColumns + col];
}
void test()
{
int[] colTotals = new int[totalColumns];
int[] rowTotals = new int[totalRows];
for (int row = 0; row < totalRows; ++row)
{
for (int col = 0; col < totalColumns; ++col)
{
int number = numberAt(row, col);
rowTotals[row] += number;
colTotals[col] += number;
}
}
Console.WriteLine("Row totals");
foreach (int rowTotal in rowTotals)
Console.Write(rowTotal + " ");
Console.WriteLine("\nCol totals");
foreach (int colTotal in colTotals)
Console.Write(colTotal + " ");
Console.WriteLine();
}
static void Main()
{
new Program().test();
}
}
}

Total by rows
for(int r = 0; r < totalRows; r++)
{
for(int c = 0; c < totalColumns; c++)
{
rowTotal[r] += numbers[r * totalColumns + c];
}
}
Total by columns
for(int c = 0; c < totalColumns; c++)
{
for(int r = 0; r < totalRows; r++)
{
colTotal[c] += numbers[r * totalColumns + c];
}
}

Related

Generate non duplicate random number

I'm trying to make a lottery console app, but have a problem with duplicated numbers in some rows.
A lottery coupon is 10 row with 7 numbers, min number is 0, max number is 36.
How can i check if the number is exist in same row in my for loop?
here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Obligatorisk_Opgave_2
{
class Program
{
static void Main(string[] args)
{
int min = 0; // minimum number
int max = 36; // maximum number
int rows = 10; // number of rows in my copun
int col = 7; // number of column in my copun
// Get the date of PC
string NameDate;
NameDate = DateTime.Now.ToString("yyyy.MM.dd");
string Week = "1-uge";
string ComName = "LYN LOTTO";
Random rnd = new Random();
Console.WriteLine("{0,22} \n {1,15} \n{2,18}", NameDate, Week, ComName);
for (int i = 0; i < rows; i++)
{
Console.Write($"{i + 1}.");
for (int j = 0; j < col; j++)
Console.Write("{1,4}", i, rnd.Next(min, max));
Console.WriteLine();
}
Console.WriteLine("***** JOKER TAL *****");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < col; j++)
Console.Write("{0,4}", rnd.Next(1,9));
Console.WriteLine();
}
}
}
}
You can use a recursive function to do this:
private static List<int> GetRandomRow(List<int> row, int colCount, int min, int max)
{
if(colCount <= 0)
{
return row;
}
var next = rnd.Next(min, max);
if(row.Contains(next))
{
return GetRandomRow(row, colCount, min, max);
}
row.Add(next);
return GetRandomRow(row, colCount - 1, min, max);
}
Then you can use your program like:
private static Random rnd = new Random();
static void Main(string[] args)
{
int min = 0; // minimum number
int max = 36; // maximum number
int rows = 10; // number of rows in my copun
int col = 7; // number of column in my copun
// Get the date of PC
string NameDate;
NameDate = DateTime.Now.ToString("yyyy.MM.dd");
string Week = "1-uge";
string ComName = "LYN LOTTO";
Random rnd = new Random();
Console.WriteLine("{0,22} \n {1,15} \n{2,18}", NameDate, Week, ComName);
for (int i = 0; i < rows; i++)
{
Console.Write($"{i + 1}.");
var row = new List<int>();
var currentRow = GetRandomRow(row, col, min, max);
foreach (var currentCol in currentRow)
{
Console.Write("{1,4}", i, currentCol);
}
Console.WriteLine();
}
Console.WriteLine("***** JOKER TAL *****");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < col; j++)
Console.Write("{0,4}", rnd.Next(1, 9));
Console.WriteLine();
}
}
Instead of random numbers you could Shuffle your List.
Shuffle Function:
public static List<T> Shuffle<T> (List<T> list) {
Random rnd = new Random();
for (int i = 0; i < list.Count; i++)
{
int k = rnd.Next(0, i);
T value = list[k];
list[k] = list[i];
list[i] = value;
}
return list;
}
Now you can call that function and shuffle the content of your List.
Example:
int min = 0;
int max = 36;
int rows = 10;
List<int> mylist = new List<int>();
for (int i = max; i >= min; i--) {
mylist.Add(i);
}
mylist = Shuffle(mylist);
for (int i = 0; i < rows; i++) {
Console.WriteLine(mylist[i]);
}
Console.ReadLine();
simply you can define variable from string data type and add each column in this variable but before add operation you should check if this column exists in this string or not
code is updated
i have definde rndNumber as an integer type before check then i have assigned rnd.Next(min, max) to it, because if i check for rnd.Next(min, max) and if it was not exist so when add it in checkNumber may be it changed again for example...
if(checkNumber.Contains(rnd.Next(min, max))) // if value of rnd.Next(min, max) was 15 and this number not exist in checkNumber so i can add it
{
checkNumber += rnd.Next(min, max); // maybe value of rnd.Next(min, max) change to will be 20
}
notice that every time you call rnd.Next(min, max) it's value will be changed
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Obligatorisk_Opgave_2
{
class Program
{
static void Main(string[] args)
{
int min = 0; // minimum number
int max = 36; // maximum number
int rows = 10; // number of rows in my copun
int col = 7; // number of column in my copun
string checkColumn = ""; // string variable for storing rows values
// Get the date of PC
string NameDate;
NameDate = DateTime.Now.ToString("yyyy.MM.dd");
string Week = "1-uge";
string ComName = "LYN LOTTO";
Random rnd = new Random();
Console.WriteLine("{0,22} \n {1,15} \n{2,18}", NameDate, Week, ComName);
for (int i = 0; i < rows; i++)
{
Console.Write($"{i + 1}.");
for (int j = 0; j < col; j++)
{
// check here if string does not contains this random value then add this it into string and write this number, else will be written duplicated number
int rndNumber = rnd.Next(min, max);
if ( !checkColumn.Contains(rndNumber.ToString()+", ") )
{
checkColumn += rndNumber.ToString()+", ";
Console.Write("{1,4}", i, rndNumber);
}
else
{
Console.Write("duplicated number");
}
}
checkColumn += "\n";
Console.WriteLine();
}
Console.WriteLine("***** JOKER TAL *****");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < col; j++)
Console.Write("{0,4}", rnd.Next(1,9));
Console.WriteLine();
}
}
}
}
I'd use something more like:
for (int i = 1; i <= rows; i++)
{
Console.Write((i + ".").PadRight(3));
var row = Enumerable.Range(min, (max - min) + 1).OrderBy(x => rnd.Next()).Take(col).ToList();
foreach(var num in row) {
Console.Write(num.ToString("00").PadLeft(3));
}
Console.WriteLine();
}
Producing:
1. 33 14 24 27 07 29 30
2. 12 31 03 19 04 02 30
3. 34 03 14 23 20 09 04
4. 09 11 24 07 00 30 17
5. 26 04 22 02 25 20 12
6. 28 26 12 08 04 25 35
7. 09 26 20 34 17 03 23
8. 25 26 35 08 29 06 01
9. 29 33 00 04 09 35 36
10. 00 14 19 25 03 21 33

How to get all possible 2x2 sub matrices in a 3x3 matrix in C#?

If matrix A of size (3x3), then should i use the method of finding determinants, like grabbing the rows and column of first element and removing it from the array 2D array to get the remaining elements and then moving to the next element and repeating the same steps ?
[{1,2,3},
{4,5,6},
{7,8,9}]
I finally was able to do it, here's what I did :
enter image description here
class program
{
public static void Main()
{
int[,] arr = new int[3, 3];
Console.WriteLine("Enter elements of " + (arr.GetUpperBound(0) + 1) + "x" + (arr.GetUpperBound(1) + 1) + " matrix:");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
arr[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Matrix entered: ");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
Console.Write("\t" + arr[i, j]);
}
Console.WriteLine();
}
Console.WriteLine("Possible sub-matrices: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j< 3; j++)
{
TrimArray(i,j,arr);
}
}
}
public static int[,] TrimArray(int row, int column, int[,] original)
{
int[,] resultant = new int[original.GetLength(0) - 1, original.GetLength(1) - 1];
for (int i = 0, j = 0; i < original.GetLength(0); i++)
{
if (i == row)
continue;
for (int k = 0, u = 0; k < original.GetLength(1); k++)
{
if (k == column)
continue;
resultant[j, u] = original[i, k];
u++;
}
j++;
}
Console.WriteLine();
for (int i = 0; i < 2; i++)
{
for (int j = 0; j< 2; j++)
{
Console.Write("\t"+resultant[i,j]);
}
Console.WriteLine();
}
return resultant;
}
}
I did this for you yesterday, I created a method that will return a square matrix, given a parent matrix and the length.
static void Main(string[] args)
{
int[][] parentMatrix = new int[][]
{
new int [] { 1, 2, 3 },
new int [] { 4, 5, 6 },
new int [] { 7, 8, 9 }
};
var chunks = GetSubMatrices(parentMatrix, 2);
Console.WriteLine(chunks);
}
static List<int[][]> GetSubMatrices(int[][] parentMatrix, int m)
{
int n = parentMatrix.Length > m ? parentMatrix.Length : throw new InvalidOperationException("You can't use a matrix smaller than the chunk size");
var chunks = new List<int[][]>();
int movLimit = n - m + 1;
var allCount = Math.Pow(movLimit, 2);
for (int selRow = 0; selRow < movLimit; selRow ++)
{
for (int selCol = 0; selCol < movLimit; selCol ++)
{
// this is start position of the chunk
var chunk = new int[m][];
for (int row = 0; row < m; row++)
{
chunk[row] = new int[m];
for (int col = 0; col < m; col++)
{
chunk[row][col] = parentMatrix[selRow + row][selCol + col];
}
}
chunks.Add(chunk);
}
}
return chunks;
}
If you have any problems using it, you can simply comment below.
I needed to solve a problem like and came up with this answer. Hope it adds to your library of answers. If the submatrix specified is not greater than 1, do nothing.
public static void GetSubMatrixes(int[,] arr, int size)
{
int parentMatrixRowLength = arr.GetLength(0);
int parentMatrixColLength = arr.GetLength(1);
var overall = new List<object>();
if(size > 1)
{
for (int i = 0; i < parentMatrixRowLength; i++)
{
//get the columns
for (int j = 0; j < parentMatrixColLength; j++)
{
var subMatrix = new int[size, size];
/*if the new matrix starts from second to the last value in either the row(horizontal or column)
* do not proceed, go to the row or column in the parent matrix
* */
if (j < parentMatrixColLength - (size - 1) && i < parentMatrixRowLength - (size - 1))
{
//add
for (int m = 0; m < subMatrix.GetLength(0); m++)
{
for (int n = 0; n < subMatrix.GetLength(1); n++)
{
/*check the sum of current column value and the sum of the current row value
* of the parent column length and row length if it goes out of bounds
*/
var row = i + m; var col = j + n;
//actual check here
if (row < parentMatrixRowLength && col < parentMatrixColLength)
{
subMatrix[m, n] = arr[i + m, j + n];
}
}
}
overall.Add(subMatrix);
}
}
}
//display the sub matrixes here
for (int i = 0; i < overall.Count; i++)
{
var matrix = overall[i] as int[,];
for (int y = 0; y < matrix.GetLength(0); y++)
{
for (int x = 0; x < matrix.GetLength(1); x++)
{
Console.Write(string.Format("{0} ", matrix[y, x]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine();
}
}
}

Multiplication table using 2D arrays and methods

I'm a new student having a bit of trouble with this assignment, but the powerpoint notes and other online guides don't seem to help. If anyone can give me a pointer it would be much appreciated!
private static int[,] GenerateTT(int size)
{
int[,] table = new int[size,size];
for (int i = 1; i < size+1; i++)
{
for (int j = 1; j < i+1; j++)
{
table[i-1, j-1] = i * j;
}
}
return table;
}
private static void DisplayTT(int[,] table)
{
Console.WriteLine();
Console.WriteLine("Here is the times table for that size:");
Console.WriteLine();
for (int i = 1; i <= table.Length; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("{0}\t", table[i-1, j-1]);
}
Console.WriteLine("\n");
}
Console.WriteLine();
}
The output is supposed to be like this (if you enter 4 for example):
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
But what I'm getting is this, plus it crashes at DisplayTT(table):
1
2 4
3 6 9
4 8 12 16
here's the relevant part of the Main method if it helps.
int size = GetValue("Please enter the size (4-20) of the times table: ", 4, 20);
Console.WriteLine();
int[,] table = GenerateTT(size);
DisplayTT(table);
You can use GetLength(X) Property for multi dimensional arrays where X is index of dimension.
for (int i = 0; i < table.GetLength(0); i++)
{
for (int j = 0; j < table.GetLength(1); j++)
{
Console.Write("{0}\t", table[i, j]);
}
Console.WriteLine("\n");
}
You should change the inner loop hi-bound:
private static int[,] GenerateTT(int size)
{
int[,] table = new int[size,size];
for (int i = 1; i < size+1; i++)
{
for (int j = 1; j < i+1; j++) // <-- change i+1 to size+1
{
table[i-1, j-1] = i * j;
}
}
return table;
}
I'd rather keep the loops start from zero:
private static int[,] GenerateTT(int size)
{
int[,] table = new int[size,size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
table[i, j] = (i+1) * (j+1);
}
}
return table;
}

Trying all possibilities for a number grid

I'm trying to solve a maths problem programmatically. I have a 6x5 grid, with a few predefined numbers, and I have to find the rest of the numbers with the condition of all rows and columns should total 34.
//Grid
static int[][] sq;
static void Main(string[] args)
{
sq = new int[6][];
for (int i = 0; i < sq.Length; i++)
{
sq[i] = new int[5] { -250, -250, -250, -250, -250, };
}
SetDefaults();
Print();
Console.WriteLine("Press enter to quit...");
Console.ReadLine();
}
static void SetDefaults()
{
sq[0][0] = 7;
sq[0][1] = 6;
sq[0][2] = 8;
sq[2][2] = 9;
sq[2][3] = 8;
sq[2][4] = 5;
sq[3][1] = 9;
sq[3][3] = 7;
sq[3][4] = 5;
sq[4][0] = 4;
sq[4][1] = 4;
sq[4][4] = 9;
sq[5][0] = 8;
sq[5][2] = 3;
sq[5][3] = 6;
sq[5][4] = 8;
}
static void Print()
{
Console.WriteLine();
for (int i = 0; i<sq.Length; i++)
{
for (int ii = 0; ii < sq[i].Length; ii++)
{
Console.Write("[" + sq[i][ii] + "\t]");
}
Console.WriteLine();
}
Console.WriteLine();
}
I think one method is try all the possibilities, with a range of 500 numbers, from -250 to 250, or an incremental range (-1,1, then -2,2, etc), but I don't know how to do this programmatically and much less efficiently.
I have a 6x5 grid
The number of columns and rows is different?
Then, no matter what's in the grid, there is no solution at all to make all sums equal. Consequently there is nothing to code.
Not putting too much effort in it, but if you are really thinking of enumerating something, you could (but shouldn't) try this naive and unoptimized approach (for a range of integers between 0 and 15):
for (int a = 0; a < 16; a++) {
for (int b = 0; b < 16; b++) {
for (int c = 0; c < 16; c++) {
for (int d = 0; d < 16; d++) {
for (int e = 0; e < 16; e++) {
for (int f = 0; f < 16; f++) {
for (int g = 0; g < 16; g++) {
for (int h = 0; h < 16; h++) {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
for (int k = 0; k < 16; k++) {
for (int l = 0; l < 16; l++) {
for (int m = 0; m < 16; m++) {
for (int n = 0; n < 16; n++) {
// test all columns and rows:
// test if 7 + 8 + 9 + a + b == 34
// test if c + d + e + f + g == 34
...
}}}}}}}}}}}}}}
Certainly possible to optimize a lot, like:
for (int a = 0; a < 16; a++) {
var b = 34 - 7 - 8 - 9 - a;
for (int c = 0; c < 16; c++) {
for (int d = 0; d < 16; d++) {
for (int e = 0; e < 16; e++) {
for (int f = 0; f < 16; f++) {
var g = 34 - c - d - e - f;
for (int h = 0; h < 16; h++) {
var i = 34 - 9 - 8 - 5 - h;
for (int j = 0; j < 16; j++) {
var k = 34 - 9 - 7 - 5 - j;
for (int l = 0; l < 16; l++) {
var m = 34 - 4 - 4 - 9 - l;
var n = 34 - 8 - 3 - 6 - 8;
// test all columns only:
// test if 7 + c + h + 4 + 8 == 34
...
}}}}}}}}
But in the end, best optimization is to return "no solution" directly.

print diagonal routes array

I make this code to print array if the number of array is
{
1, 2, 3, 4, 5,
6, 7, 8, 9,
10,11,12,13,
14,15,16,17,
18,19,20,21,
22,23,24,25
}
the out put of this code is
1,2,6,3,7,11,4,6,12,16,5,9,13,17,21,10,14,18,21,15,19,23,20,24,25
I want to make change in this my code to be the out put begging from
21 16 22 11 17 23 6 12 18 24 1 7 13 19 25 2 8 14 203 9 15 4 10 5
and this my Code
int [,] p = new int [5,5];
int sum = 1;
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
p[i, j] = sum;
richTextBox1.Text += p[i, j].ToString();
sum++;
}
}
int C;
int R=1;
for (int i = 1; i <= 5; i++)
{
C = i;
for (int r = 1; r <= i; r++)
{
Output = Output + p[r, C];
C--;
}
}
richTextBox2.Text += Output.ToString();
for (int i = 2; i >= 5; i++)
{
R = i;
for (C = 5; C >= i; C--)
{
Output = Output + p[R, C];
R++;
}
}
richTextBox2.Text += Output.ToString();
This is more fiddly than you might think!
You want to traverse the diagonals of this matrix:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
starting at the bottom left and traversing each diagonal as depicted in this very badly-drawn diagram:
I've written a helper method called DiagonalIndices() that for a given maximum index (in the case of your 5x5 matrix, it will be 4) will produce a sequence of (row,col) indices in the correct order to traverse all the diagonals.
Note that the input array MUST be square - I'm assuming that is the case for your data! It clearly is for a 5x5 matrix.
The output of the following program is
21 16 22 11 17 23 6 12 18 24 1 7 13 19 25 2 8 14 20 3 9 15 4 10 5
Here's the code:
using System;
using System.Collections.Generic;
namespace ConsoleApplication4
{
public sealed class Index
{
public Index(int row, int col)
{
Row = row;
Col = col;
}
public readonly int Row;
public readonly int Col;
}
public static class Program
{
private static void Main()
{
int [,] p = new int[5, 5];
for (int i = 0, n = 1; i < 5; ++i)
for (int j = 0; j < 5; ++j, ++n)
p[i, j] = n;
// This is the bit you will use in your program.
// Replace the Console.WriteLine() with your custom code
// that uses p[index.Row, index.Col]
int maxIndex = p.GetUpperBound(1);
foreach (var index in DiagonalIndices(maxIndex))
Console.Write(p[index.Row, index.Col] + " ");
Console.WriteLine();
}
public static IEnumerable<Index> DiagonalIndices(int maxIndex)
{
for (int i = 0; i <= maxIndex; ++i)
for (int j = 0; j <= i; ++j)
yield return new Index(maxIndex-i+j, j);
for (int i = 0; i < maxIndex; ++i)
for (int j = 0; j < maxIndex-i; ++j)
yield return new Index(j, i+j+1);
}
}
}
This is a more efficient of printing only the diagonal values in a positive direction in a matrix.
int [,] p = new int [5,5]
{
{1, 2, 3, 4,5},
{6, 7, 8, 9},
{10,11,12,13},
{14,15,16,17},
{18,19,20,21},
{22,23,24,25}
};
for (int i = 4, j = 4; i >= 0 && j > = 0; i--, j--)
{
Console.Writeline(p[ i, j ]);
}

Categories