Using JavaScript to Solve a Trivia Question

"Abacus 2" by Loadmaster (David R. Tribble)This image was made by Loadmaster (David R. Tribble)Email the author: David R. TribbleAlso see my personal gallery at Google Picasa - Own work. Licensed under CC BY-SA 3.0 via Wikimedia Commons - http://commons.wikimedia.org/wiki/File:Abacus_2.jpg#mediaviewer/File:Abacus_2.jpg

This weekend, I wound up visiting a restaurant with an irritating trivia question on their welcoming chalkboard: “How many numbers between 0 and 200 contain the number ‘1’ in them?”  (e.g. 1, 10, 11, etc.) Puzzles like this tend to stick in my craw, so I tucked it away in my “stuff to figure out later when I have more time” stack.

Since I don’t know a mathematical algorithm to generate a sequence of numbers that contain the number 1 in them, the only way I see to solve this puzzle is “brute force.” Although we can do this manually on a piece of paper fairly quickly (i.e. write the numbers 0 through 200, circle the ones that have a one in them, and then count the circled numbers), that approach is a manual process and can’t be easily reused with different parameters. It also doesn’t scale well if the range of numbers to be checked grows significantly (e.g. between 0 and 10,000).

. . . .
<script type="text/javascript">

    function howManyXinYthruZ(x, startY, endZ) {

        counter = 0; // initialize a counter

        // iterate from first number to last
        for (a = startY; a <= endZ; a++) {

            // convert number to string . . .
            aString = a.toString();

            // so we can search for X
            if (aString.search(x) != -1) {

                // if we find one, ding the counter
                counter++;

                // purely optional, for "proof"
                console.log(a);
                }
            }

    // share the final tally of matches
    console.log("count: " + counter);
}

    // invoke the function to solve the puzzle
    howManyXinYthruZ( 1, 0, 200);

</script>
. . . .

If you run this little script in a blank page in your browser and then crack open the console, you’ll see a list of all the numbers that match the specified the criteria as well as the final total of matches (i.e. 119).

The nice part of this is that if I ever encounter another trivia question similar to this one (i.e. “How many numbers between 3000 and 5000 have the number 3 in them?”), I can quickly and easily solve it with one function call:

howManyXinYthruZ( 3, 3000, 5000);

// 1,271 in case you’re curious

Not bad, JavaScript.  Not bad.