Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a next permutation in Java?

Tags:

java

#include <algorithm> 
#include <iostream> 
  
using namespace std; 
  
int main() 
{ 
    string s = { "gfg" }; 
    bool val 
        = next_permutation(s.begin(), 
                           s.end()); 
    if (val == false) 
        cout << "No Word Possible"
             << endl; 
    else
        cout << s << endl; 
    return 0; 
}

As you can see in the code, there is a next permutation function in c++. more on the next permutation function code here. However, I want to know if there is a similar function in Java.

like image 829
Skyler Xue Avatar asked Sep 19 '25 01:09

Skyler Xue


2 Answers

The absence in Java something like C++ next_permutation/prev_permutation inspired me to add Java implementation to the Maven Central

<dependency>
    <groupId>io.github.hextriclosan</groupId>
    <artifactId>algorithm</artifactId>
    <version>0.0.2</version>
</dependency>

The algorithm implemented as an iterator. Sample code like

var iterator = new NextPermutationIterator<>(List.of('A', 'B', 'B'));
iterator.forEachRemaining(System.out::println);

prints out

[A, B, B]
[B, A, B]
[B, B, A]
like image 72
triclosan Avatar answered Sep 20 '25 15:09

triclosan


No there is no inbuilt function in Java for the next_permutation. But you can use this as I use this in codeforces contests.

boolean next_permutation(int[] p) {
  for (int a = p.length - 2; a >= 0; --a)
    if (p[a] < p[a + 1])
      for (int b = p.length - 1;; --b)
        if (p[b] > p[a]) {
          int t = p[a];
          p[a] = p[b];
          p[b] = t;
          for (++a, b = p.length - 1; a < b; ++a, --b) {
            t = p[a];
            p[a] = p[b];
            p[b] = t;
          }
          return true;
        }
  return false;
}
like image 25
ANUP PAL Avatar answered Sep 20 '25 15:09

ANUP PAL