| 1 | module arrays |
| 2 | |
| 3 | // map_of_indexes returns a map, where each key is an unique value in `array`. |
| 4 | // Each value in that map for that key, is an array, containing the indexes in `array`, where that value has been found. |
| 5 | // Example: assert arrays.map_of_indexes([1,2,3,4,4,2,1,4,4,999]) == {1: [0, 6], 2: [1, 5], 3: [2], 4: [3, 4, 7, 8], 999: [9]} |
| 6 | pub fn map_of_indexes[T](array []T) map[T][]int { |
| 7 | mut result := map[T][]int{} |
| 8 | for i, e in array { |
| 9 | if _ := result[e] { |
| 10 | result[e] << i |
| 11 | } else { |
| 12 | result[e] = [i] |
| 13 | } |
| 14 | } |
| 15 | return result |
| 16 | } |
| 17 | |
| 18 | // map_of_counts returns a map, where each key is an unique value in `array`. |
| 19 | // Each value in that map for that key, is how many times that value occurs in `array`. |
| 20 | // It can be useful for building histograms of discrete measurements. |
| 21 | // Example: assert arrays.map_of_counts([1,2,3,4,4,2,1,4,4]) == {1: 2, 2: 2, 3: 1, 4: 4} |
| 22 | pub fn map_of_counts[T](array []T) map[T]int { |
| 23 | mut result := map[T]int{} |
| 24 | for e in array { |
| 25 | result[e]++ |
| 26 | } |
| 27 | return result |
| 28 | } |
| 29 | |