Skip to content

Instantly share code, notes, and snippets.

@sblcook
Created July 21, 2020 20:03
Show Gist options
  • Save sblcook/1b13789dd28ddce24eb339790e59ed1a to your computer and use it in GitHub Desktop.
Save sblcook/1b13789dd28ddce24eb339790e59ed1a to your computer and use it in GitHub Desktop.
An exercise implemented in sibilant, even though the file extension is lisp.
(def sort (input_strings)
(var str: "" i: -1 strings: [] occs: []) ;; set a list for the strings and a list for the occurrences. These are "mirrored" and stay in synch
( each str input_strings ;; iterate through every string
(if (includes? strings str) ;; check to see if we've seen it before
( do
(assign i (get strings.indexOf(str))) ;; get the index of the string (also the index of the occurrences)
(set occs[i] (+ 1 (get occs[i]))) ;; increment how many times we've seen it
(while (< (get occs[i--1]) (get occs[i])) ;; double check that it is still in descending order
(var temp (get strings[i--1])) ;; if it is out of place, switch it with the word before
(set strings[i--1] (get strings[i]))
(set strings[i] temp)
(assign temp (get occs[i--1])) ;;make sure to switch the occurrence count as well
(set occs[i--1] (get occs[i]))
(set occs[i] temp)
)
)
(do (set strings[(length strings)] str) (set occs[(length occs)] 1)) ;; we haven't seen it before--add the word and add an occurence
)
)
(assign i 0) ;; merge the two lists and print
(each str strings (set strings[i] (+ str ": " (get occs[i]) " occurrence" )) (incr i))
(console.log strings)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment