Rearrange string so that same character become n distance apart JavaScript


We are required to write a JavaScript function that takes in a string with repetitive characters and returns a new string in which all the same characters are exactly n characters away from each other. And the number should be smaller than the length of the array.

For example −

If the input string is: "accessories"
And the number n is 3
Then,
The return value should be: "secrsecisao"

Note − There may be some other permutation to achieve the required output, the order is not important, we should stick to the logic and as long as we fulfil it our output is correct.

Let's write the code for this function −

Example

const str = 'accessories';
const equalDistance = (str, num) => {
   const map = str.split("").reduce((acc, val) => {
      const count = acc.get(val);
      if(typeof count === 'number'){
         acc.set(val, count+1);
      }else{
         acc.set(val, 1);
      };
      return acc;
   }, new Map());
   const arr = Array.from(map).sort((a, b) => b[1] - a[1]);
   let newString = '';
   for(let i = 0, count = 0; i < str.length;){
      if(!arr[count][1]){
         arr.splice(count, 1);
         continue;
      };
      newString += arr[count][0];
      arr[count][1]--;
      i++;
      count = i % num;
   };
   return newString;
};
console.log(equalDistance(str, 4));
console.log(equalDistance('abb', 2));
console.log(equalDistance('aacbbc', 3));

Output

The output in the console will be −

sceasceosri
bab
acbacb

Updated on: 31-Aug-2020

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements