k.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package kata
  2. import (
  3. "fmt"
  4. "sort"
  5. "strings"
  6. )
  7. func uniqueStrings(sl []string) []string {
  8. sMap := make(map[string]struct{})
  9. for _, s := range sl {
  10. sMap[s] = struct{}{}
  11. }
  12. reduced := make([]string, len(sMap))
  13. i := 0
  14. for k := range sMap {
  15. reduced[i] = k
  16. i++
  17. }
  18. return reduced
  19. }
  20. func MinQuine(s string) []string {
  21. // Repetitions in the initial s string don't count.
  22. words := uniqueStrings(strings.Split(s, " "))
  23. // No repetition can happen with a single word.
  24. if len(words) < 2 {
  25. return []string{}
  26. }
  27. // No N-1 common substring can happen in strings shorter than 2.
  28. if len(words[0]) < 2 {
  29. return []string{}
  30. }
  31. // At least 2 words, each at least 2 letters long.
  32. maxPos := len(words[0]) - 1 // Included and >= 1.
  33. counts := make(map[string]int)
  34. for _, word := range words {
  35. for i := 0; i <= maxPos; i++ {
  36. var smaller string
  37. if i == 0 {
  38. smaller = word[1:]
  39. } else if i == maxPos {
  40. smaller = word[:maxPos]
  41. } else {
  42. smaller = word[:i] + word[i+1:]
  43. }
  44. _, ok := counts[smaller]
  45. if ok {
  46. counts[smaller]++
  47. } else {
  48. counts[smaller] = 1
  49. }
  50. }
  51. }
  52. result := make([]string, 0, len(counts))
  53. for word, count := range counts {
  54. if count > 1 {
  55. result = append(result, word)
  56. }
  57. }
  58. sort.Strings(result)
  59. fmt.Println(s, result)
  60. return result
  61. }