Permutation Step Coderbyte Solution

0

Have the function PermutationStep(num) take the num parameter being passed and return the next number greater than num using the same digits. 



For example: if num is 123 return 132, if it's 12453 return 12534. If a number has no greater permutations, return -1 (ie. 999).

Permutation step coderbyte solution in java


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;


public class PermutationStep {
int PermutationStep(int num) {
String numStr = String.valueOf(num);
List<Integer> perms = getPermutations("",
numStr, new ArrayList<Integer>());

Collections.sort(perms);

int numIndex = perms.indexOf(num);
if (numIndex == perms.size() - 1) {
return -1;
}

for (int i = numIndex; i < perms.size(); i++) {
if (perms.get(i) != num) {
return perms.get(i);
}
}

return -1;
}

List<Integer> getPermutations(String begStr,
String endStr, List<Integer> perms) {

if (endStr.length() <= 1) {
perms.add(Integer.parseInt(begStr + endStr));
} else {
for (int i = 0; i < endStr.length(); i++) {
String newString = endStr.substring(0, i)
+ endStr.substring(i + 1);

getPermutations(begStr + endStr
.charAt(i), newString, perms);
}
}
return perms;
}

public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
PermutationStep c = new PermutationStep();
System.out.print(c.PermutationStep(41352));
}
}

Permutation step coderbyte python

def PermutationsStep(num):
string = str(num)
if len(string) == 1:
return -1
for i in range(len(string)-2,-1,-1):
if string[i] < string[i+1]:
return int(string[:i] + string[i+1:] + string[i])
else:
return -1

Permutation step javascript



const permutationStep = require
('./permutation_step');

describe('permutationStep()', () => {
test('passes Coderbyte.com tests', () => {
expect(permutationStep(11121)).toBe(11211);

expect(permutationStep(41352)).toBe(41523);

expect(permutationStep(456)).toBe(465);

expect(permutationStep(111)).toBe(-1);

expect(permutationStep(23514)).toBe(23541);

expect(permutationStep(897654321))
.toBe(912345678);

expect(permutationStep(12)).toBe(21);

expect(permutationStep(9)).toBe(-1);

expect(permutationStep(44444444)).toBe(-1);

expect(permutationStep(76666666)).toBe(-1);
});
});

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !