Count the number of Duplicates
This is a list of case-insensitive characters and numeric digits. It can be taken to contain only alphabets (both uppercase and lowercase) and numeric digits.

Here is the task

Here is my solution:

function duplicateCount(text){ if(text.length!=0){ var count=0, j,myreg; text=text.toLowerCase(); for(let i=0;i<text.length;i++){ myreg= new RegExp(text[i],'gi'); if(text.match(myreg).length>=2){ count++; text = text.replace(myreg,''); } } return count; }else{ return 0; } } 

I understood the problem like this: if a character is encountered more than once, we increase the counter. As a result, bring the counter.

  • Give the text of the problem in question. In Russian. This is a Russian-language resource) - Stepan Kasyanenko
  • one
    @ doox911 actually passes the tests. True implementation with the help of regularies .. but this is - DreamChild
  • Probably because of the regular season - they don’t pass by speed, but generally pass. - nick_n_a
  • @DreamChild means, these are bad tests ( - Igor
  • @DreamChild Pass, but not all. - doox911

2 answers 2

So, for the collection:

 function duplicateCount(text){ let t = text.toLowerCase(); let s = new Set(); let dup = new Set(); for (let c of t) { if (s.has(c)) dup.add(c); s.add(c); } return dup.size; } 
  • I really liked your decision. - doox911
  ... text = text.replace(myreg,''); i--; } ... 

Test:

 Test.assertEquals(duplicateCount("abbFcccFde"), 3); 

Without i--; first the first F skipped when b removed, and then the second is skipped when c deleted.

 function duplicateCount(text, expected){ var result = 0; var counts = {}; var textL = text.toLowerCase(); for(var i = 0; i < textL.length; i++) { var currentCount = (counts[textL[i]] || 0) + 1; counts[textL[i]] = currentCount; if (currentCount == 2) result++; } console.log(`result = ${result}, expected = ${expected}`, (result == expected)? "passed" : "failed", text); return result; } duplicateCount("", 0); duplicateCount("abcde", 0); duplicateCount("aabbcde", 2); duplicateCount("aabBcde", 2,"should ignore case"); duplicateCount("Indivisibility", 1); duplicateCount("Indivisibilities", 2, "characters may not be adjacent"); duplicateCount('abcabc', 3); duplicateCount("abbFcccFde", 3); duplicateCount('bbb', 1); 

  • It is not necessary to reduce by one. Maybe line ibiiiii . - Stepan Kasyanenko
  • @StepanKasyanenko Added. - Igor