【发布时间】:2022-11-26 09:57:45
【问题描述】:
我尝试解决的问题是使用 js:
表达有序整数列表的一种格式是使用逗号分隔的列表: - 个别整数 - 或由破折号“-”分隔范围内的起始整数和结束整数表示的整数范围。该范围包括区间内的所有整数,包括两个端点。它不被视为一个范围,除非它至少跨越 3 个数字。例如“12,13,15-17”
完成该解决方案,使其采用递增顺序的整数列表并以范围格式返回格式正确的字符串。
例子:
solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
// returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20"
所以我的想法是使用 3 个函数: 1- newRangeStart:在结果中创建一个新数组来存储范围编号,并将范围的第一个元素 (RangeStarter) 放入其中。
2-olSupp :从列表中删除第三个函数 RangeArr 使用的元素,以便我们使用第一个函数获得一个新的 Arr 和一个新的 RangeStarter。
3-RangeArr :使用第一个函数,然后将列表中的元素添加到它创建的数组中,这些元素从 Range starter 开始是连续的,然后使用第二个函数从 ol 中删除使用的元素,以便下次我们使用RangeArr 函数创建另一个范围。
通过使用运行直到 ol 变空的 while 循环重复 RangeArr 函数,我们将得到一个结果数组,其中包含包含范围的数组。
现在的问题是,当我运行 RangeArr 函数时,它不会像我想要的那样从 ol 中删除使用过的元素有人帮我修复它这是我的代码:
function solution(list){
// TODO: complete solution
let ol = [...list];
let results = [];
/*This adds a new array for a range by adding the first number of the range to
an array (2D array) and stores it in the resuts array */
function newRangeStart(orderedlist,result){
result.push([orderedlist[0]]);
return result;
}
/*This functions takes the ol and deletes elements that are found in the results
so that the next time we run the newRangeStart function it creates an other array
for another range with a different start number*/
function olSupp(orderedlist,result){
let toRemove = result.flat();
let newList = [];
for (let i = 0; i < orderedlist.length; i++) {
if(!toRemove.includes(orderedlist[i])){
newList.push(orderedlist[i]);
}
}
orderedlist = [...newList];
return orderedlist;
}
/*Finally RangeArr function creates a range from the ol (ordered list)
starting by the first element of the results array and then uses olSupp to delete
the used numbers from the ol */
function RangeArr (orderedlist,result){
newRangeStart(orderedlist,result);
let i = 0;
while(orderedlist[i+1]- orderedlist[i] == 1 && orderedlist[i+2]- orderedlist[i+1]== 1) {
result[i].push(orderedlist[i+1],orderedlist[i+2]);
i = i+1;
}
olSupp(orderedlist,result);
return result;
}
/*we execute the RangeArr function until ol becomes emepty
and this will give us multiple arrays in the result array containing
the elements of each range found in the ol */
//PS: i didnt put the code beacuse it causes an infinte loop using while
RangeArr(ol,results);
console.log(ol,results);
}
solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]);
【问题讨论】:
标签: javascript algorithm