From c702e07dd93c465474a6594cc02f7d854fb98aff Mon Sep 17 00:00:00 2001 From: sundowndev Date: Wed, 18 Nov 2020 19:40:58 +0100 Subject: [PATCH] shuffle function --- README.md | 3 ++- shuffle/shuffle.go | 24 ++++++++++++++++++++++-- shuffle/shuffle_test.go | 17 ++++++++++------- 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 6bd183e..cdfec16 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,3 @@ # algorithms -My personal implementations of data structure and random algorithms + +a lot of problems, with bad solutions \ No newline at end of file diff --git a/shuffle/shuffle.go b/shuffle/shuffle.go index 5b96570..166eed8 100644 --- a/shuffle/shuffle.go +++ b/shuffle/shuffle.go @@ -1,5 +1,25 @@ package shuffle -func shuffle(arr string) string { - return arr +import ( + "math/rand" + "strings" +) + +// Shuffle returns a shuffled version of the given string +// +// Shuffle("rtfm") -> fmrt +func Shuffle(arr string) string { + var result = make([]string, len(arr)) + + for k, v := range strings.Split(arr, "") { + j := rand.Intn(len(arr) - 0) + + tmp := v + + result[k] = result[j] + result[j] = tmp + + } + + return strings.Join(result, "") } diff --git a/shuffle/shuffle_test.go b/shuffle/shuffle_test.go index cb6e4f9..806da02 100644 --- a/shuffle/shuffle_test.go +++ b/shuffle/shuffle_test.go @@ -8,21 +8,24 @@ import ( func TestShuffle(t *testing.T) { assert := assertTest.New(t) - t.Run("should shuffle string", func(t *testing.T) { - payload := "my payload to shuffle" + t.Run("should Shuffle string", func(t *testing.T) { + payload := "my payload to Shuffle" - assert.NotEqual(payload, shuffle(payload)) + assert.NotEqual(payload, Shuffle(payload)) }) - t.Run("should shuffle string", func(t *testing.T) { + t.Run("should Shuffle string", func(t *testing.T) { payload := "a" - assert.Equal(payload, shuffle(payload)) + assert.Equal(payload, Shuffle(payload)) }) - t.Run("should shuffle string", func(t *testing.T) { + t.Run("should Shuffle string", func(t *testing.T) { payload := "ab" - assert.Equal(payload, shuffle(payload)) + result := Shuffle(payload) + + assert.Contains(result, "a") + assert.Contains(result, "b") }) }