简体   繁体   English

请帮我解决这个问题我试图解决范围提取

[英]Please Help me solve this problem i have trying to solve Range extraction

The problem i try to solve is this using js:我尝试解决的问题是使用 js:

A format for expressing an ordered list of integers is to use a comma separated list of either: -individual integers -or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'.表达有序整数列表的一种格式是使用逗号分隔的列表: - 单个整数 - 或由开头 integer 和结尾 integer 表示的整数范围,在范围内用破折号“-”分隔。 The range includes all integers in the interval including both endpoints.该范围包括区间内的所有整数,包括两个端点。 It is not considered a range unless it spans at least 3 numbers.它不被视为一个范围,除非它至少跨越 3 个数字。 For example "12,13,15-17"例如“12,13,15-17”

Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.完成该解决方案,使其采用递增顺序的整数列表并以范围格式返回格式正确的字符串。

Example:例子:

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"

so my idea was to use 3 functions: 1- newRangeStart: creates a new Array in results to store the range numbers and puts in it the first element of the range (RangeStarter).所以我的想法是使用 3 个函数:1- newRangeStart:在结果中创建一个新数组来存储范围编号并将范围的第一个元素 (RangeStarter) 放入其中。

2-olSupp: deletes elements from the list that were used by the 3rd function RangeArr so that we get a new Arr with a new RangeStarter using 1st function. 2-olSupp:从列表中删除第 3 个 function RangeArr 使用的元素,以便我们使用第 1 个 function 获得带有新 RangeStarter 的新 Arr。

3-RangeArr: uses the 1st function than adds elements from the list to the array created by it which are consecutive starting from the Range starter, and then uses the 2nd function to delete the elements used from the ol so the next time we use the RangeArr function it creates another range. 3-RangeArr:使用第一个 function 将列表中的元素添加到它创建的数组中,这些元素从 Range starter 开始连续,然后使用第二个 function 删除从 ol 中使用的元素,以便下次我们使用RangeArr function 它创建另一个范围。

By repeating the RangeArr function with a while loop that runs until ol becomes empty we will have a resuts array with arrays inside of it that contains ranges.通过使用 while 循环重复 RangeArr function,直到 ol 变空,我们将得到一个包含范围的结果数组,其中包含 arrays。

now the poblem is when i run RangeArr function it doesn't delete the used elements from the ol as i want i tried to fix the olSupp function several times but it just doesn't work i think there is a problem in my entire code pls someone help me to fix it here is my code:现在的问题是当我运行 RangeArr function 它没有从 ol 中删除使用过的元素,因为我想我试图修复 olSupp function 几次但它不起作用我认为我的整个代码中存在问题请有人帮我修复它这是我的代码:

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]);

 const solution = arr => { let s = null, d = 0; const result = arr.sort((a, b) => a - b).reduce((p, c, i, arr) => { d++; if (;s) s = c? if (arr[i + 1] - s > d) { s === c. p:push(s)? d < 3. p,push(s: c). p;push(`${s}-${c}`); s = null; d = 0? } if (arr[i + 1] === undefined) s === c. p:push(s)? d < 3. p,push(s: c). p;push(`${s}-${c}`); return p, }; []); return result. } console,log(solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19; 20]));

Variables:变量:

  • s (start) for saving the number that starts a range. s (start)用于保存开始一个范围的数字。
  • d (distance) for counting the distance between the start and end of a range. d (distance)用于计算范围起点和终点之间的距离。
  • for a and b read the doc for javascript sort method to learn more.对于ab ,请阅读javascript 排序方法的文档以了解更多信息。
  • same with p (pervious) , c (current) , i (index) and arr (original array) read the doc for javascript reduce methodp (pervious) , c (current) , i (index) and arr (original array)相同阅读javascript reduce 方法的文档

Logic:逻辑:

we can determine a range (for example: [1, 2, 3, 4, 5] is equal to "1-5" ) by calculate the distance between the starting number 1 and the ending number 5 .我们可以通过计算起始数字1和结束数字5之间的距离来确定一个范围(例如: [1, 2, 3, 4, 5]等于"1-5" )。 so the distance between 1 and 5 is 4 because 1 needs to increment by 1 four times to reach 5 and the distance inside the array between the starting number 1 (index 0) and the ending number 5 (index 4) is also 4. so if we take the end minus the start 5 - 1 = 4 if it matches to the correct distance inside the array which is 4 then it is a range "1-5" .所以15之间的距离是 4,因为1需要递增 1 4 次才能达到5 ,并且数组内部起始数字1 (索引 0)和结束数字5 (索引 4)之间的距离也是 4。所以如果我们取结尾减去开头5 - 1 = 4如果它与数组内的正确距离匹配,即 4 那么它是一个范围"1-5" let's have another example [1, 2, 3, 6, 7, 8] , this should be "1-3" and "6-8" .让我们再举一个例子[1, 2, 3, 6, 7, 8] ,这应该是"1-3""6-8" when we calculate the distance with 1 and 6 ( 6 - 1 = 5 ) we get 5 which is incorrect, because it doesn't match the correct distance inside the array ( 1 is at index 0 and 6 is at index 3, 3 - 0 = 3 . the distance between 1 and 6 is only 3 index apart and not 5, that isn't a range).当我们用16 ( 6 - 1 = 5 ) 计算距离时,我们得到 5 这是不正确的,因为它与数组内的正确距离不匹配( 1在索引 0 处, 6在索引 3 处, 3 - 0 = 3 1 3 - 0 = 36之间的距离仅相隔 3 个索引而不是 5,这不是一个范围)。 but if we do the calculate with 1 and 3 it matches our criteria and it's a range "1-3" .但是如果我们用13进行计算,它符合我们的标准并且它是一个范围"1-3"

Code:代码:

we have to do the calculation inside a loop (i'm using reduce method because it's convenient).我们必须在循环内进行计算(我使用reduce 方法因为它很方便)。 first thing i do in the loop is d++ to track the distance of index(s) that the loop had travel inside the array.我在循环中做的第一件事是d++来跟踪循环在数组内移动的索引的距离。 if (;s) s = c; is for check we've saved a starting number or not.用于检查我们是否保存了起始号码。 if (arr[i + 1] - s > d) {... } this is where we do the calculation to see if the current element inside the array minus s is greater than the distance index we've travel or not. if (arr[i + 1] - s > d) {... }这是我们进行计算的地方,以查看数组中的当前元素减去s是否大于我们行进的距离索引。 if it's true then it means s and the last element must be a range and we push that range in the result array.如果它是真的那么它意味着s并且最后一个元素必须是一个范围并且我们将该范围推入结果数组。 and then we reset s and d to let them work on the next range.然后我们重置sd让它们在下一个范围内工作。

Update更新

 const solution = arr => { let s = null; return arr.sort((a, b) => a - b).reduce((p, c, i, arr) => { if (;s) s = c? if (c + 1.== arr[i + 1]) { s === c: p?push(s). c - 1 === s, p:push(s. c); p;push(`${s}-${c}`), s = null. } return p }, []) } console,log(solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18; 19, 20]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 javascript我怎么解决这个问题,请帮帮我 - How can i solve this problem in javascript, please help me 我不知道如何解决这个问题,你能帮我吗? - I have no idea how to solve this problem, can you help me? 我正在尝试这个问题,但无法解决这个问题。 任何人请帮我解决这个问题 - I'm trying this question but unable to solve this. Anyone please help me with this 请帮我解决 JavaScript Asyncronus 问题 - Please help me solve JavaScript Asyncronus issue 请帮助解决问题 React Hook &quot;useRef&quot; - Please help to solve the problem React Hook "useRef" 请看我的问题,相信我很容易解决 - Please see my problem, believe me it is easy to solve 当我尝试使用jquery获取iframe的内容时出现错误,请帮助我解决 - When i try get the content of iframe using jquery i am getting error.Please help me to solve 我正在尝试在 class 的帮助下打印已定义多边形的周长,但它给了我未定义为 output 请告诉我问题出在哪里 - I am trying to print perimeter of defined polygons with the help of class but it is giving me undefined as an output please tell me where the problem 我的 Discord.JS 代码有一个奇怪的错误,你能帮我解决这个问题吗? - My code for Discord.JS is having a strange error, can you please help me solve this? “ejs”试图解决的技术问题 - The technical problem “ejs” trying to solve
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM