From: Brendan Hansen Date: Mon, 13 Dec 2021 14:27:06 +0000 (-0600) Subject: made array.unique work on all array types X-Git-Url: https://git.brendanfh.com/?a=commitdiff_plain;h=0957511da2eba3ec0b2733ace096788e4c42a684;p=onyx.git made array.unique work on all array types --- diff --git a/core/container/array.onyx b/core/container/array.onyx index 160a7f3a..7b2928f3 100644 --- a/core/container/array.onyx +++ b/core/container/array.onyx @@ -144,26 +144,6 @@ concat :: (arr: ^[..] $T, other: [] T) { for ^o: other do push(arr, *o); } -// This assumes that the elements are sorted in some fashion, -// such that equal elements would be next to each other. -unique :: (arr: ^[..] $T) { - idx := 0; - while i := 0; i < arr.count - 1 { - defer i += 1; - - if idx != i { - arr.data[idx] = arr.data[i]; - } - - if !(arr.data[i] == arr.data[i + 1]) { - idx += 1; - } - } - - arr.data[idx] = arr.data[arr.count - 1]; - arr.count = idx + 1; -} - fold_idx_elem :: (arr: [] $T, cmp: (T, T) -> bool) -> (i32, T) { idx := 0; @@ -371,6 +351,27 @@ quicksort :: #match { } } +// This assumes that the elements are sorted in some fashion, +// such that equal elements would be next to each other. +unique :: (arr: ^[] $T) { + idx := 0; + while i := 0; i < arr.count - 1 { + defer i += 1; + + if idx != i { + arr.data[idx] = arr.data[i]; + } + + if !(arr.data[i] == arr.data[i + 1]) { + idx += 1; + } + } + + arr.data[idx] = arr.data[arr.count - 1]; + arr.count = idx + 1; +} + + fold :: (arr: [] $T, init: $R, f: (T, R) -> R) -> R { val := init; for it: arr do val = f(it, val); diff --git a/tests/aoc-2021/day13.onyx b/tests/aoc-2021/day13.onyx index d50ade6d..163339ea 100644 --- a/tests/aoc-2021/day13.onyx +++ b/tests/aoc-2021/day13.onyx @@ -12,7 +12,7 @@ cmp_point :: (p1, p2: Point) => { return p1.y - p2.y; } -apply_fold :: (dots: ^[..] Point, axis_name: str, axis_value: i32) { +apply_fold :: (dots: ^[] Point, axis_name: str, axis_value: i32) { for^ *dots do switch axis_name { case "x" do if it.x > axis_value do it.x = 2 * axis_value - it.x; case "y" do if it.y > axis_value do it.y = 2 * axis_value - it.y; @@ -53,7 +53,7 @@ main :: (args) => { string.advance(^line, 1); axis_value := cast(i32) conv.str_to_i64(line); - apply_fold(^dots, axis_name, axis_value); + apply_fold(~~ ^dots, axis_name, axis_value); if part_1_answer < 0 { part_1_answer = dots.count; }