Thursday, August 21, 2014

Welcome! Add-One!

Welcome to F-plus! I started this to post my various stumbles as I try to learn about various topics such as data analysis, visualization, general programming, machine learning, cryptography, information theory, etc. and apply the ideas in various ways. If you stumbled into here, I hope that you will also find something useful, amusing or interesting in my stumbles too.

The first thing I thought I would put up is a simple JavaScript implementation of the "add-one" exercise from "Thinking Fast and Slow" by Daniel Kahneman. Kahneman discusses this deceptively simple exercise in his book as the classic example of a task that overloads the brain's heavy thinking circuitry, what he calls System 2. Apparently, immediately after starting the exercise, you'll be at your maximum mental exertion (sort of a brain sprint) with some associated physiological effects, one of the more interesting being pupil dilation in proportion to your mental exertion.

So, on to the actual exercise. The task is started by viewing a random string of four digits and then verbally reciting them back with each digit incremented by one (modulo 10, so 9 goes to 0), i.e. 3974 should be read back as 4085. Kahneman suggests a cadence three seconds for viewing the digits, then read back incremented by one, before viewing the next set of four digits. This exercise should be enough to challenge most people, but to increase the difficulty it can be extended to "add-three" where each digit should be incremented by three or the cadence can be sped up as well.

Add-One!

And the code for this little exercise is pretty simple. We just need an html element with id="add-one" that we will update. Here, I choose an h1 tag to make it easy to read. And then we have a little bit of JavaScript to attach an event listener to the page loading window.addEventListener that calls setInterval to call our defined function named addOne() to update that h1 element at set intervals. The addOne() function just loops through and appends four digits to the string that will be inserted into the id="add-one" element. The full code is below with both the cadence and number of digits as variables:

<h1 align="center" id="add-one">Add-One!</h1>

<script type="text/javascript">
    var count_time = 3000
    var num_digits = 4
        
    function addOne() {
        var new_string='';
        for(var i=0;i<num_digits;i++) { 
            new_string+=String(Math.floor(Math.random()*10));
        }
        document.getElementById('add-one').innerHTML = new_string;
    }      
    window.addEventListener('load', 
        setInterval('addOne()', count_time),false);
</script>