Skip to content

Instantly share code, notes, and snippets.

@spytheman
Created March 18, 2023 15:37
Show Gist options
  • Save spytheman/2b9fc468664f0ac73b258c065daf577e to your computer and use it in GitHub Desktop.
Save spytheman/2b9fc468664f0ac73b258c065daf577e to your computer and use it in GitHub Desktop.
wordle in V, optimised to not use ascii_str() all the time
import json
import os
import time
import math
import runtime
fn main() {
println('Started...')
sw := time.new_stopwatch()
content := os.read_file('./wordle_min.json')!
possible_answers := json.decode([]string, content)!
mut score_index := []int{len: possible_answers.len, init: 0}
thread_count := runtime.nr_cpus()
println('thread_count: $thread_count')
chunk_size := int(math.ceil(f64(possible_answers.len) / f64(thread_count)))
println('chunk_size: $chunk_size')
ch := chan []int{}
for chunk in 0 .. thread_count {
from := chunk_size * chunk
to := if (from + chunk_size) > possible_answers.len {
possible_answers.len
} else {
from + chunk_size
}
spawn add_scores(possible_answers, from, to, ch)
}
for _ in 0 .. thread_count {
result := <-ch
for i, v in result {
score_index[i] += v
}
}
ch.close()
mut sorted_scores := score_index.clone()
sorted_scores.sort(a > b)
mut res := 'Best Words:\n > '
for i in 0 .. 5 {
score := sorted_scores[i]
res += '${possible_answers[score_index.index(score)]}: ${score} | '
}
println(res)
println('Process took ${sw.elapsed().milliseconds()} ms')
}
fn contains_char(s string, c u8) bool {
for x in s {
if x == c {
return true
}
}
return false
}
fn add_scores(possible_answers []string, from int, to int, ch chan []int) {
eprintln('spawned thread possible_answers.len: ${possible_answers.len} | from: ${from} | to: ${to}')
mut res := []int{len: possible_answers.len, init: 0}
for x in from .. to {
for y in 0 .. possible_answers.len {
for x_char_index in 0 .. 5 {
x_char := possible_answers[x][x_char_index]
if x_char == possible_answers[y][x_char_index] {
res[y] += 5
} else if contains_char(possible_answers[y], x_char) {
res[y] += 4
}
}
}
}
ch <- res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment