【发布时间】:2019-11-06 19:25:45
【问题描述】:
试图解决这个问题Codewars challenge。
你有一个由数字组成的正数 n。您最多可以做一个操作:选择数字中的一个数字的索引,在该索引处删除该数字,然后将其插入到另一个数字或数字的同一位置,以便找到您可以获得的最小数字。
任务:根据语言返回一个数组、元组或字符串(参见“示例测试”):
1) 你得到的最小数
2)你取的数字d的索引i,i尽量小
3) 插入数字 d 的索引 j(尽可能小)以获得最小的数字。
例子:
smallest(261235) --> [126235, 2, 0] or (126235, 2, 0) or "126235, 2, 0"
其他例子:
209917, [29917, 0, 1]
285365, [238565, 3, 1]
269045, [26945, 3, 0]
296837, [239687, 4, 1]
所以,为了获得可能的最小数字,我们需要从数字中删除最小的数字并将其放在数字的前面,对吗?
function smallest (n) {
//turn n into an array
let array = String(n).split("").map(Number);
let smallest = Math.min(...array);
//find index of smallest in original array
let index = array.indexOf(smallest);
//remove smallest from original array, move it to front
array.splice(index, 1);
array.unshift(smallest);
let newNumber = Number(array.join(""));
//return array of new number, index of where the smallest was,
//and index of where the smallest is now
return ([newNumber, index, 0]);
}
console.log(smallest(239687));
我的答案是返回正确的数字,但是大约一半的时间,它没有返回正确的索引i 和索引j。
编辑:最新尝试:
function smallest (n) {
let array = Array.from(String(n)).map(Number);
let original = Array.from(String(n)).map(Number);
let sorted = Array.from(String(n)).map(Number).sort((a, b) => a - b);
let swapValueOne = [];
let swapValueTwo = [];
for (let i = 0; i < array.length; i++) {
if (array[i] !== sorted[i]) {
swapValueOne.push(sorted[i]);
swapValueTwo.push(original[i]);
break;
}
}
swapValueOne = Number(swapValueOne);
swapValueTwo = Number(swapValueTwo);
let indexOne = original.indexOf(swapValueOne);
let indexTwo = original.indexOf(swapValueTwo);
//remove swapValue
array.splice(indexOne, 1);
//insert swapValue
array.splice(indexTwo, 0, swapValueOne);
return ([Number(array.join("")), indexOne, array.indexOf(swapValueOne)]);
}
console.log(smallest(296837));
^ 有时它会给出正确的数字和正确的交换索引,有时数字和交换索引都是错误的。
【问题讨论】:
-
第二个测试看起来不正确。
testing(209917, [29917, 0, 1]);但是找到的索引应该是1,应该插入到索引0 -
描述指定“[29917, 1, 0] 也可以是一个解决方案,但是 [29917, 1, 0] 中的索引
i大于 [29917, 0, 中的索引i1].",所以有一种方法可以消除歧义。
标签: javascript arrays sorting numbers