Join two 1D Arrays (A[] and B[]) into one 2D array (C[,]) - 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;
}

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);
}

C# Changing values between 2 arrays

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);

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;
}
}

Last number in an array becomes first

I know that's easy, but I don't understand how I should do it.
1 23 29 18 43 20 5
to
5 1 23 29 18 43 20
I think we should use for-loop:
for (int i = 0; i < numbers.Count - 1; i++)
{
}
but I don't know what to do in it. Something like numbers[i] = numbers[i - 1] but it isn't working. I think there are some if checks which I miss.
The most straightforward way that comes to mind is a reverse loop.
int[] numbers = { 1, 23, 29, 18, 43, 20, 5};
int lastVal = numbers[numbers.Length - 1];
for (int i = numbers.Length -1; i > 0; i--)
numbers[i] = numbers[i-1];
numbers[0] = lastVal;
Just looping from the end (after saving the last value) and moving "up" the values, finally replacing the first value with the last
Here's a oneliner:
var numbers = new[] {1, 23, 29, 18, 43, 20, 5};
numbers = new[] {numbers.Last()}.Concat(numbers.Take(numbers.Length - 1)).ToArray();
This creates a new array containing the last element, then concatenates it with the original array excluding the last element.
What you want to do is make another array of the same size as the original one, then assign the last element and loop through the array up to the previous to last element.
Something like this:
int[] original = {1, 23, 29, 18, 43, 20, 5};
int[] altered = new int[original.length];
altered[0] = original[original.length - 1];
for (int i = 1; i < original.length - 1; i++)
{
altered[i] = original[i - 1];
}
You can perform a left rotation to the table by six positions on your case and create the requested new table
int[] myArray = new int[] { 1, 23, 29, 18, 43, 20, 5 };
var newArray = LeftRotationByD(myArray, 6);
and your function for the rotation would be:
private static int[] LeftRotationByD(int[] a, int k)
{
int[] b = new int[a.Length];
int index;
int length = a.Length;
int place;
for (int i = 0; i < length; i++)
{
index = i - k;
place = length + index;
if (index >= 0) b[index] = a[i];
else b[place] = a[i];
}
return b;
}
You can use this method to shift right:
void ShiftRight(int[] array, int count)
{
var clone = (int[])array.Clone();
for (var i = 0; i < array.Length; i++)
array[(i + count) % array.Length] = clone[i];
}
And use it this way:
var a = new int[] { 1, 2, 3, 4 };
ShiftRight(a, 1);

Get the value of a specific array number in relation to a given value

I am trying to determine what the neighbour bets would be for a given number on a roulette wheel.
At the moment I pass a pocket number to a function and below is my code. "pocket_number()[0]" is the value of the number I want to determine the neighbours of.
int[] neightbourbets = neighbourbets(pocket_number()[0]);
neighbourbets() is as follows (this outputs an array of element numbers so elsewhere in my program I can extract them from the same array structure). At the moment I have a crude way of determining the the neighbour bets and getting the function to state which numbers are 6 numbers either side of it.
Is there a better way to do this? I've found one of the problems (that I've overcome with the below) is if I want to know the neighbours for "0" for example which means the code needs to get the numbers from the end of the array.
public int[] neighbourbets(int x)
{
int[] pocket_array = new[] {0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26};
int predictednum = Array.IndexOf(pocket_array,x); //element number of pocket_array for chosen number
int[] neighbourbets = new[] {0,0,0,0,0,0,0,0,0,0,0,0,0};
neighbourbets[0] = predictednum;
neighbourbets[1] = predictednum+1;
neighbourbets[2] = predictednum+2;
neighbourbets[3] = predictednum+3;
neighbourbets[4] = predictednum+4;
neighbourbets[5] = predictednum+5;
neighbourbets[6] = predictednum+6;
neighbourbets[7] = predictednum-1;
neighbourbets[8] = predictednum-2;
neighbourbets[9] = predictednum-3;
neighbourbets[10] = predictednum-4;
neighbourbets[11] = predictednum-5;
neighbourbets[12] = predictednum-6;
for (int i = 0; i < neighbourbets.Length; i++)
{
//clockwise neighours
if (neighbourbets[i] == -1) {
neighbourbets[i] = 36;
}
if (neighbourbets[i] == -2) {
neighbourbets[i] = 35;
}
if (neighbourbets[i] == -3) {
neighbourbets[i] = 34;
}
if (neighbourbets[i] == -4) {
neighbourbets[i] = 33;
}
if (neighbourbets[i] == -5) {
neighbourbets[i] = 32;
}
if (neighbourbets[i] == -6) {
neighbourbets[i] = 31;
}
//anticlockwise neighbours
if (neighbourbets[i] == 37) {
neighbourbets[i] = 0;
}
if (neighbourbets[i] == 38) {
neighbourbets[i] = 1;
}
if (neighbourbets[i] == 39) {
neighbourbets[i] = 2;
}
if (neighbourbets[i] == 40) {
neighbourbets[i] = 3;
}
if (neighbourbets[i] == 41) {
neighbourbets[i] = 4;
}
if (neighbourbets[i] == 42) {
neighbourbets[i] = 5;
}
}
return neighbourbets;
}
Any helps or guidence is appreciated! :)
Write a small helper function to wrap around the index:
private int GetPocketIndex( int start, int offset, int count )
{
int pos = ( start + offset ) % count;
if( pos >= 0 )
return pos;
else
return count + pos; // pos is negative so we use +
}
The modulus there will help it wrap around when it goes above the maximum, and the if will do it for the minimum. This could probably be done easier though, but it eludes me at the moment.
Then, if you need that specific order, perhaps something like this:
int[] offsets = new int[] { 0,
1, 2, 3, 4, 5, 6,
-1, -2, -3, -4, -5, -6 };
int[] neighbourbets = new int[offsets.Length];
for( int i = 0; i < offsets.Length; i++ )
neighbourbets[i] = GetPocketIndex( predictednum, offsets[i], pocket_array.Length );
Or, if any order will do:
int count = 6;
int[] neighbourbets = new int[count * 2 + 1];
for( int i = 0; i < neighbourbets.Length; i++ )
neightbourbets[i] = GetPocketIndex( predictednum, i - count, pocket_array.Length );
The following would give you the result with the x in the middle of the result array and the neighbours to the left and right of it:
public static int[] neighbourbets2(int x, int neighborCount)
{
int[] pocket_array = new[] { 0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26 };
int predictednum = Array.IndexOf(pocket_array, x);
// Initialize the result array. Its size is double the neighbour count + 1 for x
int[] result = new int[neighborCount * 2 + 1];
// Calc the start index. We begin at the most left item.
int startAt = predictednum - neighborCount;
// i - position in the result array
// j - position in the pocket_array
for (int i = 0, j = startAt; i < result.Length; i++, j++)
{
// Adjust j if it's less then 0 to wrap around the array.
result[i] = pocket_array[j < 0 ? j + pocket_array.Length : j];
// If we are at the end then start from the beginning.
if (j == pocket_array.Length)
{
j = 0;
}
}
return result;
}

Categories