3

I want to make permutation with javascript, this is my code

const arr = [1, 2, 3, 4, 5];

for (let i1 = 0; i1 < arr.length; i1++) {
  for (let i2 = i1 + 1; i2 < arr.length; i2++) {
    console.log(arr[i1] + ' ' + arr[i2]);
  }
}

https://jsfiddle.net/op51x6mv/1/

result from that code:

["1 2", "1 3", "1 4", "1 5", "2 3", "2 4", "2 5", "3 4", "3 5", "4 5"]

I want to ask, why are all the results from the permutation not displayed? From these results I did not see the numbers

["2 1", "3 1", "3 2", "4 1", "4 2", "4 3", "5 1", "5 2", "5 3", "5 4"]

please tell Me where the error from this code? or if You have a better code please help Me.

Thank you

3 Answers 3

3

You could loop from start to end twice and omit same indices.

const arr = [1, 2, 3, 4, 5];

for (let i1 = 0; i1 < arr.length; i1++) {
    for (let i2 = 0; i2 < arr.length; i2++) {
        if (i1 === i2) continue;
        console.log(arr[i1] + ' ' + arr[i2]);
    }
}

Sign up to request clarification or add additional context in comments.

1 Comment

oh my god you really help me. the code is simple but running. thanks you sir
1

What you want is... mathematically... not permutations, but variations without repetition (but that's actually irrelevant).

I wrote a code for this in PHP a bit earlier, here's its JS variant (selects a given number of elements, can handle repetitions in data, etc.):

const variations = (arr, n = arr.length) => {
  if(n === 0) return [[]]
  if(!(n >= 0)) return []
  const output = []
  for(let i = 0; i < arr.length; i++){
    if(arr.indexOf(arr[i]) < i) continue
    const newArr = arr.slice()
    newArr.splice(i, 1)
    output.push(...variations(newArr, n - 1).map(e => [arr[i], ...e]))
  }
  return output
}

const arr = [1, 2, 3, 4, 5];

console.log(variations(arr, 2))

//If you want to concatenate them, use:

console.log(variations(arr, 2).map(e => e.join(' ')))

Comments

0

const arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr.length; j++) {
      if (i === j) continue;
      console.log(arr[i] + ' ' + arr[j]);
  }
}

2 Comments

sorry bro I don't want to make permutations that repeat that number. example number ['1 1'] does not have to be displayed
ok ill modify my answer, you can use the continue keyword

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.