Array value resets automatically - c#

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

Related

Unity how to compare contents of two arrays regardless of order?

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)
// ...
}
}
}

reversing an array using methods and MessageBox.show

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);

Return the sorted array [duplicate]

This question already has answers here:
Fastest way to check if an array is sorted
(9 answers)
Closed 5 years ago.
Imagine i get two arrays as input, one of which is already sorted. I want to create a method which checks which array that is sorted and then returns it. Im not really sure how to do this
class Program
{
public double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
public double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
public void CheckSorting()
{
if (/* if a is sorted */)
{
return a;
}
else { /* This should be OK because if A isnt sorted then b MUST be sorted since of the arrays are always sorted in my input */
return b;
}
}
static void Main(string[] args)
{
Program checkSorting = new Program();
checkSorting.CheckSorting();
}
}
In this case, as you can see the array A should be returned as the sorted one
just.... loop over one of the arrays in a forwards direction; if the value ever goes down, that array isn't sorted
for(int i = 1 ; i < a.Length ; i++)
{
if(a[i] < a[i-1]) return b;
}
return a;
private double[] ArraySort()
{
double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
var isOrderedAscending = a.SequenceEqual(a.OrderBy(x => x));
if (isOrderedAscending)
return a;
else
return b;
}
this method might help you,
but what has to be achieved if both or not ordered ?

Load random scenes without repetition using c#

I want to load scenes randomly without repetition using c#. Any help would do.
Thanks.
int[] array = new int[] { 1, 2, 3, 4, 6, 8, 9, 10, 11, 12 };
List<int> list = new List<int>();
void Start()
{
list.AddRange(array);
}
int GetUniqueRandom(bool RemoveFromTheList)
{
if (list.Count == 0)
{
if (RemoveFromTheList)
{
list.AddRange(array);
}
else
{
return -1; // never repeat
}
}
int rand = Random.Range(0, 10);
int value = list[rand];
list.RemoveAt(rand); return value;
}
A nice clean way is to shuffle the array, then put all the elements in a stack. All you need to get a random element is to pop an item off the stack.
You will want to remove the list in the list of fields and replace with this;
Stack remainingScenes = new Stack();
Remove the content of the Start() method - you don't need it.
In your method to get a new number;
if (remainingScenes.Count == 0) {
int n = array.Length;
while (n > 1)
{
int k = rng.Next(n--);
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
foreach(var element in array) {
remainingScenes.Push(element);
}
}
return remainingScenes.Pop();
The shuffle method is from here.
Uhmmm, this looks very straightforward. Judging from your code, you only need a little modification to make it work..
List<int> list = new List<int>() { 1, 2, 3, 4, 6, 8, 9, 10, 11, 12 };
int GetUniqueRandom(bool RemoveFromTheList)
{
if (list.Count == 0)
{
return -1;//nothing in the list so return negative value
}
//generate random index from list
int randIndex = Random.Range(0, list.Count - 1);
int value = list[rand];
if(RemoveFromTheList)
{
list.RemoveAt(randIndex);
}
return value;
}
Try this:
int[] array = new int[] { 1, 2, 3, 4, 6, 8, 9, 10, 11, 12 };
Stack<int> stack = null;
Then initialize like this:
var rnd = new Random();
stack = new Stack<int>(array.OrderBy(x => rnd.Next()));
Now you just keep getting values from the stack until it is empty:
var value = stack.Pop();

How do I pick values from an array without having repeating values in C# [closed]

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);
}

Categories

Resources