Click here to Skip to main content
15,867,834 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to create a list of 16 numbers from 1 to 16 in random order. Is it possible to do this in an array? What would be the best way to do this?


using System;

class Program
{
static void Main()
{
string[] arr = new string[]
{
"1"
"2"
"3"
"4"
"5"
"6"
"7"
"8"
"9"
"10"
"11"
"12"
"13"
"14"
"15"
"16"
};
string[] shuffle = RandomStringArrayTool.RandomizeStrings(arr);
foreach (string s in shuffle)
{
Console.WriteLine(s);
}
}


I get an error that the RandomStringArrayTool doesn't exist in this context
Posted
Updated 7-May-14 6:06am
v3
Comments
Maciej Los 7-May-14 11:28am    
What have you done till now? Where are you stuck?
Member 10313138 7-May-14 12:29pm    
using System;

class Program
{
static void Main()
{
string[] arr = new string[]
{
"1"
"2"
"3"
"4"
"5"
"6"
"7"
"8"
"9"
"10"
"11"
"12"
"13"
"14"
"15"
"16"
};
string[] shuffle = RandomStringArrayTool.RandomizeStrings(arr);
foreach (string s in shuffle)
{
Console.WriteLine(s);
}
}

I get an error that the RandomStringArrayTool doesn't exist in this context
CHill60 7-May-14 12:41pm    
Well you put it in there! Why?
CHill60 7-May-14 12:45pm    
You need to implement (and instantiate) that class http://www.dotnetperls.com/shuffle[^]. This is probably a bit beyond where you have got up to, just take the advice given in the solutions below

This is homework (I know this because it is a regular question in many forums)

Homework is set for a reason - to help YOU learn, so just giving you the answer would be counter-productive.

The key thing here is not to think about generating random numbers between 1 and 16 but to randomise the order that the numbers 1 to 16 appear in the array.

So for example, you could put all of the numbers into an array and then swap them around several times based on a pair of random numbers
 
Share this answer
 
Comments
Maciej Los 7-May-14 11:30am    
Exactly!
+5!
Please, read my comment to the question and solution2 too.

To randomly generate numbers use: Random Class[^].

Try!
 
Share this answer
 
Comments
CHill60 7-May-14 11:32am    
Yes ... good link for OP to research! 5.
Maciej Los 7-May-14 11:37am    
Thank you, CHill60 ;)
Like this. Based on http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp[^]

static void Main(string[] args)
{
	List<int> numbers = new List<int>();

	for(int i = 0; i < 16; i++)
	{
		numbers.Add(i);
	}

	Shuffle(numbers);
}

public static void Shuffle<T>(IList<T> list)
{
	Random rng = new Random();
	int n = list.Count;
	while (n > 1)
	{
		n--;
		int k = rng.Next(n + 1);
		T value = list[k];
		list[k] = list[n];
		list[n] = value;
	}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900