Create string permutation using repeat statements

Asked 2 years ago, Updated 2 years ago, 48 views

a,b,c,d,e. These five letters are abcde,abced,abdce,abdec... How do I create permutations in this way, using only repetitive statements?

c c++

2022-09-22 16:47

1 Answers

If you can write a conditional sentence, there is a straightforward method even if it is a little distracting. If you turn Run in DEMO, you will see P (5, 5) = 5! = 120 results as expected. (It is JavaScript code for now, but it can be fully referred to in C)

var arr = ['a', 'b', 'c', 'd', 'e']
var txt = ''
for (var a = 0; a < arr.length; a++) {
  for (var b = 0; b < arr.length; b++) {
    If (b!=a) { // Do not select a character that has already been pulled from a.
      for (var c = 0; c < arr.length; c++) {
        If (c!=b&&c!=a) { // Already in b, do not select the letter selected from a
          for (var d = 0; d < arr.length; d++) {
            If (d!=c&&d!=b&&d!=a) { // The letters already drawn from c, b, and a are...
              for (var e = 0; e < arr.length; e++) {
                If (e!=d&&e!=c&&e!=b&&e!=a) {/ further explanation is omitted.
                  txt += arr[a] + arr[b] + arr[c] + arr[d] + arr[e] + "\n"
                }
              }
            }
          }
        }
      }
    }
  }
}
console.log(txt)

The answer may seem mischievous, but please note that I answered it in a realistic way after seeing There is no particular best practice for permutation output.


2022-09-22 16:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.