1 minute read

순열

// 3가지 card중 2개씩 뽑기
// 3 X 2 X 1 / 1
// 6가지

function permutation() {
  let cards = [1, 2, 3];
  let result = [];

  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
      if (i === j) continue;
	      let pick = [cards[i], cards[j]]
	      result.push(pick);
    }
  }
return result;
}

permutation();

/*
[
  [ 1, 2 ],
  [ 1, 3 ],
  [ 2, 1 ],
  [ 2, 3 ],
  [ 3, 1 ],
  [ 3, 2 ]
]
*/

재귀로 만들기

백준 N과 M 문제 풀이 참고

function solution(params) {
  const input = params.split(" ").map(a => +a)
  const n = input[0],
    m = input[1]

  const array = []
  for (let i = 1; i <= n; i++) {
    array.push(i)
  }
  //   console.log(array)
  const answer = []

  const visited = new Array(n).fill(false)

  permutation(0)

  //순서가 다르면 다른 값 -> 순열
  function permutation() {
    // answer.push(array[curr])
    if (answer.length == m) {
      console.log(answer.join(" "))
      return
    }

    // 숫자 중복 선택은 제외
    for (let i = 0; i < n; i++) {
      if (!visited[i]) {
        answer.push(array[i])
        visited[i] = true
        permutation()
        visited[i] = false
        answer.pop()
        // console.log("answer", answer)
        // console.log("visited", visited)
      }
    }
  }
}

// solution(`4 2`)
solution(`3 3`)

중복 순열

// 3가지 card중 2개씩 뽑기
// 3^2 = 9가지

function permutation() {
  let cards = [1, 2, 3];
  let result = [];
    
  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
      let pick = [cards[i], cards[j]];
      result.push(pick);
    }
  }
return result;
}

permutation();

/*
[
  [ 1, 1 ],
  [ 1, 2 ],
  [ 1, 3 ],
  [ 2, 1 ],
  [ 2, 2 ],
  [ 2, 3 ],
  [ 3, 1 ],
  [ 3, 2 ],
  [ 3, 3 ]
*/

조합

// 3가지 카드중 2개씩 뽑기
// (3 X 2 X 1) / (2 X 1) / 1
// 3가지

function combination() {
  let cards = [1, 2, 3];
  let result = [];
  
  for (let i = 0; i < 3; i++) {
    for (let j = i + 1; j < 3; j++) {
      let pick = [cards[i], cards[j]];
      result.push(pick);
    }
  }
  return result;
}

combination()

Updated: