Who can illuminate me about getting max per line? - c#

This is my code:
I am trying to get the maximum per line, everything is going ok until the last row. It shows me 8, but should be 4.
int[,] vek = new int[,] { { 2, 5 }, { 4, 5 }, { 8, 5 }, { 4, 2 } };
int sumL=0;
double media = 0;
int maxL = 0;
maxL = vek [0,0];
Console.WriteLine("\tL1\tL2\tTotal\tMedia");
Console.WriteLine();
for (int row = 0; row < vek.GetLength(0); row++)
{
Console.Write("{0}.\t", row + 1);
for (int col = 0; col < vek.GetLength(1); col++) {
Console.Write(vek[row, col] + "\t");
sumL += vek[row, col];// SUMA
media = (double)sumL / vek.GetLength(1); //Media
if (maxL < vek[row,col])
{
maxL = vek[row, col];
}
}
Console.WriteLine(sumL + "\t" + media + "\t" + maxL);
Console.WriteLine();
}
Console.ReadKey();
}

You need to set maxL back to 0 (or, better yet, int.MinValue) at the start of each row. Simply moving its declaration into the outer for loop would be a good way to do this.
Your code gets 5, 5, 8, 8 for the maximum because, without reseting maxL, it's taking the maximum of the rows so far instead of the maximum of each row independently.

Related

How to reverse 2d arrays in c#

array :
int[,] nums = new int[3,4]{
{6,7,9,8},
{4,2,1,3},
{9,7,0,4}
};
I need to print out the rows in reverse but keep the columns in same order.
Iooked all over the internet I don't even know where to start my code, all I have is a for loop that prints in reverse but when I run my code nothing shows up.
for (row = 3; row >= 0; row--)
{
for (column = 0; column < 4; column++)
{
Console.Write("{0} ",nums[row,column]);
}
}
I'm definitely missing something and the only error I get is the index out of bounds.
Please, do not use magic numbers like 3, 4, but actual array lengths, GetLength(...):
int[,] nums = new int[3, 4] {
{ 6, 7, 9, 8 },
{ 4, 2, 1, 3 },
{ 9, 7, 0, 4 },
};
for (int row = nums.GetLength(0) - 1; row >= 0; --row) {
for (int column = 0; column < nums.GetLength(1); ++column)
Console.Write($"{nums[row, column]} ");
if (row > 0)
Console.WriteLine();
}
Fiddle
As you know indexes in an array go from 0 to upper bound so when cycling through you should consider that for an array with 3 elements you will have indexes 0, 1 and 2, you are trying to access index 3 which does not exist.
High level languages have safeguards to avoid this, here an out of range type exception is thrown to let you know you are accessing memory that does not belong to the array.
You should avoid direct indexing because it's very easy to get these off-by-one errors, you should always try to use range based loops, if that's not possible get the length of the array by code, don't use hard coded dimensions unless you have to. Here you can use member methods to figure out the bounds of the array:
int[,] nums = {
{6,7,9,8},
{4,2,1,3},
{9,7,0,4}
};
for (var row = nums.GetUpperBound(0); row >= 0; row--)
{
for (var column = 0; column < nums.GetLength(1); column++)
{
Console.Write("{0} ",nums[row,column]);
}
Console.WriteLine(); // line break for tiddy print
}
This should work
for (row = 2; row >= 0; row--)
{
for (column = 0; column < 4; column++)
{
Console.Write("{0} ",nums[row,column]);
}
}
for (row = 3; row >= 0; row--)
The program is throwing OutOfRangeEception, because when you have an array[3,4], the last index of row is 2. Your program was trying to find an element with too large index number(3).
Here you have working code
int[,] nums = new int[3, 4] { { 6, 7, 9, 8 }, { 4, 2, 1, 3 }, { 9, 7, 0, 4 } };
for (int **row = 2**; row >= 0; row--)
{
for (int column = 0; column < 4; column++)
{
Console.Write("{0} ", nums[row,column]);
}
Console.WriteLine();
}
As you can see, changing value in for loop from 3 to 2 fixed the problem.
And one important note from me - try to declare counter variables inside for - do not make it "global" if you don't need to. In bigger project it could use more memory than necessary. When it's inside for, garbage collector will destroy the variable after all loops

Find all the index from an array whose sum value is equal to n

So, I needed to find all the index of elements from an array whose sum is equal to N.
For example : Here I want to find indexes whose sum should be equal to 10.
Input : int[] arr = { 2, 3, 0, 5, 7 }
Output: 0,1,3
If you add indexes arr[0] + arr[1] + arr[3] then 2 + 3 + 5 = 10.
I have tried this, but I am running 3 for loops and 3 if conditions, Can we write this in less code, I want to reduce code complexity.
PS: Post suggestions, not codes..
public static void Check1()
{
int[] arr = { 2, 3, 0, 5, 7 };
int target = 10; int total = 0;
bool found = false;
List<int> lst = new List<int>();
for (int i = 0; i < arr.Length; i++)
{
if (!found)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (!found)
{
total = arr[j] + arr[i];
for (int k = j + 1; k < arr.Length; k++)
{
if (total + arr[k] == target)
{
found = true;
Console.WriteLine($"{i}, {i + 1}, {k}");
break;
}
}
}
}
}
}
Console.ReadLine();
}

Incorrect loop result

First array is filled randomly, its length is set from the console .I have an array in which I need to write a sub-array of repeating numbers and the number of repeating numbers. For example {3 3 3 3 3 4}, 3 3 3 3 is the repeating numbers, 4 is their number.
The problem is that if there are repeating numbers at the end of the array, the loop doesn't output them and if I enter the debug mode, I can see that not all numbers are written. What could be the problem?
for (int i = 1; i < array.Length; i++)
{
if (array[i - 1] == array[i])
{
if((i + 1) != array.Length)
{
duplicateCount++;
addArray = array[i - 1];
duplicate += addArray + " ";
}
else
{
duplicateCount++;
lastElement = array[i - 1];
duplicate += lastElement;
}
}
else
{
if (duplicateCount != 1)
{
addPrevious = array[i - 1];
duplicate += addPrevious + " ";
duplicateArrays.Add(duplicate + duplicateCount);
duplicate = "";
duplicateCount = 1;
}
else
{
duplicateCount = 1;
}
}
}
duplicateArrays.Add(duplicate + duplicateCount);
While the Antidisestablishmentarianism code is the shortest one, it uses '^' which is index from end operator introduced in C# 8.0. I'm not carping about that but it's a difference worth knowing. Compiling the same code in the older version will generate a compile time exception. I'll be giving a long yet beginner friendly code which is pretty self-explanatory if you read it twice.
static void Main(string[] args)
{
int[] RandomArray = new int[] { 1, 2, 2, 3, 4, 4, 3, 1, 5, 2, 9, 8, 9, 8, 8, 5, 3, 4, 1 };
int RandomArrayLength = RandomArray.Length;
List<int[]> SubArrayList = new List<int[]>();
List<int> visited = new List<int>();
for (int i = 0; i < RandomArrayLength; i++)
{
int elem = RandomArray[i];
if (!visited.Contains(elem))
{
visited.Add(elem);
List<int> templist = new List<int>();
for (int j = 0; j < RandomArrayLength; j++)
{
if (elem == RandomArray[j])
{
templist.Add(elem);
}
}
if (templist.Count > 1) //You can remove this condition if you want to include all the elements
{
int elemCount = templist.Count;
List<int> sublist = new List<int>();
sublist.AddRange(templist);
sublist.Add(elemCount);
SubArrayList.Add(sublist.ToArray());
}
}
else
{
continue;
}
}
int SubArrayListCount = SubArrayList.Count;
for (int i = 0; i < SubArrayListCount; i++)
{
int[] SubArr = SubArrList[i];
int SubArrCount = SubArr.Length;
for (int j = 0; j < SubArrCount; j++)
{
Console.Write(SubArr[j].ToString() + " ");
}
Console.WriteLine();
}
}

How to calculate the average of each row in multidimensional array

What i want to do is get the average of each row of what the user inputs. I'm able to display the input, but not sure how to calculate an average of the three numbers in each row. What would be a solution? I'm new to C# so still learning.
Here's my code:
class Program
{
static void Main(string[] args)
{
int[,] number = new int[3, 5];
for (int i = 0; i < 3; i++)
{
for (int x = 0; x < 3; x++)
{
Console.WriteLine("Please enter number");
number[x, i] = int.Parse(Console.ReadLine());
}
}
for (int i = 0; i < 3; i++)
{
for (int x = 0; x < 3; x++)
{
Console.Write(number[x, i] + " ");
}
Console.WriteLine(" ");
Console.ReadLine();
}
}
}
You can do it something like this
for(int i = 0; i < 3; i++)
{
int Avg = 0;
for(int x = 0; x < 3; x++)
{
Console.Write(number[x, i] + " ");
Avg += number[x, i];
}
Avg = Avg / 3;
Console.Write("Average is" + Avg);
Console.WriteLine(" ");
Console.ReadLine();
}
I think you have to create a method like the following, that will accept a two dimensional array as input and iterate through its rows and further iteration will performed through its cols to find the sum of all elements in each rows and then it will be divided with number of cols, to get the average. Take a look into the method
public static void rowWiseAvg(int[,] inputArray)
{
int rows = inputArray.GetLength(0);
int cols = inputArray.GetLength(1);
for (int i = 0; i < rows; i++)
{
float rowAvg = 0;
for (int x = 0; x < cols; x++)
{
rowAvg += inputArray[i,x];
}
rowAvg = rowAvg / cols;
Console.Write("Average of row {0} is :{1}", i,rowAvg);
}
}
An additional note for you : When you are reading values for a multi-dimensional array, use outer loop to read values for the rows and inner loop for reading columns. in your case you are actually reads the columns first then gets values for each rows in a column. One more, use float / double to store the average
Here's a (mostly) LINQ solution:
var array = new int[,]
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
int count = 0;
var averages = array.Cast<int>()
.GroupBy(x => count++ / array.GetLength(1))
.Select(g => g.Average())
.ToArray();
// [2.5, 6.5, 10.5]
The simplest way is to use for loops, as described in other answers.
You can also utilize LINQ and use Enumerable.Range to make it another way:
public static class MultidimensionalIntArrayExtensions
{
// Approach 1 (using Select and Average)
public static double[] RowAverages(this int[,] arr)
{
int rows = arr.GetLength(0);
int cols = arr.GetLength(1);
return Enumerable.Range(0, rows)
.Select(row => Enumerable
.Range(0, cols)
.Select(col => arr[row, col])
.Average())
.ToArray();
}
// Approach 2 (using Aggregate)
public static double[] RowAverages(this int[,] arr)
{
int rows = arr.GetLength(0);
int cols = arr.GetLength(1);
return Enumerable.Range(0, rows)
.Select(row => Enumerable
.Range(0, cols)
.Aggregate(0.0, (avg, col) => avg + ((double)arr[row, col] / cols)))
.ToArray();
}
}
// Usage:
int[,] arr =
{
{ 1, 2, 3 },
{ 2, 3, 4 },
{ 3, 4, 5 },
{ 6, 7, 8 },
{ 1, 1, 1 }
};
double[] rowSums = arr.RowAverages(); // [2, 3, 4, 7, 1]
This code may look unreadable and non-OOP for some developers; and may seem good and laconic for others. If your belongs to the second group, use this code.

average of only diagonals of 2 a dimensional array C#

I have a C# midterm review question that is getting the best of me. The question is: "Use a method, and on the click of a button, call the method to sort through a 2 dimensional array (globally declared) and return the average of the first diagonal using a SINGLE for loop."
My 2 dimensional array looks like this
int[,] A = new int[,] { { -16, 19, 8, -3 },
{-17, -5, 9, 33 },
{-2, 15, -13, 29 },
{25, 39, -23, 8 } };
And my code thus far looks like this:
private void btnAverageQVI_Click(object sender, EventArgs e)
{
arrayAverage(A);
}
`public static void arrayAverage(int[,] array)
{
int total = 0;
int count = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (rows = 0; rows < array.Length; rows++)
{
total = array[0, 0] + 1;
count++;
}
double average = total / 4;
MessageBox.Show("Total: " + average);
}`
Someone please help, I feel like it's easy, but I am missing something.
public static void arrayAverage(int[,] array)
{
int total = 0;
//Get number of rows
int rows = Math.Min(array.GetLength(0),array.GetLength(1));
//Iterate through diagonal elements
for (int i= 0; i < rows; i++)
{
total += array[i, i];
}
//Multiple 1.0 to prevent data lost.
double average = 1.0*total / rows;
Console.WriteLine("Total: " + average);
}

Categories