Check array value inside for loop - c#

I have to check second value in array if is equal to zero. It's working on my first example, where is user input not looped. But is not working on second example, where user input is looped.
First example
int[] array = new int[4];
array[0] = int.Parse(Console.ReadLine());
array[1] = int.Parse(Console.ReadLine());
//This statement Works here
if (array[1] == 0)
{
Console.WriteLine("Alert!");
}
array[2] = int.Parse(Console.ReadLine());
array[3] = int.Parse(Console.ReadLine());
Second example
int[] array = new int[4];
for (int i = 0; i < array.Length; i = i + 1)
{
//Input
array[i] = int.Parse(Console.ReadLine());
//This statement is not working
if (array[1] == 0)
{
Console.WriteLine("Alert!");
}

I think you maybe want to do that:
int[] array = new int[4];
for (int i = 0; i < array.Length; i = i + 1)
{
//Input
array[i] = int.Parse(Console.ReadLine());
if (array[i] == 0) // use i instead of 1
{
Console.WriteLine("Alert!");
}
}

I just had to write this if statement outside the loop. Now it Works
int[] array = new int[4];
for (int i = 0; i < array.Length; i = i + 1)
{
//Input
array[i] = int.Parse(Console.ReadLine());
}
if (array[1] == 0)
{
Console.WriteLine("Alert!");
}

to be sure to acuire valid values rom user you could use int.TryParse() instead of int.Parse()
for (int i = 0; i < array.Length; i = i + 1)
{
while (!int.TryParse(Console.ReadLine(), out array[i]))
Console.WriteLine("Input an integer value!");
}
if (array[1] == 0)
{
Console.WriteLine("Alert!");
}

Related

Looping through a large array and adding the values together C#

I'm trying to loop through an array of 180 elements and add the first 60 elements together and store it in a list. Then add the next 60 elements together and store them in the list and repeat that for the final 60. So far my code will only add the first 60 and store them in the list. the problem seems to be the "i % 60 == 0" in the else if statement but I'm not sure why
Random r = new Random();
int[] arr = new int[180];
List<int> MyList = new List<int>();
int[] array2 = new int[2];
//intialize random numbers in 60 length array
for (int i = 0; i < arr.Length; i++)
{
arr[i] = r.Next(1, 10);
}
int score = 0;
//looping through arr
for (int i = 0; i < arr.Length; i++)
{
if (i % 60 != 0 || i == 0 )
{
score = score + arr[i];
i++;
}
else if (i % 60 == 0 && i != 0)
{
//adding the values to a list
MyList.Add(score);
//resetting score after score is added to the list
score = 0;
}
}
// converting list to my second array
array2 = MyList.ToArray();
//printing values in array
for (int i = 0; i < array2.Length; i++)
{
Console.WriteLine(array2[i]);
}
Your original loop and conditions have several problems and actually need to be:
int score = 0;
for (int i = 0; i < arr.Length; i++)
{
score = score + arr[i];
if ((i + 1) % 60 == 0)
{
MyList.Add(score);
score = 0;
}
}
But I strongly advise you to use much simpler LINQ approach (instead of doing all the stuff manually):
var array2 = new[]
{
arr.Take(60).Sum(),
arr.Skip(60).Take(60).Sum(),
arr.Skip(120).Sum()
};

ArrayIndexOutOfBounds exception in hackerrank Cut the sticks

I am trying to implement a problem in Hackerrank Cut the sticks. Problem can be found here
my code is this
static int[] cutTheSticks(int[] arr)
{
int n = arr.Length, k = 0;
int[] result = new int[n];
Array.Sort(arr);
Array.Reverse(arr);
while(arr.Length != 0)
{
result[k] = arr.Length;
k++;
for(int i = 0; i < n; ++i)
{
arr[i] -= arr[arr.Length - 1];
}
}
return result;
}
it shows error as-
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Solution.cutTheSticks (System.Int32[] arr) [0x00020] in solution.cs:24
line 24 is:
result[k] = arr.Length;
How to remove this?
There are several problems with your code. To name a few:
You are giving the result array a fixed size (int[] result=new int[n];), but it's size depends entirely on how many duplicate values are contained in the list.
You are supposed to remove from the array the smallest value(s) in each iteration. However you are just modifying the values (arr[i] -= arr[arr.Length - 1];), not removing them, so the array length will remain the same, and thus while (arr.Length != 0) will always be true, creating an endless loop. This causes k++ to keep incrementing until it reaches a value greater than the array length, which then results in the exception you are getting.
Since you are supposed to change the size of the input array, I suggest using List<int> instead, here's an example:
List<int> output = new List<int>();
List<int> input = new List<int>(arr);
while (input.Count > 0)
{
output.Add(input.Count);
int min = input.Min();
input.RemoveAll(x => x == min);
input.ForEach(x => x -= min);
}
return output.ToArray();
It is necessary to add condition k < n before assigning value to avoid IndexOutOfRangeException exception. In addition, there is a strong need a condition to avoid infinite while loop :
static int[] cutTheSticks(int[] arr) {
int n = arr.Length,
k = 0;
int[] result = new int[n];
Array.Sort(arr);
Array.Reverse(arr);
while (arr.Length != 0)
{
if (k < n)
result[k] = arr.Length;
else
break;
k++;
for (int i = 0; i < n; ++i)
{
arr[i] -= arr[arr.Length - 1];
}
}
return result;
}
UPDATE:
It is possible to pop out one element after every iteration like this:
static int[] cutTheSticks(int[] arr)
{
int n = arr.Length,
k = 0;
int[] result = new int[n];
var arrToBeRemoved = arr.ToList();
Array.Sort(arr);
Array.Reverse(arr);
while (arr.Length != 0)
{
if (k < n)
result[k] = arr.Length;
else
break;
if (k < arrToBeRemoved.Count)
arrToBeRemoved.RemoveAt(k);
arr = arrToBeRemoved.ToArray();
k++;
for (int i = 0; i < arr.Length; ++i)
{
arr[i] -= arr[arr.Length - 1];
}
}
return result;
}
I would do it that way:
static int[] cutTheSticks(int[] arr)
{
List<int> results = new List<int>();
int cutted = 0;
while (cutted != 1)
{
cutted = 0;
int min = GetMin(arr);
if (min == 0)
{
break;
}
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] >= min)
{
arr[i] -= min;
cutted++;
}
}
results.Add(cutted);
}
return results.ToArray();
}
static int GetMin(int[] arr)
{
int min = int.MaxValue;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != 0 && arr[i] < min)
{
min = arr[i];
}
}
return min;
}

Delete Element from Array Using For Loop + If Statement - C#

I Have an array, TempArray[] = {1,3,-1,5,7,-1,4,10,9,-1}
I want to remove every single -1 from this array and copy the remaining arrays into a new array called Original, which should output the numbers as 1,3,5,7,4,10,9
I can only use an if statement within a for loop!
This is what I have so far, but I keep getting an error message, System.IndexOutOfRangeException
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
//error occurs at this line
//My attempt is to set the new array, Original[i] equal to TempArray[i] only where the values are not -1.
TempArray[i] = Original[i];
}
}
If you can only use If statement in for loop. This looks like a school project. First you count how many non negative numbers are there in your array. Create new array with that length and fill that array.
int[] TempArray = new int[] {1,3,-1,5,7,-1,4,10,9,-1};
int[] Original ;
int countNonNegative=0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
countNonNegative++;
}
}
Original = new int[countNonNegative];
int index=0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[index] = TempArray[i];
index++;
}
}
Console.WriteLine("Original Length = "+Original.Length);
using System.Linq;
int[] withoutNegativeOnes = myArray
.Where(a => a != -1)
.ToArray();
var Original = new int[TempArray.Length];
var originalCounter = 0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[originalCounter++] = TempArray[i];
}
}
Now Original may contain empty spaces at the end though, but you have all the elements which aren't -1. You can use the following code to iterate through the values:
for (int i = 0; i < originalCounter; i++)
{
Console.WriteLine(Original[i]);
}
and that's because the originalCounter has the last index values that wasn't filled from TempArray's iteration.
try this one
int[] TempArray = { 1, 3, -1, 5, 7, -1, 4, 10, 9, -1 };
int[] original = TempArray.Where(i => i != -1).ToArray();
foreach(int i in original)
Console.WriteLine(i.ToString());

updating variable from inside a loop?

I'm writing a mastermind game and I need to update the value of an array size using a variable inside a while loop which increments on each loop is there any way i can do this?
bool game = false;
do
{
int codeSize;
int colourSize;
int guessNumber = 1;
int userGuess;
int black = 0;
int white = 0;
int count = 1;
Console.WriteLine("Welcome to Mastermind coded by ****");
Console.Write("How many positions > ");
codeSize = Convert.ToInt32(Console.ReadLine());
Console.Write("How many colours > ");
colourSize = Convert.ToInt32(Console.ReadLine());
Random rand = new Random();
int[] code = new int[codeSize];
int[] guess = new int[codeSize];
for (int i = 0; i < codeSize; i++)
{
code[i] = rand.Next(1, colourSize + 1);//filling the secret code array
}
Console.WriteLine("O.k. - I've generated a code -- guess it!");
while (black < codeSize)
{
int[,] history = new int[count, codeSize + 2];
Console.WriteLine("Next guess please.");
for (int n = 0; n < codeSize; n++)
{
Console.Write("Position " + guessNumber + " >");
userGuess = Convert.ToInt32(Console.ReadLine());
guess[n] = userGuess;
history[count - 1, n] = guess[n];
guessNumber++;
}
for (int x = 0; x < codeSize; x++)
{
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
{
if (guess[x] == code[x])
{
black++;
break;
}
goto case 2;
}
case 2:
{
if (guess[x] == code[x])
{
break;
}
int i = 0;
while (i < codeSize)
{
if ((guess[x] == code[i]) && (guess[i] != code[i]))
{
white++;
break;
}
i++;
}
break;
}
}
}
guessNumber = 1;
if (black == codeSize)
{
white = 0;
}
history[count - 1, codeSize + 1] = white;
history[count - 1, codeSize] = black;
count++;
Debug.WriteLine("-----------\nSecret code\n-----------");
for (int x = 0; x < codeSize; x++)
{
Debug.WriteLine(code[x]);
}
Console.WriteLine("Correct positions : {0}", black);
Console.WriteLine("Correct colours : {0}\n", white);
Console.WriteLine("History");
for (int t = 1; t < codeSize + 1; t++)
{
Console.Write(t + " ");
}
Console.WriteLine("B W");
for (int g = 0; g < codeSize + 3; g++)
{
Console.Write("--");
}
Console.Write("\n");
for (int t = 0; t < count - 1; t++)
{
for (int g = 0; g < codeSize + 2; g++)
{
Console.Write("{0} ", history[t, g]);
}
Console.WriteLine("\n");
}
if (codeSize > black)//reseting values for next turn
{
black = 0;
white = 0;
}
}
int play;
Console.WriteLine("\nYou Win!\n\nPress 1 to play again or any other number to quit");
play = Convert.ToInt32(Console.ReadLine());
if (play == 1)
game = true;
} while (game == true);
Arrays have a fixed size when you declare them and you cannot change the size afterwards without creating a new array. Try using a strongly typed List instead.
List<int> MyList = new List<int>();
// Add the value "1"
MyList.Add(1);
or the following for a table:
List<List<int>> MyTable = new List<List<int>>();
// Add a new row
MyTable.Add(new List<int>());
// Add the value "1" to the 1st row
MyTable[0].Add(1);
I believe you are asking whether you can change the length property of an array from within a loop, extending it as required.
Directly, no. There are helpers and classes which provide for such functionality, allocating more memory as needed, but I doubt this is what you really need. You could try using an array of fixed dimensions (the maximum codeSize your program will tolerate or expect), and then an integer next to it to record the length/position.
Alternatively, if you really need to expand to arbitrary sizes and store all codes, just use a List.
List<int[]> theList = new List<int[]>();
theList.Add(code);
Creates a list of integer arrays (your codes) that you can keep adding onto, and index just like any simple array.
There is a way to resize array size:
Array.Resize<T>
method. Details there: http://msdn.microsoft.com/en-us/library/bb348051(v=vs.110).aspx
But it's usually a pretty bad idea to resize the arrays loop based. You need to select another data structure to save your data or i.e. create an array of bigger size filled i.e. with zeroes.
You also need to add the items to the list as so. The list will dynamically grow based on it's size.
int myInt = 6;
List<int> myList = new List<int>();
myList.Add(myInt);

C# populate array with unique ints No Linq or ArrayLists;

This code is buggy but can't figure out why ... want to populate an array with 7 unique random integers without using arraylists or linq! I know the logic is not okay...
class Program
{
static void Main(string[] args)
{ int current;
int[] numbers = new int[7]; // size of that array
Random rNumber = new Random();
current = rNumber.Next(1, 50);
numbers[0] = current;
Console.WriteLine("current number is {0}", current);
for (int i=1;i<7;i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < numbers.Length; j++)
{
do
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
}
else
{
numbers[j++] = current;
break;
}
}while (current == numbers[j]);
}//inner for
}//outer for
for (int l = 0; l < 7; l++) // DISPLAY NUMBERS
{
Console.WriteLine(numbers[l]);
}
}// main
}//class
want to populate an array with 7 unique integers without using
arraylists or linq!
int[] list = new int[7];
for (int i = 0; i < list.Length; i++)
{
list[i] = i;
}
EDIT
I changed your inner loop, if the random number is already in the array; create a new random and reset j to 0.
for (int i = 1; i < 7; i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < numbers.Length; j++)
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
j = 0; // reset the index iterator
}
}//inner for
numbers[i] = current; // Store the unique random integer
}//outer for
I presume you are looking for random numbers, so the other answer is not what you are looking for.
There are a couple of issues here.
The inner loop is testing for duplicates. However, it is looking from 0 through the end of the array since it is using numbers.length. This should probably be i, to compare with already set values. numbers.length is always 7 regardless of whether or not you set any of the elements.
the assignment is using j, so presuming the first element is not a duplicate, it will be overwritten each time. That should be numbers[i] = current;. No ++ necessary as the for is handling the incrementing.
if you determine that a number is a duplicate, j should be reset to zer to check against the entire list again rather than having the while in the middle.
Without a complete rewrite, the changes will look something like this:
for (int i=1;i<7;i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < i; j++) //----------------- loop through set values
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
j = 0; // -----------------------reset the counter to start over
}
}//inner for
// if we got here there is no duplicate --------------------------------
numbers[i] = current;
}//outer for
(Please note that I have not tested this code, just added the changes)
you keep overwriting the same indexes in the else, and also checking too many indices causing the first to show up as a duplicate at all times which was false...
change it to:
for (int i=1;i<7;i++)
{
current = rNumber.Next(1, 50);
for (int j = 0; j < i; j++) ///< change to j < i. no need to check the others
{
do
{
if (current == numbers[j])
{
Console.WriteLine("Duplicate Found");
current = rNumber.Next(1, 50);
}
else
{
numbers[i] = current; ///< not j++ but i to prevent writing at the same locations over and over again
break;
}
}while (current == numbers[j]);
}//inner for
}//outer for
What about this?
int[] list = new int[7];
var rn = new Random(Environment.TickCount);
for (int i = 0; i < 7; i++)
{
var next = rn.Next(1, 50);
while(Contains(list, next))
{
next = rn.Next(1, 50);
}
list[i] = next;
}
private bool Contains(IEnumerable<int> ints, int num)
{
foreach(var i in ints)
{
if(i = num) return true;
}
return false;
}

Categories

Resources