Jul
09
2008
0

Something for the brain

My layman solution to Dustin’s Programming Brain Teaser.

    var arr = ['a', 'b', 'c', 'c', 'd','e', 'e', 'e', 'e', 'e', 'f', 'e', 'f', 'e', 'f', 'a', 'a', 'a', 'f', 'f', 'f'];
 
    var result = '';
 
    arr.forEach(function(value, index){
        if(index > 1 && (arr[index] == arr[index - 1]) && (arr[index - 1] == arr[index - 2])){
            if(index == (arr.length - 1) || (arr[index + 1] != arr[index])){
                result += (index < 3 || (arr[index - 2] != arr[index - 3])) ? ' &lt;span&gt;' + value + '&lt;/span&gt;' : ' ' + value +  '&lt;/span&gt;' ;
            } else {
                result += (index < 3 || (arr[index - 2] != arr[index - 3])) ? ' &lt;span&gt;' + value : ' ' + value;                
            }
        } else {
            result += ' ' + value;   
        }
    })

Remi Sharp and other guys who used regular expressions came up with much ‘cooler’ solutions. Regular Expression is really powerful. Need to work on that.

Written by Bhabishya Kumar in: JavaScript |

Powered by WordPress | Aeros Theme | TheBuckmaker.com WordPress Themes