秘密圣诞老人应用程序添加条件的问题



我正在为我的圣诞派对制作秘密圣诞老人应用程序。

目前它可以工作,但我需要添加一些条件。

function App() {
var names = ["John", "Martha", "Adam", "Jane", "Michael"];
const shuffle = (arr: string[]) => {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
};
const randomNames = shuffle(names);
const matches = randomNames.map((name, index) => {
return {
santa: name,
receiver: randomNames[index + 1] || randomNames[0],
};
});

return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Secret santa game</p>
<select>
<option>Select your name...</option>
{names.map((name) => (
<option> {name}</option>
))}
</select>
<div>
{matches.map((match) => {
return (
<div>
{match.receiver},{match.santa}
<br />
</div>
);
})}
</div>
</header>
</div>
);
}
export default App;

约翰和玛莎是夫妻,所以他们无论如何都会在聚会之外给自己买礼物,所以如果他们中的一个是接收者,另一个是圣诞老人,我想再次生成结果,这样他们就会被分配给其他人。

我不知道怎样才能完成这件事。

你可以这样定义你的关系:

const couples = { John: "Martha" };

则有一个函数来验证条件是否满足:

const conditions_check = (santa: string, receiver: string) => {
if (couples[santa] === receiver) {
return false;
} else if (couples[receiver] === santa) {
return false;
}
return true;
};

然后最后你可以检查你的条件是否满足,同时生成你的匹配和洗牌你的名字池如果需要的话:

let matches = randomNames.map((name, index) => {
let receiver = randomNames[(index + 1) % randomNames.length];
for (let i = 0; i < 25; i++) {
if (conditions_check(name, receiver)) {
break;
}
randomNames = shuffle(names);
}
return {
santa: name,
receiver: receiver
};
});

你可以在这里查看整个实现。

最新更新