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:

  1. If the character is in the oneRing array, add 1 to the total
  2. If the character is in the twoRings array, add 2 to the total
  3. 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.

Updated on: 2026-03-15T23:19:00+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements