samedi 26 juin 2021

finding occurences of each element in an array and aranging them according to the count of occurences in ascending or descending order

Q)Given an array of N elements.find the number of occurences of each character and print it in the decreasing order of occurences, if 2 or more number occurs the same number of times, print the numbers in decreasing order. Input Size : |N| <= 100000 Sample Testcase : INPUT 3 3 4 4 7 8 OUTPUT 4 3 8 7

--------------------------------------------------

i was able to convert it to map ,what further steps should i implement to get the answer

--------------------------------------------------

function asc(arr) 
{
let map=new Map
 let c=1;
  for(let i=0;i<arr.length;i++){
if(map.has(arr[i])){
  map.set(arr[i],map.get(arr[i])+1)
 }
else{
       map.set(arr[i],c)
    }
  }
let narr = [...map];
let tmp;
for(i=0;i<narr.length;i++){
  for(j=i+1;j<narr.length;j++){
    if(narr[i][1]>narr[j][1])
{
  tmp = narr[i];
  narr[i]=narr[j];
  narr[j]=tmp;
}
else if((narr[i][1]=narr[j][1])) {
    if(narr[i][0]>narr[j][0])
{      
  tmp = narr[i];
  narr[i]=narr[j];
  narr[j]=tmp;
      }
}
  }
}
return narr;
}
arr=[3,8,7,4,7,3,4];
console.log(asc(arr)); 

Aucun commentaire:

Enregistrer un commentaire