how to multiply two arrays with different sizes in C# - c#

I am trying to do my homework but what I am trying does not work.
the assignment is to basically multiply 2 arrays of different sizes together( and put all three into a message box so if you could help me with as well that would be great)
the problem is that I am getting "overflow" amounts of values, there should only be 10 but I am getting like 28
the code I currently have is
double[] array1 = new Double[10] { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
double[] array2 = new Double[5] { 0, 1, 2, 3, 4 };
double[] array3 = new double[10];
int hold = 1;
int counter = 0;
foreach (int c in array1)
{
foreach(int k in array2)
{
if (counter <= k)
{
array3[c] = (array1[c] * array2[c]);//edit3: array2 was wirtten with c when copied th outcome different but still not rigth with k
}
else
{
array3[c] = (array1[c] * hold);
}
}
foreach (int j in array3)
{
Console.WriteLine(array3[c]);
}
}
the out come looks like
0
0
0
0
0
0
0
0
0
0
6
6
6
6
6
6
6
6
6
6
12
12
12
12
12
12
12
12
12
12
20
20
20
20
20
20
20
20
20
20
it should look like
0
2
6
12
20
6
7
8
9
10
I have check stackoverflow all ready, so please just help not link me to another question, or if you do put a comment with it saying what I need to look at.
edit: the array3 have j just gives ten 0
edit2: the debugger is telling me what I already know I am making too many
values, the question is how to fix this, and only make 10 values

There are so many mistakes in your code. You need only one loop:
double[] array1 = new Double[10] { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
double[] array2 = new Double[5] { 0, 1, 2, 3, 4 };
double[] array3 = new double[10];
int hold = 1;
int counter = 0;
for (int i = 0; i < array1.Length; i++)
{
if (i < array2.Length)
{
array3[i] = array1[i] * array2[i];
}
else
{
array3[i] = (array1[i] * hold);
}
}
foreach (int j in array3)
{
Console.WriteLine(j);
}

Since you have to write something that can do a multiplication of two arrays with (possible) different lengths, you could start with determining the longest array from the shortest one, and then iterate the shortest and concatenate the leftover to the resulting array (since that stays 1 in your example), you could do this for example through:
static IEnumerable<double> Multiply( double[] left, double[] right ) {
if ( left == null ) {
throw new ArgumentNullException( nameof(left));
}
if ( right == null ){
throw new ArgumentNullException( nameof(right));
}
var largest = left.Length > right.Length ? left : right;
var smallest = left.Length > right.Length ? right : left;
return smallest.Select( ( value, idx ) => value * largest[idx] )
.Concat( largest.Skip( largest.Length - smallest.Length ) );
}
This would give you an IEnumerable<double> result back as part of the function, and you could then use it in this way:
public static void Main( string[] args ) {
var array1 = new double[10] { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var array2 = new double[5] { 0, 1, 2, 3, 4 };
var multiplication = Multiply( array1, array2 );
foreach ( var item in multiplication ) {
Console.WriteLine( item );
}
Console.ReadLine();
}
Now, when looking into your original code, lets check some parts that where problematic in your version
double[] array3 = new double[10];
Declaring the array3 to a fixed size makes your code quite vulnerable, namely if array2 or array1 changes in length, the result size would also change? In my example, in is more dynamic, as it depends on the largest array of the two.
int counter = 0;
// ...
if (counter <= k)
you define a counter to be null, but it is never incremented in the shared code, because of that your code should have crashed when hitting array2[c] where c has a value larger than the largest index in array2, which kinda explains why it only goes till 20
foreach (int c in array1)
{
foreach(int k in array2)
foreach will set the variable c and k respectively to the next value of array1 and array2 upon each iteration, but in your code you are using it more as an indexer, so you should have used the. Furthermore, you are iterating a double[] and define the variable as int, that could give very confusing results, so you would have been easier of using
for (var c = 0; c < array1.Length; c++)
{
for (var k = 0; k < array2.Length; k++)
{
And now you can use them as indexes.
And the last one is that you where looping array3 using foreach inside the first foreach loop (thus repeating your iteration), while using c as an index for your array while it should have been j variable.
Now if you fix all these points you get something like Melchia's answer, but that is also a fragile one, for example, if you would switch array1 and array2 your code won't give the expected output anymore

Related

Stretch or resample 1D array

This question might be something really simple and I might be missing something really basic, but how do you interpolate a 1D array in C#?
Lets say I have this array of n elements
int[] array1 = new int[] { 1, 3, 5, 7, 1 };
How to stretch or compress the array so that it has n values and interpolates the values, just like when you resize an image, thats it, not chopping or adding zeros or empty values to the array.
For example if I want to convert the array so it has n = 4 elements, get this
array1
>>[2, 4, 6, 4]
what I'm trying to do is the same as the resample function from matlab does
https://mathworks.com/help/signal/ref/resample.html
I suggest this solution for the case that the new array is shorter than the old one:
int[] array1 = new int[] { 1, 3, 5, 7, 9 };
int[] array2 = new int[4];
for (var i = 0; i < array2.Length; i++)
{
var doubleIndex1 = (double)i * array1.Length / array2.Length;
var index1 = (int)Math.Floor(doubleIndex1);
var rel = doubleIndex1 - index1;
array2[i] = (int)Math.Round((1.0 - rel) * array1[index1] + rel * array1[index1 + 1]);
}

how to multiply each element in an array with a loop c#

im trying to multiply each element in three different arrays by 2 with a loop but im having trouble. im really new at this so please excuse any obvious mistakes lol im not even sure ive im using the right kind of loop but heres what i have so far:
int[] firstArray = new int[] { 1, 2, 5, 6, 9 };
int[] secondArray = new int[] { 12, 3, 8, 20, 7 };
int[] thirdArray = new int[] { 2, 4, 6, 8, 10, 12 };
foreach(new int [5] in firstArray)
{
int newArray1= firstArray.Length * 2;
Console.WriteLine(newArray1);
}
i want it to print out the first new array as "2, 4, 10, 12, 18" in the console but when i run it, i get the error type and identifier are both required in a foreach statement.
any help would be greatly appreciated!
Do this with Linq
int[] resultFirstArray = firstArray.Select(r=> r * 2).ToArray();
int[] resultSecondArray = secondArray.Select(r=> r * 2).ToArray();
int[] resultThirdArray = thirdArray.Select(r=> r * 2).ToArray();
Or you can use Array.ConvertAll
Array.ConvertAll converts an entire array. It converts all elements in one array to another type.
var resultFirstArray = Array.ConvertAll(firstArray, x => 2 * x);
var resultSecondArray = Array.ConvertAll(secondArray, x => 2 * x);
var resultThirdArray = Array.ConvertAll(thirdArray, x => 2 * x);
If you just want to show the doubled values:
foreach(int value in firstArray)
{
Console.WriteLine(2 * value);
}
If you want to double the values in the array, then:
for(int i = 0 ; i < firstArray.Length ; i++)
{
firstArray[i] *= 2;
}
Then perhaps to show those values:
foreach(int value in firstArray)
{
Console.WriteLine(value);
}
If you want to create a new array with the values doubled:
var doubledArray = Array.ConvertAll(firstArray, x => 2 * x);
And to output those values:
foreach(int value in doubledArray)
{
Console.WriteLine(value);
}

Every combination of "1 item from each of N collections"

I have a nested List<List<int>> data structure, and I would like to iterate over every possible combination of the inmost int elements, such as that in each combination exactly one value from each inner List<int> is used. For example, please consider the following nested list:
var listOfLists = new List<List<int>>()
{
new List<int>() { 1, 2, 3, 4, 9 },
new List<int>() { 0, 3, 4, 5 },
new List<int>() { 1, 6 }
};
The first few combinations would yield:
1 0 1 // Indices: 0 0 0
1 0 6 // Indices: 0 0 1
1 3 1 // Indices: 0 1 0
1 3 6 // Indices: 0 1 1
2 0 1 // Indices: 1 0 0
2 0 6 // Indices: 1 0 1
2 3 1 // Indices: 1 1 0
...
How could I accomplish this?
My initial approach was to make permutations of indices, but the lengths of inner List<int> lists are not necessarily equal. Another approach I can think of is multiplying the length of each inner List<int>, then using the modulo and division operators combined with Math.Floor to determine indices, but I'm not sure how exactly this could be implemented when N collections are present.
I've answered a several similar questions, which all basically use a variation of one and the same algorithm. Here is the modified version of the Looking at each combination in jagged array:
public static class Algorithms
{
public static IEnumerable<T[]> GetCombinations<T>(this IReadOnlyList<IReadOnlyList<T>> input)
{
var result = new T[input.Count];
var indices = new int[result.Length];
for (int pos = 0, index = 0; ;)
{
for (; pos < result.Length; pos++, index = 0)
{
indices[pos] = index;
result[pos] = input[pos][index];
}
yield return result;
do
{
if (pos == 0) yield break;
index = indices[--pos] + 1;
}
while (index >= input[pos].Count);
}
}
}
Note that in order to not do allocation, the above method yields one and the same array instance. This is perfect if you want just to count or process it with foreach loop or LINQ query without storing the results. For instance:
foreach (var combination in listOfLists.GetCombinations())
{
// do something with the combination
}
If you indeed need to store the results, you can always use ToList:
var allCombinations = listOfLists.GetCombinations().Select(c => c.ToList()).ToList();
How about using LINQ?
var listOfLists = new List<List<int>>()
{
new List<int>() { 1, 2, 3, 4, 9 },
new List<int>() { 0, 3, 4, 5 },
new List<int>() { 1, 6 }
};
var result = from l in listOfLists[0]
from y in listOfLists[1]
from z in listOfLists[2]
select new List<int>()
{
l,
y,
z
};
This will of course only work for this specific list as there are 3 lists in your list of lists.

How to find all instances of mirrored duplicates?

I have been searching for some time now for any answers on how to do this.
What I am trying to do is, take an array of numbers, e.g. {1, 3, 5, 6, 8, 7, 6 ,5, 3, 1} (but it will use user input) and find the duplicates of these numbers that are mirrored and return how many indexes are involved in just one instance of said array.
I know the basics of C# but can't grasp this task. No, this is not homework. This is my own project to further my knowledge.
I am not currently around the code I have for parts of this, but would really appreciate any help/advice anyone could give me.
int[] array = {1, 3, 5, 6, 8, 7, 6 ,5, 3, 1};
//holds left index of mirrored pair, you can easily find the right one
var mirroredIndexes = new List<int>();
var length = array.Length;
for (int i = 0; i < length / 2; i++)
{
if(array[i] == array[length - i - 1])
mirroredIndexes.Add(i);
}
mirroredIndexes.ForEach(Console.WriteLine);
Console.WriteLine ("total of {0} mirrored pairs ({1})",
mirroredIndexes.Count,
string.Join(", ", mirroredIndexes.Select(i => array[i])));
prints next indexes:
0
1
2
3
total of 4 mirrored pairs (1, 3, 5, 6)
I think this is what you are after. This will return a list of matching indices.
Eg. first == last, second == second to last, third == third to last
var matches = new List<Tuple<int, int>>();
var array = new [] { 0, 1, 2, 3, 4, 5, 3, 2, 1, 0 };
if (array.Length % 2 != 0)
throw new Exception("Array must have an even amount of elements");
for (int i = 0; i < array.Length / 2; i++)
{
if (array[i] == array[array.Length - 1 - i])
{
matches.Add(new Tuple<int, int>(i, array.Length - 1 - i));
}
}
var firstMatchingIndex1 = matches[0].Item1;
// This will be 0
var firstMatchingIndex2 = matches[0].Item2;
// This will be 9
You could go further, using a custom class, and capture the actual value that matched (eg. index1 is 1, index2 is 8 and the value was 1.

How to get the difference between 2 int arrays as a percentage

Mathematically we can solve it like Given Amount / Total Amount * 100 to get the percentage difference. But what I need is to compare 2 Integer Arrays (in C# Win App) and get the percentage of the difference.
Like :
1 -----> -2
2 -----> 3
3 -----> 7
4 -----> 456
5 -----> 13
These two columns are 2 Integer Arrays and I should get the difference between them.
How can I get this? A mathematical answer or an algorithm, whatever can be used to solve the problem.
try this
var i1 = Enumerable.Range(0, 10).ToArray();
var i2 = Enumerable.Range(20, 10).ToArray();
var result = i1.Select((n, i) => n * 100 / i2[i]);
What do you mean by difference? you can get the array of differences by:
int[] array = new int[arr1.Length];
for (i = 0; i < array.Length; i++)
{
array[i] = array1[i] - array2[i];
}
How about using LINQ:
Int32[] array1 = new Int32[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Int32[] array2 = new Int32[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
Int32[] array3 = array1.Zip(array2, (a1, a2) => (a1 + a2) / 2).ToArray(); // Put whatever formula you want in there.
EDIT: Daniel and CD are correct. Code has been corrected. Thanks guys.
Thanks to everyone who replied to the question!
I thought about a solution these days but I'm not sure about the result. I have doubts about my work because I'm debugging it but each time with another 2 Arrays which contain more than 48.000 elements.
My solution so far was like :
for(int i=0;i<arr1.length;i++)
{
if(arr1[i] == arr2[i])
count++;
}
double percentage = (float)count / (float)arr1.length * 100;

Categories

Resources