Distance to nearest Vowel (Edabit)
Given a string, return an array with the distance to the nearest vowel for each character. It searches for the nearest both forwards and backwards.
Example: 'abc' -> [0,1,2]
'abzxciou' -> [0,1,1,2,2,0,0,0]
We'll force lowercase and make non-letter characters return "N/A" in the array.
function doit(str){
var o = [];
str = str.toLowerCase();
for(var xint = 0, len = str.length;xint < len;xint++){
var c = str.charCodeAt(xint);
if(c >= aCode && c <= zCode){ // is a letter
// we'll just manually check by looping. use modulo to contain value.
var leastVowelDistance = 26;
var forwardsVowelDistance = 26;
var backwardsVowelDistance = 26;
var cOffset = c - aCode;
for(var yint=0;yint<25;yint++){ // forward
var xchar = alphabet[(cOffset + yint) % 26]; // for upward
if(xchar == 'a' || xchar == 'e' || xchar == 'i' || xchar == 'o' || xchar == 'u'){
forwardsVowelDistance = yint;
break;
}
}
for(var yint = 0;yint < 25;yint++){ // backwards
var xidx = cOffset - yint + (yint > cOffset ? 26 : 0);
var xchar = alphabet[xidx];
if(xchar == 'a' || xchar == 'e' || xchar == 'i' || xchar == 'o' || xchar == 'u'){
backwardsVowelDistance = yint;
break;
}
}
leastVowelDistance = Math.min(forwardsVowelDistance,backwardsVowelDistance);
o.push(leastVowelDistance);
// debug info, shows the distance forwards and backwards for each letter
//console.log("Letter = " + alphabet[cOffset] + ", forwardsVowelDistance = " + forwardsVowelDistance + ", backwardsVowelDistance = " + backwardsVowelDistance + ", leastVowelDistance = " + leastVowelDistance);
}else{
o.push('N/A'); // not a letter
}
}
return o;
}
// note: we're not using 'y' as a vowel here
var vowels = ['a'.charCodeAt(0),'e'.charCodeAt(0),'i'.charCodeAt(0),'o'.charCodeAt(0),'u'.charCodeAt(0)];
var alphabet = [];
var aCode = 'a'.charCodeAt(0);
var zCode = 'z'.charCodeAt(0);
for(var xint=0;xint<26;xint++)alphabet.push(String.fromCharCode(aCode+xint));
function test(str){
if(str == undefined){ // make random string
var len = 5;
str = "";
var range = zCode - aCode;
for(var xint = 0;xint < len;xint++)
str += String.fromCharCode( Math.round(Math.random()*range) + aCode);
}
console.log('str: ' + str + '. result: ' + doit(str).toString());
}
test('abc');
test('xyz');
test('cabbage');
test('Spider Man');
test('$ #@ ^*$@ #*');
test('AaAaHhHh');
test('그거양은 체친구입니다.');
for(var xint = 0;xint < 5;xint++) test();
No comments:
Post a Comment