diff options
author | Richard Maw <richard.maw@gmail.com> | 2013-04-15 23:41:54 +0100 |
---|---|---|
committer | Richard Maw <richard.maw@gmail.com> | 2013-04-18 21:34:57 +0100 |
commit | 9dc14d6e56268cc7175ccf6d6edaae7ecae8d349 (patch) | |
tree | bae211413af966b6d3c980298199387f0cd1fbf0 | |
parent | b1f1a318748eb2b0815dffc82befc06d223dea77 (diff) | |
download | higher-lower-9dc14d6e56268cc7175ccf6d6edaae7ecae8d349.tar.bz2 |
iterative was higher-lower.lua, interactive asks for a guess,
binary_search always guesses in the middle of the range, and refines the
search area
cheating always gets it right in 0 guesses
-rw-r--r-- | binary_search.lua | 14 | ||||
-rw-r--r-- | cheating.lua | 10 | ||||
-rw-r--r-- | higher-lower.c | 3 | ||||
-rw-r--r-- | interactive.lua | 17 | ||||
-rw-r--r-- | iterative.lua (renamed from higher-lower.lua) | 0 |
5 files changed, 44 insertions, 0 deletions
diff --git a/binary_search.lua b/binary_search.lua new file mode 100644 index 0000000..528efe6 --- /dev/null +++ b/binary_search.lua @@ -0,0 +1,14 @@ +local check, lower, upper = ... + +while true do + local guess = math.floor(lower + (upper - lower) / 2) + local result = check(guess) + if result == 0 then + return guess + end + if result < 0 then + lower = guess + elseif result > 0 then + upper = guess + end +end diff --git a/cheating.lua b/cheating.lua new file mode 100644 index 0000000..0a41048 --- /dev/null +++ b/cheating.lua @@ -0,0 +1,10 @@ +local ffi = require "ffi" +ffi.cdef[[ +void srand(unsigned int seed); +int rand(void); +]] +ffi.C.srand(0) +local function rand_range(min, max) + return min + ffi.C.rand() / (2147483647 / (max - min + 1) + 1) +end +return rand_range(lower, upper) diff --git a/higher-lower.c b/higher-lower.c index 3309b07..7a846a2 100644 --- a/higher-lower.c +++ b/higher-lower.c @@ -3,6 +3,7 @@ #include <getopt.h> #include <lauxlib.h> #include <lua.h> +#include <lualib.h> static int rand_range(int min, int max){ return min + rand() / (RAND_MAX / (max - min + 1) + 1); @@ -32,6 +33,8 @@ int process_strategy(char const *strategy, int min, int max){ int target = rand_range(min, max); int call_count = 0; + luaL_openlibs(L); + if (luaL_loadfile(L, strategy)){ char const *errmsg = lua_tostring(L, 1); fprintf(stderr, "Failed to load strategy file %s: %s\n", diff --git a/interactive.lua b/interactive.lua new file mode 100644 index 0000000..13c7b83 --- /dev/null +++ b/interactive.lua @@ -0,0 +1,17 @@ +local check, lower, upper = ... + +while true do + print(("Guess a number between %d and %d"):format(lower, upper)) + local guess = io.read("*n") + local result = check(guess) + if result == 0 then + return guess + end + if result < 0 then + print("Too low") + lower = guess + elseif result > 0 then + print("Too high") + upper = guess + end +end diff --git a/higher-lower.lua b/iterative.lua index 470c8e0..470c8e0 100644 --- a/higher-lower.lua +++ b/iterative.lua |