Skip to content

Instantly share code, notes, and snippets.

@onyekaa
Forked from xolubi/swap.js
Last active August 29, 2015 14:27
Show Gist options
  • Save onyekaa/bb5701f98b4501b6db3f to your computer and use it in GitHub Desktop.
Save onyekaa/bb5701f98b4501b6db3f to your computer and use it in GitHub Desktop.
function swap(n) {
var arr = n.toString().split(''); // convert number to string then split into array
if (arr.length > 2) {
var swap_list = []; // arrary to push newly swapped numbers
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
if (i != j) {
new_arr = arr.slice(0); // copy old array
// Swap locations
var x = new_arr[i]; // save the old value for location i to a var
new_arr[i] = new_arr[j]; // now change location i value to the value in location j
new_arr[j] = x; //location j can now take the value in x, which was i's former value
// Forget items that begin with 0
if (new_arr[0] != '0') {
item = parseInt(new_arr.join('')); // convert result array back to integer
swap_list.push(item); //push item into the swap combo list
}
}
}
}
// with temp_list we find the highest and lowest numbers
var highest = "Highest swap is " + Math.max.apply(null, swap_list);
var lowest = "Lowest swap is " + Math.min.apply(null, swap_list);
console.log(highest);
console.log(lowest);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment