binary_search(value, sorted_data_first, sorted_data_last): {
first, last = sorted_data_first, sorted_data_last;
middle = avg(first, last);
if first = last: return void;
else: switch(value ?= middle value):
if equal: return middle;
else less: return binary_search(value, first, middle); //in lower half of data
else greater: return binary_search(value, middle, last); //in upper half of data
};
bsearch = binary_search;
quick_sort{unsorted_data_first, unsorted_data_last}(): {
first, last = sorted_data_first, sorted_data_last;
filled_beginning, filled_end = begin, end = copy(first, last);
if first != last: { //more than one element in data
reference = first;
while begin < end:
if begin value < middle value: begin = next(); //begin is on the correct side
else end value > middle value: end = next(); //end is on the correct side
else: begin, end = swap() //neither is on the correct side
with begin = next() with end = next; //now both are on the correct side
middle = begin; //begin and end are now at the same position
first, middle = quick_sort(); middle, last = quick_sort(); //sort both sides
}
};
qsort = quick_sort;
@import IO, random
guessing_game{
target = random([0, 100]r);
attempts = 0;
try(num): {
if num != target: attempts = increment();
return num ?= target;
}
}
convert{ guessing_game }(game_target):
guessing_game with target = (game_target)
;
convert{ guessing_game }(target_range):
guessing_game with target = random(target_range)
;
number_range = [0, 1000]r;
repeat: {
number_game = number_range as guessing_game;
IO write("guess a number", number_range, "\n");
guess = IO read() as integer;
while comparison = number_game try guess != equal:
IO write("your guess is", comparison, "\n"),
guess = IO read()
;
IO write format("you guessed the number in %d tries\n", number_game attempts);
IO write("try again?[y/n]\n");
if IO read() as string == "y":
continue;
else:
break;
}