我希望这个程序永远打印出列中的随机数(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 :(得分:3)
使用Linq
命名空间,您可以在列数组上执行Distinct()
,当Count()
的{{1}}等于1时,所有列都是同样,你可以停止滚动。
Distinct()
结果(每次运行的时间跨度和值会有所不同):
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;
}
}
}
}
Fiddle Demo限制为7列。
答案 1 :(得分: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;
}
}