2016-11-16 3 views
0

나는 인수로 전달 된 배열 간의 대칭 차이를 계산하는 함수를 만들었습니다. 나는 2 개의 배열을 위해 그것을했고 그것은 효과가 있었다. 문제는 이제 함수를 n 개의 변수로 확장하려고합니다. arguments.length가 2와 같으면 symm의 차이를 계산해야한다고 생각합니다. 그렇지 않으면 다른 요소와 처음 두 요소 사이의 symm diff를 계산하는 재귀 함수를 호출해야합니다. 나는 몰라, 나는 매우 혼란 스럽다.대칭 차이에 대한 재귀 함수

function sym(args) { 

    var arr=[].slice.call(arguments); 
    var cnts={}; 
    var result=[]; 

    if(arguments.length==2){ 

    arr=arguments[0].concat(arguments[1]); 
    console.log(arr); 
    for(var number in arr){ 

     if(cnts.hasOwnProperty(arr[number])){ 

     ++cnts[arr[number]].cnt; 

     } 

     else cnts[arr[number]]={cnt:1,val:arr[number]}; 

    } 

    for(var counts in cnts){ 

     if(cnts[counts].cnt===1) result.push(cnts[counts].val); 

     } 

    } 

    else{ 

     var first=arguments[0]; 
     var nextDiff=function(next){ 

     return ...........?????????; 

     }; 

    } 

    return result; 
} 

sym([1, 2, 5], [2, 3, 5], [3, 4, 5]); 
+0

([자바 스크립트를 사용하여 대칭 차를 해결하기 위해 노력] 가능 중복 http://stackoverflow.com/questions/30834946/trying-to-solve-symmetric-difference-using-javascript) –

답변

2

여기에는 두 가지 중요한 정보가 있습니다. 첫 번째는 우리가 가지고있는 것입니다

sym_diff(A1, A2, ..., An) === sym_diff(sym_diff(A1, A2), A3, ..., An) 

이것은 대칭적인 차이가 연관되어 있으며 우리가 재귀 할 수 있다는 사실에서 따릅니다.

두번째

sym_diff(A, B) === diff(A, B) ++ diff(B, A) 

++ 여기서 연합을 의미 diff 평소 상대적 차이 곳이다. 따라서

:

function sym_diff() { 
    // Convert the passed arguments to an array for convenience 
    let args = Array.prototype.slice.call(arguments); 

    // This is an example of an immediately-invoked function expression 
    // (IIFE). Basically, we define a function and then immediately call it (see * below) 
    // in one go and return the result 

    return (function sym_diff(a, b) { 
     // a: the first argument 
     // b: an array containing the rest of the arguments 

     if (!b.length) { 
      // If only a is given, return a if is an array, undefined otherwise 
      return Array.isArray(a) ? a : undefined; 
     } 
     else if (b.length === 1) { 
      // Define a function that takes two arrays s and t, and returns 
      // those elements of s that are not in t. This is an 
      // example of arrow notation` 
      let diff = (s, t) => s.filter(i => t.indexOf(i) === -1); 

      // Use the second insight to compute the sym_diff of a and 
      // b[0] 
      return diff(a, b[0]).concat(diff(b[0], a)); 
     } 
     else { 
      // Use the first insight to recursively compute the sym_diff 
      // We pass [b[0]] because sym_diff expects an array of arrays as the second argument 
      // b.slice(1) gives all of b except the first element 
      return sym_diff(sym_diff(a, [b[0]]), b.slice(1)); 
     } 
    })(args[0], args.slice(1)); //* Here is where we pass the arguments to the IIFE 
} 
+0

고마워요! 이 코드에 대해 더 자세히 설명해 주시겠습니까? 나는 시작하고 많이 이해하지 못한다. 예를 들어 .. sym_diff 호출에서 b는 무엇입니까? 첫 번째 인수를 제외한 모든 인수가 필요합니까? – Juan

+1

코드에 몇 가지 의견을 추가했습니다. 희망이 도움이됩니다. –