From 7a9b0731cf6e57043c46b8cf4e7b4dba0e4af7c1 Mon Sep 17 00:00:00 2001 From: Phil Date: Thu, 1 Sep 2022 12:13:15 -0700 Subject: [PATCH] add tests for sort_by_indices --- core/slice/sort.odin | 3 +- tests/core/slice/test_core_slice.odin | 65 +++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/core/slice/sort.odin b/core/slice/sort.odin index e0303a65a..01d762ad7 100644 --- a/core/slice/sort.odin +++ b/core/slice/sort.odin @@ -45,11 +45,12 @@ sort_by_indices :: proc(data: $T/[]$E, indices: []int, allocator := context.allo for v, i in indices { sorted[i] = data[v] } + return } sort_by_indices_overwrite :: proc(data: $T/[]$E, indices: []int) { assert(len(data) == len(indices)) - temp := make([]int, len(data), context.temp_allocator) + temp := make([]int, len(data), context.allocator) defer delete(temp) for v, i in indices { temp[i] = data[v] diff --git a/tests/core/slice/test_core_slice.odin b/tests/core/slice/test_core_slice.odin index 08dc2d3ae..fb13364fd 100644 --- a/tests/core/slice/test_core_slice.odin +++ b/tests/core/slice/test_core_slice.odin @@ -92,3 +92,68 @@ test_sort_with_indices :: proc(t: ^testing.T) { } } } + +@test +test_sort_by_indices :: proc(t: ^testing.T) { + seed := rand.uint64() + fmt.printf("Random seed: %v\n", seed) + + // Test sizes are all prime. + test_sizes :: []int{7, 13, 347, 1031, 10111, 100003} + + for test_size in test_sizes { + fmt.printf("Sorting %v random u64 values along with index.\n", test_size) + + r := rand.create(seed) + + vals := make([]u64, test_size) + r_idx := make([]int, test_size) // Reverse index + defer { + delete(vals) + delete(r_idx) + } + + // Set up test values + for _, i in vals { + vals[i] = rand.uint64(&r) + } + + // Sort + f_idx := slice.sort_with_indices(vals) + defer delete(f_idx) + + // Verify sorted test values + rand.init(&r, seed) + + { + indices := make([]int, test_size) + for _, i in indices { + indices[i] = i + } + + sorted_indices := slice.sort_by_indices(indices, f_idx) + for v, i in sorted_indices { + idx_pass := v == f_idx[i] + expect(t, idx_pass, "Expected the sorted index to be the same as the result from sort_with_indices") + if !idx_pass { + break + } + } + } + { + indices := make([]int, test_size) + for _, i in indices { + indices[i] = i + } + + slice.sort_by_indices_overwrite(indices, f_idx) + for v, i in indices { + idx_pass := v == f_idx[i] + expect(t, idx_pass, "Expected the sorted index to be the same as the result from sort_with_indices") + if !idx_pass { + break + } + } + } + } +}