Exercism: Go version of the 'Secret Handshake' exercise.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.1 KiB

// Package secret converts an integer value into a secret phrase.
package secret
// Define friendly names for the bitmasks.
const (
wnk int = 1 << iota // 00001
bli // 00010
clo // 00100
jmp // 01000
rev // 10000
)
// Handshake receives an integer argument and returns a string slice with
// the code words in the proper sequence.
func Handshake(i int) (h []string) {
// Return the original nil slice if the integer is negative.
if i < 0 {
return h
}
// Store the handshake phrases in a string slice (maps are slow).
s := []string{"wink", "double blink", "close your eyes", "jump"}
// Define an ordered set of keys.
keys := []int{wnk, bli, clo, jmp}
// Build the string slice by bitmasking the integer.
for n, k := range keys {
if i&k != 0 {
h = append(h, s[n])
}
}
// Reverse the slice (in-place) if the 5th bit is set.
if i&rev != 0 {
for i, j := 0, len(h)-1; i < j; i, j = i+1, j-1 {
h[i], h[j] = h[j], h[i]
}
}
return h
}
// Revision 2 benchmark:
//
// PASS
// BenchmarkHandshake-12 5000000 338 ns/op