Rk220
Rk220

Reputation: 181

Reducing duplicate characters in a string to a given minimum

I was messing around with the first question here: Reduce duplicate characters to a desired minimum and am looking for more elegant answers than what I came up with. It passes the test but curious to see other solutions. The sample tests are:

reduceString('aaaabbbb', 2) 'aabb'  
reduceString('xaaabbbb', 2) 'xaabb' 
reduceString('aaaabbbb', 1) 'ab'    
reduceString('aaxxxaabbbb', 2)  'aaxxaabb'

and my solution (that passes these tests):

reduceString = function(str, amount) {
  var count = 0;
  var result = '';
  for (var i = 0; i < str.length; i++) {
    if (str[i] === str[i+1]) {
      count++;
      if (count < amount) {
        result += str[i];
      }
    } else {
      count = 0;
      result += str[i];
    } 
  };
  return result;
}

Upvotes: 2

Views: 3174

Answers (6)

Artem Fedotov
Artem Fedotov

Reputation: 452

Up above regex solutions are much more better, but here is my accepted solution with reduce:

  1. make an array from string via spread operator
  2. Check the previous item
  3. find how many times char is repeated in result string
  4. otherwise concat result string with the current char

Don`t forget to use the second argument as the initial value, and return for each cases

reduceString = function(str, amount) {
    return [...str].reduce(((res, cur)=>{
        if(res.length && cur === res[res.length-1]){
            dupsCount = [...res].filter(char => char === cur).length
            if(dupsCount===amount){
                return res;
            }
            else {
                res+=cur;
                return res;
            }
        }
        res+=cur;
        return res;
    }),"")
}

Upvotes: 0

Redu
Redu

Reputation: 26161

I guess my best solution would be like

var str = "axxxaabbbbcaaxxxaab",
 redStr = (s,n) => s.replace(/(\w)\1+/g,"$1".repeat(n));
console.log(redStr(str,2));

Upvotes: 2

iomv
iomv

Reputation: 2697

With regex:

var reduceString = function(str, amount) {
var x = [ ...new Set(str) ];
for (var c of x){
    var rex = new RegExp(c + '{'+amount+',}','g');
    str = str.replace(rex,string(c,amount));
  }
  return str;
};

var string = function(c,amount){
    for(var i=0,s="";i<amount;i++)s+=c;
    return s;
};

Upvotes: 0

chungtinhlakho
chungtinhlakho

Reputation: 930

You can use reg expression instead. tested in javascript.

how it works:

(.) //match any character
\1 //if it follow by the same character
+{2 //more than 1 times
/g //global
$1 //is 1 time by $1$1 is 2 times 

     reduceString('aaaabbbb', 2) 
     reduceString('xaaabbbb', 2) 
            reduceString('aaaabbbb', 1)     
            reduceString('aaxxxaabbbb', 2) 

            function reduceString(txt,num)
            {
                var canRepeat=['$1'];
               for (i=1;i<num;i++)
               {
                  canRepeat.push('$1')
               }
                canRepeat = canRepeat.join('');

                console.log(txt.replace(/(.)\1{2,}/g, canRepeat))

            }      

Upvotes: 0

wot
wot

Reputation: 845

Just use regular expressions.

var reduceString = function (str, amount) {
    var re = new RegExp("(.)(?=\\1{" + amount + "})","g");
    return str.replace(re, "");
}

Upvotes: 6

RunningFromShia
RunningFromShia

Reputation: 610

I tried to make it as short as possible:

reduceString = function(str, amount) {
    var finalString = '', cL = '', counter;
    str.split('').forEach(function(i){
        if (i !== cL) counter = 0;
        counter++;
        cL = i;
        if (counter <= amount ) finalString = finalString + i;
    });
    return finalString;
}

Upvotes: 0

Related Questions