From 092a1156420be4121b99a6ba2e75365da66a4ec9 Mon Sep 17 00:00:00 2001 From: Emir Pasic Date: Fri, 13 Mar 2015 00:06:49 +0100 Subject: [PATCH] - add swap method to arraylist (consider adding this on all lists) --- README.md | 7 ++++--- examples/arraylist.go | 5 +++-- lists/arraylist/arraylist.go | 7 +++++++ lists/arraylist/arraylist_test.go | 7 +++++++ 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8a7d37f..021b7d2 100644 --- a/README.md +++ b/README.md @@ -168,13 +168,14 @@ func main() { list := arraylist.New() list.Add("a") // ["a"] list.Add("c", "b") // ["a","c","b"] - list.Sort(utils.StringComparator) // ["a","b","c"] + list.Sort(utils.StringComparator) // ["a","b","c"] _, _ = list.Get(0) // "a",true _, _ = list.Get(100) // nil,false _ = list.Contains("a", "b", "c") // true _ = list.Contains("a", "b", "c", "d") // false - list.Remove(2) // ["a","b"] - list.Remove(1) // ["a"] + list.Swap(0, 1) // ["b","a",c"] + list.Remove(2) // ["b","a"] + list.Remove(1) // ["b"] list.Remove(0) // [] list.Remove(0) // [] (ignored) _ = list.Empty() // true diff --git a/examples/arraylist.go b/examples/arraylist.go index 877e623..f2134c7 100644 --- a/examples/arraylist.go +++ b/examples/arraylist.go @@ -40,8 +40,9 @@ func ArrayListExample() { _, _ = list.Get(100) // nil,false _ = list.Contains("a", "b", "c") // true _ = list.Contains("a", "b", "c", "d") // false - list.Remove(2) // ["a","b"] - list.Remove(1) // ["a"] + list.Swap(0, 1) // ["b","a",c"] + list.Remove(2) // ["b","a"] + list.Remove(1) // ["b"] list.Remove(0) // [] list.Remove(0) // [] (ignored) _ = list.Empty() // true diff --git a/lists/arraylist/arraylist.go b/lists/arraylist/arraylist.go index c87dac9..6473332 100644 --- a/lists/arraylist/arraylist.go +++ b/lists/arraylist/arraylist.go @@ -142,6 +142,13 @@ func (list *List) Sort(comparator utils.Comparator) { utils.Sort(list.elements[:list.size], comparator) } +// Swaps two elements with the given indices. +func (list *List) Swap(i, j int) { + if list.withinRange(i) && list.withinRange(j) { + list.elements[i], list.elements[j] = list.elements[j], list.elements[i] + } +} + func (list *List) String() string { str := "ArrayList\n" values := []string{} diff --git a/lists/arraylist/arraylist_test.go b/lists/arraylist/arraylist_test.go index 5b1e30a..1844e27 100644 --- a/lists/arraylist/arraylist_test.go +++ b/lists/arraylist/arraylist_test.go @@ -73,6 +73,13 @@ func TestArrayList(t *testing.T) { t.Errorf("Got %v expected %v", actualValue, "c") } + list.Swap(0, 1) + + if actualValue, ok := list.Get(0); actualValue != "b" || !ok { + t.Errorf("Got %v expected %v", actualValue, "c") + } + + list.Remove(2) if actualValue, ok := list.Get(2); actualValue != nil || ok {