Browse Source

K7 find n-1 common letters (K5, poorly worded).

Frederic G. MARAND 4 years ago
parent
commit
9089c735c3

+ 13 - 0
go/kyu7/find_n_1_common_letters/find_n_1_common_letters_suite_test.go

@@ -0,0 +1,13 @@
+package kata_test
+
+import (
+	"testing"
+
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+func TestFindN1CommonLetters(t *testing.T) {
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "FindN1CommonLetters Suite")
+}

+ 68 - 0
go/kyu7/find_n_1_common_letters/k.go

@@ -0,0 +1,68 @@
+package kata
+
+import (
+	"fmt"
+	"sort"
+	"strings"
+)
+
+func uniqueStrings(sl []string) []string {
+	sMap := make(map[string]struct{})
+	for _, s := range sl {
+		sMap[s] = struct{}{}
+	}
+	reduced := make([]string, len(sMap))
+	i := 0
+	for k := range sMap {
+		reduced[i] = k
+		i++
+	}
+	return reduced
+}
+
+func MinQuine(s string) []string {
+	// Repetitions in the initial s string don't count.
+	words := uniqueStrings(strings.Split(s, " "))
+
+	// No repetition can happen with a single word.
+	if len(words) < 2 {
+		return []string{}
+	}
+	// No N-1 common substring can happen in strings shorter than 2.
+	if len(words[0]) < 2 {
+		return []string{}
+	}
+
+	// At least 2 words, each at least 2 letters long.
+	maxPos := len(words[0]) - 1 // Included and >= 1.
+	counts := make(map[string]int)
+	for _, word := range words {
+		for i := 0; i <= maxPos; i++ {
+			var smaller string
+			if i == 0 {
+				smaller = word[1:]
+			} else if i == maxPos {
+				smaller = word[:maxPos]
+			} else {
+				smaller = word[:i] + word[i+1:]
+			}
+			_, ok := counts[smaller]
+			if ok {
+				counts[smaller]++
+			} else {
+				counts[smaller] = 1
+			}
+		}
+	}
+
+	result := make([]string, 0, len(counts))
+	for word, count := range counts {
+		if count > 1 {
+			result = append(result, word)
+		}
+	}
+
+	sort.Strings(result)
+	fmt.Println(s, result)
+	return result
+}

+ 27 - 0
go/kyu7/find_n_1_common_letters/k_test.go

@@ -0,0 +1,27 @@
+package kata_test
+
+import (
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+
+	. "code.osinet.fr/fgm/codewars/kyu7/find_n_1_common_letters"
+)
+
+var _ = Describe("General tests", func() {
+	It("Sample 1", func() {
+		Expect(MinQuine("AB Ab")).To(Equal([]string{"A"}))
+	})
+	It("Sample 2", func() {
+		Expect(MinQuine("AbCD Abcd aBCd abcD")).To(Equal([]string{}))
+	})
+	It("Sample 3", func() {
+		Expect(MinQuine("ABCD AbCD aBCD aBCd abcd")).To(Equal([]string{"ACD", "BCD", "aBC"}))
+	})
+	It("Sample 4", func() {
+		Expect(MinQuine("ABCd AbCD aBCD aBCd abcd")).To(Equal([]string{"BCd", "aBC"}))
+	})
+
+	It("Repetition", func() {
+		Expect(MinQuine("ABCD ABCD aBcd")).To(Equal([]string{}))
+	})
+})