Advertisement
JulianJulianov

02.ObjectAndClasses-Randomize Words

Mar 5th, 2020
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.99 KB | None | 0 0
  1. 02.ObjectAndClasses-Randomize Words
  2. You are given a list of words in one line. Randomize their order and print each word at a separate line.
  3. Examples
  4. Input                                                  Output         Comments
  5. Welcome to SoftUni and have fun learning programming   learning     The order of the words in the output will be different after each
  6.                                                        program      execution.
  7.                                                        Welcome
  8.                                                        SoftUni
  9.                                                        and
  10.                                                        fun
  11.                                                        programming
  12.                                                        have
  13.                                                        to  
  14. Hints
  15. • Split the input string by (space) and create an array of words.
  16. • Create a random number generator – an object rnd of type Random.
  17. In a for-loop exchange each number at positions 0, 1, … words.Length-1 by a number at random position. To generate a random number in range use rnd.Next(minValue, maxValue). Note that by definition minValue is inclusive, but maxValue is exclusive.
  18. • Print each word in the array on new line.
  19.  
  20.  
  21. using System;
  22. using System.Collections.Generic;
  23. using System.Linq;
  24. using System.Text;
  25. using System.Threading.Tasks;
  26.  
  27. namespace _02RandomizeWords
  28. {
  29.     class Program
  30.     {
  31.         static void Main(string[] args)
  32.         {
  33.             Random random = new Random();
  34.             string[] input = Console.ReadLine().Split();
  35.             for (int i = 0; i < input.Length - 1; i++)
  36.             {
  37.                 int index = random.Next(0, input.Length);
  38.                 var temporary = input[index];
  39.                 input[index] = input[i];
  40.                 input[i] = temporary;
  41.             }
  42.             Console.WriteLine(string.Join(Environment.NewLine, input));
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement