How to find the smallest value in a 2d dynamic array - c#

I am trying to find the smallest number in a dynamic 2d array but i have
hit a block and cannot figure out how this is done. I have done all the set up and populated with values.
using System;
namespace _2D_Array
{
class Program
{
static void Main(string[] args)
{
// Create integers n and r and set up the 2D array
int n = 5;
int[,] a;
int R = 50;
int x;
a = new int[n + 1, n + 1];
// Create number input randomizer
Random r = new Random();
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
a[i, j] = r.Next(1, R);
// Print array with random numbers to screen to check set up is correct for i and j
Console.Write(" ");
for (int i = 1; i <= n; ++i)
Console.Write(i.ToString("00" + " "));
Console.WriteLine();
Console.WriteLine();
for (int i = 1; i <= n; ++i)
{
Console.Write(i.ToString("00" + " "));
for (int j = 1; j <= n; ++j)
Console.Write(a[i, j].ToString("00" + " "));
Console.WriteLine();
}
// Get Search Value
Console.Write("What's the value to look for? ");
x = int.Parse(Console.ReadLine());
// look through the array
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
// If the element is found
if (a[i, j] == x)
{
Console.Write("Element found at (" + i + ", " + j + ")\n");
}
}
Console.Write(" Element not found");
```
This is all i have so far. in the end i want to have the smallest
value from a set of random numbers set in my 5x5 array.

First of all, format out your code: hard to read code is hard to debug.
Often, we can query array with a help of Linq:
using System.Linq;
...
int min = a.OfType<int>().Min();
Console.Write($"The smallest element is {min}");
If you want good old nested loops:
// not 0! What if min = 123?
// Another possibility is min = a[0, 0]; - min is the 1st item
int min = int.MaxValue;
// note a.GetLength(0), a.GetLength(0): n is redundant here
// and there's no guarantee that we have a square array
for (int r = 0; r < a.GetLength(0); ++r)
for (int c = 0; c < a.GetLength(1); ++c)
min = Math.Min(min, a[r, c]);
Console.Write($"The smallest element is {min}");

Related

Check common elements of two-dimensional arrays of integers, considering the positions they are on

at the beginning I want to mention that I am a beginner in programming. So, I want to write a program that checks the similarity of two-dimensional arrays of integers. The similarity is to be determined by the amount of numbers that are in the same positions in both tables. The user gives the number of columns in the table and the elements themselves, number of rows is the same all the time.The similarity result is displayed as a percentage and the similarity itself should be calculated taking into account the number of elements of the larger array. My problem is: When the two arrays are the same size, the program throws the exception and it doesn't check all the numbers in the column.(I wrote before program for one dimensional array and it works perfectly) So far I have managed to write something like this:
This is what I want to do In the picture, the similarity between the arrays is 20%
{
Console.WriteLine("How extensive is the first table supposed to be?");
int n = int.Parse(Console.ReadLine());
int z = 2;
int[,] tab1 = new int[2, n];
Console.WriteLine("Enter the numbers into the first array:");
for (int i = 0; i < z; i++)
{
for (int j = 0; j < n; j++)
{
tab1[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
int rowLength = tab1.GetLength(0);
int colLength = tab1.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", tab1[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine("How extensive is the second table supposed to be?");
int m = int.Parse(Console.ReadLine());
int b = 2;
int[,] tab2 = new int[2, m];
Console.WriteLine("Enter the numbers into the second array: ");
for (int i = 0; i < b; i++)
{
for (int j = 0; j < m; j++)
{
tab2[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
int Len4gth = tab2.GetLength(0);
int Len2gth = tab2.GetLength(1);
for (int i = 0; i < Len4gth; i++)
{
for (int j = 0; j < Len2gth; j++)
{
Console.Write(string.Format("{0} ", tab2[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
double similarity= 0;
if (tab1.GetLength(1) > tab2.GetLength(1))
{
for (int i = 0; i < tab2.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.GetLength(1) < tab2.GetLength(1))
{
for (int i = 0; i < tab1.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab2[i, j] == tab1[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.GetLength(1) == tab2.GetLength(1))
{
for (int i = 0; i < tab1.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.Length < tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab2.Length) * 100 + "%");
}
if (tab1.Length > tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab1.Length) * 100 + "%");
}
if (tab1.Length == tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab2.Length) * 100 + "%");
}
Console.ReadKey();
You must compare each element of the first array with the elements of the second array.
use this code :
//get first array items
Console.WriteLine("How extensive is the first table supposed to be?");
int n = int.Parse(Console.ReadLine());
int[,] tab1 = new int[2, n];
Console.WriteLine("Enter the numbers into the first array:");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
tab1[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
//write first array items
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(string.Format("{0} ", tab1[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
//get second array items
Console.WriteLine("How extensive is the second table supposed to be?");
int m = int.Parse(Console.ReadLine());
int[,] tab2 = new int[2, m];
Console.WriteLine("Enter the numbers into the second array: ");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < m; j++)
{
tab2[i, j] = int.Parse(Console.ReadLine());
}
}
//write second array items
Console.WriteLine("\n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(string.Format("{0} ", tab2[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
//find similarity items
double similarity = 0;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
int firstValue = tab1[i, j];
for (int k = 0; k < 2; k++)
{
for (int d = 0; d < m; d++)
{
if (firstValue == tab2[k, d])
{
similarity += 1;
}
}
}
}
}
double percentage = n > m ? ((similarity / tab1.Length) * 100) : ((similarity / tab2.Length) * 100);
Console.WriteLine("The similarity of the arrays is: " + percentage + "%");
Console.ReadKey();
this code work without error and It does not matter which array is larger.
If you want similar elements like this example enter link description here, use this code snippet to find similar elements
//find similarity items
double similarity = 0;
int z = n > m ? m : n;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity += 1;
}
}
}
double percentage = n > m ? ((similarity / tab1.Length) * 100) : ((similarity / tab2.Length) * 100);
Console.WriteLine("The similarity of the arrays is: " + percentage + "%");
Console.ReadKey();

No. of rows 1 less than expected in a jagged array

While printing this jagged array I am getting the no of rows to be 1 less than expected. It should start with 0th index to (h-1)th index creating a total of h rows. What am I doing wrong?
h is the no. of rows.
int h = int.Parse(Console.ReadLine());
int[][] arr = new int[h][];
for(int i = 0; i < h; ++i)
{
arr[i] = new int[i+1];
}
for(int i = 0; i < h; i++)
{
Console.WriteLine();
for(int j = 0; j < i; j++)
{
Console.Write(arr[i][j] + " ");
}
}
That's because your inner for-loop has the condition j < i. If i is 0 in the first pass, the inner for-loop will not be passed.
Try it with
for(int j = 0; j < arr[i].Length; j++)
{
Console.Write(arr[i][j] + " ");
}
The arrays have a growing list of elements, starting with 1 so if you want to scan all the items:
for(int i = 0; i < h; i++)
{
Console.WriteLine();
for(int j = 0; j < (i + 1); j++)
{
Console.Write(arr[i][j] + " ");
}
}
Shouldn't it be:
new int[i];
Instead of:
new int[i+1]
Or is it h - 1? Just change that index of the array.
Or you need j < arr[i].Length

What's the best, correct way way to optimize this code and find MIN and MAX value for each ROW/COLUMN [duplicate]

This question already has answers here:
Get minimum and maximum value using linq
(3 answers)
Closed 4 years ago.
I'm trying to make this code as efficient as possible, what is the best and most correct way to do this? Also, I need to find the MIN and MAX values for each column and row and display the values next to the specific row and column.
Code:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Random rand = new Random();
int ri, ki;
int i, j;
int max = 1;
int min = 0;
int rndnumber = rand.Next(64, 128);
int[,] array = new int[9, 4]; // Izveido array 9x4 (rin x kol)
for (i = 0; i < 9; i++) //
{
for (j = 0; j < 4; j++)
array[i, j] = rand.Next(1, 100 + 1);
}
for (i = 0; i < 9; i++) //
{
for (j = 0; j < 4; j++)
{
Console.Write("|\t{0}\t ", array[i, j]); // /t - tab
}
Console.WriteLine("\n"); // new line
}
for (i = 0; i < 9; i++) //
{
for (j = 0; j < 4; j++)
if (max < array[i, j]) // Aprekina max
{
max = array[i, j];
}
}
Console.WriteLine("Maksimalais sk tabula: {0}", max);
Console.WriteLine("Min sk tabula: {0}", min);
//rndnumber = rand.Next();
//Console.WriteLine("Hello World {0}", rndnumber);
Console.ReadKey();
/*
Izveidot ka zem katras rindas un kol ir min un max skaitlis
*/
}
}
If you make the multidimensional array into an IEnumerable, you can use Linq on it:
// Order and use Cast<int>() to get an ordered IEnumerable<int>,
var orderedAscending = from x in array.Cast<int>()
orderby x
select x;
// Use linq First() & Last() to get min and max.
var min = orderedAscending.First();
var max = orderedAscending.Last();

Displaying an arrays index number

I need help with C#
I'm currently trying to find the minimum value in a 2D array. I have managed to do this however, after I have found the minimum value I want the corresponding values index number (Where it is stored in my 2D array) to be output. For example, I have a 2D and a 1D array. Once the minimum value has been discovered the index value for the 2D array needs to be changed in the 1D array.
The 2d array is c[i,j]
and the 1D array is a[i]
so how would i be able to display the j number in my c array in my a array. For example, if my minimum value was at c[1,5] I want the value in a[5] to be changed from 0 to 1. Any help would be great thanks!
P.S. if ive made this sound really confusing I apologise I'm new to this !
int n = 5, m = 10, MinValue = 100, MaxValue = 1, Total = 0, Sum = 0; //n = number of values m = max value in array MinValue = Lowest number in array
Random Rand = new Random();
int[] A = new int[n + 1];
for (int i = 1; i < n+1; i++) //Reached and unreached array - creation
{
A[i] = 0;
}
A[1] = 1;
int[,] c = new int[n + 1, n + 1]; //Create array
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
c[i, j] = Rand.Next(1, m); //Randomise the array
if (i == j)
{
c[i, j] = 99; // give void spaces the value of 99
}
if (c[i, j] > MaxValue && c[i, j] < 99)
{
MaxValue = c[i, j]; // max value takes the highest value (that isnt 99)
}
}
}
for (int p = 1; p <= n; p++)
{
for (int i = 1; i <= n+1; i++)
{
for (int j = 1; i <= n+1; i++)
{
if (c[i, j] <= MinValue)
{
if (A[i] == 1)
{
if (A[i] == 0)
{
Total = Sum + MinValue;
Sum = Total;
A[i] = 1;
}
}
}
}
}
}
Console.WriteLine("Total Value = " + Total);
Console.WriteLine("");
Console.WriteLine("The tracking array - what has been reached and what hasn't"); // Output reaching array
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.WriteLine("A[" + i + "] = " + A[i].ToString("00") + " ");
//Output the array to screen
}
Console.WriteLine("");
Console.WriteLine("The link length array"); // Output link length array
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
Console.Write("c[" + i + "," + j + "] = " + c[i, j].ToString("00") + " ");
}
Console.WriteLine();
//Output the array to screen
}
Console.WriteLine("");
Console.ReadLine();

My code won't do the sum; only the elements of the matrix appear and then nothing happens

namespace Suma_diagonala_secundara
{
class Program
{
static void Main(string[] args)
{
int n, i, j, s = 0;
Console.Write("n= ");
n = Convert.ToInt32(Console.ReadLine());
int[,] tab = new int[n, n];
for(i=0;i<n;i++)
for (j = 0; j < n; j++)
{
Console.Write("tab[{0}][{1}]= ", i + 1, j + 1);
tab[i, j] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElementele matricii sunt: ");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
Console.Write("{0} ", tab[i, j]);
Console.WriteLine("");
}
Console.WriteLine("Suma elementelor de pe diagonala secundara este: ");
for (i = 0; i < n; i++)
{
s = s + tab[i, n - i + 1];
}
Console.ReadKey();
}
}
}
In your loop
for (i = 0; i < n; i++)
{
s = s + tab[i, n - i + 1];
}
you are accessing the array out of bounds, since n - 0 + 1 = n + 1 is larger than n - 1 (the largest index in tab).
What you actually want is (note the parentheses)
for (i = 0; i < n; i++)
{
s = s + tab[i, n - (i + 1)];
}
The following line:
s = s + tab[i, n - i + 1];
Is throwing an IndexOutOfRangeException because you are requesting an index higher than the array capacity.
The correct loop code is (with decrement instead increment)
for (i = 0; i < n; i++)
{
s = s + tab[i, n - i - 1];
}

Categories