C# 2D Array - how to print the largest element in each row - c#

I'm raeding MTA 98-361 and there is a task: You are writing a program that uses a two-dimensional array. The array has four rows and five columns. You need to print the largest element in each row of the array.
My code:
static void Main(string[] args)
{
//[x, y] row, col
int[,] grid = new int[4,5] { { 1, 2, 4, 5, 6 }, //how to get largest number of each row
{ 3, 4, 7, 8, 9 },
{ 5, 6, 56, 12, 45 },
{ 7, 8, 45, 12, 78 }};
for (int row = 0; row < grid.GetLength(0); row++)
{
for (int col = 0; col < grid.GetLength(1); col++)
{
Console.Write(grid[row, col] + "\t ");
}
Console.WriteLine();
}
Console.WriteLine("Row1: {0} {1} {2} {3} {4} ", grid[0, 0], grid[0, 1], grid[0, 2], grid[0, 3], grid[0, 4]);
Console.ReadLine();
}
I know that this is my task, and should solve it, but I'm stuck.
Can you give me advice how to accomplish it?
Thanks!

Here's how you do it without spawning threads:
public static void Main()
{
int[,] grid = new int[4,5] { { 1, 2, 4, 5, 6 }, //how to get largest number of each row
{ 3, 4, 7, 8, 9 },
{ 5, 6, 56, 12, 45 },
{ 7, 8, 45, 12, 78 }};
int w=grid.GetLength(0), h=grid.GetLength(1);
Console.WriteLine(string.Join(",",
Enumerable.Range(0,w).Select(i=>Enumerable.Range(0,h).Select(j=>grid[i,j]).Max())));
}
You can see it in action here: https://dotnetfiddle.net/8u08i3

Related

How can sort by odd,even row?

I hava jagged Array
I want sort first,third row ascending order and second,fourth row descending order
public class JaggedArrayTest {
public static void Main() {
int[][] arr = new int[4][] {
new int[] {
11,
78,
56,
21
},
new int[] {
2,
7,
5,
6
},
new int[] {
8,
3,
9,
12
},
new int[] {
1,
10,
19,
17
}
};
// Traverse array elements
for (int i = 0; i < arr.Length; i++) {
for (int j = 0; j < arr[i].Length; j++) {
System.Console.Write(arr[i][j] + " ");
}
System.Console.WriteLine();
}
}
}
I want output like this
11, 21, 56, 78 
7, 6, 5,2
3, 8,9,12
19,17,10,1
Algo:-
Loop through each row.
Use Array.Sort() to sort each row
for(int row = 0; row < arr.Length; row++)
{
Array.Sort(arr[row]);
}
Although a little "allocatey", this can be done with linq and the remainder operator (to test for odd or even) fairly easily
The remainder operator ``% computes the remainder after dividing its
left-hand operand by its right-hand operand.
var results = arr.Select((values, i)
=> (i % 2 == 0 ? values.OrderBy(x => x) : values.OrderByDescending(x => x)).ToArray())
.ToArray();
foreach (var values in results)
Console.WriteLine(string.Join(", ",values));
Or an in situ, less "allocatey", and more idiomatic approach
for (var i = 0; i < arr.Length; i++)
{
Array.Sort(arr[i]);
if(i % 2 != 0)
Array.Reverse(arr[i]);
}
Output
11, 21, 56, 78
7, 6, 5, 2
3, 8, 9, 12
19, 17, 10, 1

Splitting a 2D array into 4 smaller 2D arrays

I need to loop through a 2D array of ints that is 4x4, but I also have to create 4 2x2 arrays out of it. Then I have to loop through each of those 4 2x2 arrays to pick out the average of the numbers in each 2x2 array.
public int[,] Reduced(Sampler sampler)
{
int[,] a = new int[SampleSize,SampleSize];
for (int r = 0; r < Math.Sqrt(image.Length); r+=SampleSize)
{
for (int c = 0; c < Math.Sqrt(image.Length); c+=SampleSize)
{
InsideLoop(a, r, c);
}
}
return a;
}
private void InsideLoop(int[,] a, int r, int c)
{
for (r = 0; r < SampleSize; r++)
{
for (c = 0; c < SampleSize; c++)
{
a[r, c] = image[r, c];
Console.WriteLine("Value: {0}", a[r, c]);
}
}
}
This is essentially what I've got so far, but it's working how it's written instead of how I'd like it to work. For this example, SampleSize is a variable that is set to 2. What this does currently is print out the numbers that create the first 2x2 array four times. My laptop battery is about to die, so I can't elborate more, but if anyone has any tips while I'm driving home. I had to finish posting this on my phone.
Does this work?
int sampleSize = 2;
int[,] data = {
{1, 2, 3, 4 },
{5, 6, 7, 8 },
{9, 10, 11, 12 },
{13, 14, 15, 16 }
};
//assume input data is a perfect square as per your example
int max = (int)Math.Sqrt(data.Length);
List<int[,]> samples = new List<int[,]>();
int startX = 0;
while (startX + sampleSize <= max)
{
int startY = 0;
while (startY + sampleSize <= max)
{
int[,] sample = new int[sampleSize, sampleSize];
for (int x = 0; x < sampleSize;x++)
{
for (int y = 0; y < sampleSize; y++)
{
sample[x, y] = data[x + startX, y + startY];
}
}
samples.Add(sample);
startY += sampleSize;
}
startX += sampleSize;
}
//for output testing
foreach (int[,] sample in samples)
{
Console.WriteLine(sample[0, 0].ToString().PadLeft(2) + " | " + sample[0, 1]);
Console.WriteLine(" ----- ");
Console.WriteLine(sample[1, 0].ToString().PadLeft(2) + " | " + sample[1, 1]);
Console.WriteLine();
Console.WriteLine();
}
Console.ReadLine();
and here's the output
1 | 2
-----
5 | 6
3 | 4
-----
7 | 8
9 | 10
-----
13 | 14
11 | 12
-----
15 | 16
Generalized version:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[,] original = new int[,] { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
int[,] harder = new int[,] { { 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, 26, 27 },
{ 28, 29, 30, 31, 32, 33, 34, 35, 36 },
{ 37, 38, 39, 40, 41, 42, 43, 44, 45 },
{ 46, 47, 48, 49, 50, 51, 52, 53, 54 },
{ 55, 56, 57, 58, 59, 60, 61, 62, 63 },
{ 64, 65, 66, 67, 68, 69, 70, 71, 72 },
{ 73, 74, 75, 76, 77, 78, 79, 80, 81 } };
IterateArray(original);
Console.ReadLine();
}
static void IterateArray(int[,] array)
{
double tDim = Math.Sqrt(Math.Sqrt(array.Length));
int dim = (int)tDim;
if (dim != tDim) throw new ArgumentException("Not a valid array!");
for (int i = 0; i < dim; i++)
{
IterateRows(array, dim, i);
}
}
static void IterateRows(int[,] array, int dim, int pass)
{
int maxRow = dim * dim;
IList<int> list = new List<int>(maxRow);
for (int curRow = 0; curRow < maxRow; curRow++)
{
IterateColumns(array, dim, curRow, pass, list);
if (list.Count == maxRow)
{
PrintNewArray(list, dim);
list.Clear();
}
}
}
static void IterateColumns(int[,] array, int dim, int row, int pass, IList<int> list)
{
int maxCol = dim + (dim * pass);
for (int curCol = pass * dim; curCol < maxCol; curCol++)
{
list.Add(array[row, curCol]);
}
}
static void PrintNewArray(IList<int> list, int dim)
{
for(int i = 0; i < list.Count; i++)
{
if (i % dim == 0)
{
Console.WriteLine();
}
Console.Write($"{list[i]} ");
}
Console.WriteLine($"\nAverage {list.Average()}");
}
}

How to get sub array that has maximum sum of all its items

My test is to solve this following problem:
A zero-indexed array A consisting of N integers is given.
Write a solution to find out the sub array of A, which contains consequent items that has the maximum sum of all its items.
Example:
A = [2, -1, 3, -3, 4, -9, 10, -3, 4, -4, -7, 2, 8]. The answer is [10, -3, 4]
A = [3, 2, -5, 7, 4, -8, 3, -5, 2, 4, -2, 4]. The answer is [7, 4]
A = [-2, 5, 3, 6, -1,-5]. The answer is [-2, 5, 3, 6].
Please help me to give me the way to resolve it.
Basicly, what you need to do is to traverse the array and check for the maximum value of the sum of elements. Once you have found the max sum, you have the last element of your resulting subarray.
Once you have found the max element, you need to traverse back and do the same in order to find the sub array with maximum sum of elements.
int iNewTopHigh = 0;
int iNewTopLow = 0;
int iIndNewTopHigh = 0;
int iIndNewTopLow = 0;
int iSumHigh = 0;
int iSumLow = 0;
int[] iArr = {2, -1, 3, -3, 4, -9, 10, -3, 4, -4, -7, 2, 8};
//{3, 2, -5, 7, 4, -8, 3, -5, 2, 4, -2, 4};
//{-2, 5, 3, 6, -1,-5};
//Get the top
for(int i = 0; i < iArr.Length; i++){
iSumHigh += iArr[i];
if(iSumHigh > iNewTopHigh){
iIndNewTopHigh = i;
iNewTopHigh = iSumHigh;
}
}
//Get the bottom
for(int i = iIndNewTopHigh; i != 0; i--){
iSumLow += iArr[i];
if(iSumLow > iNewTopLow){
iIndNewTopLow = i;
iNewTopLow = iSumLow;
}
}
//Print results
for(int i = iIndNewTopLow ; i <= iIndNewTopHigh; i++){
Console.Write(iArr[i] + ", ");
}

How to output lowest number in array (also to see if I'm doing this right)

Back with another C# question.
Here's my current task:
Problem Definition:
A computer program is required to read the daily hours parked by customers. There are 30 entries for customer’s parking hours (integer numbers) stored in a data file ‘hours.txt’. You are required to read the file and store the data in an array. Calculate the highest, lowest and average of the daily parking hours.
Sample Data:
30 parking hours: {8, 24, 9, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8}
Highest parking hours = 24
Lowest parking hours = 1
Average parking hours = 9.13
Overall Tasks:
Read the data file ‘hours.txt’ into an array of data type integer
Find highest value
Find lowest value
Calculate the average
Output the array of hours, highest, lowest and average (formatted to 2 decimal places)
Note: Since the topic of “files” is not covered until Session 6, for now, declare your array and assign the numbers as shown below
int[] hoursArray = {8, 24, 9, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8};
In session 6 you will need to modify your code so the data is read from the hours.txt file.
So from this I gather I need to run a program that spits out the average, highest, and lowest of the hours entered. Note that it says to use the data from a text file, but further down says that is for a different topic, so I haven't done that. Instead, I had opted for manually entering in the 30 digits.
First question I suppose, is is that right, or is there a way that using
int[] hoursArray = {8, 24, 9, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8};
the data is automatically entered without the user manually entering the digits? Not sure if I'm reading the task right.
Second question is here is the code I have done. I can succesfully output the average and highest value, but I don't seem to be able to output the lowest value below 8 (ie, the value of 1 in there). How do I fix this?
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IntsArray
{
class Program
{
static void Main(string[] args)
{
int[] hours;
hours = new int[30];
int[] hoursArray = { 8, 24, 9, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8 };
hours[0] = 8;
hours[1] = 24;
hours[2] = 9;
hours[3] = 7;
hours[4] = 6;
hours[5] = 12;
hours[6] = 10;
hours[7] = 11;
hours[8] = 23;
hours[9] = 1;
hours[10] = 2;
hours[11] = 9;
hours[12] = 8;
hours[13] = 8;
hours[14] = 9;
hours[15] = 7;
hours[16] = 9;
hours[17] = 15;
hours[18] = 6;
hours[19] = 1;
hours[20] = 7;
hours[21] = 6;
hours[22] = 12;
hours[23] = 10;
hours[24] = 11;
hours[25] = 23;
hours[26] = 1;
hours[27] = 2;
hours[28] = 9;
hours[29] = 8;
for (int index = 0; index < hours.Length; index++)
{
Console.Write("Enter your hours: ");
hours[index] = int.Parse(Console.ReadLine());
}
int total = 0;
double average = 0;
for (int index = 0; index < hours.Length; index++)
{
total = total + hours[index];
}
average = (double)total / hours.Length;
Console.WriteLine("Average = " + average.ToString("N2"));
int high = hours[0];
for (int index = 1; index < hours.Length; index++)
{
if (hours[index] > high)
{
high = hours[index];
}
}
Console.WriteLine("Highest number = " + high);
int low = hours[0];
for (int index = 0; index > hours.Length; index++)
{
if (hours[index] < low)
{
low = hours[index];
}
}
Console.WriteLine("Lowest number = " + low);
Console.ReadKey();
}
}
}
Thank you in advance :)
For getting the lowest number change following piece of code
for (int index = 0; index > hours.Length; index++)
{
if (hours[index] < low)
{
low = hours[index];
}
}
Console.WriteLine("Lowest number = " + low);
To
for (int index = 0; index < hours.Length; index++)
{
if (hours[index] < low)
{
low = hours[index];
}
}
Console.WriteLine("Lowest number = " + low);
Simply use the Linq extension methods
int[] hours = { 8, 24, 9, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8, 8, 9, 7, 9, 15, 6, 1, 7, 6, 12, 10, 11, 23, 1, 2, 9, 8 };
Console.WriteLine("Average = {0:F2}", hours.Average());
Console.WriteLine("Highest number = {0}", hours.Max());
Console.WriteLine("Lowest number = {0}", hours.Min());
Output
Average = 9.13
Highest number = 24
Lowest number = 1

How can I separate a multi-dimension (2D) array by rows into multiple 1D arrays?

I am programming in C# and I currently have the 2D array below:
int[,] results = {
{ 4, 7, 9, 3, 8, 6, 4},
{ 4, 8, 6, 4, 8, 5, 6},
{ 7, 3, 9, 2, 2, 1, 8}
};
I'd like to create a loop or function which outputs 3 separate arrays, copying the values from each row.
e.g. output:
row1 = {4, 7, 9, 3, 8, 6, 4}
row2 = {4, 8, 6, 4, 8, 5, 6}
etc
I have been able to copy the values of each row into a separate string which is then written in the console with this line of code:
for (int a = 1; a < (rows+1); a++)
{
for (int b = 1; b < (columns+1); b++)
{
scores = scores + " " + results[(a-1), (b-1)];
}
scores = "";
}
you need a convertion from a 2D array into a jagged array
int[,] array = { { 4, 7, 9, 3, 8, 6, 4},
{ 4, 8, 6, 4, 8, 5, 6},
{ 7, 3, 9, 2, 2, 1, 8}
};
int[][] jagged = new int[array.GetLength(0)][];
for (int i = 0; i < array.GetLength(0); i++)
{
int[] row = new int[array.GetLength(1)];
for (int j = 0; j < array.GetLength(1); j++)
{
row[j] = array[i, j];
}
jagged[i] = row;
}
int[] row1 = jagged[0];
int[] row2 = jagged[1];
int[] row3 = jagged[2];
difference between multidimensional array and jagged array:
//multidimensional array
int[,] multi = { { 7, 2, 6, 1 }, { 3, 5, 4, 8 } };
//array of arrays (jagged array)
int[][] jagged = new int[][] { new int[] { 7, 2, 6, 1 }, new int[] { 3, 5, 4, 8 } };
LINQ variant:
var m0 = new int[,] { { 1, 2 }, { 3, 4 } };
var rows = Enumerable.Range(0, m0.GetLength(0)).Select(i => Enumerable.Range(0, m0.GetLength(1)).Select(j => m0[i, j]));
foreach (var r in rows) Console.WriteLine(string.Join(" ", r));
Console.ReadLine();
a 'smarter' variant (flattern an array and take by N values):
var rows = m0.Cast<int>().Select((v, i) => new { i = i / m0.GetLength(1), v }).GroupBy(e => e.i).Select(g => g.Select(e => e.v));
Just a piece of cake using JsonSoft as
var json = JsonConvert.SerializeObject(results);
int[][] arr = JsonConvert.DeserializeObject<int[][]>(json);
int[] arr1 = arr[0];
int[] arr2 = arr[1];
int[] arr3 = arr[2];

Categories

Resources