Created
December 22, 2021 15:29
-
-
Save thanhnguyen2187/f14032df0ada5b3ea7de3541061f13c2 to your computer and use it in GitHub Desktop.
A sample Janet program to read a "special" csv file, convert the data into weighted options, and randomly pick one
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
(math/seedrandom (os/cryptorand 8)) | |
(math/random) | |
(defn read-raw-text | |
[path] | |
(-> path | |
(file/open :r) | |
(file/read :all))) | |
(defn read-special-csv-lines | |
[raw-text] | |
(->> raw-text | |
(|(string/split "\n" $)) | |
(map string/trim) | |
(|(slice $ 1 -2)))) | |
(defn parse-special-csv-line | |
[csv-line] | |
(->> csv-line | |
(string/split ",") | |
(map string/trim))) | |
(defn infere-option | |
[values_] | |
(def [name weight] values_) | |
{:name name | |
:weight (parse weight)}) | |
(defn pick-an-option | |
[options] | |
(let [weights (map |(get $ :weight) options) | |
weights-sum (sum weights) | |
weights-accumulated (accumulate2 + weights) | |
random-threshold (* weights-sum (math/random)) | |
picked-option-index (find-index | |
(fn [weight] | |
(>= weight random-threshold)) | |
weights-accumulated) | |
picked-option (options picked-option-index)] | |
picked-option)) | |
(defn printf-picked-option | |
[option] | |
(string "The picked option: " | |
(get option :name))) | |
(def path "/tmp/input.csv") | |
(->> path | |
read-raw-text | |
read-special-csv-lines | |
(map parse-special-csv-line) | |
(map infere-option) | |
pick-an-option | |
printf-picked-option) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment