Skip to content

Instantly share code, notes, and snippets.

@worker8
Last active October 29, 2020 13:59
Show Gist options
  • Select an option

  • Save worker8/0816491097455cfe3c98 to your computer and use it in GitHub Desktop.

Select an option

Save worker8/0816491097455cfe3c98 to your computer and use it in GitHub Desktop.
/* Returns either the index of the location in the array,
or -1 if the array did not contain the targetValue */
/* note to self: took around 40~50 mins to get the answer */
/* note to self: took even longer to make the program pass because the checking is a bit rigid, I used round() instead of floor, and it wouldn't let me pass,
it does help me to think about many different ways of solving though. */
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var midpoint;
var guess = 0;
var x=0;
while (max >= min){
x++;
guess = floor((max+min)/2);
if (targetValue === array[guess]) {
println("num of guess: "+x);
return guess;
} else if (targetValue > array[guess]) {
min = guess + 1;
} else {
max = guess - 1;
println(guess);
}
}
return -1;
};
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
// for (var i = 0; i < primes.length; i++) {
// println(i + ":" + primes[i]);
// }
var result = doSearch(primes, 3);
//println("Found prime at index " + result);
for (var i=0;i<primes.length;i++){
//println(primes[i]+":"+doSearch(primes, primes[i]));
}
Program.assertEqual(doSearch(primes, 73), 20);
Program.assertEqual(doSearch(primes, 2), 0);
Program.assertEqual(doSearch(primes, 3), 1);
Program.assertEqual(doSearch(primes, 5), 2);
Program.assertEqual(doSearch(primes, 7), 3);
@spainsinqusitor

Copy link
Copy Markdown

helped a ton, if possible could you add more comments of your thought process I actually want to understand why the program didn't understand what I was doing

@jeonghnr

jeonghnr commented Mar 5, 2020

Copy link
Copy Markdown

Thanks to you, I solved the problem well. Thank you very much.

@federico-aguilar

Copy link
Copy Markdown

Thanks! This really came in handy for part 4. However, I'm curious as to why you included

for (var i=0;i<primes.length;i++){
//println(primes[i]+":"+doSearch(primes, primes[i]));
}

What did that do? Is it to error check something?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment