2011-12-26 3 views
1

이 간단한 알고리즘을 만들었지 만 Chrome은 이상하게 작동합니다. 재귀 적으로 호출되는 함수가 돌아 오지 않습니다 ... 알고리즘의 임무는 rs 배열의 모든 가능성을 순환 시키며, 0 또는 1.JS의이 재귀 알고리즘이 작동하지 않는 이유는 무엇입니까?

//rs is the list of all variables that can be 0 or 1 
//cS, or currentStack is the variable that s 

rs = [0, 0, 0]; 

circ = function(cS) 
{ 
    for (pos = 0; pos <= 1; pos ++) 
    { 
      rs[cS] = pos; 
      if (cS + 1 < rs.length) 
       circ(cS + 1); 
    } 
    return 0;      
} 

circ(0); //this should cycle trough all the possibilities of the rs array, it should look like this: 
/* 
000 - first element of rs, not last, so continue to the next 
000 - second element of rs, not last, so continue to the next 
000 - third element of rs, last, so continue with the for loop 
001 - the for loop ends, return to the second element 
011 - second element of rs, not last, so continue to the next 
010 - third element of rs, last, so continue with the for loop 
011 - the for loop ends, return to the first element 
111 - first element of rs, not last, so continue to the next 
101 - second element of rs, not last, so continue to the next 
100 - third element of rs, last, so continue with the for loop 
101 - the for loop ends, return to the second element 
111 - second element of rs, not last, so continue to the next 
110 - third element of rs, last, so continue with the for loop 
111 - the for loop ends, return to the second element 
111 - the for loop ends, return to the first element 
111 - return 
*/ 

그러나, 단순히 다음과 같이 진행됩니다

000 
000 
000 
001 
return 

사람이 일어나는 이유를 말씀해 주시겠습니까? 나는 무엇을 잘못 했는가?

+0

무엇을 갖고 싶습니까? 매회 'rs'의 요소를 덮어 쓰는 것입니다. – pimvdb

+0

복제 가능한 [자바 스크립트 재귀 요소 작성 실패] (http://stackoverflow.com/questions/5333572/javascript-recursive-element-creation-fails) – outis

+0

이것은 가능한 조합을 순환하는 정말 이상한 방법입니다. 중첩 된 for 루프는 훨씬 더 읽기 쉬운 방법으로 트릭을 수행합니까? 코드 끝에있는 주석의 원하는 출력조차도 반복되는 값이 많기 때문에 약간 이상하게 보입니다. 반환을 전혀 사용하지 않으면 함수가 0을 반환하는 이유는 무엇입니까? – nnnnnn

답변

6

"pos"를 var으로 지정하는 것을 잊었습니다. 당신이 var 잊었 때문에

var circ = function(cS) 
{ 
    for (var pos = 0; pos <= 1; pos ++) 
    { 
      rs[cS] = pos; 
      if (cS + 1 < rs.length) 
       circ(cS + 1); 
    } 
    return 0;      
} 

는 "POS는"글로벌 있었다, 그래서 recusive 전화는 엉망 부모 환경을 것입니다.

여기서만 문제가 있다고 보장 할 수는 없습니다. 예를 들어 작성된 함수에서 모든 순열을 반복 할 수는 있지만 어디에도 복사하거나 복사하지 않으므로 결과는 [1, 1, 1]이됩니다.

+0

답변 해 주셔서 감사합니다! 이전에는 전역 범위에 어려움이 있었고 var 키워드로 변수를 선언하지 않았습니다 ... 함수 (var cS)도 사용해야합니까? C++에서와 같이, funtion의 argument를 초기화해야합니다. 오 그래, 그리고 이것은 단순화 된 버전입니다. 실제 하나는 이러한 순열을 사용하고 0과 1은 아니지만 다른 숫자들도 마찬가지입니다. – corazza

+1

아니요, JavaScript는 매개 변수에 키워드를 요구하지 않습니다. 당신이 JS로 막 시작했다면, 좋은 소개는 Eloquent JavaScript라는 무료 책이다. http://eloquentjavascript.net/ – juandopazo

+1

@bane 매개 변수는 * 항상 * 지역 변수와 같다. * 로컬 변수와 유사). – Pointy

관련 문제