shuffle function

pull/3/head
sundowndev 2020-11-18 19:40:58 +01:00
parent 2ff274452e
commit c702e07dd9
3 changed files with 34 additions and 10 deletions

View File

@ -1,2 +1,3 @@
# algorithms
My personal implementations of data structure and random algorithms
a lot of problems, with bad solutions

View File

@ -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, "")
}

View File

@ -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")
})
}