ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [javascript] 조합, 순열 및 객체 정렬
    javascript & nodejs 2022. 6. 23. 12:44
    728x90
    반응형

    재귀 함수를 이용한 조합

    //조합-combination
    
    let getCombi = (arr,selectnum)=>{
    	const rest = [];
        if (selectnum === 1){
        	return arr.map((v)=>[v]);
        }
        arr.forEach((fixed, index, origin)=>{
        	const rest = origin.slice(index + 1);
            const combi = getCombi(rest, selectnum - 1);
            const fixed_combi = combi.map((v)=>[fixed, ...v]);
            result.push(...fixed_combi);
        });
        return result;
    }

    조합은 중복을 하지 않으며 모든 경우의 수를 조합할 수 있다.

    예를 들어 1,2,3과 1,3,2는 같은 것으로 취급한다.

     

    재귀 함수를 이용한 순열

    // 순열-Permutation
    
    let getPermutation = (arr,selectnum)=>{
    	const result = [];
        if (selectnum === 1){
        	arr.map((v)=>[v]);
        }
        arr.forEach((fixed, index, origin)=>{
        	const rest = [...origin.slice(0, index), ...origin.slice(index + 1)];
            const permutation = getPermutation(rest, selectnum - 1);
            const fixed_permutation = permutation.map((v)=>[fixed, ...v]);
            result.push(...fixed_permutation);
        });
        return result;
    }

    순열은 중복을 허용하며 모든 경의 수를 조합할 수 있다.

    예를 들어 1,2,3과 1,3,2를 다른것으로 취급한다.


    객체를  value 기준으로 정렬하는 방법

    let people = {
    	"워렌버핏" : 100,
    	"피터린치" : 75,
        "고길동" : 150,
        "둘리" : 20,
    }
    
    // value를 기준으로 정렬해보기
    //Object.entries(people)을 하면 객체가 배열로 바뀐다.
    
    //내림차순
    let s = Object.entries(people).sort((a,b)=>a[1] - b[1]);
    //오름차순
    let u = Object.entries(people).sort((b,a)=>b[1] - a[1]);
    728x90
    반응형
Designed by Tistory.