Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Distance to nearest vowel in a string - JavaScript
We are required to write a JavaScript function that takes in a string with at least one vowel, and for each character in the string we have to map a number representing its nearest distance from a vowel.
For example: If the string is ?
const str = 'vatghvf';
Then the output should be ?
const output = [1, 0, 1, 2, 3, 4, 5];
How It Works
The algorithm works by:
- Finding all vowel positions in the string
- For each character, calculating the minimum distance to any vowel
- Returning an array of these distances
Example Implementation
const str = 'vatghvf';
const nearest = (arr = [], el) => arr.reduce((acc, val) => Math.min(acc,
Math.abs(val - el)), Infinity);
const vowelNearestDistance = (str = '') => {
const s = str.toLowerCase();
const vowelIndex = [];
for(let i = 0; i < s.length; i++){
if(s[i] === 'a' || s[i] === 'e' || s[i] === 'i' || s[i] === 'o' ||
s[i] === 'u'){
vowelIndex.push(i);
};
};
return s.split('').map((el, ind) => nearest(vowelIndex, ind));
};
console.log(vowelNearestDistance(str));
[ 1, 0, 1, 2, 3, 4, 5 ]
Alternative Approach Using Set
Here's a cleaner version using a Set for vowel checking:
const vowelNearestDistanceOptimized = (str = '') => {
const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
const s = str.toLowerCase();
const vowelPositions = [];
// Find all vowel positions
for(let i = 0; i < s.length; i++) {
if(vowels.has(s[i])) {
vowelPositions.push(i);
}
}
// Calculate distances
return s.split('').map((char, index) => {
return Math.min(...vowelPositions.map(pos => Math.abs(pos - index)));
});
};
// Test with different examples
console.log(vowelNearestDistanceOptimized('hello'));
console.log(vowelNearestDistanceOptimized('programming'));
[ 1, 0, 2, 2, 1 ] [ 2, 1, 0, 1, 2, 1, 0, 1, 2, 3, 4 ]
Step-by-Step Breakdown
Let's trace through the example 'vatghvf':
- Position 0 ('v'): nearest vowel at position 1 ? distance = 1
- Position 1 ('a'): is a vowel ? distance = 0
- Position 2 ('t'): nearest vowel at position 1 ? distance = 1
- Position 3 ('g'): nearest vowel at position 1 ? distance = 2
- Position 4 ('h'): nearest vowel at position 1 ? distance = 3
- Position 5 ('v'): nearest vowel at position 1 ? distance = 4
- Position 6 ('f'): nearest vowel at position 1 ? distance = 5
Conclusion
This algorithm efficiently finds the nearest vowel distance for each character by first collecting vowel positions, then calculating minimum distances. The Set-based approach provides cleaner vowel detection than multiple OR conditions.
Advertisements
