I was wondering if there is a way to check for repeated characters in a string without using double loop. Can this be done with recursion?
An example of the code using double loop (return true or false based on if there are repeated characters in a string):
var charRepeats = function(str) { for(var i = 0; i <= str.length; i++) { for(var j = i+1; j <= str.length; j++) { if(str[j] == str[i]) { return false; } } } return true; }
Many thanks in advance!
The function should detect if the string is a repetition of a same set of characters or not. If it is a repetition of the same set of characters then we should return true, false otherwise. const output = true; because the string 'car' is getting repeated over and over again in the string.
(A recursive solution can be found at the end, of this answer.)
You could use the builtin javascript Array functions some
MDN some reference
var text = "test".split(""); text.some(function(v,i,a){ return a.lastIndexOf(v)!=i; });
callback parameters:
v ... current value of the iteration
i ... current index of the iteration
a ... current array
.split("") create an array from a string
.some(function(v,i,a){ ... }) goes through an array until the functionreturns true
, and ends than right away. (doesn't loop through the whole array, if it finds an match earlier)Details to the some function can be found here
Tests, with several different strings:
var texts = ["test", "rest", "why", "puss"]; for(var idx in texts){ var text = texts[idx].split(""); document.write(text + " -> " + text.some(function(v,i,a){return a.lastIndexOf(v)!=i;}) +"<br/>"); } //tested on win7 in chrome 46+
If recursion is needed.
Update for recursion:
//recursive function function checkString(text,index){ if((text.length - index)==0 ){ //stop condition return false; }else{ return checkString(text,index + 1) || text.substr(0, index).indexOf(text[index])!=-1; } } // example Data to test var texts = ["test", "rest", "why", "puss"]; for(var idx in texts){ var txt = texts[idx]; document.write( txt + " ->" + checkString(txt,0) + "<br/>"); } //tested on win7 in chrome 46+
This will do:
function isIsogram (str) { return !/(.).*\1/.test(str); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With