Wrong number of indices inside []; expected 6 - c#

i have a problem regarding my code. I have tried searching on it, but it only confused me more.
I want to split an array(called Array for simplicity) of size 6 in half. one of the halves will move to another array, called Split1
But it gives me an error when trying to move the numbers using a for loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int[,,,,,] Array = new int[7, 5, 9, 4, 2, 1];
int[] Split1 = new int[3];
for (int i = 0; i <= Array.Length / 2; i++)
{
Split1[i] = Array[i]; //This is where i get my error
}
}
}
}
If you could point me to the right direction, I would be grateful

This
int[,,,,,] Array = new int[7, 5, 9, 4, 2, 1];
is not an array with 6 elements, this is a 6-dimentional array.
You should define your one dimensional array like this:
int[] Array = new int[] {7, 5, 9, 4, 2, 1};
Additionally, your loop condition is incorrect, you should use < to check upper bound instead of <=:
for (int i = 0; i < Array.Length / 2; i++)

Initialize your array as
int[] Array = new int[6]{7, 5, 9, 4, 2, 1};
What you did before was attempt to create array with 6 dimensions and address one of its cell.
As others pointed out, in loop you want to count from 0 to 2, therefore change <= for <.

You have wrong index with loop
for (int i = 0; i < Array.Length / 2; i++)
{
Split1[i] = Array[i]; //This is where i get my error
}

The way you declare the Array is incorrect, see the following code.
int[] Array = new int[] {7, 5, 9, 4, 2, 1}; // initialization will set the size automatically
int[] Split1 = new int[3];
for (int i = 0; i < 3; i++)
{
Split1[i] = Array[i];
}

1.) You can initialize 1D arrays in many ways :
string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
In your case :
int[] Array = new int[] {7, 5, 9, 4, 2, 1};
2.) Array.Length won't return number of elements inside array. You need Array.Count(). Refer this link for more detail.
for (int i = 0; i <= Array.Count() / 2; i++)
{
Split1[i] = Array[i]; //This is where i get my error
}

Related

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.

C# Multiply Each row of array by set of factors

I have a multidimensional array and I want to multiply each row of it by a single dimensional array containing factors to create a new multidimensional array. However, the number of rows in the multidimensional array will vary from one run to the next, so I'll need a way to loop the multiplication through each row of the multidimensional array until the last row is reached.
Here is a simple example, I have multidimensional array:
{ { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12} }
and I want to multiply each row by:
{0.5, 0.4, 0, 0.8}
to get:
{ { 1*0.5, 2*0.4, 3*0, 4*0.8}, { 5*0.5, 6*0.4, 7*0, 8*0.8}, { 9*0.5, 10*0.4, 11*0, 12*0.8} }
I've tried to use .Length within a for loop using the example code.
double [] factors = {0.5, 0.4, 0, 0.8};
int [,] myarray = new int [3,4] {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};
double [] output = new double[myarray.Length];
for(int i = 0; i < myarray.Length; ++i)
output[i] = myarray[i] * factors;
I'm getting syntax errors that extension method 'Length' cannot be applied to type int, and also indexing with [] cannot be applied to type int.
I'd suggest a ragged array. Multidimensional arrays exist, but are poorly supported and almost nobody uses them. If you use a jagged array, you can be more concise. More importantly, you can be more intentional about it:
double[][] myArray = getMeSomeData();
double[] factors = getMeSomeRowFactors();
foreach (var row in myArray)
{
MultiplyRow(row, factors)
}
. . .
void MultiplyRow( double[] row, double[] factors )
{
for ( int col = 0 ; col < row.length ; ++col )
{
row[col] = row[col] * factors[col];
}
}
Or even better: use Linq:
double[][] myArray = getMeSomeData();
double[] factors = getMeSomeRowFactors();
myArray = myArray
.Select( row => row.Select( (cell, i) => cell * factors[i] ).ToArray() )
.ToArray()
;
Or even [arguably] better;
double[][] myArray = getMeSomeData();
double[] factors = getMeSomeRowFactors();
myArray = myArray
.Select( Multiply(factors) )
.ToArray()
;
. . .
Func<double,int,double[]> Multiply( double[] factors )
{
return (cell, i) => cell * factors[i];
}
I am not sure if you find it useful, but you can achieve it by using MathNet.Numerics:
PM> Install-Package MathNet.Numerics
using MathNet.Numerics.LinearAlgebra.Double;
using System.Linq;
...
var myarray = new double[3, 4]
{
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};
var factors = new double[4] { 0.5, 0.4, 0, 0.8 };
var matrix1 = Matrix.Build
.DenseOfArray(myarray);
var matrix2 = Matrix.Build
.DenseOfRows(Enumerable.Repeat(factors, matrix1.RowCount));
var res = matrix1.PointwiseMultiply(matrix2).ToArray();
You can get the length of each dimension by using the method GetLength:
double[,] output = new double[myarray.GetLength(0), myarray.GetLength(1)];
for (int i = 0; i < myarray.GetLength(0); i++)
{
for (int j = 0; j < myarray.GetLength(1); j++)
{
output[i, j] = myarray[i, j] * factors[j];
}
}
In case your array is huge, you can speed up the calculation by using all processors/cores of your PC:
Parallel.For(0, myarray.GetLength(0), i =>
{
for (int j = 0; j < myarray.GetLength(1); j++)
{
output[i, j] = myarray[i, j] * factors[j];
}
});

moving every int in the array one place backwards

I'm trying to move every int in array one "cell" (position) backwards (and take the first int to the last position) in a for loop. (example: if i have array of 5,6,9 the result will be 6,9,5).
Here is my code:
int[] arr = { 1, 2, 3, 4, 5, 6 };
int temp=arr[0];
for (int i=1; i < arr.Length-1; i++)
{
arr[i - 1] = arr[i];
}
arr[arr.Length - 1] = temp;
for (int i = 0; i < arr.Length - 1; i++)
{
Console.WriteLine(arr[i]);
}
Instead of getting
2,3,4,5,6,1
I'm getting
2,3,4,5,5.
Why is my code not working? What is the right way to do such process?
This code does what you need. Sort the array.
int[] arr = { 1, 2, 3, 4, 5, 6 };
//int[] arr = { 5, 6, 9 };
//string[] arr = { "A", "B", "C" };
var result = Enumerable.Range(1, arr.Length).Select(i => arr[i % arr.Length]).ToArray();
foreach (var item in result)
{
Console.WriteLine(item);
}
Input data and Results:
//Input: { 1, 2, 3, 4, 5, 6 };
//Result: 2,3,4,5,6,1
//Input: { 5, 6, 9 };
//Result: 6,9,5
//Input: { "A", "B", "C" };
//Result: B,C,A
Remove the -1 :
for (int i=1; i < arr.Length-1; i++)
in both loops and let the loops run until the end. The condition should be i < arr.Length You never reach the last position.
Although you use arr[arr.Length - 1] to Index the last element, it is different with the loop. If you take a closer look at the finishing condition it says: < that means that i will never get the value of Length - 1 the loop will end one iteration before that. Another way to fix your code would be to change the condition and let i run until it gets this value. You can achieve it by: i <= arr.Length - 1. The little difference should also do the trick. This time the loop will end exactly after I has reached the value of the index of the last element
All you need to do is remove the - 1 from your for loop condition, as it is not iterating over all the elements in your array.
If iterating over an array of 6 elements, the indices are from 0 -> 5. So, for your example, you want your loop to go from index 1 to 5 (what you had been doing is iterating over indices 1-4 (since you were subtracting by 1).
int[] arr = { 1, 2, 3, 4, 5, 6 };
int temp=arr[0];
for (int i=1; i < arr.Length; i++)
{
arr[i - 1] = arr[i];
}
arr[arr.Length - 1] = temp;
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}

Passing array value to another array in reverse order

I want to pass int a[] values into int b[]. but I'm facing confusion. Can anyone correct me out. The output of b is 0,0,0,45,4,2,1. it supposed to be like 7,6,5,4,45,2,1.
static void Main()
{
int[] a = new int[] { 1, 2, 45, 4, 5, 6, 7 };
int[] b = new int[7];
int temp = 0;
for (int i = 0; i <= a.Length - 1; i++)
{
b[(b.Length - i) - 1] = a[i];
Console.WriteLine(b[i]);
}
}
The problem here is that you're inserting items starting from the last index of b, but you're outputting them starting from the first index. The code to copy the items is correct, but you need to adjust your line that outputs the result to the console to show the items in b using the same index that you just used to insert the item.
Note there are a couple of other improvments you can make, such as using array initializer syntax for a, using a.Length to instantiate b instead of a hard-coded number, removing the unused temp variable, using i < a.Length for the for condition (instead of i <= Length - 1, which does a subtraction operation on each iteration), and storing the b index in a variable instead of calculating it twice:
static void Main()
{
int[] a = new int[] {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[a.Length];
for (int i = 0; i < a.Length; i++)
{
int bIndex = b.Length - i - 1;
b[bIndex] = a[i];
Console.WriteLine(b[bIndex]);
}
Console.ReadLine();
}
However, this will still output the items in the order in which you insert them, which will be the same order as they appear in a. If you want to show that the items in b are the reverse of a, the easiest way is to do it after you've populated b. Note we can make use of the string.Join method here to join each item with a comma:
static void Main()
{
int[] a = new int[] {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[a.Length];
for (int i = 0; i < a.Length; i++)
{
b[b.Length - i - 1] = a[i];
}
Console.WriteLine($"'a' array: {string.Join(",", a)}");
Console.WriteLine($"'b' array: {string.Join(",", b)}");
Console.ReadLine();
}
Output
If you want to create a reverse array from an existing array, you can use Reverse extension method:
//using System.Linq;
int[] a = new int[] { 1, 2, 45, 4, 5, 6, 7 };
int[] b = a.Reverse().ToArray();
You can learn more about Extension Methods.
You can have this syntax
int[] a = {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[7];
for (int i = 0, j = b.Length - 1; i < a.Length; i++, j--)
{
b[i] = a[j];
Console.WriteLine(b[i]);
}

C# For Loop and Array (practice exercise)

I'm trying to pick up C# and have been doing some practice programs. In this one, I try to transfer the integers in practiceArray to practiceArray2 but am unsuccessful, instead obtaining this as the output:
System.Int32[]
System.Int32[]
The code of my program is as follows:
static void Main(string[] args)
{
int[] practiceArray = new int[10] {2,4,6,8,10,12,14,16,18,20 };
int[] practiceArray2 = new int[practiceArray.Length];
for (int index = 0; index < practiceArray.Length; index++)
{
practiceArray2[index] = practiceArray[index];
}
Console.WriteLine(practiceArray);
Console.WriteLine(practiceArray2);
}
Console.WriteLine doesn't have any complicated logic for outputting complex objects, it just calls ToString() if it's not a string. You need to concatenate the values in the arrays manually, using string.Join etc.
For instance: Console.WriteLine(string.Join(", ", practiceArray));
int[] practiceArray = new int[10] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
int[] practiceArray2 = new int[practiceArray.Length];
for (int index = 0; index < practiceArray.Length; index++)
{
practiceArray2[index] = practiceArray[index];
}
foreach (int pArray in practiceArray)
Console.Write(pArray + " ");
foreach (int pArray2 in practiceArray2)
Console.Write(pArray2 + " ");
Console.Read();

Categories