+ 5
Need algorithm advices
I don't have the code with me but I started to write an algorithm to do something quite simple. I'm afraid to fall and trap myself in a "if" nested structure when I will continue. Here is the thing: From an API, my script will receive strings with this kind look "12, 127, 298". What I want to do is: If number are not following each other I have to keep it "12 - 127 - 298" but if I got "12, 13, 14, 127, 298" it should become "12 to 14 - 127 - 298". I never know how many numbers I'm going to receive...
7 ответов
+ 16
I wrote a js script for u maybe it will help
//your array(from api)
var arr = [12, 13, 14, 15, 130, 190, 191, 192, 273, 402];
//result array after formatting
var result = [];
var i = 0;
//idk why i named it calc...
function calc(){
//check if the next element is equals to this element +1
if(arr[i] + 1 == arr[i+1]){
var from = arr[i];
//increase i as long as the numbers increse by 1
do{
i++;
}while(arr[i] + 1 == arr[i+1]);
result.push(from + " to " + arr[i]);
i++;
}else{
//if the numbers don't increase by 1 just add a new element
result.push(arr[i]);
i++;
}
//stop calling when you reach the end
if(i < arr.length){
calc();
}
}
calc();
alert(result);
feel free to ask if something is not clear
I know it could be better, I just wrote it very fast on my phone so...
+ 12
@Geoffrey Lavenez Wow it's Great! Glad I could help you 😁
+ 5
For sure my problem is not about how to split or convert string to number, it's really about how to group them in the most easy way without build a mastermind.
+ 5
Oh yeah finally made it with your help Kamil!
Here is the result: https://code.sololearn.com/WBo7W7g9EPRm
+ 5
Wouhouh I just update it and I don't see any more bug :3
+ 4
Thanks Kamil! I will tell you tomorrow, I don't want to test with my phone =)
+ 4
Thanks! I still need to correct a small bug but the main is there.