2015-08-03 2 views
-3

Я хотел, чтобы эта программа печатала случайные числа (1-6) в столбцах навсегда, пока все строки каждого столбца не имеют одинаковое число. Если пользователь вводит 5 для примера, он будет распечатывать 5 столбцов случайных чисел (1-6), пока каждая строка из этих 5 столбцов не станет одинаковой. Я застрял, я не знаю, как проверить все элементы массива, независимо от того, все они одинаковы друг с другом.Как проверить, имеет ли массив одинаковое число

namespace Dice_Roll_2._0 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int userinput = Convert.ToInt16(Console.ReadLine()); 
      Random Dice = new Random(); 
      bool search = true; 

      while (search) 
      { 
       var output = string.Empty; 
       int[] numberofdice = new int[userinput+1]; 

       for (int i = 1; i <=userinput; i++) 
       { 
        numberofdice[i] = Dice.Next(1, 7); 
        output += numberofdice[i]; 
        if (i < userinput) 
        { 
         output += "\0"; 

        } 

        if (numberofdice[i-1] == numberofdice[i]) 
        { 
         search = false; 
        } 

       } 
       Console.WriteLine(output); 

      } 
      Console.ReadLine(); 
     } 
    } 
} 

ответ

0

Массив индексация должна начинаться с 0. Для того, чтобы проверить, что все элементы одинаковы, вы можете использовать цикл для сравнения каждого элемента с первым.

static void Main(string[] args) 
{ 
    int userinput = Convert.ToInt16(Console.ReadLine()); 
    Random Dice = new Random(); 
    int[] numberofdice = new int[userinput + 1]; 

    while(true) 
    { 
     var output = string.Empty; 

     // Generate the userinput random numbers 
     // as well as output string 
     for(int i = 0; i < userinput; i++) 
     { 
      numberofdice[i] = Dice.Next(1, 7); 
      output += numberofdice[i]; 
     } 
     Console.WriteLine(output); 

     // Check that they are all same by comparing with first 
     bool same = true; 
     int first = numberofdice[0]; 
     for(int i = 1; i < userinput; i++) 
     { 
      if(numberofdice[i] != first) 
      { 
       same = false; 
       break; 
      } 
     } 

     // If all were the same, stop. 
     if(same) 
      break; 
    } 
} 
3

С Linq пространства имен, вы можете сделать Distinct() в массиве столбцов и когда Count() из Distinct() равен 1, то все столбцы одинаковы, и вы можете остановить прокатки.

using System; 
using System.Linq; 

public class Program 
{ 
    public static void Main() 
    { 
     Console.Write("Enter number of columns: "); 
     int userinput = Convert.ToInt16(Console.ReadLine()); 
     int[] columns = new int[userinput]; 

     Random Dice = new Random(); 
     bool search = true; 

     DateTime start = DateTime.Now; 
     while (search) 
     { 
      for (int i = 0; i < columns.Length; i++) 
      { 
       columns[i] = Dice.Next(1, 7); 
      } 

      if (columns.Distinct().Count() == 1) 
      { 
       Console.WriteLine("All columns match with the value of {0}", columns[0]); 
       Console.WriteLine("It took {0} to get all columns to match", DateTime.Now.Subtract(start)); 
       search = false; 
      } 
     } 
    } 
} 

Результатов (Временный диапазон и значение будут варьироваться в зависимости от каждого прогона):

Enter number of columns: 5 
All columns match with the value of 4 
It took 00:00:00.0156260 to get all columns to match 

Fiddle Demo ограниченно 7 столбцов.

Смежные вопросы