Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Created July 1, 2020 05:43
Show Gist options
  • Save Shaddyjr/92f9cfe8d0bb65e11b1654f6939cba9f to your computer and use it in GitHub Desktop.
Save Shaddyjr/92f9cfe8d0bb65e11b1654f6939cba9f to your computer and use it in GitHub Desktop.
// Original TED Riddle Video: https://www.youtube.com/watch?v=YeMVoJKn1Tg
// check if number valid
function state_is_valid(array, two_found, ten_found){
// whole number
// not great than 60
// no duplicates
const last_num = array[array.length-1];
const normal_check = Math.floor(last_num) == last_num && last_num <= 60 && !has_duplicates(array);
if(normal_check){
if(two_found){
// array needs to have a 2
if(array.indexOf(2) < 0){
return false;
}
if(ten_found){
// array needs to have a 10
if(array.indexOf(10) < 0){
return false;
}
}
}
return true;
}
return false;
}
function has_duplicates(array){
const history = {};
for(const num of array){
if(!history[num]){
history[num] = 1
}else{
return true;
}
}
return false;
}
// returns true if array has solution
function is_solution(array){
// has numbers 2, 10, and 14 in order
const solutions = [2, 10, 14]
for(const num of array){
if(num == solutions[0]){
solutions.shift();
if(!solutions.length){
return true;
}
}
}
return false;
}
// main
function main(){
// keep running queue of objects
const queue = [[0]];
let [two_found, ten_found] = [false, false];
while(queue.length){
const curr_state = queue.shift();
const curr_num = curr_state[curr_state.length - 1];
// try all 3 possibilities
// +5, +7, sqrt
const possibilities = [curr_num + 5, curr_num + 7, curr_num ** .5];
for(const possibility of possibilities){
new_state = [...curr_state];
new_state.push(possibility);
if(!two_found && possibility == 2){
two_found = true;
}else if(two_found && !ten_found && possibility == 10){
ten_found = true;
}
if(state_is_valid(new_state, two_found, ten_found)){
if(is_solution(new_state)){
// stop when solution found
return console.log("SOLUTION! ", new_state.join(", "));
}
queue.push(new_state);
}
}
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment