martes, 25 de octubre de 2016

Write a function for doing an in-place shuffle of an array.
The shuffle must be "uniform," meaning each item in the original array must have the same probability of ending up in each spot in the final array.
Assume that you have a function getRandom(floor, ceiling) for getting a random integer that is >= floor and <= ceiling.

  
function getRandom(floor, ceiling){
   // console.log('getRandom floor:'+floor+' ceiling:'+ceiling);
   return  parseInt(floor) + parseInt( Math.random()*(ceiling - floor));
}
function swapInPlace(array,i,k){
    //console.log('swap i:'+i+' k:'+k);
 var v1 = array[i];
 var v2 = array[k];
 array[i] = v2;
 array[k] = v1;
}
function shuffleInPlace(array) {
    var floor = 0, ceiling = array.length;
    for(var i in array){
        var k = getRandom(i, ceiling)
  swapInPlace(array,i,k);
    }
}
var array = ['a','b','c'];
console.log('original array: '+array);
shuffleInPlace(array);
console.log('shuffled array: '+array);
https://www.interviewcake.com/question/java/shuffle

martes, 4 de octubre de 2016

You're working with an intern that keeps coming to you with JavaScript code that won't run because the braces, brackets, and parentheses are off. To save you both some time, you decide to write a braces/brackets/parentheses validator.
Let's say:
  • '(', '{', '[' are called "openers."
  • ')', '}', ']' are called "closers."
Write an efficient function that tells us whether or not an input string's openers and closers are properly nested.
Examples:
  • "{ [ ] ( ) }" should return true
  • "{ [ ( ] ) }" should return false
  • "{ [ }" should return false
ref: https://www.interviewcake.com/question/javascript/bracket-validator



  
var openers = ['(', '{', '['];
var closers = [')', '}', ']'];
function braces_brackets_parentheses_validator(code) {
    var stack = [];
    for(var i in code){
        index = openers.indexOf(code[i]);
        if(index >= 0){
            //console.log('push:'+code[i]);
            stack.push(code[i]);
        }else{
            index = closers.indexOf(code[i]);
            if(index >= 0){
                if(stack[stack.length-1] != openers[index]){
                    console.log('opener:"'+stack[stack.length -1]+'" unexpected closer:"'+closers[index]+'" at index:'+i);
                    return false;
                }
                //console.log('pop:'+stack[stack.length -1]);
                stack.pop();
            }
        }
    }
        
    return true;
}

// run your function through some test cases here
// remember: debugging is half the battle!
console.log(braces_brackets_parentheses_validator('{ [ ] ( ) }'));
console.log(braces_brackets_parentheses_validator('{ [ ( ] ) }'));
console.log(braces_brackets_parentheses_validator('{ [ }'));