Skip to content

Instantly share code, notes, and snippets.

@Robert-Wett
Created February 3, 2015 03:13
Show Gist options
  • Save Robert-Wett/c4a99026025e38d3b6e3 to your computer and use it in GitHub Desktop.
Save Robert-Wett/c4a99026025e38d3b6e3 to your computer and use it in GitHub Desktop.
Repeated Characters in a String
/**
* Return the number of characters that are repeated in a given word/sentence
*/
// mine, with no big bells and whistles. Split the text and increase the count
// for each instance of the character. Tally everything above count of 1 and return.
function duplicateText( text ) {
var counts = {};
var numDups = 0;
text.split('').map(function( c ) {
if ( counts[c] ) counts[c]++;
else counts[c] = 1;
});
Object.keys( counts ).map(function( key ) {
if ( counts[key] > 1 ) numDups++;
});
return numDups;
}
// clever regex
// Breaks down the text into an array, sorts it to bring all characters next to each other, then
// counts the matches it receives for characters repeated.
function duplicateCount(text){
return (text.toLowerCase().split('').sort().join('').match(/(\w)\1+/g )||[]).length
}
// actually readable and clever
// This one rocks - it maps each character and checks that it exists at that index
// and that it ISN'T the last occurence of the character. Very clever use of .lastIndexOf()
function duplicateCount(text){
text = text.toLowerCase()
return text.split('').filter(function (c, i) {
return text.indexOf(c) == i && text.indexOf(c) != text.lastIndexOf(c)
}).length
}
// wtf...
function duplicateCount(text){
return text.toLowerCase().split('').reduce(function(r, v){
return r.c[v] = (r.c[v] || 0) + 1, r.t = r.t + (r.c[v] == 2), r;
}, {c: {}, t: 0}).t;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment