I'm having issue with the following code:
public int ReverseArray(int[] rArray)
{
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8 };
Array.Reverse(array);
foreach (int value in array)
{
return (value);
}
return 0;
}
private void reverseButton_Click(object sender, EventArgs e)
{
int[] input = new int[10];
int output = ReverseArray(input);
MessageBox.Show(""+ output);
}
The code is supposed to take the given array (int[] array = { 1, 2, 3, 4, 5, 6, 7, 8 };) and reverse it upon a button click; however, when I click on the reverseButton, I only get the number 8 and not the entire array. I'm sure it's the way my reversButton code is written, but I'm not sure how to fix it.
How can I fix my code to where when I click on reverseButton, the entire array will be displayed in reverse order?
You are not returning whole array back and also not iterating the array result and Array is a collection of items to you need to tell it to get each item one by one and print.
You can do something like following to make it work:
public int[] ReverseArray(int[] rArray)
{
Array.Reverse(array);
return array;
}
and in button click event you can use it:
int[] input = { 1, 2, 3, 4, 5, 6, 7, 8 };
input = ReverseArray(input);
string items = String.Join(",",input);
MessageBox.Show(items);
Because your method ReverseArray just returns one value:
public int[] ReverseArray(int[] rArray)
{
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8 };
Array.Reverse(array);
return array;
}
To show whole array you can combine it into some string:
int[] output = ReverseArray(input);
var message = string.Join(", ", output);
And show:
MessageBox.Show(message);
Related
Looking for the most efficient way. I found this on comparing lists regardless of order:
https://answers.unity.com/questions/1307074/how-do-i-compare-two-lists-for-equality-not-caring.html
What about comparing array contents regardless of order?
You can use the Intersect method. Here is a simple console application
using System;
using System.Linq;
class Program
{
static void Main()
{
var nums1 = new int[] { 2, 4, 6, 8, 10, 9 };
var nums2 = new int[] { 1, 3, 6, 9, 12, 2 };
if (nums1.Intersect(nums2).Any()) // check if there is equal items
{
var equalItems = nums1.Intersect(nums2); // get list of equal items (2, 6, 9)
// ...
}
}
}
Ok this silly problem is connected to the post HERE. What I did is basically removed the return and was able to set the values of the xValues array depending on combobox selection index. as per this pic
But as I try to call another method to divide certain variable with xValues.Length it gives me 'System.DivideByZeroException error as the value for xValues and xValues.Length resets to zero. Here is the code snippet:
int[] xValues = { }; //declaring empty array
private void comboBox1_SelectedValueChanged(object sender, EventArgs e) //using selection
//to set the xValues
{
if (comboBox1.SelectedIndex == 0)
{
int[]xValues= { 1, 2, 3, 4, 5 };
}
else if (comboBox1.SelectedIndex == 1)
{
int[] xValues = { 6, 7, 8, 9, 10 };
}
else if (comboBox1.SelectedIndex == 2)
{
int[] xValues = { 11, 12, 13, 14, 15 };
}
}
And then lets say I'm calling a method doSomeThing()
public void doSomeThing()
{
int bSum = bValues.Sum(); //bValues comes from different input and in debugger
//it shows expected values.
int aSum = xValues.Sum(); //Here the debugger tells me aSum doesn't exists
int slope = bSum / xValues.Length; //Divided by zero exception error goes here.
}
Why and how the the values are resetting for xValues?
waka's answer is right about what's wrong - you're declaring new local variables which are entirely independent of the instance variable.
However, waka's fix isn't quite right - you can only initialize arrays in that particular way at the point of the declaration of the variable. To assign a new value to the variable, you need slightly different syntax:
xValues = new[] { 1, 2, 3, 4, 5 };
Or if you want to specify the element type explicitly:
xValues = new int[] { 1, 2, 3, 4, 5 };
You are not resetting anything. You declare a new int array (as in: a new object) every time the selected value changes! That's why the length of the array in the other method is always 0: Because it's still the global empty int array.
int[] xValues = { }; //declaring empty array
private void comboBox1_SelectedValueChanged(object sender, EventArgs e) //using selection
//to set the xValues
{
if (comboBox1.SelectedIndex == 0)
{
xValues= new int[] { 1, 2, 3, 4, 5 };
}
else if (comboBox1.SelectedIndex == 1)
{
xValues = new int[] { 6, 7, 8, 9, 10 };
}
else if (comboBox1.SelectedIndex == 2)
{
xValues = new int[] { 11, 12, 13, 14, 15 };
}
}
This should do the trick.
Set the length of the xValues array to five if it will always be five. I.e
int[] xValues =new int[5];
Then in your if statements just assign the xValues array the new values i.e.
xValues =new {1,2,3,4,5};
You never told the computer how big the array was. But by saying
int[]xValues xValues =new {1,2,3,4,5}
You are changing the scope for that variable; you are not actually referencing the original xValues array
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am using C# and I have an array that stores 20 integers.
I have 3 variables and I would like to assign them all to randomly-picked integers from the array, but I have to make it so that the values picked from the array are not the same.
Is there any way to do this other than by using a lot of if statements?
This answer is based on ThariqNugrohotomo's suggestion regarding selecting three distinct values from a shuffled array. I implemented a version of Fisher-Yates Shuffle algorithm, which is based on DotNetPerls example. The reason three distinct values are selected after the shuffle is performed is due to the fact that the source array may have repeating values. If we simply shuffle them, then there's a possibility of duplicates.
using System;
using System.Linq;
namespace ShuffleAndTakeUnique
{
public class Program
{
static Random _random = new Random();
static void Main(string[] args)
{
int[] array = { 3, 4, 6, 2, 5, 11, 12, 20, 19, 18, 17, 15, 16, 1, 7, 8, 9, 10, 13, 14 };
var values = Shuffle<int>(array).Distinct().Take(3).ToArray();
foreach(var val in values)
{
Console.WriteLine(val);
}
}
public static T[] Shuffle<T>(T[] source)
{
T[] array = new T[source.Length];
Array.Copy(source, array, source.Length);
var random = _random;
for (int i = array.Length; i > 1; i--)
{
int j = random.Next(i);
T tmp = array[j];
array[j] = array[i - 1];
array[i - 1] = tmp;
}
return array;
}
}
}
Below are older ideas:
Here's a quick and dirty Console Application that stores three unique int values in a List<int>. You may then assign the values from that list to your variables. The list serves as a way to ensure uniqueness of the values. This is just an example, so obviously alter it to your needs and clean it up.
using System;
using System.Collections.Generic;
namespace App
{
class Program
{
static Random random = new Random();
static int[] array = { 3, 4, 6, 2, 5, 11, 12, 20, 19, 18, 17, 15, 16, 1, 7, 8, 9, 10, 13, 14 };
static List<int> results = new List<int>();
static void Main(string[] args)
{
while (results.Count < 3)
{
int num = array[random.Next(array.Length)];
if (!results.Contains(num))
{
results.Add(num);
}
}
foreach(var result in results)
{
Console.WriteLine(result);
}
}
}
}
EDIT:
Here's an example that uses a generic method that will give you back an array of specified length (up to the maximum of the original array) that contains unique values from the original array:
using System;
using System.Collections.Generic;
using System.Linq;
namespace GetUniqueValues
{
class Program
{
static void Main(string[] args)
{
int[] array1 = { 3, 4, 6, 2, 5, 11, 12, 20, 19, 18, 17, 15, 16, 1, 7, 8, 9, 10, 13, 14 };
var values1 = GetUniqueValues<int>(array1, 3);
foreach (var val in values1)
{
Console.WriteLine(val);
}
string[] array2 = { "apple", "orange", "cherry", "melon", "grapefruit", "grapes", "peach", "watermelon" };
var values2 = GetUniqueValues<string>(array2, 4);
foreach (var val in values2)
{
Console.WriteLine(val);
}
}
public static T[] GetUniqueValues<T>(T[] array, int valuesCount)
{
var values = new List<T>();
if (array != null && array.Length > 0 && valuesCount > 0)
{
var distinctCount = array.Distinct().Count();
if (valuesCount > distinctCount)
{
valuesCount = distinctCount;
}
var random = new Random();
while(values.Count < valuesCount)
{
T val = array[random.Next(array.Length)];
if (!values.Contains(val))
{
values.Add(val);
}
}
}
return values.ToArray();
}
}
}
Note that I make sure that the number of distinct values in the array is not less than the requested number of values. Otherwise, we'd be stuck in an infinite loop. If you pass an empty array or a count less than one, it will return an empty array. I prefer that over null... but once again, it's up to you.
Another way is to pass a copy of the original array as a List<T> and remove any occurrence of a value, once it's picked. That way, there is no way you can ever choose it again. Here's a quick, untested draft (I didn't test this at all), but you'll get the idea:
while(values.Count < valuesCount && list.Count > 0)
{
T val = list[random.Next(list.Count)];
values.Add(val);
list.RemoveAll(val);
}
How can I make a Function to compact an array with duplicate entries?
For example!
A function that will take a sorted array of integers and return the array compacted. That is, given an array containing: 1, 2, 6, 8, 8, 8, 9, 10, 10, when the function returns, the contents of the array should be: 1, 2, 6, 8, 9, 10.
This is NOT hw. I am trying to make a function that will do this.
How about:
array = array.Distinct().ToArray();
or, as a function:
private int[] RemoveDuplicates(int[] array)
{
return array.Distinct().ToArray();
}
then call it with:
array = RemoveDuplicates(array);
extension methods:
public static T[] RemoveDuplicates<T>(this T[] array)
{
return array.Distinct().ToArray();
}
public static List<T> RemoveDuplicates<T>(this List<T> list)
{
return list.Distinct().ToList();
}
using for array:
int[] array = new[] {1, 3, 4, 3};
array = array.RemoveDuplicates();
using for list:
List<int> list = new List<int> {1, 3, 4, 3};
list = list.RemoveDuplicates();
The most straightforward way is probably with Linq
array = array.Distinct().ToArray()
However, Linq is not always the fastest approach.
If you do not wish to use Linq, you can do something like this (untested, but close)
List<int> compacted = new List<int>();
// If array is not a local variable:
// Assign to a variable to avoid re-evaluating the property every loop iteration
// Otherwise use array.Length as the loop termination condition to enable array
// bounds check elimination. Thanks #Harold for the insight
// http://blogs.msdn.com/b/clrcodegeneration/archive/2009/08/13/array-bounds-check-elimination-in-the-clr.aspx
int max = array.Length;
int last = 0;
for (int i=0; i < max; i++)
{
if (i == 0)
{
compacted.Add(array[i]);
last = array[i];
}
else
{
if (array[i] != last) compacted.Add(array[i]);
last = array[i];
}
}
array = compacted.ToArray();
I have an array with elemnents in order 1,2,3,4,5 and I would need to reverse it so it will be 5,4,3,2,1.
What about the following pseudo code? Is here not an easier way
EDIT: I Am sorry I thought multidimensional array
someclass [,] temporaryArray=new someclass [ArrayLenght,ArrayLenght];
//for each dimension then
for(int I=0;I<ArrayLenghtOfDimension;I++)
{
temporaryArray[ArrayLenghtOfDimension-I]=Array[I];
}
Array=temporaryArray;
The array base class has a Reverse() extension method built in
int[] originalArray = new int[] { 1, 2, 3, 4, 5 };
int[] reversedArray = originalArray.Reverse().ToArray();
Note that the Reverse method returns IEnumerable, so you need to call ToArray() on the result.
And if you need to just iterate over the elements in the array, then all you need is
foreach (int element in originalArray.Reverse())
Console.WriteLine(element);
Oops - Reverse is on IEnumerable, not Array, so you can use that with any collection.
IEnumerable<int> IEnumerableInt = new List<int>() { 1, 2, 3 };
int[] reversedArray2 = IEnumerableInt.Reverse().ToArray();
Yes there is fast solution exists in .net
int[] values = new int[] { 1, 2, 3, 4, 5 };
Array.Reverse(values);
Your array is reversed. so you can iterate through it
foreach (int i in values)
{
Response.Write(i.ToString());
}
the above code will display
54321
It will also work for string[], char[] or other type of arrays
Event though the Array class has Reverse methods defined:
Array.Reverse(originalArray); // original array is now reversed
If all you need to do is iterate backwards over it do the following:
for(int I= ArrayLength - 1; I >= 0; I--)
{
}
This avoid re-allocating memory for the reversed array.
Array.Reverse is the best way to do this. Do you care about order of the elements at all? If so,then you can do the following.
int[] originalArray = new int[] { 10, 2, 13, 4, 5 };
int[] descOrderedArray = originalArray.OrderByDescending(i => i).ToArray();
int[] ascOrderedArray = originalArray.OrderBy(i => i).ToArray();
For a multi-dimensional array it's the same idea
int[][] multiDimArray = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 } };
int[][] reversedMultiArray = multiDimArray.Reverse().ToArray();
produces an array of two arrays that is: {4, 5, 6}, {1, 2, 3}