2016-09-24 5 views
0

내 Javscript 기능이 브라우저를 계속 충돌시킵니다. 그것이 충돌 할 때가 거의 없지만, 당신은 그 때가 있습니다. 파이어 버그를 사용하면 모든 것을 망가 뜨리는 while 회 돌이처럼 보입니다. 누구든지 어떤 생각을 가지고 있습니까? 우선While 루프가 브라우저를 닫습니다.

function generateTeams(pos = 0) { 
    // Array of ID's 
    var currentTeams = []; 
    // 2D array with matches and teamIds 
    var matches = []; 

    $.each($teamList, function() { 
    // Push integer into a new array 
    if (this.position >= pos) currentTeams.push(this.id); 
    }); 

    // NumberOfTeams is ALWAYS even numbers, and can be divided by 2 
    var numberOfTeams = currentTeams.length; 
    var numberOfMatches = numberOfTeams/2; 

    if ((numberOfTeams > 2) && (numberOfTeams % 2 == 0)) { 
    var currentCount = numberOfTeams; 

    for (var i = 0; i < numberOfMatches; i++) { 
     var numOne = Math.floor(Math.random() * currentCount); 
     var numTwo = Math.floor(Math.random() * currentCount); 

     // Checks if the numbers are the same, or if two spesific teams is against each-other. 
     while ((numOne == numTwo) || (currentTeams[numOne] == 1 && currentTeams[numTwo] == 3) || (currentTeams[numOne] == 3 && currentTeams[numTwo] == 1)) { 
     numTwo = Math.floor(Math.random() * currentCount); 
     } 

     // Creates a match-array with the two team ID's 
     matches.push([parseInt(currentTeams[numOne]), parseInt(currentTeams[numTwo])]); 

     // Simple way to remove them from the start-array. 
     if (numOne > numTwo) { 
     currentTeams.splice(numOne, 1); 
     currentTeams.splice(numTwo, 1); 
     } else { 
     currentTeams.splice(numTwo, 1); 
     currentTeams.splice(numOne, 1); 
     } 

     currentCount -= 2; 
    } // End for-loop 
    } else { 
    matches.push([parseInt(currentTeams[0]), parseInt(currentTeams[1])]); 
    } // End if 

    currentMatches = matches; 
} // End generateTeams 
+1

while 루프의 맨 위에있는 조건은 루프 내부에서 아무런 문제없이 유지된다는 것을 의미합니다. 관련된 값을 추적하기 위해'console.log()'호출을 추가 할 수 있습니다. – Pointy

답변

2

그것은이다는 좋은 생각이 아닌 결정적 런타임과 같은 while 루프를 가지고있다. 통계적으로는 수시로 끝내기까지 매우 오랜 시간이 걸릴 수 있습니다.

또한 완료 할 수없는 조건이 있습니다. 팀 1과 팀 3이 끝까지 머물러 있으면 종료 할 수 없습니다. 팀 수가 너무 많으므로 자주 발생합니다.

운 좋게도 주어진 문제의 구제를 위해 while 루프가 필요하지 않습니다. for 루프에서 먼저 일치하는 첫 번째 팀을 선택하고 currentTeams에서이를 제거한 다음 나머지 두 번째 팀에서 두 번째. 그런 식으로 동일한 팀을 두 번 선택하는 것은 불가능합니다.

두 팀의 상태가 정말 필요한 경우 : 먼저 currentTeams에서 제거하십시오. 그런 다음 상대방을 선택하여 첫 번째 경기를 만듭니다. 그런 다음 두 번째 특별 팀을 목록에 다시 넣고 이전에 설명한대로 나머지 경기를 결정합니다.

+0

감사합니다. 처음에는 팀 중 하나에 대해 일치 항목을 선택한 다음 다른 모든 항목과 함께 배열에서 제거하려고합니다. – H0wie12