Palindrome challenge on Coderbyte - javascript

I can't figure out why the following code does not work for the Coderbyte challenge where you have to test a string to see if it is a palindrome (the characters being the same when read in reverse as they are normally). I know there are better ways to write the code for the same result, but I still think this way should work (assuming no capital letters or non-alphabetic characters in the input string). But testing it doesn't yield the results I need. Here it is:
function Palindrome(str) {
var myArray = str.split("");
for(var i = 0; i < myArray.length; i++) {
if(myArray[i] === " ") {
myArray.splice(i, 1);
}
}
var firstHalf = myArray.slice(0, Math.floor(myArray.length/2));
var secHalf = myArray.slice(Math.ceil(myArray.length/2));
secHalf.reverse();
if(firstHalf === secHalf) {
return true;
}
return false;
}
What I'm trying to do is split up the input string into an array, remove the spaces, specify the first and second halves of that array, reverse the second half, then compare if the two halves are equal. In cases where the number of characters in the string str is odd the middle character isn't taken into account since it shouldn't matter. And I did try asking this on Coderbyte but my question was not posted for some reason.

You can't do the array comparison using === since that checks if the object references are equal (the variable refers to the same array).
For example:
var a = [1, 2, 3];
var b = [1, 2, 3];
var c = a;
a === a; // true
a === b; // false
a === c; // true
You should check through the array contents by looping:
function Palindrome(str) {
var myArray = str.split("");
for(var i = 0; i < myArray.length; i++) {
if(myArray[i] === " ") {
myArray.splice(i, 1);
}
}
var firstHalf = myArray.slice(0, Math.floor(myArray.length/2));
var secHalf = myArray.slice(Math.ceil(myArray.length/2));
secHalf.reverse();
for (var i = 0; i < firstHalf.length; i++){
if (firstHalf[i] != secHalf[i]) return false;
}
return true;
}

You are comparing two arrays directly with ===. That won't work. First join them into strings:
var myArray = str.split("");
for(var i = 0; i < myArray.length; i++) {
if(myArray[i] === " ") {
myArray.splice(i, 1);
}
}
var firstHalf = myArray.slice(0, Math.floor(myArray.length/2));
var secHalf = myArray.slice(Math.ceil(myArray.length/2));
secHalf.reverse();
// join them like this
firstHalf = firstHalf.join('');
secHalf = secHalf.join('');
return firstHalf === secHalf;
If you want shorter/simpler/faster way to do this, try:
function Palindrome(str) {
str = str.replace(/ /g, '');
return str == str.split('').reverse().join('');
}

Related

Alternative to perform Permutation

I am currently trying to find the various permutations of a string. The code used works for strings with 5 characters. But With more than 5, it throws an error -"too much recursion".
function doPerm(str, arr) {
if (typeof (str) == 'string')
str = str.split('');
if (str.length === 0){
if(allowedPerm(arr.join('')))
permutations.push(arr.join(''));
}
for (var i = 0; i < str.length; i++) {
var x = str.splice(i, 1);
//console.log(i+"--"+str);
arr.push(x);
doPerm(str, arr);
arr.pop();
str.splice(i, 0, x);
}
}
//doPerm("abcde", []);//works returns 120
doPerm("abcdefa", []);
What can I change to avoid this??. And also is there a better way to do it??

Count repeated letters in a string

I'm stuck with the following problem:
I need to find repeated characters in a string.
Basically what I want is regular expression that will match like that
hello - ["ll"];
here - ["ee"];
happiness - ["pp","ss"];
pupil - ["pp"];
I have the one that matches consecutive repeated characters
/([a-z])\1+/g
Also the one that will match repeated chars and everything between them like this one
/([a-z])(?:.*)\1+/g
But cant figure out the correct one.
You can use
([a-zA-Z]).*(\1)
Demo regex
Since you have clarified that you are looking for a solution that will handle something other than double letters in a string, you should use a non-regex approach such as:
Build an associative array with the count of the characters in the string:
var obj={}
var repeats=[];
str='banana'
for(x = 0, length = str.length; x < length; x++) {
var l = str.charAt(x)
obj[l] = (isNaN(obj[l]) ? 1 : obj[l] + 1);
}
console.log(obj)
Prints
{ b: 1, a: 3, n: 2 }
Then build an array of your specifications:
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key]>1) {
repeats.push(new Array( obj[key]+ 1 ).join( key ));
}
}
console.log(repeats)
Prints:
[ 'aaa', 'nn' ]
This method also works well!!
let myString = 'abababc';
let result = {};
for (let str of myString) {
result[str] = result.hasOwnProperty(str) ? result[str] + 1 : 1;
}
console.log(result);
The result will be like this {a: 3, b: 3, c: 1}
For your scenario you second solution seems better. You can get the second letter by other capture group
Regex you be (it is your 2nd RegEx with more one capture group):
/([a-z])(?:.*)(\1)+/g
var re = /([a-z])(?:.*)(\1)+/g;
var str = ['hello', 'here', 'happiness', 'pupil'];
var m;
var result = new Array();
for(var i = 0; i < str.length; i++) {
result[i] = str[i] + "->";
while ((m = re.exec(str[i])) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
result[i] += m[1];
result[i] += m[2] + ",";
}
}
document.getElementById("results").innerHTML = result.join("</br>");
<div id="results"></div>
var obj = {};
var str = "this is my string";
for (var i = 97; i < 97 + 26; i++)
obj[String.fromCharCode(i)] = 0;
for (var i = 0; i < str.length; i++) {
obj[str.charAt(i).toLowerCase()]++;
}
From there you can say obj["a"] to get the number of occurrences for any particular letter.
More complicated than a RegExp solution, however it properly handles banana and assassin, where there are two overlapping groups of characters.
This does make use of array.map, array.filter, and array.reduce, which means this exact solution doesn't support <=IE8, however it can be polyfilled quite easily.
function findDuplicateCharacters(input) {
// Split the string and count the occurrences of each character
var count = input.split('').reduce(function(countMap, word) {
countMap[word] = ++countMap[word] || 1;
return countMap;
}, {});
// Get the letters that were found, and filter out any that only appear once.
var matches = Object.keys(count)
.filter(function (key) { return (count[key] > 1); })
// Then map it and create a string with the correct length, filled with that letter.
.map(function (key) {
return new Array(count[key] + 1).join(key);
});
return matches;
}
var results = ['hello', 'here', 'happiness', 'pupil', 'banana'].map(findDuplicateCharacters);
document.getElementById("results").innerHTML = results.join('<br />');
<div id="results"></div>
var re = /([a-z])(?:.*)(\1)+/g;
var str = ['aaaccbcdd'];
var m;
var result = new Array();
for(var i = 0; i < str.length; i++) {
result[i] = str[i] + "->";
while ((m = re.exec(str[i])) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
result[i] += m[1];
result[i] += m[2] + ",";
}
}
document.getElementById("results").innerHTML = result.join("</br>");
<div id="results"></div>
function charCount(str){
let arr = str.split('');
return arr.reduce((a,p)=>{
a[p] = a[p] ? (a[p]+1) : 1;
return a;
},{});
};
//Try this method
const countRepeatChar = (str) => {
let obj = {};
if (str) {
for (let i = 0; i < str.length; i++) {
if (obj[str[i]]) {
obj[str[i]] += obj[str[i]];
} else {
obj[str[i]] = 1;
}
}
console.log(obj);
}
};
countRepeatChar("aabcddeee");

Writing a string splitting function without using the split method in javascript

I'm trying to create a simple function that takes a string and a delimiter and then splits the string into an array based on the delimiter value. I'm trying to write this function without using the split method in javascript. So say I have a sampleInput = '123$456$789' and a delimiter = '$' then the function stringDelimiter(sampleInput, delimiter) will return ['123', '456', '789'].
var stringDelimiter = function (sampleInput, delimiter) {
var stringArray = [];
var garbageArray = [];
var j = 0;
for (var i = 0; i < sampleInput.length; i++) {
if (sampleInput.charAt(i) == delimiter) {
garbageArray = sampleInput.charAt(i);
j++;
} else {
if (!stringArray[j]) stringArray[j] = '';
stringArray[j] += sampleInput.charAt(i);
}
}
return stringArray;
}
The problem I'm having is if the delimiter appears at the beginning of the string it returns the first element of the array undefined. I'm stuck as to how I can handle this case. So if I have sampleInput = '$123$456$789' and delimiter = '$' it returns ['123', '456', '789'] and not ['undefined','123', '456', '789'].
Any help would be appreciated.
This is a little simpler, and it might do what you want:
var stringDelimiter = function (sampleInput, delimiter) {
var stringArray = [''];
var j = 0;
for (var i = 0; i < sampleInput.length; i++) {
if (sampleInput.charAt(i) == delimiter) {
j++;
stringArray.push('');
} else {
stringArray[j] += sampleInput.charAt(i);
}
}
return stringArray;
}
Your garbageArray seemed unnecessary.
What about using regular expressions?
function x_split(s)
{
return s.match(/([^$]+)/g);
}
E.g.
http://jsfiddle.net/2F9MX/2/
If the current character is delimiter and if the current iteration is 0, continue
This function accepts a string, a delimiter and a flag if empty (aka undefined, null or empty string) elements should be removed from the result array. (Not tested, it was a quick code for now.)
UPDATE
Now it's tested (a bit) and corrected, and I've created a jsFiddle here. Besides, it supports empty delimiter, empty input string, and delimiter with length > 1.
function CustomSplit(str, delimiter, removeEmptyItems) {
if (!delimiter || delimiter.length === 0) return [str];
if (!str || str.length === 0) return [];
var result = [];
var j = 0;
var lastStart = 0;
for (var i=0;i<=str.length;) {
if (i == str.length || str.substr(i,delimiter.length) == delimiter)
{
if (!removeEmptyItems || lastStart != i)
{
result[j++] = str.substr(lastStart, i-lastStart);
}
lastStart = i+delimiter.length;
i += delimiter.length;
} else i++;
}
return result;
}
In case someone needs one for TypeScript (and MicroBit for which I wrote it), here's a altered version of #Scott Sauyet answer for TypeScript:
The code:
function splitString(sampleInput: string, delimiter: string): string[] {
let stringArray = ['']
let j = 0
for (let i = 0; i < sampleInput.length; i++) {
if (sampleInput.charAt(i) == delimiter) {
j++;
stringArray.push('')
} else {
stringArray[j] += sampleInput.charAt(i)
}
}
return stringArray
}
Usage example
let myString = "Lorem ipsum dolor sit amet"
let myArray = splitString(myString, " ")
myArray[0] // "Lorem"
myArray[1] // "ipsum"
You can use this method
const splitCode = (strValue, space) => {
let outPutArray = [];
let temp = '';
for(let i= 0; i< strValue.length; i++){
let temp2 = '';
for(let j= i; j<space.length+i;j++){
temp2 = temp2+strValue[j];
}
if(temp2 === space){
outPutArray.push(temp);
i=i+space.length-1;
temp = '';
}else{
temp = temp+strValue[i];
}
}
return outPutArray.concat(temp)
}

return the first non repeating character in a string in javascript

So I tried looking for this in the search but the closest I could come is a similar answer in several different languages, I would like to use Javascript to do it.
The problem is I have an arbitrary string that I would like to return the first non repeating character. EX: 'aba' -> would return b
'aabcbd' -> would return c.
This is what I have so far, just a simple for loop to start.
var someString = 'aabcbd';
var firstNonRepeatedCharacter = function(string) {
for(var i = 0; i < someString.length; i++){
}
};
http://jsfiddle.net/w7F87/
Not sure where to go from here
You can use the indexOf method to find the non repeating character. If you look for the character in the string, it will be the first one found, and you won't find another after it:
function firstNonRepeatedCharacter(string) {
for (var i = 0; i < string.length; i++) {
var c = string.charAt(i);
if (string.indexOf(c) == i && string.indexOf(c, i + 1) == -1) {
return c;
}
}
return null;
}
Demo: http://jsfiddle.net/Guffa/Se4dD/
If you're looking for the first occurrence of a letter that only occurs once, I would use another data structure to keep track of how many times each letter has been seen. This would let you do it with an O(n) rather than an O(n2) solution, except that n in this case is the larger of the difference between the smallest and largest character code or the length of the string and so not directly comparable.
Note: an earlier version of this used for-in - which in practice turns out to be incredibly slow. I've updated it to use the character codes as indexes to keep the look up as fast as possible. What we really need is a hash table but given the small values of N and the small, relative speed up, it's probably not worth it for this problem. In fact, you should prefer #Guffa's solution. I'm including mine only because I ended up learning a lot from it.
function firstNonRepeatedCharacter(string) {
var counts = {};
var i, minCode = 999999, maxCode = -1;
for (i = 0; i < string.length; ++i) {
var letter = string.charAt(i);
var letterCode = string.charCodeAt(i);
if (letterCode < minCode) {
minCode = letterCode;
}
if (letterCode > maxCode) {
maxCode = letterCode;
}
var count = counts[letterCode];
if (count) {
count.count = count.count + 1;
}
else {
counts[letterCode] = { letter: letter, count: 1, index: i };
}
}
var smallestIndex = string.length;
for (i = minCode; i <= maxCode; ++i) {
var count = counts[i];
if (count && count.count === 1 && count.index < smallestIndex) {
smallestIndex = count.index;
}
}
return smallestIndex < string.length ? string.charAt(smallestIndex) : '';
}
See fiddle at http://jsfiddle.net/b2dE4/
Also a (slightly different than the comments) performance test at http://jsperf.com/24793051/2
var firstNonRepeatedCharacter = function(string) {
var chars = string.split('');
for (var i = 0; i < string.length; i++) {
if (chars.filter(function(j) {
return j == string.charAt(i);
}).length == 1) return string.charAt(i);
}
};
So we create an array of all the characters, by splitting on anything.
Then, we loop through each character, and we filter the array we created, so we'll get an array of only those characters. If the length is ever 1, we know we have a non-repeated character.
Fiddle: http://jsfiddle.net/2FpZF/
Two further possibilities, using ECMA5 array methods. Will return undefined if none exist.
Javascript
function firstNonRepeatedCharacter(string) {
return string.split('').filter(function (character, index, obj) {
return obj.indexOf(character) === obj.lastIndexOf(character);
}).shift();
}
console.log(firstNonRepeatedCharacter('aabcbd'));
On jsFiddle
Or if you want a bit better performance, especially on longer strings.
Javascript
function firstNonRepeatedCharacter(string) {
var first;
string.split('').some(function (character, index, obj) {
if(obj.indexOf(character) === obj.lastIndexOf(character)) {
first = character;
return true;
}
return false;
});
return first;
}
console.log(firstNonRepeatedCharacter('aabcbd'));
On jsFiddle
I came accross this while facing similar problem. Let me add my 2 lines.
What I did is a similar to the Guffa's answer. But using both indexOf method and lastIndexOf.
My mehod:
function nonRepeated(str) {
for(let i = 0; i < str.length; i++) {
let j = str.charAt(i)
if (str.indexOf(j) == str.lastIndexOf(j)) {
return j;
}
}
return null;
}
nonRepeated("aabcbd"); //c
Simply, indexOf() gets first occurrence of a character & lastIndexOf() gets the last occurrence. So when the first occurrence is also == the last occurence, it means there's just one the character.
Here's a Solution using Regex to replace all repeating characters and then returning the first character.
function firstNonRepeat(str) {
// Sorting str so that all repeating characters will come together & replacing it with empty string and taking first character using substr.
var rsl = str.split('').sort().join('').replace(/(\w)\1+/g,'').substr(0,1);
if(rsl) return rsl;
else return 'All characters are repeated in ' + str;
}
console.log(firstNonRepeat('aaabcccdeeef'));
console.log(firstNonRepeat('aaacbdcee'));
console.log(firstNonRepeat('aabcbd'));
First of all, start your loop at 1, not 0. There is no point in checking the first character to see if its repeating, obviously it can't be.
Now, within your loop, you have someString[i] and someString[i - 1]. They are the current and previous characters.
if someString[i] === someString[i - 1] then the characters are repeating, if someString[i] !== someString[i - 1] then they are not repeating, so you return someString[i]
I won't write the whole thing out for you, but hopefully the thought process behind this will help
function FirstNotRepeatedChar(str) {
var arr = str.split('');
var result = '';
var ctr = 0;
for (var x = 0; x < arr.length; x++) {
ctr = 0;
for (var y = 0; y < arr.length; y++) {
if (arr[x] === arr[y]) {
ctr+= 1;
}
}
if (ctr < 2) {
result = arr[x];
break;
}
}
return result;
}
console.log(FirstNotRepeatedChar('asif shaik'));
Here's an O(n) solution with 2 ES6 Sets, one tracking all characters that have appeared and one tracking only chars that have appeared once. This solution takes advantage of the insertion order preserved by Set.
const firstNonRepeating = str => {
const set = new Set();
const finalSet = new Set();
str.split('').forEach(char => {
if (set.has(char)) finalSet.delete(char);
else {
set.add(char);
finalSet.add(char);
}
})
const iter = finalSet.values();
return iter.next().value;
}
let arr = [10, 5, 3, 4, 3, 5, 6];
outer:for(let i=0;i<arr.length;i++){
for(let j=0;j<arr.length;j++){
if(arr[i]===arr[j+1]){
console.log(arr[i]);
break outer;
}
}
}
//or else you may try this way...
function firstDuplicate(arr) {
let findFirst = new Set()
for (element of arr)
if (findFirst.has(element ))
return element
else
findFirst.add(element )
}
function firstUniqChar(str) {
let myMap = new Map();
for(let i = 0; i < str.length; i++) {
let char = str.charAt(i);
if(!myMap.has(char)) {
myMap.set(char, 0);
}
myMap.set(char, myMap.get(char) + 1 );
}
for(let [key, value] of myMap) {
if(value === 1) {
return key;
}
}
return null;
}
let result = firstUniqChar("caabbdccee");
console.log(result);
You can use Map Object and set key and value, where in value you store the count for that particular character, After that you can iterate over map and check where is value 1 and return that key.
Map Object remembers the original insertion order of the keys.
This solution should works with array with integers and string.
function firstNoneRepeating(list, map = new Map()) {
for (let item of list) {
if (map.has(item)) {
map.set(item, map.get(item) + 1);
} else {
map.set(item, 1);
}
}
for (let [key, value] of map.entries()) {
if (value === 1) {
return key;
}
}
}
console.log(firstNoneRepeating("aabcbd"));
console.log(firstNoneRepeating([5, 2, 3, 4, 2, 6, 7, 1, 2, 3]));
let str='aabcbd'
let ans=''
for (let i=0;i<str.length;i++){
if(str.indexOf(str.charAt(i))===str.lastIndexOf(str.charAt(i))){
ans+=str.charAt(i)
break
}
}
console.log(ans)
Fill an empty array with zeros, with same length as the string array, and tally up how many times they appear through the loop. Grab the first one in the tallied array with a value of 1.
function firstNotRepeatingCharacter(s) {
const array = s.split("");
let scores = new Array(array.length).fill(0);
for (let char of array) {
scores[array.indexOf(char)]++;
}
const singleChar = array[scores.indexOf(1)];
return singleChar ? singleChar : "_"
}
You can iterate through each character to find() the first letter that returns a single match(). This will result in the first non-repeated character in the given string:
const first_nonrepeated_character = string => [...string].find(e => string.match(new RegExp(e, 'g')).length === 1);
const string = 'aabcbd';
console.log(first_nonrepeated_character(string)); // c
Here is my solution which have time complexity of o(n)
function getfirstNonRepeatingCharacterInAString(params) {
let count = {};
for (let i = 0; i < params.length; i++) {
let count1 = 0;
if (!count[params.charAt(i)]) {
count[params.charAt(i)] = count1 + 1;
}
else {
count[params.charAt(i)] = count[params.charAt(i)] + 1;
}
}
for (let key in count) {
if (count[key] === 1) {
return key;
}
}
return null;
}
console.log(getfirstNonRepeatingCharacterInAString("GeeksfoGeeks"));
Here is my solution using forEach and convert the string into an array
function firstNotRepeatingCharacter(s) {
var strArr = s.split("");
var found = "_";
strArr.forEach(function(item, index) {
if (strArr.indexOf(item) == index && strArr.indexOf(item, index + 1) == -1) {
if (found === "_") {
found = item;
}
}
})
return found;
}
firstNotRepeatingCharacter("abacabad")
Here is another approach:
Everytime you find equal chars store it in an array and break out of the loop. If the char is not found in the array then you have your first nonRepeating char
function nonRepeatingChars(value) {
const memory = []
for (let i = 0; i < value.length; i++) {
for (let j = i + 1; j < value.length; j++) {
if (value[i] === value[j]) {
memory.push(value[j])
break;
}
}
if (!memory.some(x => x === value[i])) {
return value[i];
}
}
return "all chars have duplicates";
}
console.log('First non repeating char is:',nonRepeatingChars("esen"))
console.log('First non repeating char is:',nonRepeatingChars("esesn"))
console.log('First non repeating char is:',nonRepeatingChars("eseulsn"))
console.log('First non repeating char is:',nonRepeatingChars("esesnn"))
> var firstNonRepeatedCharacter = function (str){
> for(i=0;i<str.length;i++){
> if(str.indexOf(str.charAt(i)) === str.lastIndexOf(str.charAt(i))){
> console.log(str.charAt(i));
> break;
> } } }
>
> firstNonRepeatedCharacter ("areerak");
you can check below link
https://codepen.io/t3veni/pen/wvvxJzm
Easy way to solve this algorithm, very straight forward.
function firstNonRepeatChar(str){
let map = {};
for(let i=0; i<str.length; i++){
if(Object.keys(map).includes(str[i])){
map[str[i]]++
}
else{
map[str[i]] = 1;
}
}
for(let j=0; j< Object.values(map).length; j++){
if(Object.values(map)[j] == 1){
console.log(Object.keys(map)[j]);
return
}
if (j == Object.values(map).length-1 && Object.values(map)[j] != 1){
console.log('_');
return;
}
else{
continue;
}
}
}
nonRepeat("aaabbcccdeeef");
Here is one other solution just using array, using 26 unique character as length of array:
var firstUniqChar = (function(s) {
var arr = [];
var str = s.toLowerCase();
for(let c of str){
let index = c.charCodeAt(0) - "a".charCodeAt(0);
arr[index]? ++arr[index]: arr[index]=1;
}
for(let c of str){
let index = c.charCodeAt(0) - 97;
if(arr[index] == 1){
return c;
};
}
return -1;
}("aabcbd"));
console.log(firstUniqChar);
We can keep track of frequency of each character of the string in an object.
For example : for "aabcbd" we can store the frequency as
{ "a":2, "b":2, "c":1, "d":1 }
This will take O(n) time.
Then we can traverse over this object and find the first character with frequency 1, which will also take O(n) time. So, the time complexity for this approach will be O(n).
const firstNonRepeating=(str)=>{
const obj={};
str.split("").forEach(item=>{
obj[item]
? obj[item]++
: obj[item]=1;
});
const item = Object.keys(obj).find(key=> obj[key] === 1);
return item;
}
Note: I use ES6 Object.keys method which may not work in older
browsers.
//To find first non repeating letter
//It will check for both upper and lower case
//only use one String.indexOf()
var mystr="ohvhvtccggt";
var checkFirstNonRepeating=function(){
var ele=[];
for(var i=0;i<mystr.length;i++) {
var key=mystr.charAt(i);
if(!ele[key])
ele[key]=0;
ele[key]++;
//Just check for second occurance of character
//no need to use indexOf twice
if(mystr.indexOf(key,i+1)==-1 && ele[key]<2)
return mystr[i];
}
return "All repeating letters";
}
console.log(checkFirstNonRepeating());
/*
Input : "ohvhvtoccggt"
Output : All repeating letters
Input :"oohjtht"
Output :j
*/
I used object to keep track of characters count in a string then return the char that has the fa value of 1. Here is a demo:
function firstNotRepeatingCharacter(s) {
// initialize an empty object to store chars
let seen = {};
let letter = '';
// iterate over each char in a string
// if it is already there increase value by one
// else set the value to 1
for(let char of s){
if (seen[char]){
seen[char] +=1;
} else {
seen[char] = 1;
}
}
// iterate over the new constructed object
// if the value is 1 and the output variable is empty
// return the associated key to the value 1
// else return '_'
for(let v in seen){
while(seen[v] == 1 && letter === ''){
letter += v;
return letter;
}
}
return('_');
}
console.log(firstNotRepeatingCharacter("abacabad"));
console.log(firstNotRepeatingCharacter("cbc"));
console.log(firstNotRepeatingCharacter("bcccccccccccccyb"));
console.log(firstNotRepeatingCharacter("aaa"));
The most satisfactory and easy to understand answer is the following.
function firstNotRepeatingCharacter(s) {
const arr = s.split("");
for(let i = 0; i < arr.length; i++){
let chr = arr[i];
if( arr.indexOf(arr[i]) == arr.lastIndexOf(arr[i])){
return arr[i]
}
}
return "_"
}
Explanation: It loops through all the characters of a string from forward and backward and then compares the values. If the index of both forward and backward search is true then it returns that character.
let str = 'aabbcdd';
let val = str.split('').reduce((a, e)=>{ if(str.indexOf(e) == str.lastIndexOf(e)) {a = e }; return a})
console.log(val); // c
the implementation below has a good time complexity and it accounts for letters with different cases:
steps
must touch every character in the string to know if it's repeated or not
function firstNonRepeatingLetter(wordd) {
const chars = {}
let word = wordd.toLowerCase()
// go through chars
// store chars in hash with values of array storing index of char and true if only 1 encountered so far
for (let i = 0; i < word.length; i += 1) {
let char = word[i]
if (chars[char]) {
chars[char][0] = false
} else {
chars[char] = [true, i]
}
}
let output = ''
let index;
for (let key in chars) {
// return char with true and lowest index
if (chars[key][0]) {
index = index === undefined ? chars[key][1] : index
if (index >= chars[key][1]) {
output = key
}
}
}
return index === undefined ? '' : wordd[index]
}
console.log(firstNonRepeatingLetter('sTreSS')) //T```
The bellow solution is a kind of frequency counter pattern and it will run only one loop, so O(n) will be the time complexity.
function firstNotRepeatingCharacter(str) {
const obj = {};
for (let i = 0, L = str.length; i < L; i++) {
const char = str[i];
obj[char] = obj[char] ? obj[char] + 1 : 1;
}
for (let key of Object.keys(obj)) {
if (obj[key] == 1) {
return key;
}
}
return -1;
}
Here is another solution
function firstNotRepeatingCharacter(s) {
const obj = {};
for (let i of s) {
if(!obj[i]) {
obj[i] = 1;
} else if (obj[i]) {
obj[i] = +obj[i] + 1;
}
}
for (let [key, value] of Object.entries(obj)) {
if(value == 1) return key;
}
return "_"
}
Using below method can achieve first non repeated character
function main(str) {
str = String(str).toLowerCase();
let non_repeated_char = 'N/A';
for (let i = 0; i < str.length; i++) {
let currentChar = str[i];
let repeated_times = String(str).split('').filter(e => e == currentChar).length;
if (repeated_times === 1) {
non_repeated_char = currentChar;
break;
}
}
return non_repeated_char;
};
let Result = main("basketball");
console.log("The Non Repeated char is-->", Result);

Remove duplicate commas and extra commas at start/end with RegExp in Javascript, and remove duplicate numbers?

Assume we have a string like the following :
,34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56
How can we convert it to the following string with RegExp in Javascript ?
34,23,4,5,634,12,3,1234,54,123,43,2,3424,45,56
Actually, I wanna remove repeated items and first and last , char
[edited] To turn these into a set of unique numbers, as you are actually asking for, do this:
function scrapeNumbers(string) {
var seen = {};
var results = [];
string.match(/\d+/g).forEach(function(x) {
if (seen[x]===undefined)
results.push(parseInt(x));
seen[x] = true;
});
return results;
}
Demo:
> scrapeNumbers(',1,22,333,22,,333,4,,,')
[1, 22, 333, 4]
If you had an Array.prototype.unique() primitive, you could write it like so in one line:
yourString.match(/\d+/g).map(parseBase10).unique()
Unfortunately you need to be a bit verbose and define your own parseBase10 = function(n){return parseInt(n)} due to this ridiculous hard-to-track-down bug: javascript - Array#map and parseInt
No need for regex. Few tricks
text = ',34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56';
text = text.replace(/,+/g, ','); //replace two commas with one comma
text = text.replace(/^\s+|\s+$/g,''); //remove the spaces
textarray = text.split(","); // change them into array
textarray = textarray.filter(function(e){ return e.length});
console.log(textarray);
// Now use a function to make the array unique
Array.prototype.unique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(this[i] in u)
continue;
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
textarray = textarray.unique();
text = textarray.join(','); //combine them back to what you want
console.log(text);
Demo
If you are familier with jQuery
text = text.replace(/,+/g, ',');
text = $.trim(text);
text = $.unique(text.split(",")).filter(function(e){ return e.length}).join(",");
console.log(text);
Demo
This will do it:
function arrIndex(fnd, arr) {
for (var len = arr.length, i = 0; i < len; i++) {
if (i in arr && arr[i] === fnd) {
return i;
}
}
return -1;
}
function scrapeNumbers(str) {
var arr = str.replace(/,+/g, ",").replace(/^,/, "").replace(/,$/, "").split(",");
for (var i = 0, len = arr.length, rtn = []; i < len; i++) {
if (i in arr && arrIndex(arr[i], rtn) == -1) {
rtn.push(arr[i]);
}
}
return rtn.join(",");
}
var str = ",,34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56,,";
alert(scrapeNumbers(str));
Here is a jsFiddle
Note: I created a custom array.indexOf function for a better browser support

Categories

Resources