#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.
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]
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With