I'm encountering a problem with the code :
for (int i = 0; i < nr; i++)
{
intarray = new int[nr];
intarray[i] = generateRandom(4);
Console.WriteLine(intarray[i]+"Test1 "+i);
}
for (int i = 0; i < intarray.Length; i++)
{
Console.WriteLine(intarray[i]+"Test2 "+i);
}
//nr = 3
Some outputs : http://prntscr.com/5d8msx http://prntscr.com/5d8nkm ... .My problem that first 2 (intarray[0] and intarray[1]) are always 0, why are they always 0 because they aren't supposed to. intarray is initialiazed outside the function. Btw the generateRandom is this
Random r = new Random();
static int generateRandom(int max)
{
int randnum = r.Next(0, max);
return randnum;
}
You are creating a new array in the for-loop each time:
intarray = new int[nr];
This part should be outside the loop.
Since int is a value-type, all values of the array are initialized with its default value (0)
Initialize you array outside loop.
var intarray = new int[nr];
for (int i = 0; i < nr; i++)
{
intarray[i] = generateRandom(4);
Console.WriteLine(intarray[i]+"Test1 "+i);
}
for (int i = 0; i < intarray.Length; i++)
{
Console.WriteLine(intarray[i]+"Test2 "+i);
}
What you are doing now is create new array every time. and int init by 0.
I think your logic is wrong.
Every iteration in your first for loop, you are creating a new array reference. Since your array type is int, all elements of your array fills with 0 by default.
Since in Random.Next(int, int) overload, minimum values is inclusive, it might generate 0 as a result.
For example;
In your first iteration i is 0 and you create an array referance called intarray with new int[3] and you assing intarray[0] some random number (which is from 0 to 3) but the other elements in your array (intarray[1] and intarray[2]) are filled with 0 which is default value for an int.
At last iteration; your nr value is 3 and your i is 2. That means you fill your intarray[2] with a random number from 0 to 3, but since you didn't assing any value your intarray[0] and intarray[1] elements, they still keep 0 value by default.
As a solution, you should initialize your array outside of your for loop, like;
intarray = new int[nr];
for (int i = 0; i < nr; i++)
{
intarray[i] = generateRandom(4);
Console.WriteLine(intarray[i] + "Test1 " + i);
}
for (int i = 0; i < intarray.Length; i++)
{
Console.WriteLine(intarray[i] + "Test2 " + i);
}
Related
Here is a simple method in C# to reverse the element of the array. For instance, if I input {1,2,3,4} the result should be {4,3,2,1}.
public int[] reverse(int[] array)
{
int[] new_array = new int[array.Length];
for (int i = 0; i < array.Length-1; i++)
{
new_array[i] = array[array.Length-1 - i];
}
return new_array;
}
However, when I run it and give an input as {1,2,3,4}, it result in {4,3,2,0}, why does the last element become 0 instead of 1?
Issue exists here for (int i = 0; i < array.Length-1; i++).
You have to use <= if you are comparing it with Length-1 or use < sign with Length
Try this code.
public int[] reverse(int[] array)
{
int[] new_array = new int[array.Length];
for (int i = 0; i < array.Length; i++)
{
new_array[i] = array[array.Length-1 - i];
}
return new_array;
}
The problem you are having is that you are checking the array length and subtracting one.
for (int i = 0; i < array.Length - 1; i++)
This says if I is less than the length of your array minus one. There for you will never check the last element in your array.
This may be slightly easier to understand. I am basically running my for loop backwards and keeping a counter for both the new array and the original one.
var array = new int[] { 1, 2, 3, 4 };
int[] new_array = new int[array.Length];
for (int i = array.Length -1, n=0 ; i >= 0 ; i--,n++)
{
new_array[n] = array[i];
}
you can use Linq Instead of Writing Too many lines of code
Using
using System.Linq;
To Reverse Array
var reverse = array.Reverse();
Or
int[] reverse = array.Reverse().ToArray();
You don't need array.Length-1 because this will go beyond the index of array so only array.Length is enough.
int[] array = new int[4] { 4, 3, 2, 1 };
int[] new_array = new int[array.Length];
for (int i = 0; i< array.Length; i++)
{
new_array[i] = array[(array.Length - 1) - i];
}
Try this:
for (int i = array.Length - 1,j=0; i >= 0; i--,j++)
{
new_array[j] = array[i];
}
I have the below code.
int[] a = new int[] { 8, 9 };
for(int i=0;i<n;i++)
{
print i;
int z;
//during first iteration
z=8;
during second iteration
z=9;
}
Output should be something like this.
during first iteration i=0 and z=8
during second iteration i=1 and z=9
array a contains 2 elements. N and number of elements in array a will be always same. next my for loop will execute. during first iteration want z value should be 8(first element of array ) and second iteration my z value should be 9. I want to map 1st element of integer array to first iteration of for loop and so on.
try
for (int i = 0; i < a.Length; i++) // or i < n if you want
{
print i;
int z = a[i]; // this line will get value from a one by one, 0, 1, 2, 3 and so on...
}
Edit 1 -
After seeing the comments on the other answer, the array 'a' turns out is a dynamic array which have size n (which is 2)
the revised edition:
int n = 2;
int[] a = new int[n];
string input = null;
for (int i = 0; i < a.Length; i++) // or i < n if you want
{
print i;
input = Console.ReadLine();
try {
a[i] = int.Parse(input);
Console.WriteLine(string.Format(
"You have inputted {0} for the {1} element",
input, i
));
} catch { Console.WriteLine("Non integer input"); i -= 1; }
}
you can try this
int [] a = {8,9};
for(int i=0; i< a.Length; i++)
{
int z = a[i]; //for taking value from array at the specific ith position
Console.WriteLine("i: " + i + " z:" + z);
}
try this
List<int> a = new List<int>();
int n = 2; // you can change it according to your need
for (int i = 0; i < n; i++)
{
string str = Console.ReadLine(); // make sure you enter an integer and conver it
int z = int.Parse(str);
a.Add(z);
}
foreach (int k in a)
{
Console.WriteLine(k);
}
I am wanting to create multiple arrays of ints(in C#). However they all must have a unique number in the index, which no other array has that number in that index. So let me try show you what I mean:
int[] ints_array = new int[30];
for (int i = 0; i < ints_array.Count(); i++)
ints_array[i] = i;
//create a int array with 30 elems with each value increment by 1
List<int[]> arrayList = new List<int[]>();
for(int i = 0; i < ints_array.Count(); i++)
arrayList.Add(ints_array[i]. //somehow sort the array here randomly so it will be unique
So I am trying to get the arrayList have 30 int[] arrays and each is sorted so no array has the same int in the same index as another.
Example:
arrayList[0] = {5,2,3,4,1,6,7,8,20,21... etc }
arrayList[1] = {1,0,5,2,9,10,29,15,29... etc }
arrayList[2] = {0,28,4,7,29,23,22,17... etc }
So would this possible to sort the array in this unique kind of way? If you need anymore information just ask and ill fill you in :)
Wouldn't it be easier to create the arrays iteratively using an offset pattern?
What I mean is that if you created the first array using 1-30 where 1 is at index 0, the next array could repeat this using 2-30 where 2 is at index 0 and then wrap back to 1 and start counting forward again as soon as you go past 30. It would be an easy and repeatable way to make sure no array shared the same value/index pair.
You can do it like that:
List<int[]> arrayList = new List<int[]>();
Random rnd = new Random();
for (int i = 0; i < ints_array.Length; i++)
{
ints_array = ints_array.OrderBy(x => rnd.Next()).ToArray();
var isDuplicate = arrayList.Any(x => x.SequenceEqual(ints_array));
if (isDuplicate)
{
while (arrayList.Any(x => x.SequenceEqual(ints_array)))
{
ints_array = ints_array.OrderBy(x => rnd.Next()).ToArray();
}
}
arrayList.Add(ints_array);
}
I think, this wouldn't be so efficient for bigger numbers than 30.But in this case it shouldn't be a problem, in my machine it takes 7 milliseconds.
Jesse's idea would be best unless you needed a pure random pattern. In that case I would recommend generating a random number, checking all your previous arrays, and then placing it in an array if it did not match any other arrays current index. Otherwise, generate a new random number until you find a fresh one. Put that into a loop until all your arrays are filled.
Use a matrix (2D-array). It is easier to handle than a list of arrays. Create a random number generator. Make sure to initialize it only once, otherwise random number generator may create bad random numbers, if created in too short time intervals, since the slow PC-clock might not have ticked in between. (The actual time is used as seed value).
private static Random random = new Random();
Create two helper arrays with shuffeled indexes for rows and columns:
const int N = 30;
int[] col = CreateUniqueShuffledValues(N);
int[] row = CreateUniqueShuffledValues(N);
Then create and initialize the matrix by using the shuffeled row and column indexes:
// Create matrix
int[,] matrix = new int[N, N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[row[i], col[j]] = (i + j) % N;
}
}
The code uses these two helper methods:
private static int[] CreateUniqueShuffledValues(int n)
{
// Create and initialize array with indexes.
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = i;
}
// Shuffel array using one variant of Fisher–Yates shuffle
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm
for (int i = 0; i < n; i++) {
int j = random.Next(i, n);
Swap(array, i, j);
}
return array;
}
private static void Swap(int[] array, int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
int size = 10;
// generate table (no duplicates in rows, no duplicates in columns)
// 0 1 2
// 1 2 0
// 2 0 1
int[,] table = new int[size, size];
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
table[y, x] = (y + x) % size;
// shuffle rows
Random rnd = new Random();
for (int i = 0; i < size; i++)
{
int y1 = rnd.Next(0, size);
int y2 = rnd.Next(0, size);
for (int x = 0; x < size; x++)
{
int tmp = table[y1, x];
table[y1, x] = table[y2, x];
table[y2, x] = tmp;
}
}
// shuffle columns
for (int i = 0; i < size; i++)
{
int x1 = rnd.Next(0, size);
int x2 = rnd.Next(0, size);
for (int y = 0; y < size; y++)
{
int tmp = table[y, x1];
table[y, x1] = table[y, x2];
table[y, x2] = tmp;
}
}
// sample output
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
Console.Write("{0} ", table[y, x]);
Console.WriteLine();
}
Well im trying to find a maxValue in a array and its harder then i feel it should. Normally this code here works. If i declare an array and manually put in numbers for the array it find the max value fine. But when i put in a method to make an array with random numbers it breaks and returns the last value set as the maximum one.
static int MaxArray(int[] Array)
{
int maxVal = Array[0];
for(int i = 0; i < Array.Length; i++)
{
if(Array[i] > maxVal)
{
maxVal = Array[i];
}
}
return maxVal;
}
static void Main(string[] args)
{
Random r = new Random();
int[] myArray = new int[5];
for(int i = 0; i < myArray.Length; i++)
{
int rNumb = r.Next(0, 100);
for (int v = 0; v < myArray.Length; v++)
{
myArray[v] = rNumb;
}
Console.WriteLine(myArray[i]);
}
Console.WriteLine("Press entere to find the max value");
Console.ReadKey();
Console.Write(MaxArray(myArray));
Console.Read();
}
The inner for-loop in your Main method is useless. It fills the whole array with the current random number (so at the end the whole array will contain the last random number repeated).
The correct code is the following:
for(int i = 0; i < myArray.Length; i++)
{
int rNumb = r.Next(0, 100);
myArray[i] = rNumb;
Console.WriteLine(myArray[i]);
}
You were overwriting the values with your second for loop,
for (int v = 0; v < myArray.Length; v++)
{
myArray[v] = rNumb;
}
will write the current random number at each index of your array. The last random number will overwrite previous ones, so it will be declared as max since it's the only available number in your array.
Try this instead :
static void Main(string[] args)
{
Random r = new Random();
int[] myArray = new int[5];
for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = r.Next(0, 100);
Console.WriteLine(myArray[i]);
}
Console.WriteLine("Press entere to find the max value");
Console.Write(MaxArray(myArray));
Console.Read();
}
But honestly that MaxArray method is useless, don't reinvent the wheel, use Max from LINQ instead :
Console.Write(myArray.Max());
This is easily achieved using Linq.
using System.Linq;
private static Random _random = new Random();
public static int[] GenerateRandomArray(int arrayLength)
{
return Enumerable.Range(0, arrayLength).Select(i => _random.Next(0, 100)).ToArray();
}
public static int FindMaxValue(int[] array)
{
return array.Max();
}
It's because your array initialization is completely useless. This is what you're looking for:
for(int i = 0; i < myArray.Length; i++)
{
myArray[i] = r.Next(0, 100);
Console.WriteLine(myArray[i]);
}
At the end of it, the array will look like this (with your code):
{n, n, n, n, n}
where n is the last random number.
You don't need this loop. You should change this
for (int v = 0; v < myArray.Length; v++)
{
myArray[v] = rNumb;
}
with
myArray[i] = rNumb;
By writing this loop you are overwriting all the values in the array with the last value.
The reason you get the last value set as the maximum every time is because you set every element in the array to the last random number generated on the last iteration of the outer for loop.
Your Console.WriteLine(myArray[i]); is giving you a false impression of what the values of the array you pass into MaxValue() actually are!
I'm trying to write a code that will fill array with unique numbers.
I could write the code separately for 1, 2 and 3 dimensional arrays but number of for cycles grow to "infinity".
this is the code for 2D array:
static void fillArray(int[,] array)
{
Random rand = new Random();
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
array[i, j] = rand.Next(1, 100);
for (int k = 0; k < j; k++)
if (array[i, k] == array[i, j])
j--;
}
}
print_info(array);
}
Is it possible to do something like this for n-dimensional arrays?
My approach is to start with a 1-d array of unique numbers, which you can shuffle, and then slot into appropriate places in your real array.
Here is the main function:
private static void Initialize(Array array)
{
var rank = array.Rank;
var dimensionLengths = new List<int>();
var totalSize = 1;
int[] arrayIndices = new int[rank];
for (var dimension = 0; dimension < rank; dimension++)
{
var upperBound = array.GetLength(dimension);
dimensionLengths.Add(upperBound);
totalSize *= upperBound;
}
var singleArray = new int[totalSize];
for (int i = 0; i < totalSize; i++) singleArray[i] = i;
singleArray = Shuffle(singleArray);
for (var i = 0; i < singleArray.Length; i++)
{
var remainingIndex = i;
for (var dimension = array.Rank - 1; dimension >= 0; dimension--)
{
arrayIndices[dimension] = remainingIndex%dimensionLengths[dimension];
remainingIndex /= dimensionLengths[dimension];
}
// Now, set the appropriate cell in your real array:
array.SetValue(singleArray[i], arrayIndices);
}
}
The key in this example is the array.SetValue(value, params int[] indices) function. By building up the correct list of indices, you can use this function to set an arbitrary cell in your array.
Here is the Shuffle function:
private static int[] Shuffle(int[] singleArray)
{
var random = new Random();
for (int i = singleArray.Length; i > 1; i--)
{
// Pick random element to swap.
int j = random.Next(i); // 0 <= j <= i-1
// Swap.
int tmp = singleArray[j];
singleArray[j] = singleArray[i - 1];
singleArray[i - 1] = tmp;
}
return singleArray;
}
And finally a demonstration of it in use:
var array1 = new int[2,3,5];
Initialize(array1);
var array2 = new int[2,2,3,4];
Initialize(array2);
My strategy assigns sequential numbers to the original 1-d array to ensure uniqueness, but you can adopt a different strategy for this as you see fit.
You can use Rank property to get the total number of dimentions in your array
To insert use SetValue method
In the first two for loops you are analysing the array properly (i and j go from the start to the end of the corresponding dimension). The problem comes in the most internal part where you introduce a "correction" which actually provokes an endless loop for j.
First iteration:
- First loop: i = 0;
- Second loop: j = 0;
- Third loop: j = -1
Second iteration
- First loop: i = 0;
- Second loop: j = 0;
- Third loop: j = -1
. etc., etc.
(I start my analysis in the moment when the internal loop is used for the first time. Also bear in mind that the exact behaviour cannot be predicted as far as random numbers are involved. But the idea is that you are making the j counter back over and over by following an arbitrary rule).
What you want to accomplish exactly? What is this last correction (the one provoking the endless loop) meant to do?
If the only thing you intend to do is checking the previously stored values, you have to rely on a different variable (j2, for example) which will not affect any of the loops above:
int j2 = j;
for (int k = 0; k < j2; k++)
if (array[i, k] == array[i, j2])
j2--;