Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript prototype sorting function don't compare with all members

Tags:

javascript

while I was cracking the leet code task I bumped into some unexpected behavior of the .sort function, so I couldn't finish my task until I implemented the insertion sorting function myself which helped me to sort an array of chars properly.

So the question: why this function doesn't compare with all the array members?


function customSortString(order: string, s: string): string {
    const map={};
    for(let i=0;i<order.length;i++){
        map[order[i]]=i;
    }
    const newStr=[...s].sort((a,b)=>{
        if(map[a]===undefined || map[b]===undefined || a===b){
            return 0;
        }
        if(map[a]<map[b]){
            return -1;
        }
        return 1;
    })
    return newStr.join('');
    
};

if I call

customSortString("exv","xwvee")

it will return 'xweev', but expected "eexvw"

here is a description of the problem enter image description here

If I put console.log into to sorting function

w x
v w
e v
e w
e v
e e
e v

So I can see, that "x" is not compared with "e". But if it did compare it would return 1 and would display "e" first then "x"

I hope I explained clearly, but ask questions if you didn't

like image 627
fake822 Avatar asked Nov 28 '25 18:11

fake822


2 Answers

You need to move unknown characters to the end, with a large value.

function customSortString(order, s) {
    const map = {};
    for (let i = 0; i < order.length; i++) map[order[i]] = i + 1;
    return [...s]
        .sort((a, b) => (map[a] || Infinity) - (map[b] || Infinity))
        .join('');
};

console.log(customSortString("exv", "xwvee"));
like image 169
Nina Scholz Avatar answered Dec 01 '25 08:12

Nina Scholz


Another, more efficient answer,I use the map to record the frequency of every letters appearance,if a letter not in the map I will add it ,finally, I use repeat() to calculate all the letters in the map

function sortStr(order, s) {
  console.time('test')
  const map = {};
  for (const i of order) {
    map[i] = 0
  }
  for (const i of s) {
    const num = map[i]
    map[i] = (num || 0) + 1
  }
  let res = '';
  for (const i in map) {
    res += i.repeat(map[i])
  }
  console.timeEnd('test')
  return res
}
const str = 'sdlfjsdifsdkfnweoosdfopdkmfndweoddfjosdfopdkmfndweoddfjosdfopdkmfndweoddfosdfopdkmfndweosdfopdkmfndweoddfjsdigklwjroddfjsdigklwjrjsdigklwjrsdigklwjrsdigklwjrdjlfgjsnfklgosdfopdkmfndweoddfjsdosdfopdkmfndweoddfjsdigklwjrigklwjroskfosdfopdkmfndweoddfjsdigklwjrgmcjbdlsmclgeosdfopdkmfndweoddfjsdigklwjrriciogiodfklsdgi'
console.log(sortStr('iskgupoeqvxzlafrdmn', str))
like image 28
moon Avatar answered Dec 01 '25 06:12

moon