순열, 중복순열, 조합, 중복조합 [JS]

wkahd01·2021년 10월 31일
1

알고리즘

목록 보기
17/24

순열

// 순열
let data = [1, 2, 3, 4]
let r = 2

function permutation(data, r) {
  const result=[]
  if(r===1){
      return data.map(v=>[v])
  }
  for (let i = 0; i < data.length; i++) {
      const main = data[i]
      const sub = data.filter(v=>v!==data[i])
      //console.log(main,sub)
      const permuteD = permutation(sub,r-1)

      result.push(... permuteD.map((v)=>[main,...v]))

  }
  return result
}
const result = permutation(data,r)
console.log(...result,result.length)

중복순열

// 중복 순열
const data = [1, 2, 3, 4]
const r = 2

function permuteWithRepetition(data, r) {
    const result=[]
    if(r===1){
        return data.map(v=>[v])
    }
    for (let i = 0; i < data.length; i++) {
        const main = data[i]
        const sub = data
        //console.log(main,sub)
      const permuteR = permuteWithRepetition(sub,r-1)
      result.push(...permuteR.map((v)=>[main,...v]))

    }
    return result
}
const result = permuteWithRepetition(data,r);
console.log(...result,result.length)

조합

// 조합
const data = [1, 2, 3, 4]
const r = 2

function combination(data, r) {
    const result=[]
    if(r===1){
        return data.map(v=>[v])
    }
    for (let i = 0; i < data.length; i++) {
        const main = data[i]
        const sub = data.slice(i+1)
        
        const permuteR = combination(sub,r-1)
        result.push(...permuteR.map((v)=>[main,...v]))

    }
    return result
}
let result = combination(data,r);
console.log(...result,result.length)

중복 조합

// 중복 조합
const data = [1, 2, 3, 4]
const r = 2

function combinationWithRepetition(data, r) {
    const result=[]
    if(r===1){
        return data.map(v=>[v])
    }
    for (let i = 0; i < data.length; i++) {
        const main = data[i]
        const sub = data
        
        let permuteR = combinationWithRepetition(sub,r-1)
        result.push(...permuteR.map((v)=>[main,...v]))

    }
    return result
}
let result = combinationWithRepetition(data,r);
result=[...new Set(result.map(v=>JSON.stringify(v.sort())))].map(v=>JSON.parse(v))
console.log(...result,result.length)
profile
꾸준하게 공부하기

0개의 댓글