조합과 순열, 부분 집합(javascript)

스카치·2023년 3월 29일
0
post-thumbnail

조합, 중복조합

// 조합
function getCombinations(arr, selectNumber) {
  const result = []
  if (selectNumber === 1) return arr.map(v=>[v])
  arr.forEach( (fixed, index,origin) => {
    let rest = origin.slice(index+1)
    // let rest = origin.slice(index) // 중복 조합
    let combinations = getCombinations(rest, selectNumber-1)
    let attach = combinations.map(combination => [fixed, ...combination])
    result.push(...attach)
  }); 
  return result
}

순열

// 순열
function getCombinations(arr, selectNumber) {
  const result = []
  if (selectNumber === 1) return arr.map(v=>[v])
  arr.forEach( (fixed, index,origin) => {
    let rest = [...origin.slice(0,index),...origin.slice(index+1)]
    let combinations = getCombinations(rest, selectNumber-1)
    let attach = combinations.map(combination => [fixed, ...combination])
    result.push(...attach)
  }); 
  return result
}

부분 수열

// 부분 수열
function getCombinations(arr, selectNumber) {
  const result = []
  if (selectNumber === 1) return arr.map(v=>[v])
  arr.forEach( (fixed, index,origin) => {
    let rest = [...origin.slice(0,index),...origin.slice(index+1)] 
    let combinations = getCombinations(rest, selectNumber-1)
    result.push(...combinations) ////
    let attach = combinations.map(combination => [fixed, ...combination])
    result.push(...attach)
  }); 
  return result
}

중복 순열

// 중복 순열
function getCombinations(arr, selectNumber) {
  const result = []
  if (selectNumber === 1) return arr.map(v=>[v])
  arr.forEach( (fixed, index,origin) => {
    //// 자신을 제외한 나머지 부분 없음.
    let combinations = getCombinations(arr, selectNumber-1)
    let attach = combinations.map(combination => [fixed, ...combination])
    result.push(...attach)
  }); 
  return result
}

부분 집합

// 부분 집합
// 비트연산자 사용
function getCombinations(arr){
  let result = [];

  for(let i = 1; i < (1 << arr.length); i++) {
    result.push([]);
    for(let j = 0; j < arr.length; j++) {
      if(i & (1 << j)) result[i-1].push(arr[j])
    }
  }
  return result
}

모든 경우의 수

// 모든 경우의 수 (수열의 반복 호출)
function getCombinations(arr, selectNumber) {
  const result = []
  if (selectNumber === 1) return arr.map(v=>[v])
  arr.forEach( (fixed, index,origin) => {
    let rest = [...origin.slice(0,index),...origin.slice(index+1)]
    let combinations = getCombinations(rest, selectNumber-1)
    let attach = combinations.map(combination => [fixed, ...combination])
    result.push(...attach)
  }); 
  return result        
}
const getAllPermutations = (arr) => {
  let results = [];
  arr.forEach((value, index, origin) => {
    results.push(...getCombinations(origin, index + 1));
  });

  return results;
}

0개의 댓글