Reputation: 19
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
Upvotes: 0
Views: 1158
Reputation: 7469
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++;
}
}
Upvotes: 0
Reputation: 15683
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.
Upvotes: 0
Reputation: 274835
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]}");
}
}
}
Upvotes: 1