I need to make a loop that multiply each element in an array by all array elements, except itself .
Example ->
[1 3 4]
[1 3 4]
1 3, 1 4, 3 1, 3 4, 4 1, 4 3
I've wrote the following code:
foreach (int first in Array)
foreach (int second in Array)
Console.WriteLine(first + " " + second );
The code that I wrote multiplies every number with itself and the other elements.
any ideas on how to fix this?
Thanks
You should loop through the indices of the array instead of its elements. This way, you can check whether you are dealing with the same element by checking whether the two indices are equal:
var arr = new int[] {1, 3, 4};
var result = new List<string>();
for (int i = 0 ; i < arr.Length ; i++) {
for (int j = 0 ; j < arr.Length ; j++) {
if (i != j) {
result.Add($"{arr[i]} {arr[j]}");
}
}
}
Try nested for loops, with two indexes:
for (int ix1 = 0; ix1 < myArray.Length; ix1++) {
// Numbers before ix1.
for (int ix2 = 0; ix2 < ix1; ix2++) {
Console.WriteLine(myArray[ix1] + " " + myArray[ix2]);
}
// Numbers after ix1
for (int ix2 = ix1 + 1; ix2 < myArray.Length; ix2++) {
Console.WriteLine(myArray[ix1] + " " + myArray[ix2]);
}
}
I am more used to Java than C#, so best check my syntax for Javaisms.
Another approach that you can use:
int[] lst = new int[] { 2, 3, 4 };
int[] multipliedList = new int[lst.Length * (lst.Length - 1)];
int idx = 0;
for (int i = 0; i < lst.Length; i++)
{
int currIdx = 0;
foreach (var item in lst)
{
if (i != currIdx)
{
multipliedList[idx] = lst[i] * item;
idx++;
}
currIdx++;
}
}
Related
I have a 2D Array in C# with user input to fill the Array. I need help to find the sum for every column and row.
var input = Console.ReadLine();
var n = int.Parse(input);
int[,] intArr = new int[n, 3];
for (int i = 0; i < n; i++)
{
input = Console.ReadLine();
var parts = input.Split(' ');
for (int j = 0; j < 3; j++)
{
intArr[i, j] = int.Parse(parts[j]);
}
}
if (n == 1)
{
Console.WriteLine("Sum of column " + Convert.ToString(n) + ": " + (intArr[n - 1, 0] + intArr[n - 1, 1] + intArr[n - 1, 2]));
Console.WriteLine("Row1: " + (intArr[n - 1, 0]));
Console.WriteLine("Row2: " + (intArr[n - 1, 1]));
Console.WriteLine("Row3: " + (intArr[n - 1, 2]));
}
if (n == 2)
{
Console.WriteLine("Sum of column " + Convert.ToString(n - 1) + ": " + (intArr[n - 2, 0] + intArr[n - 2, 1] + intArr[n - 2, 2]));
Console.WriteLine("Sum of column " + Convert.ToString(n) + ": " + (intArr[n - 1, 0] + intArr[n - 1, 1] + intArr[n - 1, 2]));
Console.WriteLine("Row 1: " + (intArr[n - 2, 0] + intArr[n - 1, 0]));
Console.WriteLine("Row 2: " + (intArr[n - 2, 1] + intArr[n - 1, 1]));
Console.WriteLine("Row 3: " + (intArr[n - 1, 2] + intArr[n - 1, 1]));
}
}
User input:
2
1 2 3
4 5 6
The output:
Sum of column 1: 6
Sum of column 2: 15
Row 1: 5
Row 2: 7
Row 3: 11
I want this output for N columns enter by user, but I am stuck!
Thank you!
Not sure, is your problem that you get an undesired result or that you have a model with a fixed number of elements? An array is a fixed size data container, so if you want any number of columns the architecture perhaps is where you want to change away from array.
Anyway, problem 1 is that you let user chose how many rows they want, but now how many column, so presuming there will be 3 conflicts with you data. So you have on array the .getUpperBound() for that which takes a range parameter and this way we can use a dynamic strucure
//From:
for (int i = 0; i < n; i++)
{
input = Console.ReadLine();
var parts = input.Split(' ');
for (int j = 0; j < 3; j++)
{
intArr[i, j] = int.Parse(parts[j]);
}
}
//TO:
var rows = new List<int[]>();
for (int i = 0; i < n; i++)
{
input = Console.ReadLine();
var parts = input.Split(' ');
var listOf = new List<int>();
for (int j = 0; j < parts.GetUpperBound(0); j++)
{
listOf.Add(int.Parse(parts[j]));
}
rows.Add(listOf.ToArray());
}
from https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=net-5.0 You get the aggregation capability
[Fact]
public void SumExerciseTest()
{
/*
The output:
Sum of column 1: 6
Sum of column 2: 15
Row 1: 5
Row 2: 7
Row 3: 11 => 9
*/
var testData = new[] { "1 2 3", "4 5 6" };
var input = "2"; // Console.ReadLine();
var n = int.Parse(input);
var rows = new List<int[]>(n);
for (int i = 0; i < n; i++)
{
input = testData[i];
var parts = input.Split(' ');
var listOf = new List<int>();
for (int j = 0; j <= parts.GetUpperBound(0); j++)
{
listOf.Add(int.Parse(parts[j]));
}
rows.Add(listOf.ToArray());
}
var rowSums = new List<int>(n);
foreach (int[] row in rows)
{
rowSums.Add(row.Aggregate((result, item) => result + item));
}
int maxLength = 0;
var rowLengths = new List<int>(n);
foreach (int[] row in rows)
{
rowLengths.Add(row.Length);
}
maxLength = rowLengths.Max();
int[] columnSums = new int[maxLength];
for (int idx = 0; idx < columnSums.Length; idx++){
foreach (var row in rows)
{
if (row.GetUpperBound(0) >= idx)
{
columnSums[idx] += row[idx];
}
}
}
int counter = 0;
//Outputting:
foreach(var sum in rowSums)
{
counter += 1;
System.Diagnostics.Debug.WriteLine($"Row {counter}: {sum}");
}
counter = 0;
foreach(var sum in columnSums)
{
counter += 1;
System.Diagnostics.Debug.WriteLine($"Column {counter}: {sum}");
}
Well, let's implement (extract) methods for summing arbitrary column and row:
private static int SumColumn(int[,] array, int column) {
if (array == null)
throw new ArgumentNullException(nameof(array));
if (column < 0 || column >= array.GetLength(1))
throw new ArgumentOutOfRangeException(nameof(column));
int result = 0;
for (int r = 0; r < array.GetLength(0); ++r)
result += array[r, column];
return result;
}
private static int SumRow(int[,] array, int row) {
if (array == null)
throw new ArgumentNullException(nameof(array));
if (row < 0 || row >= array.GetLength(0))
throw new ArgumentOutOfRangeException(nameof(row));
int result = 0;
for (int c = 0; c < array.GetLength(1); ++c)
result += array[row, c];
return result;
}
then you can put
for (int c = 0; c < intArr.GetLength(1); ++c)
Console.WriteLine($" Sum of column {c + 1}: {SumColumn(intArr, c)}");
for (int r = 0; r < intArr.GetLength(0); ++r)
Console.WriteLine($" Sum of row {r + 1}: {SumRow(intArr, r)}");
Firstly thank you for taking the time to look at my question.
I have a csv file of letters for which i need to get the last letter of the array and move it to the start while "pushing" the other letters across
E.G.
--Source--
a,b,c,d,[e]
--Rotated--
e,a,b,c,d
for (var i = 0; i < Array.Length - 1; i++)
{
temp = Array[Array.Length];
Array[Array.Length] = Array[Array.Length - 1];
Array[i + 1] = Array[i];
Array[i] = temp;
}
For this I am aware that not all characters would be effected but i cant think of a loop to get all values moved
Use Copy method:
int last = arr[arr.Length - 1];
Array.Copy(arr, 0, arr, 1, arr.Length - 1);
arr[0] = last;
You can shift the numbers to right by using the modulo % operator :
int[] arr = { 1, 2, 3, 4, 5 };
int[] newArr = new int[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
newArr[(i + 1) % newArr.Length] = arr[i];
}
newArr = {5,1,2,3,4}
DEMO HERE
EDIT:
Or you could make a method that shifts the numbers in your initial array without the need for creating a new array. The method rightShiftArray takes two parameters, the initial array arr an the number of shifts (shift) you want to perform:
public void rightShiftArray(ref int[] arr, int shift)
{
for (int i = 0; i < shift; i++)
{
int temp;
for (int j = 0; j < arr.Length - 1; j++)
{
temp = arr[j];
arr[j] = arr[arr.Length - 1];
arr[arr.Length - 1] = temp;
}
}
}
For example:
int[] arr = { 1, 2, 3, 4, 5 };
rightShiftArray(ref arr, 2);
The code above shifts the numbers in the initial array arr twice to the right and gives you the following output:
arr = { 4, 5, 1, 2, 3};
DEMO HERE
if you doesn't want to allocate new array, you can use this code :
newValue = Array[Array.Length-1];
for (var i = 0; i < Array.Length; i++)
{
temp = Array[i];
Array[i] = newValue;
newValue = temp;
}
I am working on an issue where i need to Declare a two - dimensional array named multiplicationTable
that contains 4 elements by 4 elements.Initialize it in
a nested loop to contain elements that equal to the value
that is the product of the two index values for
each element. In a second nested loop, display the values
in the console output, with column elements separated with
commas, and row elements separated with carriage returns. This is what i have so far, for some reason can't wrap my brain around the solution! Any help would be appreciated!.
double[,] multiplicationTable = new double[4, 4];// { {1,2,3,4 }, {5,6,7,8 }, {9,10,11,12 }, {13,14,15,16 } };
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
double d = multiplicationTable[i, j];
if (j < multiplicationTable.GetLength(1) - 1)
{
Console.Write(d + ",");
}
else
{
Console.Write(d);
}
}
Console.Write("\n");
}
Console.ReadKey();
double[,] multiplicationTable = new double[4, 4];
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
multiplicationTable[i, j] = i * j;
double d = multiplicationTable[i, j];
if (j < multiplicationTable.GetLength(1) - 1)
{
Console.Write(d + ",");
}
else
{
Console.Write(d);
}
}
Console.Write("\n");
}
Console.ReadKey();
Why not try to solve this with String.Join method? It is easy to use and will save you a lot of if-else statements. Here it is how it will look like with this method:
double[,] multiplicationTable = new double[4, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
var temp = new string[4];
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
temp[j] = multiplicationTable[i, j].ToString();
}
Console.WriteLine(string.Join(",", temp));
}
Console.ReadKey();
double[,] multiplicationTable = new double[4, 4];
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
var temp = new string[multiplicationTable.GetLength(0)];
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
multiplicationTable[i, j] = i * j;
temp[j] = multiplicationTable[i, j].ToString();
}
Console.WriteLine(string.Join(",", temp));
}
The wished output is a lot of array that looks like this:
public decimal [] array 1 = {1, 1, 0, 0, 0};
public decimal [] array 2 = {0, 1, 1, 0, 0};
public decimal [] array 3 = {0, 0, 1, 1, 0};
public decimal [] array 4 = {0, 0, 0, 1, 1};
The dimension does not fit my problem, because the problem demands a array of 14 elements, but the idear is the same. The question is how do I create this in a smart way. I tried a "for loop" creating array 1, but as the loop carried on it overwrote array 1 with array 2:
class Program
{
public decimal[] array_1 = { 0, 0, 0, 0, 0 };
public void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
if (i == 0)
{
array_1 [i] = 1;
array_1 [i + 1] = 1;
}
else if (i == 1)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
else if (i == 2)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
else if (i == 3)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
else if (i == 4)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
}
}
}
The output of the above is a array with only ones and not four different arrays as firstly wished.
decimal[][] arrays = { array_1, array_2, array_3, array_4 };
for (int a = 0; a < arrays.Length; a++) {
for (int i = 0; i < arrays[a].Length; i++) {
arrays[a][i] = i == a || i == a+1 ? 1 : 0;
}
}
Or, you can create one two-dimensional array:
decimal[,] array = new decimal[4, 5];
for (int row = 0; row < array.GetLength(0); row++) {
for (int column = 0; column < array.GetLength(1); column++) {
array[row, column] = column == row || column == row+1 ? 1 : 0;
}
}
Use multidimensional array:
class Program
{
public decimal[,] arrayObj = new decimal[5, 5];
public void Main(string[] args)
{
for (int i = 0; i < 4; i++)
{
arrayObj[i][i] = 1;
arrayObj[i+1] = 1;
}
}
If you want a collection (say, decimal[][] - jagged array) of arrays, I suggest using Linq:
int n = 4;
decimal[][] arrays = Enumerable.Range(1, n)
.Select(index => Enumerable
.Range(1, n + 1)
.Select(x => (decimal) (x == index || x == index + 1 ? 1 : 0))
.ToArray())
.ToArray();
and then use the collection
decimal array1 = arrays[0];
Test
string report = string.Join(Environment.NewLine, arrays
.Select(array => string.Join(" ", array)));
Outcome:
1 1 0 0 0
0 1 1 0 0
0 0 1 1 0
0 0 0 1 1
If you insist on 2d array:
int n = 4;
decimal[,] arrays = new decimal[n, n + 1];
for (int i = 0; i < arrays.GetLength(0); ++i) {
arrays[i, i] = 1;
arrays[i, i + 1] = 1;
}
I was just asking if there is a simple way of doing this.
i.e. Replacing two consecutive cell with one cell having different value.
For ex: - if my array =[0,3,1,2,3,4], and i want to replace index 0,and 1 with the value 5
to become like this array=[5,1,2,3,4]
Can you guys suggest some simple way for doing this.
i do this code but there is something wrong:
int J = 0;
if (max != 1)
{
for (int iii = 0; iii < output.Length -1; iii++)
{
if ((output[iii] == imax) && (output[iii + 1] == jmax))
{
temp = temp + 1;
output[J] = Convert.ToByte(temp);
J = J + 1;
iii = iii + 1;
}
else
{
output[J] = output[iii];
J = J + 1;
output[J] = output[iii + 1];
}
}
}
because when i want to check the 2 consecutive index ,i want to pass them to the anther 2 index
If you care about performance you want to do as little operations that can harm performance. Try this extension method:
public static int[] ReplaceConsecutiveCells(this int[] array, int startIndex, int replaceWith)
{
int[] targetArray = new int[array.Length - 1];
for (int i = 0; i < array.Length; i++)
{
if (i < startIndex)
{
targetArray[i] = array[i];
}
else if (i == startIndex)
{
targetArray[i] = replaceWith;
}
else if (i == startIndex + 1)
{
// no action
}
else
{
targetArray[i - 1] = array[i];
}
}
return targetArray;
}
Use it like this:
array = array.ReplaceConsecutiveCells(0, 5);
int[] array = new int[] { 0, 3, 1, 2, 3, 4 };
List<int> list = array.ToList();
list.RemoveRange(0,2);
list.Insert(0, 5);
array = list.ToArray();
Yet another variant
int[] array = new int[] { 0, 3, 1, 2, 3, 4 };
Array.Reverse(array);
Array.Resize(ref array, 5);
Array.Reverse(array);
array[0] = 5;
do
{
RNG_NXT =RNG +1;
for (int iii = 0; iii <Nold -1; iii++)
{
if ((output[iii] == imax) && (output[iii + 1] == jmax))
{
output[J] = Convert.ToByte(RNG_NXT);
J = J + 1;
iii = iii + 1;
}
else
{
output[J] = output[iii];
J = J + 1;
}
}
RNG++;
}
while( RNG < RNG_MAX) ;