Skip to content

Commit

Permalink
Shuffle the colors on click
Browse files Browse the repository at this point in the history
  • Loading branch information
jbranchaud committed Aug 21, 2018
1 parent 504478e commit d8c12a5
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
34 changes: 34 additions & 0 deletions src/ListUtils.re
@@ -0,0 +1,34 @@
let swap = (items, i, j) => {
/* find the values that need to be swapped */
let i_item = List.nth(items, i);
let j_item = List.nth(items, j);

/* partial application of mapi to create swapper function */
let swapper =
List.mapi((index, item) =>
switch (index) {
| x when x == i => j_item
| x when x == j => i_item
| _ => item
}
);

/* swap the items in the items list */
swapper(items);
};

/* Fisher-Yates Shuffle
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */
let shuffle = (items: list('a)) => {
Random.init(int_of_float(Unix.time()));

let len = List.length(items);
let boxed_items = ref(items);

for (i in len - 1 downto 1) {
let j = Random.int(i);
boxed_items := swap(boxed_items^, i, j);
};

boxed_items^;
};
17 changes: 13 additions & 4 deletions src/index.re
Expand Up @@ -22,9 +22,12 @@ let colors = [
let width = 450;
let height = 450;

let setup = env => Env.size(~width, ~height, env);
let setup = env => {
Env.size(~width, ~height, env);
colors;
};

let draw_circles = env => {
let draw_circles = (colors, env) => {
let xSpacing = width / 9;
let ySpacing = height / 9;

Expand All @@ -48,9 +51,15 @@ let draw_circles = env => {
};
};

let draw = (_state, env) => {
let draw = (colors, env) => {
Draw.background(Utils.color(~r=255, ~g=255, ~b=255, ~a=255), env);
draw_circles(env);
draw_circles(colors, env);

if (Env.mousePressed(env)) {
ListUtils.shuffle(colors);
} else {
colors;
};
};

run(~setup, ~draw, ());

0 comments on commit d8c12a5

Please sign in to comment.