Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
37
Task/Best-shuffle/Go/best-shuffle.go
Normal file
37
Task/Best-shuffle/Go/best-shuffle.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ts = []string{"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"}
|
||||
|
||||
func main() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
for _, s := range ts {
|
||||
// create shuffled byte array of original string
|
||||
t := make([]byte, len(s))
|
||||
for i, r := range rand.Perm(len(s)) {
|
||||
t[i] = s[r]
|
||||
}
|
||||
// algorithm of Icon solution
|
||||
for i := range t {
|
||||
for j := range t {
|
||||
if i != j && t[i] != s[j] && t[j] != s[i] {
|
||||
t[i], t[j] = t[j], t[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
// count unchanged and output
|
||||
var count int
|
||||
for i, ic := range t {
|
||||
if ic == s[i] {
|
||||
count++
|
||||
}
|
||||
}
|
||||
fmt.Printf("%s -> %s (%d)\n", s, string(t), count)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue