shuffle function
parent
2ff274452e
commit
c702e07dd9
|
@ -1,2 +1,3 @@
|
|||
# algorithms
|
||||
My personal implementations of data structure and random algorithms
|
||||
|
||||
a lot of problems, with bad solutions
|
|
@ -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, "")
|
||||
}
|
||||
|
|
|
@ -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")
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue