Robson » Little Red Book » The next permutation

Chapter 9 - Question 3

Given a sequence of character that is not the alphabetically last permutation of those characters, generate the alphabetically next permutation.

Solution 1

I recently noticed a lot of people using the J programming language, so I thought I'd try it out. I have no intention of learning it properly or thoroughly, I just want to get a very basic understanding so that I can use it when necessary.

J can be used to perform many operations based on permutations. These are some of the ones I've discovered.

Find the next permutation of a string:

    string=: 'QWERTY'
    1 A. string

Show the current and next four permutations:

    string=: 'QWERTY'
    (i.5) A. string

Show the 9th permutation of the numbers 0, 1, 2, 3:

    9 A. i.4
1 2 3 0

Show all permutations of 1, 2, 3:

(replace the factorial with the amount of numbers)

    (i.!3) A. 1+ i.3
1 2 3
3 2 1

Find the ninth permutation of the fourth permutation:

   (9) A. (4) A. 'HELLO'


© 2004-19 robson | cc unless stated