How to compare values in one array? - c#

How can I compare elements in one array?
if the next number in the array is greater than the previous one, then transfer these two values further ... And accordingly, if this is not so, transfer them to another method ...
double[] ipp = { 0.255, 0.232, 0.618, 0.713 };
I'm trying to do so, but the array goes beyond the number of indices
for (int i = 0; i < ipp.Length; i++)
{
if (ipp[i+1] > ipp[i]) // problem
{
// ----> send this
//(ipp[i+1];ipp[i]) values
//to another method
}
}

The problem is in the upper bound check in your for loop. When i = ipp.Length - 1 and you access array item ipp[i + 1] you access an element outside of the array bounds, therefore the problem occurs.
You need to change upper bound check to the i < ipp.Length - 1:
for (int i = 0; i < ipp.Length - 1; i++)
{
if (ipp[i + 1] > ipp[i])
{
...
}
}

Related

Check a matrix's value in a certain position and compare it to another

Im trying to make a function that will take a matrix as a paramater, then display this array to the console using diffrent symbols. To acomplish this im trying to check the value of Matrix[1,1] and compare it to see what symbol needs to be displayed. This is all using C#.
I tried to use this code to read a matrix and display a symbol to the console
// Displays the gameboard requested
public static void DisplayBoard(int[,] gameboard)
{
int boardLength = gameboard.GetLength(0); // Gets the size of the board and stores it
// Displays the game board to the console as a square with correct symbols
for (int i = 1; i <= boardLength; i++)
{
for (int j = 1; j <= boardLength; j++)
{
// Checks the arrays position and changes the symbol based on its value
if (gameboard[i, j] == 1) // Player one X
{
Console.Write("X");
}
else if (gameboard[i, j] == 2) // Player 2 O
{
Console.Write("O");
}
else // default empty square
{
Console.Write("-");
}
}
Console.WriteLine(string.Empty);
}
}
I Expected this to read the matrixs value and run the for loops, if the value in matrix[1,1] is equal to 0 i expected it to be throw to the else statement and print "-" to the console, is equal to 1 itll print "x" and 2 will be a "o". It would then move to the next row and repeat the loops till the array has been translated to the console.
What happens is im displayed the System.IndexOutOfRangeException: error on the first line with an if statement, if (gameboard[i, j] == 1),
This is mainly an issue of the way C# works with arrays of nested arrays and the oddities of working with them (index starts at 0, length starts at 1). You're calling the length which contains all ints in the array regardless of how deeply nested they are, whereas you need to be calling the rank which defines the number of nested arrays in your array. Remember this is a 2d array, so we can't count from a single "length" to get it to work.
So for example, you might end up calling gameboard[1,9] when the first nested array doesn't contain 9 elements... and this gets your issue!
You can fix this issue by modifying your syntax as below to consider both length and width of your array where all nested arrays are of the same size:
public static void DisplayBoard(int[,] gameboard)
{
int boardLength = gameboard.Rank - 1;
int boardWidth = gameboard.GetLength(0) / boardLength;
for (int i = 0; i <= boardLength; i++)
{
for (int j = 0; j <= boardWidth; j++)
{
// Checks the arrays position and changes the symbol based on its value
if (gameboard[i, j] == 1) // Player one X
{
Console.Write("X");
}
else if (gameboard[i, j] == 2) // Player 2 O
{
Console.Write("O");
}
else // default empty square
{
Console.Write("-");
}
}
Console.WriteLine(string.Empty);
}
}
Here we calculate the length and width and then use these two parts to actually iterate through our 2d array.
Try changing your for loops. The index starts at 0, not 1.
for (int i = 0; i < boardLength; i++)

Increasing sequence in one dimensional array

You're given an array of integers,in case if you see subsequence in which each following bigger than the previous on one(2 3 4 5) you have to rewrite this subsequence in the resulting array like this 2 - 5 and then the rest of the array. So in general what is expected when you have 1 2 3 5 8 10 11 12 13 14 15 the output should be something like 1-3 5 8 10-15.
I have my own idea but can't really implement it so all I managed to do is:
static void CompactArray(int[] arr)
{
int[] newArr = new int[arr.length];
int l = 0;
for (int i = 0,k=1; i <arr.length ; i+=k,k=1) {
if(arr[i+1]==arr[i]+1)
{
int j = i;
while (arr[j+1]==arr[j]+1)
{
j++;
k++;
}
if (k>1)
{
}
}
else if(k==1)
{
newArr[i] = arr[i];
}
}
In short here I walk through the array and checking if next element is sum of one and previous array element and if so I'm starting to walk as long as condition is true and after that i just rewriting elements under indices and then move to the next.
I expect that people will help me to develop my own solution by giving me suggestions instead of throwing their own based on the tools which language provides because I had that situation on the russian forum and it didn't help me, and also I hope that my explanation is clear because eng isn't my native language so sorry for possible mistakes.
If I understand the problem correctly, you just need to print the result on the screen, so I'd start with declaring the variable which will hold our result string.
var result = string.Empty
Not using other array to store the state will help us keep the code clean and much more readable.
Let's now focus on the main logic. We'd like to loop over the array.
for (int i = 0; i < array.Length; i++)
{
// Let's store the initial index of current iteration.
var beginningIndex = i;
// Jump to the next element, as long as:
// - it exists (i + 1 < array.Length)
// - and it is greater from current element by 1 (array[i] == array[i+1] - 1)
while (i + 1 < array.Length && array[i] == array[i+1] - 1)
{
i++;
}
// If the current element is the same as the one we started with, add it to the result string.
if (i == beginningIndex)
{
result += $"{array[i]} ";
}
// If it is different element, add the range from beginning element to the one we ended with.
else
{
result += $"{array[beginningIndex]}-{array[i]} ";
}
}
All that's left is printing the result:
Console.WriteLine(result)
Combining it all together would make the whole function look like:
static void CompactArray(int[] array)
{
var result = string.Empty;
for (int i = 0; i < array.Length; i++)
{
var beginningIndex = i;
while (i + 1 < array.Length && array[i] == array[i+1] - 1)
{
i++;
}
if (i == beginningIndex)
{
result += $"{array[i]} ";
}
else
{
result += $"{array[beginningIndex]}-{array[i]} ";
}
}
Console.WriteLine(result);
}

trying to int.parse multi array string

Im doing this:
string[,] string1 = {{"one", "0"},{"Two", "5"},{"Three","1"}};
int b = 0;
for(int i = 0; i <= string1.Length; i++)
{
b = int.Parse(string1[i, 1]); // Error occurs here
}
Im getting an error saying that "index extent the limits of the array" (or something like that, the error is in danish).
There are two problems:
string1.Length will return 6, as that's the total length of the array
You're using <= for the comparison, so it would actually try to iterate 7 times.
Your for loop should be:
for (int i = 0; i < string1.GetLength(0); i++)
The call to GetLength(0) here will return 3, as the size of the "first" dimension. A call to GetLength(1) return 2, as the second dimension is of size 2. (You don't need that though, as you're basically hard-coding the knowledge that you want the second "column" of each "row".)
See the docs for Array.GetLength() for more details.
Your array bounds are incorrect in the loop:
for(int i = 0; i <= string1.Length; i++)
should read:
for(int i = 0; i < string1.GetLength(0); i++)
Two things were wrong: <= versus < meant you were going one item too far, and .Length returns the total length of the array (6) versus GetLength(0) which returns the length of the first dimension (3).
You already have the right answer, I'll update mine just to correct it. To right iteration should be
for (int i = 0; i < string1.GetLength(0); i++)
{
b = int.Parse(string1[i, 1]);
}
Because i stands for the length of the first dimension, and the fixed 1 will return the number, that is the second element.
I'm sorry for the wrong answer I gave first.
Change i <= string1.Length to i < string1.Length.
change to
for(int i = 0; i <= string1.GetLength(0); i++)
{
b = Int32.Parse(string1[i][0]);
}
Your code is refering at index 1 rather than 0 which causes exception known as Array out of bound
Try this:
for(int i = 0; i < string1.GetLength(0) ; i++)
{
b = int.parse(string1[i, 0]); // Error occurs here
}
Array.GetLength Method
Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.
Also worth mentioning that int.Parse may throw a FormatException, consider int.TryParse.

How to write groups of numbers using Console.Write?

I'm very new to C# (And Stack Overflow, forgive me for any poor etiquette here), and I'm writing the game Mastermind in a console application. I'm trying to show a list of the user's guesses at the end of the game, and I know that using Console.WriteLine(); will just give me 30-odd lines off numbers which don't tell the user anything.
How can I alter my code so that the program displays 4 numbers in a group, at a time? For example:
1234
1234
1234
//Store numbers in a history list
ArrayList guesses = new ArrayList(); //This is the ArrayList
Console.WriteLine("Please enter your first guess.");
guess1 = Convert.ToInt32(Console.ReadLine());
guesses.Add(guess1);
foreach (int i in guesses)
{
Console.Write(i);
}
I assume that each element of your byte array is a single digit (0-9). If that assumption is invalid -- please let me know, I'll modify the code :)
Action<IEnumerable<int>> dump = null;
dump = items =>
{
if(items.Any())
{
var head = String.Join("", items.Take(4));
Console.WriteLine(head);
var tail = items.Skip(4);
dump(tail);
}
};
dump(guesses);
It looks like you're most of the way there, you have a console write that writes them all out without linebreaks. Next add an integer count and set it to zero. Increment it by one in the foreach loop. count % 4 == 0 will then be true for all counts that are a multiple of four. This means you can stick an if block there with a write-line to give you your groups of four.
List<int> endResult = new List<int>();
StringBuilder tempSb = new StringBuilder();
for(int i=0; i < groups.Count; i++)
{
if(i % 4 == 0) {
endResult.Add(int.Parse(sb.ToString()));
tempSb.Clear(); // remove what was already added
}
tempSb.Append(group[i]);
}
// check to make sure there aren't any stragglers left in
// the StringBuilder. Would happen if the count of groups is not a multiple of 4
if(groups.Count % 4 != 0) {
groups.Add(int.Parse(sb.ToString()));
}
This will give you a list of 4 digit ints and make sure you don't lose any if your the number of ints in your groups list is not a multiple of 4. Please note that I am continuing based on what you provided, so groups is the ArrayList of ints.
This is some thing I quickly put together:
Update:
ArrayList guesses = new ArrayList(); //This is the ArrayList
// Four or more
guesses.Add(1); guesses.Add(2);
guesses.Add(3);guesses.Add(4);
guesses.Add(5); guesses.Add(6); guesses.Add(7);guesses.Add(8); guesses.Add(9);
//Uncomment-Me for less than four inputs
//guesses.Add(1); guesses.Add(2);
int position = 0;
if (guesses.Count < 4)
{
for (int y = 0; y < guesses.Count; y++)
{
Console.Out.Write(guesses[y]);
}
}
else
{
for (int i = 1; i <= guesses.Count; i++)
{
if (i%4 == 0)
{
Console.Out.WriteLine(string.Format("{0}{1}{2}{3}", guesses[i - 4], guesses[i - 3],
guesses[i - 2], guesses[i - 1]));
position = i;
}
else
{
if (i == guesses.Count)
{
for (int j = position; j < i; j++)
{
Console.Out.Write(guesses[j]);
}
}
}
}
}

How can i check the index length in long[] array?

For example i have a long[] x
And im doing:
for (int i=0; i<x.length;x--)
{
}
I know that in x for example i have 30 indexs cells.
How can i loop over the cells(indexs) in the x array and find on each cell the length of it and also to get/show the numbers in each cell.
If in x[0] there is 232
And in x[1] there is 21
And so on...
I want to display 232,21,....etc
And then i want to check that if x[i].length is above 0 do...
But there is no x[i].length
So how do i do it ?
I did:
public long GetHistogramMaximum(long[] histogram)
{
long result = 0;
long count = 0;
for (int i = 0; i < histogram.Length; i++)
{
if (histogram[i] > 0)
{
MessageBox.Show(histogram[i].ToString());
break;
}
}
return result;
}
And its working but each time its showing me the number twice why the messagebox is working twice each time ?
If in the first array the number is 33454 then i see the messagebox once and then once again. Whats wrong here ? I want it to show me the number only once each time.
Its like repeating each number and show it once and then once again and only then moving to the next one.
EDIT **
Maybe the problem its showing the number twice each time have something to do with the scroll event im using ?
void trackBar1_Scroll(object sender, EventArgs e)
{
myTrackPanelss1.trackBar1.Minimum = 0;
myTrackPanelss1.trackBar1.Maximum = counter - 1;//list_of_histograms.Count-1;
long[] tt = list_of_histograms[myTrackPanelss1.trackBar1.Value];
histogramControl1.DrawHistogram(tt);
long res = GetTopLumAmount(tt, 1000);
long max = GetHistogramMaximum(tt);
if (res > -1)
label24.Text = (res / 1000.0).ToString();
setpicture(myTrackPanelss1.trackBar1.Value);
this.pictureBox1.Refresh();
}
For some reason its getting to the scroll and do everything here again. Twice in a row.
What can be the problem ?
A long[] basically holds a number of long values. Doing x[i].length is invalid, because a long does not have a property length. What is it that you are trying to achieve?
long[] x = {1,2,3} ;
x.length; //this is valid because you are querying the length / count of the array
x[0].length; //this is invalid because 1 does not have a property length
EDIT
Your loop counter will be the index. So,
for (int i =0; i < x.Length; i++)
{
//check for maximum, when you find it
Console.WriteLine("The maximum value is " + x[i]);
Console.WriteLine("The maximum value is present at index " + i);
}
As Michael says, you can find the length of the array via x.Length. In C#, x.Length (where x is an array) will return a 32-bit integer that represents the total number of elements across all dimensions. You only have a 1D array here, so that should be sufficient for what you're trying to achieve.
If you're also after the value stored in the array, the value is called as:
x[i];
So, in an example:
for ( int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
... would display the value in the array in your console.
Is that what you were asking?
Here is how to do something based on the values in the array.:
for (int i=0; i < x.Length; i++)
{
// print the number to the screen.
Console.WriteLine(x[i]);
if (x[i] > 0) {
// do something else.
}
}
I'm not sure what you meant by x--, but that's probably wrong from your description.
You could cast it to a string and get the length property.
x[i].ToString().Length
Although if you want to check if the length is above zero, then surely just the presence of a value proves this?
Your function has a terrible problem:
public long GetHistogramMaximum(long[] histogram)
{
long result = 0;
long count = 0;
for (int i = 0; i < histogram.Length; i++)
{
if (histogram[i] > 0)
{
MessageBox.Show(histogram[i].ToString());
break;
}
}
return result;
}
This way, you check the values in your array.
When i=0, it checks x[i]. So, 33454 (the value you gave in x[0]) is greater than 0, it shows the number and "break;", so it stops the "for" and do what's next: it returns the result variable that is never modified.
So variables result and count are useless in your code.
Rewrite with something that way for getting the maximum in your array:
public long GetHistogramMaximum(long[] histogram)
{
long result = 0;
for (int i = 0; i < histogram.Length; i++)
{
if (histogram[i] > result)
{
MessageBox.Show(string.Format("{0} is greater than {1}", histogram[i], result);
result = histogram[i];
}
}
return result;
}

Categories