Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- /// <summary>
- /// Write a program that enters in integer n and prints the numbers 1, 2, …, n
- /// in random order.
- /// </summary>
- public class RandomizeTheNumbers
- {
- public static void CreateArray(int n)
- {
- int[] numbers = new int[n];
- // Fill up 'numbers' array
- for (int i = 0; i < n; i++)
- {
- numbers[i] = i + 1;
- }
- Shuffle(numbers);
- // Print out the shuffled array
- for (int i = 0; i < n; i++)
- {
- Console.Write(numbers[i] + " ");
- }
- }
- public static void Shuffle<T>(T[] array) // Fisher-Yates Shuffle
- {
- Random rng = new Random();
- var random = rng;
- for (int i = array.Length; i > 1; i--)
- {
- // Pick random element to swap.
- int j = random.Next(i); // 0 <= j <= i-1
- // Swap.
- T tmp = array[j];
- array[j] = array[i - 1];
- array[i - 1] = tmp;
- }
- }
- static void Main()
- {
- Console.WriteLine("Give me a integer n and I will give you you ther integer 1 - n in random order.");
- Console.Write("n = ");
- int n = int.Parse(Console.ReadLine());
- CreateArray(n);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement