Character with longest consecutive repetition - javascript

i think i have wirtten the correct code for the problem only one thing and it that i return the first longest sequence how can i alter that to return the last maximum sequence?
an example from codewars editor :
for input '00000000000000111111111111111112222222222222223333333333333344444444444445555555555555666666666666777777777777888888888888888999999999999999999aaaaaaaaabbbbbbbbbbbbbbbbcccccccccccccccccccdddddddddddddddddddeeeeeeeeeeeeeeefffffffffffffggggggggggggggghhhhhhhhhhhhhiiiiiiiiiijjjjjjjjjjjjjjkkkkkkkkkkkkllllllllllmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooopppppppppppppppppqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrssssssssssttttttttttttuuuuuuvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyzzzzzzzzzzzzzz'
Expected: ['c', 19], instead got: ['0', 19]
here is my code:
function longestRepetition(s) {
var count = 0;
var temp = s.charAt(0);
var arr = [];
for (var i = 0; i < s.length; i++) {
if (temp === s.charAt(i)) {
count++
temp = s.charAt(i)
}
else {
temp = s.charAt(i);
arr.push(count)
count = 1;
}
if(i==s.length-1)
arr.push(count);
}
if(arr.length>0)
{
var Max=arr[0]
for(var i=0;i<arr.length;i++)
{
if(Max<=arr[i])
Max=arr[i];
}
}
else var Max=0;
var mindex=arr.indexOf(Max);
return [s.charAt(mindex),Max]
}

I think this would be easier with a regular expression. Match any character, then backreference that character as many times as you can.
Then, you'll have an array of all the sequential sequences, eg ['000', 'aaaaa']. Map each string to its length and pass into Math.max, and you'll know how long the longest sequence is.
Lastly, filter the sequences by those which have that much length, and return the last item in the filtered array:
function longestRepetition(s) {
const repeatedChars = s.match(/(.)\1*/g);
const longestLength = Math.max(...repeatedChars.map(str => str.length));
const longestChars = repeatedChars.filter(str => str.length === longestLength);
return [longestChars.pop(), longestLength];
}
console.log(longestRepetition('00000000000000111111111111111112222222222222223333333333333344444444444445555555555555666666666666777777777777888888888888888999999999999999999aaaaaaaaabbbbbbbbbbbbbbbbcccccccccccccccccccdddddddddddddddddddeeeeeeeeeeeeeeefffffffffffffggggggggggggggghhhhhhhhhhhhhiiiiiiiiiijjjjjjjjjjjjjjkkkkkkkkkkkkllllllllllmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooopppppppppppppppppqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrssssssssssttttttttttttuuuuuuvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyzzzzzzzzzzzzzz'));

The issue in your code is that minindex is an index in your arr, but that index has nothing to do with s. So s.charAt(minindex) makes no sense. You should maintain for which character you had found the count. For instance you could push in arr both the count and the corresponding character (as a subarray with two values). Then the rest of your code would only need little modification to make it work.
Applying this idea to your code without changing anything else, we get this:
function longestRepetition(s) {
var count = 0;
var temp = s.charAt(0);
var arr = [];
for (var i = 0; i < s.length; i++) {
if (temp === s.charAt(i)) {
count++
temp = s.charAt(i) // Not necessary: was already equal
}
else {
arr.push([temp, count]); // <--- pair, BEFORE changing temp
temp = s.charAt(i);
count = 1;
}
if(i==s.length-1)
arr.push([temp, count]); // <---
}
if(arr.length>0)
{
var Max=arr[0]; // <-- Max is now a pair of char & count
for(var i=0;i<arr.length;i++)
{
if(Max[1]<arr[i][1]) // Comparison changed to just less-than
Max=arr[i];
}
}
else Max=[null, 0]; // Must be a pair here also
return Max; // Just return the pair
}
console.log(longestRepetition('00000000000000111111111111111112222222222222223333333333333344444444444445555555555555666666666666777777777777888888888888888999999999999999999aaaaaaaaabbbbbbbbbbbbbbbbcccccccccccccccccccdddddddddddddddddddeeeeeeeeeeeeeeefffffffffffffggggggggggggggghhhhhhhhhhhhhiiiiiiiiiijjjjjjjjjjjjjjkkkkkkkkkkkkllllllllllmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooopppppppppppppppppqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrssssssssssttttttttttttuuuuuuvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyzzzzzzzzzzzzzz'));
But you can do the same with less code:
function longestRepetition(s) {
let result = [null, 0]; // pair of character and count
for (var i = 0; i < s.length; null) {
let start = i++;
while (i < s.length && s[i] === s[start]) i++; // Find end of series
if (i - start > result[1]) result = [s[start], i - start];
}
return result;
}
console.log(longestRepetition('00000000000000111111111111111112222222222222223333333333333344444444444445555555555555666666666666777777777777888888888888888999999999999999999aaaaaaaaabbbbbbbbbbbbbbbbcccccccccccccccccccdddddddddddddddddddeeeeeeeeeeeeeeefffffffffffffggggggggggggggghhhhhhhhhhhhhiiiiiiiiiijjjjjjjjjjjjjjkkkkkkkkkkkkllllllllllmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooopppppppppppppppppqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrssssssssssttttttttttttuuuuuuvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyzzzzzzzzzzzzzz'));

The solution below answers the question with O(n) runtime:
function longestRepetition(s) {
let count = s.length > 0 ? 1 : 0
let char = s.length > 0 ? s[0] : ''
for (let string_i = 0; string_i < s.length - 1; string_i += 1) {
// keep track of current_char
let current_char = s[string_i]
let next_char = s[string_i + 1]
// while the next char is same as current_char
let tracker = 1
while (current_char === next_char) {
// add one to tracker
tracker += 1
string_i += 1
next_char = s[string_i + 1]
}
// if tracker greater than count
if (tracker > count) {
// returned char = current char
// count =tracker
count = tracker;
char = current_char;
}
}
return [char, count]
}
console.log(longestRepetition("bbbaaabaaaa"))//, ["a",4]

Related

want to get a count of repeated values on an array [duplicate]

This question already has answers here:
JavaScript function to automatically count consecutive letters in a string
(5 answers)
Closed 1 year ago.
I am a beginner in javascript, I want to get a count of repeated values on an array
I have a string "aaaaaabbbbbbbcccccccaa" and I want the output array be like ["a6", "b7", "c7", "a2"];
I tied but failed. Please help me out
Thanks In Advance :)
var a = "aaaaaabbbbbbbcccccccaa";
function aa(data){
var a = [];
var x = [];
//var b = data.split("")
// var b = data.split("").filter((val,key, arr)=>{
// //console.log(arr.indexOf(val) +" "+ key )
// return arr.indexOf(val) === key
// })
//console.log(b);
for(let i = 0; i<= data.length-1; i++){
for(let j = 0; j<= data.length-1; j++){
if(data[i] !== data[j] && x.indexOf(data[i]+""+j) <0){
x.push(data[i]+""+j);
a.push(data[i] +""+ j);
break;
}
}
}
console.log(x);
return a;
}
console.log(aa(a));
I'd use a regular expression to match repeated characters in the string, then map them to match[0] + match.length to get the concatenated substring for that portion:
const aa = data => data
.match(/(.)\1*/g)
.map(match => match[0] + match.length);
console.log(aa('aaaaaabbbbbbbcccccccaa'));
If you don't want to use a regular expression, don't use a nested loop like that from 0 to the string length - instead, count up repeated characters from inside the first loop, starting at the current i index and incrementing it:
function aa(data) {
const result = [];
for (let i = 0; i < data.length; i++) {
const char = data[i];
let matches = 1;
while (data[i + 1] === char) {
i++;
matches++;
}
result.push(char + matches);
}
return result;
}
console.log(aa('aaaaaabbbbbbbcccccccaa'));

How to shuffle a number following a sequence (not random)

I need to build a function that returns a given number shuffled writing one digit from the front of the number and the following taken from the back, then the 3rd digit from the front of the number and the 4th from the back and so on.
Example:
const initialNumber = 123456 should return
const finalNumber = 162534
or
const initialNumber2 = 104 should return
const finalNumber2 = 140
Also, the number should be between the values of 0 and 100.000.000.
How to do it? Should I first transform the number into an array first of all using the split() method and then using a for loop?
You can do it with splitting the input into array and reduce:
const shuffle = input => input.toString().split('').reduce((acc, item, index, data) => {
const arr = (index % 2 ? data.slice().reverse() : data);
return acc.concat(arr[Math.floor(index / 2)]);
}, []).join('');
console.log(shuffle(104)); // 140
console.log(shuffle(123456)); // 162534
console.log(shuffle(1234567)); // 1726354
A bit reduced code:
const shuffle = input => input.toString().split('').reduce((acc, item, index, data) =>
acc.concat((index % 2 ? data.slice().reverse() : data)[Math.floor(index / 2)]), []
).join('');
I would prefer converting the number to a string, then using that string in a for loop.
function shuffle(num) {
var str = num.toString();
var result = "";
if(!isNaN(num) && num >= 0 && num <= 100000000) {
for(var i = 0; i < str.length; i++) {
if(i % 2 == 0) {
result += str[Math.floor(i / 2)];
} else {
result += str[str.length - Math.floor(i / 2 + 1)];
}
}
}
return result;
}
console.log(shuffle(123456)); // 162534
console.log(shuffle(1234567)); // 1726354
console.log(shuffle(104)); // 140
This may work as a very basic algo.
function shuffleNum(num,i){
var numArr = num.toString().split('');
var front = numArr.splice(0,i);
var back = numArr.pop();
var shuffledArr = front.concat(back,numArr);
return parseFloat(shuffledArr.join(''));
}
// Test
var num = 12345;
for(var i=0;i<num.toString().length;i++){
num = shuffleNum(num);
console.log(num);
}
// Output
// 51234
// 45123
// 34512
// 23451
// 12345
The best way is to use array push function.
function shuffle(a) {
var b = a.toString();
var c = [];
for(let i=0; i<b.length/2; i++) {
c.push(b[i]);
if(i==(Math.ceil(b.length/2)-1) && b.length%2==1) continue;
c.push(b[b.length-i-1]);
}
return c.join("");
}
Java code snippet.
public static int solution(int a) {
int[] arr = Integer.toString(a).chars().map(e->e-'0').toArray();
System.out.println(Arrays.toString(arr));
int[] temp = new int[arr.length];
int j=1;
for(int i = 0; i<arr.length; i++) {
if(i % 2 == 0) {
temp[i] = arr[i/2];
} else {
temp[i] = arr[arr.length - j];
j++;
}
}
System.out.println(Arrays.toString(temp));

Find all permutations of smaller string s in string b (JavaScript)

I've been trying to find a O(n) solution to the following problem: Find the number of anagrams (permutations) of string s in string b, where s.length will always be smaller than b.length
I read that the optimal solution involves keeping track of the frequencies of the characters in the smaller string and doing the same for the sliding window as it moves across the larger string, but I'm not sure how that implementation actually works. Right now my solution doesn't work (see comments) but even if it did, it would take O(s + sn) time.
EDIT: Sample input: ('aba', 'abaab'). Output: 3, because 'aba' exists in b starting at index 0, and 'baa' at 1, and 'aab' at 2.
function anagramsInStr(s,b) {
//O(s)
let freq = s.split("").reduce((map, el) => {
map[el] = (map[el] + 1) || 1;
return map;
}, {});
let i = 0, j = s.length;
// O(n)
for (let char in b.split("")) {
// O(s)
if (b.length - char + 1 > s.length) {
let window = b.slice(i,j);
let windowFreq = window.split("").reduce((map, el) => {
map[el] = (map[el] + 1) || 1;
return map;
}, {});
// Somewhere about here compare the frequencies of chars found in the window to the frequencies hash defined in the outer scope.
i++;
j++;
}
}
}
Read through the comments and let me know if you have any questions:
function countAnagramOccurrences(s, b) {
var matchCount = 0;
var sCounts = {}; // counts for the letters in s
var bCounts = {}; // counts for the letters in b
// construct sCounts
for (var i = 0; i < s.length; i++) {
sCounts[s[i]] = (sCounts[s[i]] || 0) + 1;
}
// all letters that occur in sCounts
var letters = Object.keys(sCounts);
// for each letter in b
for (var i = 0; i < b.length; i++) {
// maintain a sliding window
// if we already have s.length items in the counts, remove the oldest one
if (i >= s.length) {
bCounts[b[i-s.length]] -= 1;
}
// increment the count for the letter we're currently looking at
bCounts[b[i]] = (bCounts[b[i]] || 0) + 1;
// test for a match (b counts == s counts)
var match = true;
for (var j = 0; j < letters.length; j++) {
if (sCounts[letters[j]] !== bCounts[letters[j]]) {
match = false;
break;
}
}
if (match) {
matchCount += 1;
}
}
return matchCount;
}
console.log(countAnagramOccurrences('aba', 'abaab')); // 3
EDIT
A note about the runtime: this is sort of O(nk + m), where n is the length of s, m is the length of b, and k is the number of unique characters in b. Since m is always less than n, we can reduce to O(nk), and since k is bounded by a fixed constant (the size of the alphabet), we can further reduce to O(n).

longest substring of non repeating characters javascript

The problems asks "given a string, find the longest non-repeating sub-string without repeating characters". I am a little stumped why returning my code is not working for the string "dvdf" for example. Here is my code :
function lengthOfLongestSubstring(check) {
var letters = check.split("");
var max = 0;
var result = [];
for (var i = 0; i < letters.length; i++) {
var start = i
if (result.indexOf(letters[i]) === -1) {
result.push(letters[i])
} else {
i = i - 1
result = []
}
if (max === 0 || max < result.length) {
max = result.length
}
}
return max
}
This implementation gives the correct result for "dvdf".
It adds characters to current_string while there is no duplicate. When you find a duplicate cut current_string to the point of the duplicate. max is the max length current_string had at any time. This logic seems correct to me so I think it's correct.
function lengthOfLongestSubstring(string) {
var max = 0, current_string = "", i, char, pos;
for (i = 0; i < string.length; i += 1) {
char = string.charAt(i);
pos = current_string.indexOf(char);
if (pos !== -1) {
// cut "dv" to "v" when you see another "d"
current_string = current_string.substr(pos + 1);
}
current_string += char;
max = Math.max(max, current_string.length);
}
return max;
}
lengthOfLongestSubstring("dvdf"); // 3
The value of current_string in each round is "", "d", "dv", "vd", "vdf".
By replacing the result array with a map storing the last index for each encountered character, you can modify the loop body to jump back to one after the last index of an identical character and continue your search from there instead of just restarting from the current position via currently i = i - 1 which fails in cases such as 'dvdf':
Below is your code with changes to accommodate a map in place of an array:
function lengthOfLongestSubstring(check) {
var letters = check.split("");
var max = 0;
var result = new Map();
var start = 0;
for (var i = 0; i < letters.length; i++) {
if (!result.has(letters[i])) {
result.set(letters[i], i);
} else {
i = result.get(letters[i]);
result.clear();
}
if (max < result.size) {
max = result.size;
}
}
return max;
}
// Example:
console.log(lengthOfLongestSubstring("dvdf")); // 3
Here's a solution using Sliding window and HashMap.
var lengthOfLongestSubstring = function(str) {
if (!!!str.length || typeof str !== 'string') return 0;
if (str.length == 1) return 1;
let hashTable = {};
let longestSubstringLength = 0;
let start = 0;
for (let i = 0; i < str.length; i++) {
if (hashTable[str[i]] !== undefined && hashTable[str[i]] >= start) {
start = hashTable[str[i]] + 1;
}
hashTable[str[i]] = i;
longestSubstringLength = Math.max(longestSubstringLength, (i - start + 1))
}
return longestSubstringLength;
}
I figured out an easier solution:
function longestSubstring(str) {
let left = 0;
let max = 0;
let result = new Set();
for (let r = 0; r < str.length; r++) {
//The code will check for an existing item on the set
// If found, all the previously saved items will be deleted
// the set will return to being empty
while (result.has(str[r])) {
result.delete(str[left]);
left += 1;
}
result.add(str[r]);
max = Math.max(max, r - left + 1);
}
console.log(result);
return max;
}
console.log(longestSubstring('abcabccbc')); //3
Today (January 7th, 2021) this was the Leetcode question of the day. I initially used a solution very similar to the selected answer. Performance was okay but after reviewing the answer solution documentation I rewrote my answer using the sliding window technique (examples were only in Java and Python) since I was curious about how much of a performance improvement this would result in. It is slightly more performant (144ms versus 160ms) and has a lower memory footprint (42mb versus 44.9mb):
function lengthOfLongestSubstring(s: string): number {
let stringLength = s.length;
let maxLength = 0;
const charMap = new Map();
let pos = 0;
for (let i = 0; i < stringLength; i++) {
if (charMap.has(s[i])) {
pos = Math.max(charMap.get(s[i]), pos);
}
maxLength = Math.max(maxLength, i - pos + 1);
charMap.set(s[i], i + 1);
}
return maxLength;
}
console.log(lengthOfLongestSubstring("dvdf"));
Try this:
function lengthOfLongestSubstring (str) {
const map = new Map();
let max = 0;
let left = 0;
for (let right = 0; right < str.length; right++) {
const char = str[right];
if (map.get(char) >= left) left = map.get(char) + 1;
else max = Math.max(max, right - left + 1);
map.set(char, right);
}
return max;
}
You can try this:
function lengthOfLongestSubstring(str) {
let longest = "";
for (let i = 0; i < str.length; i++) {
if (longest.includes(str[i])) {
return longest.length
} else {
longest += str[i];
}
}
return longest.length;
}
console.log(lengthOfLongestSubstring("abcabcbb"));
console.log(lengthOfLongestSubstring("bbbbb"));
console.log(lengthOfLongestSubstring("abcdef"));
console.log(lengthOfLongestSubstring(""));
reset i to i -1 is incorrect. you need another loop inside the for loop. you try something like this (i didn't check the index carefully).
function lengthOfLongestSubstring(check){
var letters = check.split("");
var max = 0;
for (var i = 0; i < letters.length; i++) {
var result = [];
var j = i;
for(;j < letters.length; j++) {
if (result.indexOf(letters[j]) === -1) {
result.push(letters[j]);
} else {
break;
}
}
if(j - i > max) {
max = j - i;
}
}
return max;
}
You can try sliding window pattern to solve this problem.
function lengthOfLongestSubstring(str) {
let longest = 0;
let longestStr = "";
let seen = {};
let start = 0;
let next = 0;
while (next < str.length) {
// Take current character from string
let char = str[next];
// If current character is already present in map
if (seen[char]) {
// Check if start index is greater than current character's last index
start = Math.max(start, seen[char]);
}
// If new substring is longer than older
if (longest < next - start + 1) {
longest = next - start + 1;
// Take slice of longer substring
longestStr = str.slice(start, next + 1);
}
// Update current characters index
seen[char] = next + 1;
// Move to next character
next++;
}
console.log(str, "->", longestStr, "->", longest);
return longest;
}
lengthOfLongestSubstring("dvdfvev");
lengthOfLongestSubstring("hello");
lengthOfLongestSubstring("1212312344");
Find Longest Unique Substring using Map Method
var str = "aaabcbdeaf";
var start = 0;
var map = new Map();
var maxLength = 0;
var longStr = '';
for(next =0; next< str.length ; next++){
if(map.has(str[next])){
map.set(str[next],map.get(str[next])+1);
start = Math.max(start,map.get(str[next]));
}
if(maxLength < next-start+1){
maxLength = next-start+1;
longStr = str.slice(start,next+1);
}
map.set(str[next],next);
}
console.log(longStr);
You can try something like that:
function maxSubstring(s) {
const array = []
const lengthS = s.length
const pusher = (value) => {
if (value !== '') {
if (array.length > 0) {
if (array.indexOf(value) === -1) {
array.push(value)
}
} else {
array.push(value)
}
}
}
pusher(s)
for (const [index, value] of s.split('').entries()) {
let length = lengthS
let string = s
const indexO = s.indexOf(value)
pusher(value)
while (length > indexO) {
pusher(string.slice(index-1, length + 1))
length = --length
}
string = s.slice(index, lengthS)
}
array.sort()
return array.pop()
}
console.log(maxSubstring('banana'))
console.log(maxSubstring('fgjashore'))
console.log(maxSubstring('xyzabcd'))
Find Longest unique substring without using MAP(). Just simple slice().
The same can be used to return longest unique string.
Just replace "return max => return str"
const string = "dvdf";
var lengthOfLongestSubstring = function() {
if(string.length == 1) return 1;
if(string.length == 0) return 0;
let max = 0,i = 0, str = "";
while(i < string.length){
const index = str.indexOf(string.charAt(i));
if(index > -1) {
// s = "fiterm".slice(1,4) => ite
str = str.slice(index + 1, string.length);
}
str += string.charAt(i);
max = Math.max(str.length, max);
i++;
}
return max;
};
Logest unqiue substring:
function lengthOfLongestSubstring(s) {
if(s.length < 2) {
return s.length;
}
let longestLength = 1;
let currentStr = '';
for(let i=0 ; i < s.length ; i++){
if(currentStr.includes(s.charAt(i))){
let firstSeen = currentStr.indexOf(s.charAt(i));
currentStr = currentStr.substring(firstSeen+1,currentStr.length);
}
currentStr += s.charAt(i);
longestLength = Math.max(currentStr.length,longestLength);
}
return longestLength;
};
One liner with reduce method.
const subStrOfUniqueChar = str => [...str].reduce((p,c) => ( p.includes(c) ? (p += c, p.substr(p.indexOf(c)+1)) : p += c),'');
console.log(subStrOfUniqueChar('dvdf').length);
function lengthOfLongestSubstring(s: string): number {
const arr = s.split("");
let longest = 0;
const set: Set<string> = new Set();
for (let i = 0; i < arr.length; i++) {
set.add(arr[i]);
let tryIndex = i + 1;
while (arr[tryIndex] && !set.has(arr[tryIndex])) {
set.add(arr[tryIndex]);
tryIndex++;
}
if (set.size > longest) {
longest = set.size;
}
set.clear();
}
return longest;
}
I wanted to toss my hat in this ring because I feel like I've found a pretty creative solution to this. No if/else blocks are needed as the substring.indexOf() will attempt to find the matching string character in the array and delete the indexes of the array up to, and including, the match (+1). If an indexOf() call finds no match it will return a -1, which added to +1 becomes a .splice(0,0) which will remove nothing. The final Math check factors in the last character addition in the loop to determine which outcome is higher.
const findSubstring = string => {
let substring = [];
let maxCount = 0;
for (let i = 0; i < string.length; i++) {
maxCount = Math.max(substring.length, maxCount);
substring.splice(0, substring.indexOf(string[i]) + 1);
substring.push(string[i]);
}
maxCount = Math.max(substring.length, maxCount);
return maxCount;
}
uses sliding window concept
function lengthOfLongestSubstring(s) {
var letters = s.split("");
var subStr = "";
var result = [];
var len = 0;
let maxLen = 0;
for (var i = 0; i < letters.length; i++) {
const position = result.indexOf(letters[i]);
if (position === -1) {
result.push(letters[i]);
len += 1;
} else if (letters[i]) {
result = result.splice(position + 1);
len = result.length + 1;
result.push(letters[i]);
}
maxLen = len > maxLen ? len : maxLen;
}
return maxLen;
}
console.log(lengthOfLongestSubstring(" "));
Sliding Window Technique O(n)
you can use hash or Map in
loop through string char
Maintain dictionary of unique char
if char exist in memory take clear hash update the count in longest variable and clear count
start from first repeated char + 1 again.
var lengthOfLongestSubstring = function(s) {
if(s.length<2) return s.length;
let longest = 0;
let count=0;
let hash={}
for (let i = 0; i < s.length; i++) {
//If char exist in hash
if(hash[s[i]]!=undefined){
i=hash[s[i]];
hash={}
longest = Math.max(longest, count);
count = 0;
}else{
hash[s[i]]=i
count = count+1;
}
}
return Math.max(longest, count);
};
console.log(lengthOfLongestSubstring("abcabcbb"))
console.log(lengthOfLongestSubstring("au"))

Replace a letter with its alphabet position

This looked fairly straightforward to me when I started, but for some reason I'm getting an empty array everytime I try to run the result on codewars. I'm hoping you can help me identify what the problem is.
function alphabetPosition(text) {
text.split(' ').join('');
var chari = "";
var arr = [];
var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
for(var i = 0; i < text.len; i++){
chari = text.charAt(i).toLowerCase();
if(alphabet.indexOf(chari) > -1){
arr.push(alphabet.indexOf(chari));
}
}
return arr;
}
console.log(alphabetPosition("Hello World"));
My idea is to get the text from the parameter then strip out the spaces. I made a variable for my empty array and make an alphabet string that I can later search through. In the for loop, i make each character lowercase, and if the character is found in the alphabet string, its position gets pushed into the array (arr). I appreciate your time.
The Kata works with this code. Try with this one:
function alphabetPosition(text) {
var result = "";
for (var i = 0; i < text.length; i++) {
var code = text.toUpperCase().charCodeAt(i)
if (code > 64 && code < 91) result += (code - 64) + " ";
}
return result.slice(0, result.length - 1);
}
console.log(alphabetPosition("The sunset sets at twelve o' clock."));
You need the String#length property
text.length
instead of text.len.
function alphabetPosition(text) {
var chari,
arr = [],
alphabet = "abcdefghijklmnopqrstuvwxyz",
i;
for (var i = 0; i < text.length; i++){
chari = text[i].toLowerCase();
if (alphabet.indexOf(chari) !== -1){
arr.push(alphabet.indexOf(chari));
}
}
return arr;
}
console.log(alphabetPosition("Hello World!!1"));
A solution with ES6
function alphabetPosition(text) {
return [...text].map(a => parseInt(a, 36) - 10).filter(a => a >= 0);
}
console.log(alphabetPosition("Hello World!!1"));
First : deleting space
Second : mapping each char with its alphabet rank
Third : test with the string Happy new year
var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
var alphabetPosition = text =>
text.split('').map(x => alphabet.indexOf(x) + 1);
console.log(alphabetPosition("happy new year"));
function alphabetPosition(text) {
const words = text.toLowerCase().replace(/[^a-z]/g,"");
return [...words].map(v=> v.charCodeAt() - 96);
}
First we take the text and transform it into lowercase to get rid of the capital letters using text.toLowerCase() and then we do .replace(/[^a-z]/g,"") to replace all the non a-z characters with nothing.
The next step is to spread the string out into an array using [...words] and then mapping it to get the ascii character code of each a-z character.
Since a = 97 and b = 98 etc we will subtract 96 so that we get a = 1 and b = 2 etc (the position of the letters in the alphabet)
You can make it even easier, by making use of the acii code. Because a = ascii code 97, b = 98 etc. And there is a javascript function String.charCodeAt( n ) which returns the ascii code at a specific function. You only have to alter the offset for capitals (if you want to support them).
function alphabetPosition( text ) {
var positions = [];
for ( var i = 0; i < text.length; i++ ) {
var charCode = text.charCodeAt( i );
if ( charCode >= 97 && charCode <= 122 ) {
positions.push( charCode - 96 );
} else if ( charCode >= 65 && charCode <= 90 ) { // get rid of this if you don't care about capitals
positions.push( charCode - 64 );
}
}
return positions;
}
var positions = alphabetPosition( 'Hello World' );
console.log(positions);
Checkout this working fiddle
This example will return based on a 0 based array, and uses lambda expressions with filter. I recycle the original byte array created by splitting the text passed to the method.
function alphabetPosition(text) {
var bytes = text.split('');
var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
for (var i = 0, len = text.length; i < len; i++) {
bytes[i] = alphabet.indexOf(bytes[i].toLowerCase());
}
return bytes.filter(n => { if(n > -1) return n; } ).join(' ');
}
console.log(alphabetPosition("Hello World"));
For a 1 based array result Kata Codewars Friendly
function alphabetPosition(text) {
var bytes = text.split('');
var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
for (var i = 0, len = text.length; i < len; i++) {
bytes[i] = alphabet.indexOf(bytes[i].toLowerCase()) + 1;
}
return bytes.filter(n => { if(n > 0) return n; } ).join(' ');
}
console.log(alphabetPosition("Hello World"));
You can also use .charCodeAt function:
function alphabetPosition(text) {
start = "a".charCodeAt(0);
end = "z".charCodeAt(0);
res = [];
for (var i = 0; i < text.length; i++) {
index = text.charAt(i).toLowerCase().charCodeAt(0);
if (index >= start && index <= end) {
res.push(index - start +1); // +1 assuming a is 1 instead of 0
} else {
res.push(0); // Or do w/e you like with non-characters
}
}
return res;
}
console.log(alphabetPosition("Hello World"));
You may do something like this;
var alpha = [].reduce.call("abcdefghijklmnopqrstuvwxyz0123456789 .,!",(p,c,i) => (p[c] = i,p),{}),
str = "Happy 2017 whatever..!",
coded = [].map.call(str, c => alpha[c.toLowerCase()]);
console.log(coded);
change len to length:
(var i = 0; i < text.len; i++)
// change to
(var i = 0; i < text.length; i++)
Here is a much shorter version that does the same:
function alphabetPosition(text){
return text.split('').map(function(character){ return character.charCodeAt(0) - 'a'.charCodeAt(0) + 1; })
}
console.log(alphabetPosition("Hello World"));
This was my solution on CodeWars. Works perfectly ;)
let alphabetPosition = (text) => {
let str = Array.from(text.toLowerCase().replace(/[^a-z]/g,''));
let arr = [];
for (let i = 0; i < str.length; i++) {
arr.push(str[i].charCodeAt() - 96);
}
return arr.join(' ');
}
my answer
function alphabetPosition(text) {
if (text.match(/[a-z]/gi)) { // if text is not emtpty
let justAlphabet = text.match(/[a-z]/gi).join("").toLowerCase(); //first extract characters other than letters
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let a = []; // Create an empty array
for (let i = 0; i < justAlphabet.length; i++) {
a.push(alphabet.indexOf(justAlphabet[i]) + 1); //and characters index number push in this array
}
return a.join(" ");
} else {
return "";
}
}
console.log(alphabetPosition("The sunset sets at twelve o' clock."));
this one should work
const lineNumberHandler = (arr) => {
const alphabet = 'abcdefghijklmnopqrstuwxyz';
return arr.map((el) => `${alphabet.indexOf(el) + 1}:${el}`);
}
This may solve the issue too:
function alphabetPosition(text) {
const alphabet = 'abcdefghijklmnopqrstuvwxyz'
const textWithoutSpaces = text.replace(/\s/g, '');
const numbers = Array.from(textWithoutSpaces).map((letter) => {
const lowerCaseLetter = letter.toLowerCase();
const charI = alphabet.indexOf(lowerCaseLetter)+1
if(charI) return charI
return null
})
const withoutEmptyValues = numbers.filter(Boolean)
return withoutEmptyValues.join(' ')
}
function alphabetPosition(text) {
const letters = text.split('')
const result = letters.map((l, ix) => {
const code = l.toUpperCase().charCodeAt() - 64
if (l.length && code > 0 && code <= 26) {
return code
}
})
return result.join(' ').replace(/\s+/g, ' ').trim()
}
I like to do "Single Line Responsibility", so in every line you can find only one action.
The return line, delete all multiples spaces.
An optimized version of it.
function alphabetPosition(text) {
let split = text.split("");
split = split.filter((el) => /^[a-zA-Z]+$/.test(el));
let str = "";
split.forEach(
(el) => (str += el.toLowerCase().charCodeAt(0) - "96" + " ")
);
return str.trim();
}
console.log(alphabetPosition("The sunset sets at twelve o' clock."));
function alphaPosition(test){
//the object assigns the position value to every alphabet property
const lookupAlph = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26}
//converts our text first to lowercase, then removes every non-alphabet
// it proceeds to covert the text to an array,
// then we use the map method to convert it to its position in the alphabet
// the last thing we do is convert our array back to a string using the join method
const alphaPosition = text.toLowerCase()
.replace(/[^a-z]/g, "")
.split("")
.map((a) => lookupAlph[a])
.join(" ")
return alphaPosition;
}

Categories