Sum of a 2 dimensional array c# beginner - c#

i'm still learning c# and hava a question about my code. In theory i should get the value of 60 returned, but for some reason it only returns 47. Any one got an idea why? I want to solve it using while-loops and if. So a Solution without using foreach is required.
Any Help would be much appreciated.
My Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace B7ArraysPart2
{
class Program
{
/// <summary>
/// Returns the sum of all elements in the given array
/// [TESTMETHOD]
/// </summary>
/// <param name="arr">Array to build the sum over</param>
/// <returns>Sum of all elements in the given array</returns>
public static int Sum(int[,] arr)
{
//get arr.Length of both dimensions
int length1d = arr.GetLength(0);
int length2d = arr.GetLength(1);
//set the individual variables to 0
int sum1d = 0;
int sum2d = 0;
int i = 0;
int i2 = 0;
int c = 0;
//Doing first Row
while (i < length1d)
{
int add = arr[0, i];
sum1d += add;
i++;
}
//Doing second to all rows
if (c < length2d)
{
c++;
i2 = 0;
while (i2 < length1d)
{
int add2 = arr[c, i2];
sum2d += add2;
i2++;
}
}
Console.WriteLine("{0}, {1}", sum1d, sum2d);
return sum1d+sum2d;
}
static void Main(string[] args)
{
int[,] myArr2D;
myArr2D = new int[3, 3];
myArr2D[0, 0] = 10;
myArr2D[0, 1] = 11;
myArr2D[0, 2] = 12;
myArr2D[2, 0] = 13;
myArr2D[1, 2] = 14;
//Console.WriteLine("{0}", myArr2D[2, 0]);
Console.WriteLine("{0}", Sum(myArr2D));
Console.ReadKey();
}
}
}

Just iterate over 2d array in normal way and sum values.
int sum = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
sum += arr[i, j];
}
}
return sum;
This can be easily converted to while loop.
int sum = 0;
int i = 0;
while (i < arr.GetLength(0))
{
int j = 0;
while (j < arr.GetLength(1))
{
sum += arr[i, j];
j += 1;
}
i += 1;
}
return sum;

Maybe you could try something like this :
static void Main(string[] args)
{
int[,] myArr2D;
myArr2D = new int[3, 3];
myArr2D[0, 0] = 10;
myArr2D[0, 1] = 11;
myArr2D[0, 2] = 12;
myArr2D[2, 0] = 13;
myArr2D[1, 2] = 14;
int sum = myArr2D.Cast<int>().Sum();
Console.WriteLine(sum); // 60
Console.ReadKey();
}

Related

how can i sort a matrix's each row from smallest to largest and then find the matrix's peak value?

i need to write a program that takes 1 to 100 integers randomly, then i need to take this program's transpose, then I need to sort this matrix (each row in itself) from smallest to largest.
and finally, i need to find this matrix's peak value. here is what i have written for the program. for now, it creates a random matrix (20x5) and then it takes its transpose. can you help me with finding its peak value and then sort its each row?
PS.: using classes is mandatory!
using System;
namespace my_matrix;
class Program
{
public int[,] Create(int[,] myarray, int Row, int Clm)
{
Random value = new Random();
myarray = new int[Row, Clm];
int i = 0;
int j = 0;
while (i < Row)
{
while (j < Clm)
{
myarray[i, j] = value.Next(1, 100);
j++;
}
i++;
j = 0;
}
return myarray;
}
public int[,] Print(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====ARRAY=====");
for (int a = 0; a < Row; a++)
{
for (int b = 0; b < Clm; b++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
public int[,] Transpose(int[,] myarray, int Row, int Clm)
{
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return myarray;
}
public int[,] Print_Transpose(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====TRANSPOSE=====");
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
static void Main(string[] args)
{
Program x = new Program();
int[,] myarray = new int[20, 5];
int[,] a = x.Create(myarray, 20, 5);
x.Print(a, 20, 5);
x.Print_Transpose(a, 20, 5);
}
}
i don't know how to make a class which sorta each row from smallest to largest and also i dont know how to create a class which finds the matrix's peak value.
You can run over the array, keeping the maxNum:
public int getMax(int[,] fromArray)
{
int maxNum = 0;
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
if (maxNum < fromArray[a,b])
{
maxNum = fromArray[a, b];
}
}
}
return maxNum;
}
Call the function like:
Console.Write("Max number = {0:D}", x.getMax (a));
If you want a sort method, you can place all values in a List, sort them and convert back to array.
public int[] SortArray(int[,] fromArray)
{
List<int> newList = new List<int>(fromArray.Length);
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
newList.Add (fromArray[a, b]);
}
}
newList.Sort();
return newList.ToArray<int>();
}

How to write recursive function for nested loops in C#

How can I write recursive function for this for loops I am making sum of this array elements.
int[,,,] exampleArray = new int[1,2,3,4];
int sum = 0;
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 4; l++)
{
sum += exampleArray[i, j, k, l];
}
}
}
}
Console.WriteLine(sum);
it is actually quite simple, just need a way to represent all 4 indexes as single variable:
static int recursiveSum(int[,,,] a, int index = 0)
{
int ti = index;
int l = ti % a.GetLength(3); ti /= a.GetLength(3);
int k = ti % a.GetLength(2); ti /= a.GetLength(2);
int j = ti % a.GetLength(1); ti /= a.GetLength(1);
int i = ti % a.GetLength(0); ti /= a.GetLength(0);
if (ti > 0) {
return 0;
}
return a[i, j, k, l] + recursiveSum(a, index + 1);
}
static void Main(string[] args)
{
int[,,,] exampleArray = new int[1, 2, 3, 4];
int sum = recursiveSum(exampleArray);
Console.WriteLine(sum);
}

Selection-sort algorithm sorting wrong

Okay I'm having a problem with the selection sort algorithm. It'll sort ints just fine but when I try to use it for doubles it starts to sort randomly.
here's my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sorter.ListSort;
using System.Collections;
namespace ConsoleApp20
{
class Program
{
static void Main(string[] args)
{
var x = new List<double>();
x.Add(23.1);
x.Add(1.5);
x.Add(3);
x.Add(15.23);
x.Add(101.2);
x.Add(23.35);
var sorted = selectionSort(x);
foreach (double s in sorted)
Console.WriteLine(s);
Console.ReadLine();
}
public static List<double> selectionSort(List<double> data)
{
int count = data.Count;
// Console.WriteLine(count);
for (int i = 0; i < count - 1; i++)
{
int min = i;
for (int j = i + 1; j < count; j++)
{
if (data[j] < data[min])
min = j;
double temp = data[min];
data[min] = data[i];
data[i] = temp;
}
}
return data;
}
}
}
Now this is what the algorithm is returning
As we can see 3 is NOT bigger than 15.23, what's going on?
Like MoreON already mentioned in the comments, you should swap the elements after you've found the min value.
So it should look like this
public static List<double> selectionSort(List<double> data)
{
int count = data.Count;
// Console.WriteLine(count);
for (int i = 0; i < count - 1; i++)
{
int min = i;
for (int j = i + 1; j < count; j++)
{
if (data[j] < data[min])
min = j;
}
double temp = data[min];
data[min] = data[i];
data[i] = temp;
}
return data;
}
But if you don't want to reinvent the wheel, you could also use:
var sorted = x.OrderBy(o => o).ToList();
You need to change place for int min
for (int i = 0; i < count - 1; i++)
{
for (int j = i + 1; j < count; j++)
{
int min = i;
if (data[j] < data[min])
min = j;
double temp = data[min];
data[min] = data[i];
data[i] = temp;
}
}
Add a new method called swap and use the following selection sort code.
void swap(int *a,int*b){
int temp=*a;
*a=*b;
*b=temp;
}
void selectionSort(int arr[],int n){
int min_index;
for(int i=0;i<n-1;i++)
{
min_index=i;
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[min_index])
min_index=j;
}
swap(&arr[min_index],&arr[i]);
}
}

diagonal difference OutOfRange Exception C#

I have to write a program that finds the difference between the sums of square matrix diagonals for homework, but my code throws IndexOutOFRange exception and I have no idea how to fix it.
Source code below:
//input 3 11 2 4 4 5 6 10 8 -12 //desired output: 15
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class diagonalDifference
{
static void Main()
{
int N = Convert.ToInt16(Console.ReadLine());
int[,] arr = new int[N, N];
string str = string.Empty;
for (int i = 0; i < N; ++i)
{
string[] strArr = Console.ReadLine().Split(' ');
for (int j = 0; j < strArr.Length; ++j)
{
arr[i, j] = Convert.ToInt16(strArr[j]);
}
}
int left = 0, right = N - 1, ldTotal = 0, rdTotal = 0;
while (left <= right)
{
ldTotal += arr[left, left];
rdTotal += arr[left++, right];
}
Console.WriteLine(Math.Abs(ldTotal - rdTotal));
}
}
class diagonalDifference
{
static void Main()
{
int N = Convert.ToInt16(Console.ReadLine());
int[,] arr = new int[N, N];
string str = string.Empty;
for (int i = 0; i < N; ++i)
{
string[] strArr = Console.ReadLine().Split(' ');
for (int j = 0; j < strArr.Length; ++j)
{
arr[i, j] = Convert.ToInt16(strArr[j]);
}
}
int left = 0, right = N - 1, ldTotal = 0, rdTotal = 0;
while (left <= (N-1))
{
ldTotal += arr[left, left];
rdTotal += arr[left, right];
Left++;
Right--;
}
Console.WriteLine(Math.Abs(ldTotal - rdTotal));
}
}
class Result
{
/*
* Complete the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*/
public static int diagonalDifference(List<List<int>> arr)
{
int l=arr.Count;
int d1=0;
int d2=0;
for(int i=0;i<l;i++)
{
d1=d1+arr[i][i];
d2=d2+arr[i][l-1-i];
}
return (Math.Abs(d1-d2));
}
}

Count No Of 1's Colony From [1,0] 2D Array Using C#

I have a 2D array of integers which stores only values [1,0] as shown below.
int[,] INPUT = new int[10, 10] {
{1,1,0,0,0,1,1,1,0,0},
{1,0,0,0,1,0,0,0,1,0},
{0,0,0,1,1,0,0,1,0,1},
{1,1,0,0,0,0,0,1,1,0},
{0,1,0,0,0,1,0,1,1,0},
{0,0,0,0,1,0,1,0,0,0},
{1,0,0,1,0,0,1,1,1,0},
{0,1,0,0,1,1,0,0,1,1},
{0,1,1,1,0,1,0,1,1,0},
{0,0,0,0,0,1,1,0,0,0},
};
I need to identify a Colony count for the input image, where a Colony is defined as a contiguous sequence of 1s (Like in this array, there are 3 colony of 1's). Connection between 1s can be either adjacent or on the diagonal.
I am required to use recursion for this.
class Program
{
public static int count;
public static int colony;
public static int[,] INPUT;
public static int rows = 10;
public static int cols = 10;
static void Main(string[] args)
{
int[,] INPUT = new int[10, 10] {
{1,1,0,0,0,1,1,1,0,0},
{1,0,0,0,1,0,0,0,1,0},
{0,0,0,1,1,0,0,1,0,1},
{1,1,0,0,0,0,0,1,1,0},
{0,1,0,0,0,1,0,1,1,0},
{0,0,0,0,1,0,1,0,0,0},
{1,0,0,1,0,0,1,1,1,0},
{0,1,0,0,1,1,0,0,1,1},
{0,1,1,1,0,1,0,1,1,0},
{0,0,0,0,0,1,1,0,0,0},
};
// Showing All Values From Upper 2D array
Console.WriteLine("Input File Contain: \n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write(INPUT[i, j]);
}
Console.WriteLine();
}
// Getting Total 1's Count Only
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (INPUT[i, j] == 1)
{
count = count + 1;
}
}
Console.WriteLine();
}
// Getting Total 1's Colony Only
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (INPUT[i, j] == 1)
{
INPUT[i, j] = 0;
colony = GetColony(i, j);
}
}
}
Console.WriteLine("Counts Of 1 Are: " + count);
Console.WriteLine("Counts Of 1's Colony Are: " + colony );
}
static public int GetColony(int i, int j)
{
if ((i < rows) && (j < cols))
{
if ((INPUT[i - 1, j] == 1) || (INPUT[i + 1, j] == 1) || (INPUT[i, j - 1] == 1) || (INPUT[i, j + 1] == 1))
{
INPUT[i, j] = 0;
return GetColony(i, j);
}
else
{
return 1;
}
}
else
{
return 1;
}
}
}

Categories