Code Wars: Find the smallest (NOT PASSED YET)
https://www.codewars.com/kata/573992c724fc289553000e95/train/javascript
function smallest(n) {
let arr = (n).toString().split("");
let index = 0;
let smallest = arr[0];
let smallest2 = arr[1];
let replaceItem;
let final;
//find the smallest number that is not the first number in array
for (i = 1; i < arr.length; i++) {
if(arr[i] < smallest) {
index = i;
smallest = arr[i];
}
}
//if above does not go thru, find next largest number after 1st number
if (index === 0) {
for (i = 2; i < arr.length; i++) {
if(arr[i] < smallest2) {
index = i;
smallest2 = arr[i];
}
}
}
//remove the element retreived from the loops above
replaceItem = arr.splice(index, 1);
//place the removed element to the first number it is less than
for (i = 0; i < arr.length; i++) {
if (replaceItem < arr[i]) {
arr.splice(i, 0, replaceItem);
final = i;
break;
}
}
return [parseInt(arr.join(""), 10), index, final] //parsetInt to remove leading zeros from string
}
function smallest(n) {
let arr = (n).toString().split("");
let index = 0;
let smallest = arr[0];
let smallest2 = arr[1];
let replaceItem;
let final;
//find the smallest number that is not the first number in array
for (i = 1; i < arr.length; i++) {
if(arr[i] < smallest) {
index = i;
smallest = arr[i];
}
}
//if above does not go thru, find next largest number after 1st number
if (index === 0) {
for (i = 2; i < arr.length; i++) {
if(arr[i] < smallest2) {
index = i;
smallest2 = arr[i];
}
}
}
//remove the element retreived from the loops above
replaceItem = arr.splice(index, 1);
//place the removed element to the first number it is less than
for (i = 0; i < arr.length; i++) {
if (replaceItem < arr[i]) {
arr.splice(i, 0, replaceItem);
final = i;
break;
}
}
return [parseInt(arr.join(""), 10), index, final] //parsetInt to remove leading zeros from string
}
Comments
Post a Comment