Skip to content

Instantly share code, notes, and snippets.

@bobbicodes
Created June 21, 2021 00:43
Show Gist options
  • Save bobbicodes/b1b1fb72685fe410ce589a3e6e4d03bd to your computer and use it in GitHub Desktop.
Save bobbicodes/b1b1fb72685fe410ce589a3e6e4d03bd to your computer and use it in GitHub Desktop.
Selection sort toy
(ns selection
(:require [reagent.core :as r]))
(defn button [label onclick]
[:button
{:on-click onclick}
label])
(defn polygon [& points]
[:polygon
{:stroke "black"
:stroke-width 0.3
:fill "none"
:points (apply str (interpose " " points))}])
(defn rect [x y w h]
[:rect
{:width w
:height h
:fill "#00d0ff"
:x x
:y y
:stroke "black"
:stroke-width 0.05}])
(defn svg-bar [w h x y]
[:g
[:rect
{:width w
:height h
:fill "yellow"
:x x
:y y
:stroke "#00d0ff"
:stroke-width 0.05}]])
(defonce elements (r/atom (vec (repeatedly 20 #(rand-int 100)))))
(defonce sorted (r/atom []))
(defn remove-nth
[nums n]
(into (vec (take n nums)) (drop (+ 1 n) nums)))
(defn bars []
(let [bars (into @sorted @elements )
bar-width (/ 80 (count bars))]
(into [:g]
(for [bar (range (count bars))]
(svg-bar bar-width (nth bars bar) (* bar bar-width) (- 100 (nth bars bar)))))))
(defn render-sort []
[:svg {:width "80%"
:view-box (str "0 0 100 100")}
[:g
(rect 0 0 80 100)
[bars]]])
(defn app []
(let [min-val (apply min-key second (map-indexed vector @elements))
val (last min-val)
idx (first min-val)]
[:div#app
[:div [:h2 "Selection Sort"]
[button "Reset" (fn []
(reset! elements (vec (repeatedly 25 #(rand-int 100))))
(reset! sorted []))]]
[render-sort]
[:p (str "Elements: " @elements)]
[:p (str "Sorted: " @sorted)]
[:p (str "Smallest element: " val " at index " idx)]
[button "Swap!" (fn []
(swap! sorted conj val)
(swap! elements #(remove-nth % idx)))]]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment