This question already has answers here:
Randomize a List<T>
(28 answers)
Closed 6 years ago.
i have some list with 5 numbers (exp. 1 2 3 4 5) i want to order them in random ordering each time (page refresh) examples: (2 4 3 1 5) (1 3 5 4 2) (5 1 2 3 4)... code in C#, Thanks
var loadcards = (from card in db.GameCards
select card).Take(5).ToList();
foreach (var item in loadcards)
{
Response.Write("<script>alert('" + item.cardId + "');</script>");
}
Something like this:
int[] RandomizeOrder(int[] input)
{
Random RNG = new Random();
bool[] cellMap = new bool[input.Length];
int[] output = new int[input.Length];
for(int i = 0; i < input.Length; i++)
{
int index = RNG.Next(input.Length)
while(cellMap[index)
index = RNG.Next(input.Length);
cellMap[index] = true;
output[index] = input[i];
}
return output;
}
PS: You can remove the cellMap if none of the values is 0
Related
So, I have this task where I have to find the competitors who won in a tie.
Basically the input is a txt file, which has the number of competitors and the number of competitions in it's first row. The second and third rows are the maximum and minimum points. The rows after the third represent competitors and they have the amount of points they won.
I have to find the number of competitors who if they won, they won in a tie and their indexes.
One input:
6 8
9 9 9 9 9 9 9 9
5 5 5 5 5 5 5 5
8 4 6 6 6 6 6 6
7 5 7 6 6 6 6 5
6 6 6 5 5 5 5 6
8 6 8 7 7 7 7 6
8 6 6 6 6 6 6 6
8 6 6 6 6 6 6 1
The first row is 6 and 8 which means there is 6 competitors and 8 competition, the maximum points are 9 the minimum points are 5.
In this case the output is:
5 1 3 4 5 6
In the first column the winning point is 8, number 1 4 5 and 6 got 8 points which means they tied and should be added to the output, in the second column the winning point is 6, number 3 4 5 6 got 6 points so 3 should be added to the output too, and so on...
I've got this so far:
static void Main(string[] args)
{
string[] fRow = Console.ReadLine().Split(' '); //splitting the first row to get N and M
int N = int.Parse(esor[0]);
int M = int.Parse(esor[1]);
int[] maxPoint = new int[M];
int[] minPoint = new int[M];
string[] maxP = new string[M];
string[] minP = new string[M];
maxP= Console.ReadLine().Split(' ');
minP = Console.ReadLine().Split(' ');
for (int i = 0; i < M; i++)
{
maxPoint[i] = Convert.ToInt32(maxP[i]);
minPoint[i] = Convert.ToInt32(minP[i]);
}
int[,] matrix = new int[N, M];
int[] s = new int[M];
int mCol = 0; int mRow = 0;
for (int i = 0; i < N; i++) //adding the points to the matrix
{
string[] row = Console.ReadLine().Split(' ');
for (int h = 0; h < N; h++)
{
s[h] = Convert.ToInt32(row[h]);
matrix[mCol, mRow] = s[h];
mCol++;
if (mCol==N)
{
mCol = 0;
mRow++;
}
}
}
int max = 0; //trying to find the greatest point in each column
int[] winPoint = new int[M];
for (int i = 0; i < M; i++)
{
for (int h = 0; h < N; h++)
{
if (matrix[i, h] > max)
{
max = matrix[i, h];
}
if (h == N-1)
{
h = 0;
}
}
}
}
And I got stuck here, I'm trying to find the greatest point in each column so they I could search for the same numbers in the colums and count the amount of ties, but I don't know how to do it. If someone could help me I'd really appreciate it, or if I should to it in a different way just tell me.
This question already has answers here:
Is using Random and OrderBy a good shuffle algorithm? [closed]
(13 answers)
Closed 7 years ago.
I need help to create an algorithm to make 9 random numbers. Each number must not be equal to any other. Restated as 9 random numbers from 1-9.
I had something like this in mind:
int[] numlist = new int[9];
Random rand = new Random();
int temp;
foreach (int i in numlist) {
temp = rand.Next(1, 10);
//check if temp is already a value of a lower index in numlist
//if so, rolls another random number and checks it again...
numlist[i] = temp;
}
I had a method that had ifs inside for loops inside while loops inside foreach loops and such...
It sounds to me, like you may be better-off starting with your list of 1..9 - and shuffling it, to get a random order.
Use a Fisher–Yates shuffle
var random = new Random();
int[] array = Enumerable.Range(1, 9).ToArray();
for (int i = array.Length; i > 1; i--)
{
// Pick random element to swap.
int j = random.Next(i); // 0 <= j <= i-1
// Swap.
var tmp = array[j];
array[j] = array[i - 1];
array[i - 1] = tmp;
}
If you know what values you're needing then just OrderBy and it will randomise them.
var numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
var shuffled = numbers.OrderBy(a => System.Guid.NewGuid()).ToArray();
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
using System;
using System.IO;
namespace Sudoku
{
class Game
{
private int[,] puzzle = new int[9, 9];
public void saveToFile()
{
StreamWriter str = new StreamWriter("SUDOKU.txt");
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
str.Write(puzzle[i, j] + " ");
}
str.Write("\t\n");
}
str.Close();
}
public void readFromFile()
{
clear();
StreamReader str = new StreamReader("SUDOKU.txt");
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
puzzle[i, j] = Convert.ToInt32(str.Read());
}
}
str.Close();
}
}
}
I can not download the data from the file.
Saving works fine and has a view of the txt file:
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 2 9 7 8
6 4 2 9 7 8 5 3 1
9 7 8 5 3 1 6 4 2
How it all written in my array 9x9 skipping all the gaps that would be all the data is written correctly?
Instead of using str.Read() which would require you to read single characters (or a buffer that you specified), try using str.Readline() to read a single line for each iteration of i.
public void readFromFile()
{
StreamReader str = new StreamReader("SUDOKU.txt");
for (int i = 0; i < 9; ++i)
{
string[] lineNumbers = str.ReadLine().Split(' ');
for (int j = 0; j < 9; ++j)
{
puzzle[i, j] = Convert.ToInt32(lineNumbers[j]);
}
}
str.Close();
}
This reads a single line at a time (each iteration of i), splits the line into lineNumbers by separating the current line by space characters. Each number on the current line can then be accessed by lineNumbers[j] within your inner loop (each iteration of j).
This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 7 years ago.
I want to know if there is a way in C# to convert an integer to an array of digits so that I can perform (Mathematical) operations on each digit alone.
Example: I need the user to input an integer i.e 123, 456
then the program creates two arrays of three elements {1,2,3}, {4,5,6}.
Off the top of my head:
int i = 123;
var digits = i.ToString().Select(t=>int.Parse(t.ToString())).ToArray();
You could create such array (or List) avoiding string operations as follows:
int x = 123;
List<int> digits = new List<int>();
while(x > 0)
{
int digit;
x = Math.DivRem(x, 10, out digit);
digits.Add(digit);
}
digits.Reverse();
Alternative without using the List and the List.Reverse:
int x = 456;
int[] digits = new int[1 + (int)Math.Log10(x)];
for (int i = digits.Length - 1; i >= 0; i--)
{
int digit;
x = Math.DivRem(x, 10, out digit);
digits[i] = digit;
}
And one more way using ToString:
int x = 123;
int[] digits = Array.ConvertAll(x.ToString("0").ToCharArray(), ch => ch - '0');
You can use this and not convert to a string:
var digits = new List<int>();
var integer = 123456;
while (integer > 0)
{
digits.Add(integer % 10);
integer /= 10;
}
digits.Reverse();
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Count Frequency in a Randomly Generated List of Numbers
I am currently working with arrays and random numbers. I have a created a form that will let me generate random numbers from 1 - 20 with a textbox1 to choose the quantity of numbers displayed. I am displaying the results inside a multiline textbox2. I have been able to calculate the sum and average of the set of numbers generated.
My second step:
Is there away to tally or mark the times a number is generated and display it in the multiline textbox(last picture)? Would I need to create an array and make it full of zero?
private void button1_Click(object sender, EventArgs e)
{
int n = Convert.ToInt32(textBox1.Text);
int[] y = new int[n];
double sum = 0;
for (int i = 0; i < n; i++)
{
int x = 1 + r.Next(20);
y[i] = x;
sum += x;
if (n < 101)
textBox2.AppendText(x + " ");
}
double avg = sum / n;
textBox2.AppendText(Environment.NewLine + sum + " " + avg + Environment.NewLine);
double vsum = 0;
for (int i = 0; i < n; i++)
vsum += (y[i] - avg) * (y[i] - avg);
}
Form.cs
Count the times an integer is randomly selected
"Would I need to create an array and make it full of zero?"
Yes, that would be a good start.
Have an array of counters (all initially zero) and count up the number of occurrences for each number as it appears.
Here's the code that can do what you want:
var r = new Random();
var n = int.Parse(this.textBox1.Text);
var y =
Enumerable
.Range(0, n)
.Select(x => r.Next(20) + 1)
.ToArray();
var sum = y.Sum();
var avg = (double)sum / (double)n;
var frequency = y.ToLookup(x => x);
textBox2.Text = String.Join(Environment.NewLine, new[]
{
"Results",
String.Format("{0} {1}", sum, avg),
}.Concat(Enumerable
.Range(1, 20)
.Select(x => String.Format("{0} ({1}x)", x, frequency[x].Count()))));
Running this with a value of 25 I got this result:
Results
278 11.12
1 (0x)
2 (2x)
3 (1x)
4 (1x)
5 (1x)
6 (2x)
7 (0x)
8 (1x)
9 (2x)
10 (4x)
11 (1x)
12 (0x)
13 (0x)
14 (0x)
15 (2x)
16 (1x)
17 (2x)
18 (2x)
19 (3x)
20 (0x)
Is that what you're after?
You can add a Dictionary<int, int> counter that counts. Insert those lines after int x = ...
if (counter.ContainsKey(x))
counter[x]++;
else
counter.Add(x, 1);
After that the dictionary holds one key value pair for each distinct random number you have created and the number of time it has been created. You could also use the dictionary to replace the y array altogether.
You could also do a
Dictionary<int,int>
store the number in question as the key (the first int)
store the number of times generated as the value (the second int).
Dictionary<int,int> numbers = new Dictionary<int,int>();
//initialize dictionary
for (int i = 1; i < 21; i++)
{
numbers.Add(i,0);
}
//this only covers generating number and adding to dictionary
Random random = new Random();
int nextNum = random.NextInt(1,20);
numbers[nextNum]++;
References:
http://www.dotnetperls.com/keyvaluepair
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx