Last active
August 10, 2019 10:44
-
-
Save mzaks/208720f8617ad23507e5cca0611a9342 to your computer and use it in GitHub Desktop.
Binary search in Happy Tree Frame programming language
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
frame { | |
items: [int] # implicit input | |
value: int # implicit input | |
min_index: int | |
max_index: int | |
mid_index: int | |
<- found_index: int # explicit output | |
} | |
# sel is selector | |
# seq is sequence | |
# rep_fail is repeat on fail | |
tree { | |
seq { | |
# setup | |
min_index = 0 | |
max_index = items.count - 1 | |
sel { | |
# Not part of standard binary search algorithm | |
# early exit if value is outside of the items range | |
# or is equal to min / max value | |
seq { | |
items[min_index] == value | |
found_index = min | |
} | |
seq { | |
items[min_index] > value | |
foun_index = -1 | |
} | |
seq { | |
items[max_index] == value | |
found_index = max | |
} | |
seq { | |
items[max_index] < value | |
found_index = -1 | |
} | |
success | |
} | |
rep_fail { | |
sel { | |
found_index != null | |
seq { | |
mid_index = min_index + max_index | |
mid_index = mid_index / 2 | |
items[mid_index] == value | |
found_index = mid_index | |
} | |
seq { | |
sel { | |
seq { | |
items[mid_index] < value | |
min_index = mid_index + 1 | |
} | |
max_index = mid_index - 1 | |
} | |
min_index > max_index | |
} | |
} | |
} | |
seq { | |
found_index != null | |
found_index > -1 | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
frame { | |
values: [int] | |
guessed_number: int | |
guessed_number_index: int | |
} | |
tree { | |
seq { | |
values = [5, 13, 56, 99] | |
rep_fail { | |
seq { | |
tell "Guess one of the numbers between 1 and 100" | |
# using a sub tree to get user input | |
readInt { | |
guessed_number <- subFrame.value | |
} | |
sel { | |
# using the binary search sub tree | |
find_index { | |
subFrame.items <- values | |
subFrame.value <- guessed_number | |
guessed_number_index <- subFrame.found_index | |
} | |
tell "sorry, that was wrong" | |
fail | |
} | |
tell "Congrats, you found a number" | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment