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

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. // Package secret converts an integer value into a secret phrase.
  2. package secret
  3. // Define friendly names for the bitmasks.
  4. const (
  5. wnk int = 1 << iota // 00001
  6. bli // 00010
  7. clo // 00100
  8. jmp // 01000
  9. rev // 10000
  10. )
  11. // Handshake receives an integer argument and returns a string slice with
  12. // the code words in the proper sequence.
  13. func Handshake(i int) (h []string) {
  14. // Return the original nil slice if the integer is negative.
  15. if i < 0 {
  16. return h
  17. }
  18. // Store the handshake phrases in a string slice (maps are slow).
  19. s := []string{"wink", "double blink", "close your eyes", "jump"}
  20. // Define an ordered set of keys.
  21. keys := []int{wnk, bli, clo, jmp}
  22. // Build the string slice by bitmasking the integer.
  23. for n, k := range keys {
  24. if i&k != 0 {
  25. h = append(h, s[n])
  26. }
  27. }
  28. // Reverse the slice (in-place) if the 5th bit is set.
  29. if i&rev != 0 {
  30. for i, j := 0, len(h)-1; i < j; i, j = i+1, j-1 {
  31. h[i], h[j] = h[j], h[i]
  32. }
  33. }
  34. return h
  35. }
  36. // Revision 2 benchmark:
  37. //
  38. // PASS
  39. // BenchmarkHandshake-12 5000000 338 ns/op