gpt4 book ai didi

javascript - 数组未定义 - Codewars Kata 循环赛

转载 作者:行者123 更新时间:2023-11-30 19:02:52 32 4
gpt4 key购买 nike

我正在尝试做这个套路 - https://www.codewars.com/kata/organize-a-round-robin-tournament/train/javascript .

任务是创建一个组织循环赛的函数。

例子:

buildMatchesTable(4)

应返回如下矩阵:

[
[[1,2], [3, 4]], // first round: 1 vs 2, 3 vs 4
[[1,3], [2, 4]], // second round: 1 vs 3, 2 vs 4
[[1,4], [2, 3]] // third round: 1 vs 4, 2 vs 3
]

我已经创建了一个非常笨拙的解决方案,直到最后一个障碍。我留下了一个数组 (arr6),它是一个以正确顺序列出所有比赛的数组,但作为一个简单的数组,而不是指定各个回合的子数组。所以我尝试创建一个函数 cut 来生成一个格式正确的数组,它告诉我 arr7 没有定义。

我的解决方案写得不好,因为我是新手,但我认为修复应该相对简单,与函数中未正确返回值或函数调用顺序错误有关。谢谢。

function buildMatchesTable(numberOfTeams) {
let n = numberOfTeams; let h = n/2; let arr = []; let arr2 = [[],[]];
let arr3 = [...Array(n-1)].map(v => v); let arr4 = [];
//create array
for (var i = 1; i <= n; i++) {arr.push(i)} //[1, 2, 3, 4]
//split array
arr2[0] = arr.splice(0, arr.length/2);
arr2[1] = arr.splice(0, arr.length); //[[1, 2], [3, 4]]

//create a function that produces matches in a round from array[i]
function round (arr2) {
for (var i = 0; i < arr2[0].length; i++){
arr4.push([arr2[0][i], arr2[1][i]]);
}
arr2 = arr4;
return arr2; // [[1 v 3], [2 v 4]] etc.
}
//create a function that tranforms the arr to gameweek +1 (rotate everything clockwise apart from team 1
function trans(arr2){
//create new arr5 that is the same as arr2
arr5 = [[],[]];
for (var i = 0; i < arr2[0].length; i++) {
arr5[0].push(arr2[0][i])
arr5[1].push(arr2[1][i])
}

//rotate every element apart from arr2[0,0] : [[1, 3], [4, 2]]
let h = arr2[0].length - 1;
arr2[0][1] = arr5[1][0];
arr2[1][h] = arr5[0][h];
for (var i = 2; i <= h; i++){
arr2[0][i] = arr5[0][i-1];}
for (var i = 0; i <= h-1; i++){
arr2[1][i] = arr5[1][i+1];}
return arr2;
}

function final (n, arr2, arr3){ //putting all the functions together
for (var i = 0; i < n-1; i++){
arr3[i] = (round(arr2));
trans(arr2);
}
return arr3; // [[1, 3], [2, 4, [1, 4], [3, 2], [1, 2], [4, 3]] X 3
}

final(n, arr2, arr3)
let arr6 = arr3[0]; // arr6 = [[1, 3], [2, 4, [1, 4], [3, 2], [1, 2], [4, 3]]

function cut(arr6, n) {
let arr7 = [];
let index = 0;
while (index < arr6.length) {
arr7.push(arr6.slice(index, n/2+index));
index += n/2;
}
return arr7;
}

cut(arr6, n);

console.log(n);
console.log(arr);
console.log(arr2);
console.log(arr3[0]);
console.log(arr4);
console.log(arr6);
console.log(arr7);//not working!
//return arr7
}
buildMatchesTable(6)

最佳答案

难怪,您要在函数内部声明 let arr7 = [];。把它从函数中取出来,和arr6、arr4等同级

关于javascript - 数组未定义 - Codewars Kata 循环赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321626/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com