Issue
I'm working in javascript & trying to figure out an algorithm to append incremental numbers to strings, based on existing strings in the program.
Input:
['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4', "Untitled Form"];
So say the user wants to add another string to this list, and they've selected "Untitled Form" as the string to add. So given the input and the existing list, the algorithm would search in the list to check if there is any incrementing number missing e.g In the above code the "Untitled Form - 2" is missing, It should return "Untitled Form - 2" as the new string to add.
Output:
['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4', "Untitled Form - 2"];
It's the same function as in Windows Explorer where you keep adding New Folders ("New Folder (1)", "New Folder (2)" and on and on)
I have a solution for this problem but I think it is not very efficient and the algorithm also checks for the highest number and adds the incremental number after that is "Untitled Form - 6".
Solution
You can do it by extracting existing indexes
and sort them, then compare every index with next one, if difference is bigger than 1
, so you can realize that there is an missed index in that place.like this:
let list = ['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4'];
const findNextIndex = (arr)=> {
const sortedArr = arr.map(item => Number(item.split('-')[1] || 0)).sort((a,b)=> a-b);
if(!sortedArr.includes(0)) return 0;
let index = sortedArr[sortedArr.length-1] + 1; //maximum value
for(let i =0; i< sortedArr.length; i++){
if(sortedArr[i+1] - sortedArr[i] > 1){
index = sortedArr[i] + 1;
break;
}
}
return index;
}
const nextIndex = findNextIndex(list);
list = [...list, `Untitled Form${nextIndex ? ` - ${nextIndex}` : ''}`]
console.log(list)
Answered By - Saeed Shamloo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.