Skip to content
Snippets Groups Projects

GRIP Interview Question 2020

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Simon Katan

    What do thewse function do ? What is the difference between choose and deepChoose ?

    choose.js 1.05 KiB
    Utils.prototype.choose = function(inputArray, num) {
    
    	if (inputArray == undefined) {
    		throw "Error: utils.choose, inputArray is undefined";
    	}
    	if (num == undefined) num = 1;
    	if (num > inputArray.length) {
    		throw "Error: utils.choose, number of items excedes size of input array";
    	}
    	var output = [];
    	var ids = [];
    
    	for (var i = 0; i < inputArray.length; i++) {
    		ids.push(i);
    	}
    
    	for (var i = 0; i < num; i++) {
    		var idx = this.getRandomInt(0, ids.length - 1);
    		output.push(inputArray[ids[idx]]);
    		ids.splice(idx, 1);
    	}
    
    	if (num == 1) {
    		return output[0];
    	} else {
    		return output;
    	}
    }
    
    Utils.prototype.deepChoose = function(inputArray, num) {
    
    	if (num == undefined) num = 1;
    	if (num > inputArray.length) {
    		throw "Error: utils.deepChoose, " + num + "  items excedes input array of " +
    			inputArray.length;
    	}
    	var output = [];
    
    	for (var i = 0; i < num; i++) {
    		var idx = this.getRandomInt(0, inputArray.length - 1);
    		output.push(inputArray[idx]);
    		inputArray.splice(idx, 1);
    	}
    
    	if (num == 1) {
    		return output[0];
    	} else {
    		return output;
    	}
    }
    0% or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment