rustils/
array.rs

1extern crate rand;
2
3use std::usize::MAX;
4
5pub trait ArrayUtils<T> {
6
7    fn swaping(&mut self, a: usize, b: usize)
8        -> bool;
9
10    fn index_of(&self, search: &T)
11        -> usize;
12
13    fn chunk(&self, size: usize)
14        -> Vec<Vec<T>>;
15
16    fn fill_mut(&mut self, value: &T);
17
18    fn unique(&self)
19        -> Vec<T>;
20
21    fn unique_adv(&self)
22        -> (Vec<T>, Vec<T>);
23}
24
25pub fn swaping<T: Ord + Copy>(ary: &mut [T], a: usize, b: usize)
26    -> bool {
27
28    if a == b { return true }
29    else{
30        if a > ary.len()-1 || b > ary.len()-1 { return false }
31        else{
32            let temp = ary[a];
33            ary[a] = ary[b];
34            ary[b] = temp;
35            true
36        }
37    }
38}
39
40pub fn index_of<T: Ord + Copy>(ary: &[T], search: &T)
41    -> usize {
42
43    for i in 0..ary.len() {
44        if &ary[i] == search {
45            return i;
46        }
47    }
48
49    MAX
50}
51
52pub fn chunk<T: Clone>(ary: &[T], size: usize)
53    -> Vec<Vec<T>> {
54
55    let mut iter = ary.chunks(size);
56    let mut next = iter.next();
57    let mut res = Vec::<Vec<T>>::new();
58
59    while !next.is_none() {
60        res.push((*(next.unwrap())).to_vec());
61        next = iter.next();
62    }
63
64    res
65}
66
67pub fn fill_mut<T: Copy>(ary: &mut [T], value: &T) {
68    for i in 0..ary.len() {
69        ary[i] = *value;
70    }
71}
72
73pub fn unique<T: Copy + PartialEq>(ary: &[T])
74    -> Vec<T> {
75
76    unique_adv(&ary).0
77}
78
79pub fn unique_adv<T: Copy + PartialEq>(ary: &[T])
80    -> (Vec<T>, Vec<T>) {
81
82    let mut res = Vec::<T>::new();
83    let mut removed = Vec::<T>::new();
84
85    'outer: for i in 0..ary.len() {
86
87        for j in 0..res.len() {
88            if ary[i] == res[j] {
89                removed.push(ary[i]);
90                continue 'outer;
91            }
92        }
93
94        res.push(ary[i]);
95    }
96
97    (res, removed)
98}