Skip to content

Instantly share code, notes, and snippets.

@xolubi
Last active August 29, 2015 14:27
Show Gist options
  • Save xolubi/b2b168d1c245200be09b to your computer and use it in GitHub Desktop.
Save xolubi/b2b168d1c245200be09b to your computer and use it in GitHub Desktop.
/*
12590 = 10592 (sort array. ignore 0. 1 is next smallest and already in front. pay attention to 0. swap with number after 1 )
21045 = 12045 (sort array. ignore 0. 1 is next smallest but not in front. swap with number in front)
21450 = 12450 (sort array. ignore 0. 1 is next smallest but not in front. swap with number in front)
10390 = 10039 (sort array. ignore 0. 1 is next smallest and already in front. pay attention to 0. we have a 0 after 1 already. move to next 0, swap with third number)
20305 = 20035 (sort array. ignore 0. 2 is next smallest and already in front. pay attention to 0. we have a 0 after 2 already. move to next 0, swap with third number)
21352 = 12352 (sort array. no zero. 1 is smallest but not in front. swap with number in front)
16289 = 12689 (sort array. no zero. 1 is smallest and already in front. move to next)
*/
var input = "21450";
var arr = input.split('');
var sorted_arr = JSON.parse(JSON.stringify(arr));
sorted_arr.sort();
console.log(arr);
console.log(sorted_arr);
var j = 0;
var zeroIgnored = false;
for (i = 0; i < arr.length; i++) {
//check if first element is a zero
if (i == 0) {
if (sorted_arr[0] == '0') {
j++;
zeroIgnored = true;
console.log('ignored zero');
}
}
console.log(i);
console.log(j);
if (arr[i] !== sorted_arr[j]) {
//smallest number isn't in front.
var swapIndex = arr.indexOf(sorted_arr[j]);
var buffer = arr[i];
arr[i] = arr[swapIndex];
arr[swapIndex] = buffer;
break;
} else {
//smallest is already in front
if (!zeroIgnored) {
j++;
} else {
//pay attention to zero
j = 0;
}
}
}
//unfortunately, this doesn't handle a case of multiple zeros.
console.log(arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment