-2

Can anyone help me to get the string characters replacing with '(' for single repetition of a character and replacing with ')' for multiple repetition of a character from a given string in JavaScript.

For Example:

let a = "abbcdeeff";
// Output -> ())(())))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Ram
  • 17
  • 2
  • Show us your approach please – tarkh Apr 21 '21 at 11:57
  • Hi, A random string of character is passed, for example: "draft" I need the output to be as (((((. If I pass the string value as "people" I need the output to be as ))()() – Ram Apr 21 '21 at 12:12

2 Answers2

2

Perhaps this using frequency counting from this question

const counter = s => [...s].reduce((a, c) => (a[c] = a[c] + 1 || 1) && a, {})

const tranformStr = s => {
  const freq = counter(s)
  return s.replace(/./g,char => freq[char] > 1 ? ")" : "(")
};


let a = "abbcdeeff"; // Output -> ())(())))
console.log(tranformStr(a))
let b = "draft";
console.log(tranformStr(b)); // (((((
let c = "people"
console.log(tranformStr(c)); // ))()()
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

let a = "abbcdeeff";
// Output -> ())(())))
function getResult(text){
  const stringToTest = text.split('');
  let OutputString ='';
  for (var i=0; i< stringToTest.length; i++) {
        let count = 0;
        for (var j=0; j<stringToTest.length; j++) {
            if (a[i] == a[j])
                count++;
        }
        count == 1 ? OutputString += '(' : OutputString += ')';       
    }
    return OutputString;
}
console.log(getResult(a))
Toxy
  • 696
  • 5
  • 9