Answer the question
In order to leave comments, you need to log in
The algorithm for arranging the positions of numbers in the game "15" - displays -1. Where is the mistake?
in startGameButton_Click everything -1 is displayed. I still haven't noticed what's wrong.
How to determine if randomly came up with the same number, I don’t know how else, except for brute force. Why does it exit the loop. He must iterate over it until the random number returns a number that is different from the numbers that were already there.
private void startGameButton_Click(object sender, EventArgs e)
{
int[] t_numbers;
MessageBox.Show("Game started...");
GetRandomLocate(out t_numbers);
string str = "";
foreach (var t in t_numbers)
str += t.ToString() + " ";
MessageBox.Show(str);
}
private void GetRandomLocate(out int[] t_numbers)
{
Random random = new Random();
bool flag = true;
t_numbers = new int[Logic.size];
for (int i = 0; i < Logic.size; i++)
t_numbers[i] = -1;
for(int i = 0;i<Logic.size;i++)
{
while(flag)
{
int rnd = random.Next(0, Logic.size + 1);
int ind = 0;
foreach (var t in t_numbers)
if (t == rnd)
ind = 1;
if (ind == 0)
{
t_numbers[i] = rnd;
flag = !flag;
}
else
flag = true;
}
}
}
Answer the question
In order to leave comments, you need to log in
1. Generate an array from 1 to 15.
2. Shuffle it
3. Take any of the array and delete (queue or stack mode - it doesn't matter).
The most normal way to mix is to take an ordinal element in a loop in a ready-made array and swap it with a random one. Why do you need a smut with a double cycle?
var rnd = new Random();
var arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ];
for(var i; i < arr.Length; i++)
{
var newPosition = rnd.Next(arr.Length);
var temp = arr[newPosition];
arr[newPosition] = arr[i];
arr[i] = temp;
}
The way you control the uniqueness of the numbers on the button is far from optimal. Imagine how many iterations it takes to randomize the number 24 if you already have numbers from 0 to 23 (for a 5x5 field); The chance is 1/25, which means that on average it will take 25 iterations. It's not much, but it's not optimal.
What I suggest: create a List, put n numbers in there (from 0 to n). And then use the following code:
t_numbers = new int[Logic.size];
List<int> numbers = new List<int>();
int randomIndex = -1;
for (int i = 0; i < Logic.size; i++)
numbers.Add(i);
int i = 0;
do
{
randomIndex = random.Next(0, numbers.Count);
t_numbers[i++] = numbers[randomIndex];
numbers.RemoveAt(randomIndex);
} while(numbers.Count > 0);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question