This file contains 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
#!/usr/bin/awk -f | |
function turn_gainer(state, idx,i,max,c,k) { | |
max_offset = state["turns"] > 9 ? 9 : state["turns"] | |
# We first try to search every move that gains a turn in one move, | |
# than moves that gain a turn in two moves etc. | |
for ( offset = 1; offset <= max_offset; offset++ ) { | |
max = 0 | |
idx = 0 | |
for ( start = 1; start <= state["size"] - offset; start++ ) { | |
if ( is_extra_turn(state, start, start + offset)) { | |
idx = start | |
k = highest_points_idx(state,start, start + offset) | |
c = (state[k]+state[k+1]) % 10 | |
if ( c > max ) { | |
max = c | |
idx = k | |
} | |
} | |
} | |
if ( idx ) return idx | |
} | |
# If there isn't a turn to gain, we just search for the highest points | |
return highest_points_idx(state, 1, state["size"] - 1) | |
} | |
function print_state(state, start, end, i ) { | |
for( i = start; i <= end; i++ ) { | |
printf state[i] | |
if ( i != end ) | |
printf "," | |
} | |
} | |
function highest_points_idx ( state, start, end, max, i, idx, c ) { | |
idx = start | |
for ( i = start; i < end ; i++ ) { | |
c = (state[i]+state[i+1]) % 10 | |
if ( c > max) { | |
max = c | |
idx = i | |
} | |
} | |
return idx | |
} | |
function is_extra_turn (state, start, end, sum, i ) { | |
sum=0 | |
for ( i = start; i <= end; i++ ) { | |
sum += state[i] | |
} | |
if ( sum % 10 == 0 ) | |
return 1 | |
else | |
return 0 | |
} | |
function pop (a, pos, i ) { | |
a[pos] = (a[pos] + a[pos+1]) % 10 | |
a["score"] += a[pos] | |
for (i = pos + 2; i <= a["size"]; i++ ) | |
a[i-1] = a[i] | |
a[a["size"]] = int(rand()*10) | |
if ( a[pos] == 0 ) | |
a["turns"]++ | |
else | |
a["turns"]-- | |
} | |
function print_game (a, i) { | |
for ( i = 1; i <= a["size"]; i++ ) { | |
printf "%s", a[i] | |
if ( i <= a["size"] - 1) | |
printf " (%s) ", i | |
} | |
printf "\n" | |
} | |
BEGIN { | |
if (seed) | |
srand(seed) | |
else | |
srand() | |
state["turns"] = 10 | |
state["score"] = 0 | |
state["size"] = 10 | |
for ( i = 1; i <= state["size"] ; i++ ) | |
state[i] = int(rand()*10); | |
while ( state["turns"] > 0 ) { | |
print_game(state) | |
pos = turn_gainer(state) | |
printf "AI: %d\n",pos | |
pop(state, pos) | |
printf "Gain: %d Score: %d Turns: %d\n", state[pos], state["score"], state["turns"] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run it with awk -f numpop.awk. If you want to run it in a loop you better call it with awk -v seed="$RANDOM" -f, srand in awk uses epoch for srand and you get the same seed if you run it multiple times in the same second