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
Counting rings in letters using JavaScript
We need to write a JavaScript function that counts the number of rings (closed loops) present in letters of a string. Different letters contain different numbers of rings based on their visual structure.
Understanding Letter Rings
Letters with rings are those that contain closed loops in their visual representation:
- One ring: A, D, O, P, Q, R, a, b, d, e, g, o, p, q
- Two rings: B (has two closed loops)
- No rings: All other letters
Example Implementation
const str = 'some random text string';
function countRings(str) {
const oneRing = ['A', 'D', 'O', 'P', 'Q', 'R', 'a', 'b', 'd', 'e', 'g', 'o', 'p', 'q'];
const twoRings = ['B'];
let totalRings = 0;
for (let char of str) {
if (oneRing.includes(char)) {
totalRings += 1;
} else if (twoRings.includes(char)) {
totalRings += 2;
}
}
return totalRings;
}
console.log(countRings(str));
console.log("Breakdown: 's'(0) + 'o'(1) + 'm'(0) + 'e'(1) + ' '(0) + 'r'(0) + 'a'(1) + 'n'(0) + 'd'(1) + 'o'(1) + 'm'(0) + ' '(0) + 't'(0) + 'e'(1) + 'x'(0) + 't'(0) + ' '(0) + 's'(0) + 't'(0) + 'r'(0) + 'i'(0) + 'n'(0) + 'g'(1) = 7");
7 Breakdown: s(0) + o(1) + m(0) + e(1) + (0) + r(0) + a(1) + n(0) + d(1) + o(1) + m(0) + (0) + t(0) + e(1) + x(0) + t(0) + (0) + s(0) + t(0) + r(0) + i(0) + n(0) + g(1) = 7
Alternative Using Array Methods
function countRingsWithMap(str) {
const oneRing = ['A', 'D', 'O', 'P', 'Q', 'R', 'a', 'b', 'd', 'e', 'g', 'o', 'p', 'q'];
const twoRings = ['B'];
return str.split('').reduce((total, char) => {
if (oneRing.includes(char)) return total + 1;
if (twoRings.includes(char)) return total + 2;
return total;
}, 0);
}
// Test with different strings
console.log(countRingsWithMap('BOB')); // B(2) + O(1) + B(2) = 5
console.log(countRingsWithMap('Programming')); // P(1) + r(0) + o(1) + g(1) + r(0) + a(1) + m(0) + m(0) + i(0) + n(0) + g(1) = 5
5 5
How It Works
The function iterates through each character in the string and checks:
- If the character is in the
oneRingarray, add 1 to the total - If the character is in the
twoRingsarray, add 2 to the total - Otherwise, add nothing (character has no rings)
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| for...of loop | High | Good | Simple iteration |
| reduce() | Medium | Good | Functional programming |
Conclusion
Counting rings in letters involves identifying characters with closed loops and summing their ring values. The approach uses arrays to categorize letters by their ring count and iterates through the string to calculate the total.
Advertisements
