So for each number sequence, we need to find the next bigger one by swapping digits. That's awesome lets try. The hardest part was to define the algorithm. Here's how I did it:
/*
Instruction
start with 2nd digit from right
swap with next smallest to the right
if result is bigger than exit that's the solution
start with 3rd digit from right
if exists, swap with next smallest to the right, sort to the right. solution
start with 4rd digit from right
if exists, swap with next smallest to the right, sort to the right. solution
return first number (minimal)
*/
And here's my solution:
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function (nums) {
function swap(index1, index2) {
var temp = nums[index1]
nums[index1] = nums[index2]
nums[index2] = temp;
}
function next_bigger_from(pos) {
var current = nums[pos];
result = -1;
var min = Infinity;
for (var i = pos + 1; i < len; i++) {
if (nums[i] > current && nums[i] < Infinity) {
result = i;
min = nums[i];
}
}
return result;
}
function sort_from(pos) {
for (var i = pos; i < len - 1; i++) {
for (var j = i + 1; j < len; j++) {
if (nums[i] > nums[j]) {
swap(i, j)
}
}
}
}
var len = nums.length;
if (len < 2) {
console.log("" + nums)
return;
}
var rotator = 2; // from right
while (rotator <= len) {
var pos = len - rotator;
var pos2 = next_bigger_from(pos);
if (pos2 == -1) {
rotator += 1;
continue;
}
swap(pos, pos2);
sort_from(pos+1);
console.log("" + nums)
return;
}
nums = nums.sort();
console.log("" + nums)
return;
};
nextPermutation([1, 2, 3])
nextPermutation([3, 2, 1])
nextPermutation([1, 1, 5])
var nums = [1, 3, 5, 7];
for (var i = 0; i < 24; i++) {
nextPermutation(nums)
}
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
So what is wrong with the following solution by the OP? It doesn't change the array nums
but rather returns an array x
. This is why the second test (of the 4 digits sequence) fails for your code. By the way, even if I try nums = nextPermutation(nums)
for the second test the results are still wrong.
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var nextPermutation = function(nums) {
for (let i = nums.length - 1; i >= 0; i--) {
if (nums[i] > nums[i - 1]) {
var x = [...nums.slice(0, i - 1), nums[i], nums[i - 1]]
console.log("" + x) // <- This gives a different value as compared to
return x // the returned value
}
}
console.log("" + nums.reverse()) // added for verbosity
return nums.reverse()
};
nextPermutation([1, 2, 3])
nextPermutation([3, 2, 1])
nextPermutation([1, 1, 5])
var nums = [1, 3, 5, 7];
for (var i = 0; i < 24; i++) {
nextPermutation(nums)
}