## function: Generating a Secret Code

01 Jul

I knew this would be a more challenging function for me. From the outset I’ve been considering a couple different strategies for accomplishing this function. One idea was to have the secret code be an object – one thing I liked about this was that I’ve never used an Object in any coding before aside from the codecademy exercises where you have a lot of help in getting it right. The other idea was to make the guess an Array. I should say that I’ve never used an array before for anything that wasn’t a reformatted exercise either. I also thought that perhaps an array might be a bit easier too.

S0, I chose to go forward with the array idea. It makes sense to me. An array is a list of variables all collected together and in a fixed order (the first position is called [0], the second is [1] and so on. Some examples of arrays are:

var x = [1,2,3,5,8,13];

console.log(x[0]); would print the number in the ‘0’ position to the console, (i.e. 1)

console.log(x[3]); would print the number in the ‘3’ position to the console, (i.e. 5)

Array can also be lists of strings:

var cats = [“William”, “Oliver”, “Chloe”, “Anna”];

console.log(cats[1]); would print the number in the ‘1’ position to the console, (i.e. Oliver)

What I like about this is that the numbers have order – just what I’ll need to set and crack a combination.

Here’s the function I came up with to do this – It wasn’t easy for me, at one point I managed to make an array that had another nested array inside of it. I couldn’t make heads or tails of it, but thanks to some good people on stack overflow, the problem was identified and solved.

//sets up an array of numbers that will be the secret code

// code is the number of digits, number is the integers used for each digit

setSecretCode = function(code,numbers){

var secretCode = “0”;

var secret = [];

console.log(“***reached setSecretCode function***”);

for (i=0; i < code; i++){

secret[i] = Math.floor(Math.random()*numbers+1);

}

return secret; to return result to be used going forward

};

This function is called:

var secret = setSecretCode(enteredCode,enteredNumber);

//printout of array for debugging

console.log(“secret code is: “+ secret);