C# For Loop with Random Int Generator locks the program - c#

I have 2 one dimensional arrays, containing the exact same values:
public int[] start = new int[21] { 0, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14 };
public int[] end = new int[21] { 0, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14 };
Below is the code I use to generate a random index, and grab the element from the array with said index, and stick it in a 2D array, with randomly generated X and Y index.
for (int i = 0; i < 21; i++)
{
Random ranNum = new Random();
int genX = 0;
int genY = 5;
int indx = 1;
while (gameBoard[genX, genY].rank > -1)
{
genX = ranNum.Next(0, 9);
genY = ranNum.Next(5, 8);
}
while (start[indx] == -1)
{
indx = ranNum.Next(0, 21);
}
if (gameBoard[genX, genY].rank == -1)
{
gameBoard[genX, genY].rank = start[indx];
start[indx] = -1;
}
while (gameBoard[genX, genY].rank > -1)
{
genX = ranNum.Next(0, 9);
genY = ranNum.Next(0, 3);
}
while (end[indx] == -1)
{
indx = ranNum.Next(0, 21);
}
if (gameBoard[genX, genY].rank == -1)
{
gameBoard[genX, genY].rank = end[indx];
end[indx] = -1;
}
}
Basically, it takes a value from the "start" and "end" arrays, replaces them with a '-1' (so they don't get picked again), scans the 2D array for '-1s' (so it doesn't place the number in a location that already has one), and places it there.
Notice that the min and max value for the random are different for the "start" and "end" arrays. This is to ensure that they end up far away from each other, on the other side of the 2D array.
This code works. Now, I have a code that resets all the variables back to their previous state. A reset function which also works. See, if the user is not content with the random placement, they can reset the arrays, and randomize again.
At which point the program simply hangs / locks up. No error, no messages, it just stops working. Please, could you share any ideas on how / why this happens?
Note: If I remove the entire while loop concerning the "end" array, the program can randomize and reset all it wants.
Anyway, the code for the reset:
int resVal = 0;
for (int i = 0; i < 21; i++)
{
startBoard[i] = resVal;
enemyBoard[i] = resVal;
if (i == 0)
resVal++;
else if (i >= 6 && i < 19)
resVal++;
}
for (int y = 0; y < 8; y++)
{
for (int x = 0; x < 9; x++)
{
gameBoard[x, y] = new classPiece();
gameBoard[x, y].rank = -1;
}
}

Move Random ranNum = new Random(); out of the cycle.

Related

How to add the current iteration's value to the previous iteration's value in a loop C#

I can find a Java version for my question, but not C#. My current attempt goes crazy when attempting to add them. I feel like there is a simple fix, but I'm struggling to think of it.
// See https://aka.ms/new-console-template for more information
int[] input = { 28, 2, 3, -3, -2, 1, 2, 35, -1, 0, 0, -1 };
for (int i = 0; i < input.Length; i++)
{
int x = input[i];
int y = input[i++];
int output = x + y;
Console.WriteLine(output);
}
If I understand your task answer is (updated):
var sum = 0;
var input = new int[] { 28, 2, 3, -3, -2, 1, 2, 35, -1, 0, 0, -1 };
for (var i = 0; i < input.Length - 1; i++)
{
sum += input[i];
Console.WriteLine(sum);
}
This is the correct code :
int[] input = { 28, 2, 3, -3, -2, 1, 2, 35, -1, 0, 0, -1 };
for (int i = 0; i < input.Length - 1; i++)
{
int x = input[i];
int y = input[i + 1];
int output = x + y;
Console.WriteLine(output);
}

Using foreach to get the even numbers out of array c#

I have this homework assignment where I have array called myArr with values 4, 9, 2, 5, 1, 4, 8, 3, 3 and I have to extract even numbers out of there and place them in myOtherArray and then printing them with foreach. I tried doing the code but I kinda got stuck since I know it won't work.
Here is my attempt:
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int num = 0;
int[] myOtherArr = new int[num];
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
num++;
}
}
Num is the counter to count how many even numbers are there, but right now I don't know how to save them into myOtherArray because I get the error that Index was outside the bounds of the array.
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
myArr[i] = myOtherArr[i];
}
}
Right now I don't know how to do this. Please help I want to be ready for my exam comming soon.
Thank you all in forward for your answers.
you can also try using Array.FindAll() built-in method to achieve this , instead of looping construct. Please try below code.
var myArr = new int[] { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
var myOtherArr = Array.FindAll(myArr, v => v%2 == 0);
Thank you.
I would try something like this
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
var i=0;
foreach (var item in myArr)
if (item % 2 == 0) i++;
var myOtherArr= new int[i];
i=0;
foreach (var item in myArr)
if (item % 2 == 0) { myOtherArr[i] = item; i++; }
I did it this way because you don't have to figure out the length of the array.
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int[] myOtherArr;
List<int> cache = new List<int>();
//goes through each number in this array and stores the ones for that round in "num".
//If the number is "% 2 == 0" then it will be added to a list.
foreach (int num in myArr)
{
if (num % 2 == 0)
{
cache.Add(num);
}
}
//the list is converted and stored in your array
myOtherArr = cache.ToArray();
//all numbers are displayed
foreach (int num in myOtherArr)
{
Console.WriteLine(num);
}
but you can also write it like this (I like to do this, for example).
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int[] myOtherArr;
List<int> cache = new List<int>();
//goes through each number in this array and stores the ones for that round in "num".
//If the number is "% 2 == 0" then it will be added to a list.
foreach (int num in myArr)
if (num % 2 == 0)
cache.Add(num);
//the list is converted and stored in your array
myOtherArr = cache.ToArray();
//all numbers are displayed
foreach (int num in myOtherArr)
Console.WriteLine(num);
The problem is here:
int[] myOtherArr = new int[num]; // you initialize the array to 0 length.
Try this:
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int num = 0;
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
num++;
}
}
int[] myOtherArr = new int[num];
int j = 0;
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
myOtherArr[j] = myArr[I];
j++;
}
}

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.

Last number in an array becomes first

I know that's easy, but I don't understand how I should do it.
1 23 29 18 43 20 5
to
5 1 23 29 18 43 20
I think we should use for-loop:
for (int i = 0; i < numbers.Count - 1; i++)
{
}
but I don't know what to do in it. Something like numbers[i] = numbers[i - 1] but it isn't working. I think there are some if checks which I miss.
The most straightforward way that comes to mind is a reverse loop.
int[] numbers = { 1, 23, 29, 18, 43, 20, 5};
int lastVal = numbers[numbers.Length - 1];
for (int i = numbers.Length -1; i > 0; i--)
numbers[i] = numbers[i-1];
numbers[0] = lastVal;
Just looping from the end (after saving the last value) and moving "up" the values, finally replacing the first value with the last
Here's a oneliner:
var numbers = new[] {1, 23, 29, 18, 43, 20, 5};
numbers = new[] {numbers.Last()}.Concat(numbers.Take(numbers.Length - 1)).ToArray();
This creates a new array containing the last element, then concatenates it with the original array excluding the last element.
What you want to do is make another array of the same size as the original one, then assign the last element and loop through the array up to the previous to last element.
Something like this:
int[] original = {1, 23, 29, 18, 43, 20, 5};
int[] altered = new int[original.length];
altered[0] = original[original.length - 1];
for (int i = 1; i < original.length - 1; i++)
{
altered[i] = original[i - 1];
}
You can perform a left rotation to the table by six positions on your case and create the requested new table
int[] myArray = new int[] { 1, 23, 29, 18, 43, 20, 5 };
var newArray = LeftRotationByD(myArray, 6);
and your function for the rotation would be:
private static int[] LeftRotationByD(int[] a, int k)
{
int[] b = new int[a.Length];
int index;
int length = a.Length;
int place;
for (int i = 0; i < length; i++)
{
index = i - k;
place = length + index;
if (index >= 0) b[index] = a[i];
else b[place] = a[i];
}
return b;
}
You can use this method to shift right:
void ShiftRight(int[] array, int count)
{
var clone = (int[])array.Clone();
for (var i = 0; i < array.Length; i++)
array[(i + count) % array.Length] = clone[i];
}
And use it this way:
var a = new int[] { 1, 2, 3, 4 };
ShiftRight(a, 1);

Get the value of a specific array number in relation to a given value

I am trying to determine what the neighbour bets would be for a given number on a roulette wheel.
At the moment I pass a pocket number to a function and below is my code. "pocket_number()[0]" is the value of the number I want to determine the neighbours of.
int[] neightbourbets = neighbourbets(pocket_number()[0]);
neighbourbets() is as follows (this outputs an array of element numbers so elsewhere in my program I can extract them from the same array structure). At the moment I have a crude way of determining the the neighbour bets and getting the function to state which numbers are 6 numbers either side of it.
Is there a better way to do this? I've found one of the problems (that I've overcome with the below) is if I want to know the neighbours for "0" for example which means the code needs to get the numbers from the end of the array.
public int[] neighbourbets(int x)
{
int[] pocket_array = new[] {0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26};
int predictednum = Array.IndexOf(pocket_array,x); //element number of pocket_array for chosen number
int[] neighbourbets = new[] {0,0,0,0,0,0,0,0,0,0,0,0,0};
neighbourbets[0] = predictednum;
neighbourbets[1] = predictednum+1;
neighbourbets[2] = predictednum+2;
neighbourbets[3] = predictednum+3;
neighbourbets[4] = predictednum+4;
neighbourbets[5] = predictednum+5;
neighbourbets[6] = predictednum+6;
neighbourbets[7] = predictednum-1;
neighbourbets[8] = predictednum-2;
neighbourbets[9] = predictednum-3;
neighbourbets[10] = predictednum-4;
neighbourbets[11] = predictednum-5;
neighbourbets[12] = predictednum-6;
for (int i = 0; i < neighbourbets.Length; i++)
{
//clockwise neighours
if (neighbourbets[i] == -1) {
neighbourbets[i] = 36;
}
if (neighbourbets[i] == -2) {
neighbourbets[i] = 35;
}
if (neighbourbets[i] == -3) {
neighbourbets[i] = 34;
}
if (neighbourbets[i] == -4) {
neighbourbets[i] = 33;
}
if (neighbourbets[i] == -5) {
neighbourbets[i] = 32;
}
if (neighbourbets[i] == -6) {
neighbourbets[i] = 31;
}
//anticlockwise neighbours
if (neighbourbets[i] == 37) {
neighbourbets[i] = 0;
}
if (neighbourbets[i] == 38) {
neighbourbets[i] = 1;
}
if (neighbourbets[i] == 39) {
neighbourbets[i] = 2;
}
if (neighbourbets[i] == 40) {
neighbourbets[i] = 3;
}
if (neighbourbets[i] == 41) {
neighbourbets[i] = 4;
}
if (neighbourbets[i] == 42) {
neighbourbets[i] = 5;
}
}
return neighbourbets;
}
Any helps or guidence is appreciated! :)
Write a small helper function to wrap around the index:
private int GetPocketIndex( int start, int offset, int count )
{
int pos = ( start + offset ) % count;
if( pos >= 0 )
return pos;
else
return count + pos; // pos is negative so we use +
}
The modulus there will help it wrap around when it goes above the maximum, and the if will do it for the minimum. This could probably be done easier though, but it eludes me at the moment.
Then, if you need that specific order, perhaps something like this:
int[] offsets = new int[] { 0,
1, 2, 3, 4, 5, 6,
-1, -2, -3, -4, -5, -6 };
int[] neighbourbets = new int[offsets.Length];
for( int i = 0; i < offsets.Length; i++ )
neighbourbets[i] = GetPocketIndex( predictednum, offsets[i], pocket_array.Length );
Or, if any order will do:
int count = 6;
int[] neighbourbets = new int[count * 2 + 1];
for( int i = 0; i < neighbourbets.Length; i++ )
neightbourbets[i] = GetPocketIndex( predictednum, i - count, pocket_array.Length );
The following would give you the result with the x in the middle of the result array and the neighbours to the left and right of it:
public static int[] neighbourbets2(int x, int neighborCount)
{
int[] pocket_array = new[] { 0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 30, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26 };
int predictednum = Array.IndexOf(pocket_array, x);
// Initialize the result array. Its size is double the neighbour count + 1 for x
int[] result = new int[neighborCount * 2 + 1];
// Calc the start index. We begin at the most left item.
int startAt = predictednum - neighborCount;
// i - position in the result array
// j - position in the pocket_array
for (int i = 0, j = startAt; i < result.Length; i++, j++)
{
// Adjust j if it's less then 0 to wrap around the array.
result[i] = pocket_array[j < 0 ? j + pocket_array.Length : j];
// If we are at the end then start from the beginning.
if (j == pocket_array.Length)
{
j = 0;
}
}
return result;
}

Categories