我正在尝试制作一个Secret Santa代码,以便在运行该程序时,它将从数组中获取所有名称并将它们配对。
我已经尝试了多种方法来执行此操作,但是最终只是在输出中重复了一个条目。例如:
弗雷德和莎拉
Yusef和Kyle
萨拉和弗雷德
萨拉(Sarah)来了两次,这不好。 这是开始代码,我当然首先将数组随机化,但是不知道在那之后该怎么做。
int main() {
int i = 0, j, n = 10;
loop:
for (j = 0; j <= n; j++) {
putchar(j++ >= n - 1 ? '#' : ' ');
}
puts("");
if (i++ < n) goto loop;
return 0;
}
任何想法,任何人都可以帮忙吗?
我也尝试过这种方法,我认为这可以解决问题,但是它返回索引超出数组范围的错误
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp27
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
String[] students = {"Fred","Mary","Yusef","Kyle","Sophie", "Lydia", "Max", "Donald","Yasmin","Archie"};
string[] shuffleStudents = students.OrderBy(x => random.Next()).ToArray();
}
}
}
}
答案 0 :(得分:1)
您可以尝试将它们洗牌,然后打印结果。这是我做的代码:
using System;
using System.Linq;
namespace _05_01_19_5am
{
class Program
{
public static void Main()
{
Random random = new Random();
String[] students = { "Fred", "Mary", "Yusef", "Kyle", "Sophie", "Lydia", "Max", "Donald", "Yasmin", "Archie" };
var shuffleThem = students.OrderBy(s => Guid.NewGuid()).ToArray();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(shuffleThem[i] + " + " + shuffleThem[i+5]);
}
}
}
}
答案 1 :(得分:0)
摆弄一些东西,找到了解决方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp27
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
string[] students = { "Fred", "Mary", "Yusef", "Kyle", "Sophie", "Lydia", "Max", "Donald", "Yasmin", "Archie"};
string[] shuffleStudents = students.OrderBy(x => random.Next()).ToArray();
Console.WriteLine("Your pairs for Secret Santa has been completed!");
int count = 0;
for (int j = 0; j < 5; j++)
{
Console.Write("{0} and {1} \n", shuffleStudents[count], shuffleStudents[count+1]);
for (int i = 0; i < 2; i++)
{
count++;
}
}
Console.Read();
}
}
}