2020-08-22 15:20:49 +03:00
|
|
|
const (
|
2020-12-06 00:21:20 +03:00
|
|
|
unsorted = [2, 30, 10, 20, 1]
|
|
|
|
sorted_asc = [1, 2, 10, 20, 30]
|
2020-08-22 15:20:49 +03:00
|
|
|
sorted_desc = [30, 20, 10, 2, 1]
|
|
|
|
)
|
|
|
|
|
|
|
|
fn test_sorting_simple() {
|
2020-12-20 18:08:56 +03:00
|
|
|
mut a := unsorted.clone()
|
2020-08-22 15:20:49 +03:00
|
|
|
a.sort()
|
|
|
|
eprintln(' a: $a')
|
|
|
|
assert a == sorted_asc
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_sorting_with_condition_expression() {
|
2020-12-20 18:08:56 +03:00
|
|
|
mut a := unsorted.clone()
|
2020-12-06 00:21:20 +03:00
|
|
|
a.sort(a > b)
|
2020-08-22 15:20:49 +03:00
|
|
|
eprintln(' a: $a')
|
|
|
|
assert a == sorted_desc
|
|
|
|
}
|
|
|
|
|
2021-01-21 00:19:35 +03:00
|
|
|
fn test_sorting_primitives_with_condition_expression() {
|
|
|
|
mut x := ['9', '87', '3210', '654']
|
|
|
|
x.sort(a.len < b.len)
|
|
|
|
assert x == ['9', '87', '654', '3210']
|
|
|
|
}
|
|
|
|
|
2021-03-17 03:42:51 +03:00
|
|
|
// fn get_score(word string) int {
|
|
|
|
// mut total := 0
|
|
|
|
// for letter in word {
|
|
|
|
// total += int(letter) - 97
|
|
|
|
// }
|
|
|
|
// return total
|
|
|
|
// }
|
2021-01-21 00:19:35 +03:00
|
|
|
|
2021-03-17 03:42:51 +03:00
|
|
|
// fn test_sorting_with_fn_call_in_condition_expression() {
|
|
|
|
// mut words := ['aaaa', 'a', 'b', 'foo', 'bar']
|
|
|
|
// words.sort(get_score(a) < get_score(b))
|
|
|
|
// }
|
2021-01-21 00:19:35 +03:00
|
|
|
|
2020-12-06 00:21:20 +03:00
|
|
|
fn mysort(mut a []int) {
|
2020-08-22 15:20:49 +03:00
|
|
|
a.sort()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn test_sorting_by_passing_a_mut_array_to_a_function() {
|
2020-12-20 18:08:56 +03:00
|
|
|
mut a := unsorted.clone()
|
2020-08-22 15:20:49 +03:00
|
|
|
mysort(mut a)
|
|
|
|
eprintln(' a: $a')
|
|
|
|
assert a == sorted_asc
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
fn test_sorting_by_passing_an_anonymous_sorting_function() {
|
|
|
|
mut a := unsorted
|
|
|
|
a.sort(fn(a &int, b &int) int { return *b - *a })
|
|
|
|
eprintln(' a: $a')
|
|
|
|
assert a == sort_desc
|
|
|
|
}
|
|
|
|
*/
|
2020-12-06 00:21:20 +03:00
|
|
|
fn test_sorting_u64s() {
|
|
|
|
mut a := [u64(3), 2, 1, 9, 0, 8]
|
|
|
|
a.sort()
|
|
|
|
eprintln(' a: $a')
|
|
|
|
assert a == [u64(0), 1, 2, 3, 8, 9]
|
|
|
|
a.sort(a > b)
|
|
|
|
eprintln(' a: $a')
|
|
|
|
assert a == [u64(9), 8, 3, 2, 1, 0]
|
|
|
|
}
|
2021-07-23 08:55:55 +03:00
|
|
|
|
|
|
|
struct User {
|
|
|
|
age int
|
|
|
|
name string
|
|
|
|
}
|
|
|
|
|
|
|
|
fn g(mut users []User) {
|
|
|
|
users.sort(a.name > b.name)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn f(mut users []User) {
|
|
|
|
users.sort(a.name < b.name)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn z(mut users []User) {
|
|
|
|
users.sort(a.name < b.name)
|
|
|
|
}
|