C# Changing values between 2 arrays - c#

I'm trying to change values between two arrays, but im not getting get that right.
This is what I've done so far
I cant show the total of the first array and i cant make any swap at the second array
public static void exe4()
{
int[,] matriz1 = new int[,] { { -2, 3, 4, 11, -8 }, { -1, 0, -12, -6, 9 }, { 23, 4, 6, 8, -3 } };
int[,] matriz2 = new int[,] { { 2, 3, 8 }, { -2, -4, -5 }, { 0, 8, -14 }, { 3, 5, 6 }, { -9, -8, -1 } };
int troca1 = 0;
int troca2 = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
troca1 = matriz1[i, j];
matriz1[1, 0] = matriz2[0, 2];
matriz1[1, 1] = matriz2[1, 2];
matriz1[1, 4] = matriz2[4, 1];
}
Console.WriteLine();
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
troca2 = matriz2[i, j];
matriz2[0, 2] = matriz1[1, 0];
matriz2[1, 2] = matriz1[1, 1];
matriz2[4, 2] = matriz1[1, 4];
}
Console.WriteLine();
}
Console.WriteLine("\nApós a troca dos valores:\n");
Console.WriteLine("Matriz1:\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("{0}\t", matriz1[i, j]);
}
Console.WriteLine();
}
Console.WriteLine("\nMatriz2:\n");
Console.WriteLine();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("{0}\t", matriz2[i, j]);
}
Console.WriteLine();
}
That's how it's supposed to be:

Analyzing your solution
It sounds like you're only interested in swapping very few and specific values in those matrices, so for-loops seem unnecessary as you already know the positions in the matrices you want to swap.
Apart from that I noticed that your for-loops only goes from 0 to 2 (for (int i = 0; i < 3; i++)) but your matrices have a length of 4 in one dimension, so the loops never reach the ends.
An alternative solution
If you just want to swap those specific values, you could do it like this:
int[,] matriz1 = new int[,]
{
{ -2, 3, 4, 11, -8 },
{ -1, 0, -12, -6, 9 },
{ 23, 4, 6, 8, -3 }
};
int[,] matriz2 = new int[,]
{
{ 2, 3, 8 },
{ -2, -4, -5 },
{ 0, 8, -14 },
{ 3, 5, 6 },
{ -9, -8, -1 }
};
int temporary;
// Swap A[1,0] with B[0,2]
temporary = matriz1[1,0];
matriz1[1,0] = matriz2[0,2];
matriz2[0,2] = temporary;
// Swap A[1,1] with B[1,2]
temporary = matriz1[1,0];
matriz1[1,1] = matriz2[1,2];
matriz2[1,2] = temporary;
// Swap A[1,4] with B[4,2]
temporary = matriz1[1,0];
matriz1[1,4] = matriz2[4,2];
matriz2[4,2] = temporary;
... or with a little helper function:
void Swap(int[,] matrixA, int row1, int col1, int[,] matrixB, int row2, int col2)
{
var temp = matrixA[row1, col1];
matrixA[row1, col1] = matrixB[row2, col2];
matrixB[row2, col2] = temp;
}
// ...
Swap(matriz1, 1, 0, matriz2, 0, 2);
Swap(matriz1, 1, 1, matriz2, 1, 2);
Swap(matriz1, 1, 4, matriz2, 4, 2);

Related

How to add the current iteration's value to the previous iteration's value in a loop C#

I can find a Java version for my question, but not C#. My current attempt goes crazy when attempting to add them. I feel like there is a simple fix, but I'm struggling to think of it.
// See https://aka.ms/new-console-template for more information
int[] input = { 28, 2, 3, -3, -2, 1, 2, 35, -1, 0, 0, -1 };
for (int i = 0; i < input.Length; i++)
{
int x = input[i];
int y = input[i++];
int output = x + y;
Console.WriteLine(output);
}
If I understand your task answer is (updated):
var sum = 0;
var input = new int[] { 28, 2, 3, -3, -2, 1, 2, 35, -1, 0, 0, -1 };
for (var i = 0; i < input.Length - 1; i++)
{
sum += input[i];
Console.WriteLine(sum);
}
This is the correct code :
int[] input = { 28, 2, 3, -3, -2, 1, 2, 35, -1, 0, 0, -1 };
for (int i = 0; i < input.Length - 1; i++)
{
int x = input[i];
int y = input[i + 1];
int output = x + y;
Console.WriteLine(output);
}

How to return an array fibonaci numbers in C #?

I want to make a function that takes an array of integers as input and print an array of int as Fibonaci series like: third element= second element + first element.
Here is my code so far:
static void Result(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] < 0)
Console.WriteLine("arr[i]", arr[i], " number to get must be greater or equal than 0");
var n = arr[i] + 1;
var a = new int[n];
arr[0] = 0;
if (arr[i] == 0)
{
a[1] = 1;
}
for ( i = 2; i < n; i++)
{
a[i] = a[i - 2] + a[i - 1];
}
}
}
public static void Main()
{
int[] arr = {7, 8, 3, 9, 11,16,14,91, };
Result(arr);
}
if input is : 1 ,3 ,4 ,6, 7 ,8 10, 11, 15 ,25 output should be: 1, 3, 4, 7, 11 so 1+3=4, 4+3=7 and so on.
I took a look at your code and you were very close.
The biggest issue was you were starting at i = 0 which would cause errors if you attempted to access arr[-1] and arr[-2].
We can solve that by starting with i = 2.
For example:
static int[] Result(int[] arr)
{
int[] result = arr;
for (int i = 2; i < arr.Length; i++)
{
result[i] = result[i-1] + result[i-2];
}
return result;
}
int[] arr = { 1 ,3 ,4 ,6, 7 ,8, 10, 11, 15 ,25 };
arr = Result(arr);
Console.WriteLine(string.Join(", ",arr));
// outputs: 1, 3, 4, 7, 11, 18, 29, 47, 76, 123
Another side note is that unless you're passing the int[] arr as a reference you will need to return a new int[] as the result since Result()'s changes to arr are not reflected on the array.

Square with Maximum Sum

I am learning C#, and I am doing Multidimensional Arrays at the moment. I want to write a program that reads a matrix and then finds the biggest sum of 2x2 submatrix and prints it.
int[] dimensions = Console.ReadLine()
.Split(", ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int rows = dimensions[0];
int columns = dimensions[1];
int[,] matrix = new int[rows,columns];
for (int i = 0; i < rows; i++)
{
int[] numbers = Console.ReadLine()
.Split(", ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
for (int j = 0; j < columns; j++)
{
matrix[i, j] = numbers[j];
}
}
int maxSum = int.MinValue;
int selectedRow = -1;
int selectedCol = -1;
for (int row = 0; row < matrix.GetLength(0) - 1; row++)
{
for (int col = 0; col < matrix.GetLength(1) - 1; col++)
{
int currentSum = matrix[row, col] + matrix[row, col + 1] + matrix[row + 1, col] + matrix[row + 1, col + 1];
if (currentSum > maxSum)
{
maxSum = currentSum;
selectedRow = row;
selectedCol = col;
}
}
}
Console.WriteLine($"{matrix[selectedRow, selectedCol]} {matrix[selectedRow, selectedCol + 1]}");
Console.WriteLine($"{matrix[selectedRow + 1, selectedCol]} {matrix[selectedRow + 1, selectedCol + 1]}");
Console.WriteLine(maxSum);
So, I read the matrix, but I am not sure how to start finding the submatrices and compare their sums. I would be very grateful if you could give me some hints.
You need to check values only current, under positions of your i and current, right positions of your j.
I mean it will check like this:
[7,1] [1,3] [3,3]
[1,3] [3,9] [9,8]
And so on.
After every compare, calculate sum of this 2x2 matrix and save it to dictionary.
For return, you just need to find the max value of key and get value of it key.
public class MatrixTest
{
public static IEnumerable<object[]> TestData =>
new List<object[]>
{
new object[]
{
new int[,]
{
{7, 1, 3, 3, 2, 1},
{1, 3, 9, 8, 5, 6},
{4, 6, 7, 9, 1, 0}
},
new int[,]
{
{9, 8},
{7, 9}
},
33
},
new object[]
{
new int[,]
{
{10, 11, 12, 13},
{14, 15, 16, 17}
},
new int[,]
{
{12, 13},
{16, 17}
},
58
}
};
[Theory]
[MemberData(nameof(TestData))]
public void Test(int[,] input, int[,] expectedArray, int expectedSum)
{
MatrixHandler m = new MatrixHandler();
var resp = m.GetMax2x2Matrix(input);
resp.Item1.Should().Be(expectedSum);
resp.Item2.Should().BeEquivalentTo(expectedArray);
}
}
public class MatrixHandler
{
public (int, int[,]) GetMax2x2Matrix(int[,] source)
{
var sumsPlusTempArrays = new Dictionary<int, int[,]>();
int[,] temp;
int sum = 0;
for (int i = 0, n0 = source.GetLength(0) - 1; i <= n0; i++)
{
for (int j = 0, n1 = source.GetLength(1) - 1; j <= n1; j++)
{
if (i + 1 <= n0 && j + 1 <= n1)
{
temp = new int[2,2];
temp[0, 0] = source[i, j];
temp[0, 1] = source[i, j + 1];
temp[1, 0] = source[i + 1, j];
temp[1, 1] = source[i + 1, j + 1];
sum = CalculateSum(temp);
sumsPlusTempArrays.TryAdd(sum, temp);
}
}
}
var key = sumsPlusTempArrays.Select(x => x.Key).Max();
var value = sumsPlusTempArrays[key];
return (key, value);
}
private int CalculateSum(int[,] source)
{
int sum = 0;
for (int i = 0, n0 = source.GetLength(0); i < n0; i++)
{
for (int j = 0, n1 = source.GetLength(1); j < n1; j++)
{
sum += source[i, j];
}
}
return sum;
}
}

Join two 1D Arrays (A[] and B[]) into one 2D array (C[,])

I have two 1D arrays :
double A = new double[7] {4, 2, 54, 16, 9, 55, 27}
and
double B = new double[7] {8, 88, 21, 12, 8, 30, 11}
how can i join those array become one 2D array C[2,6], that contain both 1D array above?
probably like this :
double C = new double[2,7] {{4, 2, 54, 16, 9, 55, 27} , {8, 88, 21, 12, 8, 30, 11}};
I tried this code but, only array A printed.
public static double[,] _matrix_byRow(double[] Mat1, double[] Mat2)
{
int i, j, y;
double[,] newMat = new double[2, 7];
for (i = 0; i < 2; i++)
{
for (j = 0; j < 7; j++)
{
newMat[i, j] = Mat1[j];
}
}
for (i = 0; i < 2; i++)
{
for (y = 0; y < 7; y++)
{
newMat[i, y] = Mat2[y];
}
}
return newMat;
}
Try this instead:
public static double[,] _matrix_byRow(double[] Mat1, double[] Mat2)
{
double[,] newMat = new double[2, 7];
for (var j = 0; j < 7; j++)
{
newMat[0, j] = Mat1[j];
newMat[1, j] = Mat2[j];
}
return newMat;
}

Apply Dijkstra in a real sparse matrix in C#

I Have this code to get "shortest path" using Dijkstra
but I know a real problem involves sparse matrices (matrix populated primarily with zeros).
Is there a way to improve efficiency in this code?
If so what improvements?¡
The graph is:
using System;
namespace DijkstraAlgorithm
{
/*
* Dijkstra's algorithm, named after its discoverer, Dutch computer scientist Edsger Dijkstra,
* is a greedy algorithm that solves the single-source shortest path problem for a directed graph
* with non negative edge weights. For example, if the vertices (nodes) of the graph represent cities
* and edge weights represent driving distances between pairs of cities connected by a direct road,
* Dijkstra's algorithm can be used to find the shortest route between two cities. Also, this algorithm
* can be used for shortest path to destination in traffic network.
* Pseudocode
function Dijkstra(L[1..n, 1..n]) : array [2..n]
array D[2..n]
set C
C <- {2, 3, 4, 5, 6, …, n}
for i <- 2 to n
D[i] <- L[1,i]
repeat n - 2 times
v <- C // minimum D[v] extract to C
v <- C - {v}
for each w in C do
D[w] <- min(D[w], D[v] + L[v,w])
return D
*/
class Dijkstra
{
private int rank = 0;
private int[,] L;
private int[] C;
public int[] D;
private int trank = 0;
public Dijkstra(int paramRank,int [,]paramArray)
{
L = new int[paramRank, paramRank];
C = new int[paramRank];
D = new int[paramRank];
rank = paramRank;
for (int i = 0; i < rank; i++)
{
for (int j = 0; j < rank; j++) {
L[i, j] = paramArray[i, j];
}
}
for (int i = 0; i < rank; i++)
{
C[i] = i;
}
C[0] = -1;
for (int i = 1; i < rank; i++)
D[i] = L[0, i];
}
public void DijkstraSolving()
{
int minValue = Int32.MaxValue;
int minNode = 0;
for (int i = 0; i < rank; i++)
{
if (C[i] == -1)
continue;
if (D[i] > 0 && D[i] < minValue)
{
minValue = D[i];
minNode = i;
}
}
C[minNode] = -1;
for (int i = 0; i < rank; i++)
{
if (L[minNode, i] < 0)
continue;
if (D[i] < 0) {
D[i] = minValue + L[minNode, i];
continue;
}
if ((D[minNode] + L[minNode, i]) < D[i])
D[i] = minValue+ L[minNode, i];
}
}
public void Run()
{
for (trank = 1; trank <rank; trank++)
{
DijkstraSolving();
Console.WriteLine("iteration" + trank);
for (int i = 0; i < rank; i++)
Console.Write(D[i] + " ");
Console.WriteLine("");
for (int i = 0; i < rank; i++)
Console.Write(C[i] + " ");
Console.WriteLine("");
}
}
static void Main(string[] args)
{
int[,] L ={
{-1, 5, -1, -1, -1, 3, -1, -1},
{ 5, -1, 2, -1, -1, -1, 3, -1},
{-1, 2, -1, 6, -1, -1, -1, 10},
{-1, -1, 6, -1, 3, -1, -1, -1},
{-1, -1, -1, 3, -1, 8, -1, 5},
{ 3, -1, -1, -1, 8, -1, 7, -1},
{-1, 3, -1, -1, -1, 7, -1, 2},
{-1, -1, 10, -1, 5, -1, 2, -1}
};
Dijkstra clss = new Dijkstra((int)Math.Sqrt(L.Length),L);
clss.Run();
Console.WriteLine("Solution is");
foreach (int i in clss.D)
{
Console.WriteLine(i);
}
Console.WriteLine("Press Enter for exit.");
Console.Read();
}
}
}
In the code the matrix is an easy one, but if I have an sparse one...??
One possible improvement would be to stop using an array for the graph, and instead use a SparseMatrix class, which will result in better iteration over the matrix's entries.
You can probably find several libraries that provide SparseMatrix implementations:
http://www.extremeoptimization.com/QuickStart/SparseMatricesCS.aspx
http://sparsematrix.codeplex.com/
http://metanumerics.codeplex.com/
Another improvement might be to use multi-threads, but since each iteration of the Dijkstra algorithm is based on the previous iteration, that would have to be done extremely carefully.

Categories