Skip to content

Commit

Permalink
Merge pull request #350 from vaskoz/day167
Browse files Browse the repository at this point in the history
Day167
  • Loading branch information
vaskoz committed Feb 7, 2019
2 parents fdb67be + 0923bb5 commit fa9395c
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,4 @@ problems from
* [Day 164](https://github.com/vaskoz/dailycodingproblem-go/issues/340)
* [Day 165](https://github.com/vaskoz/dailycodingproblem-go/issues/343)
* [Day 166](https://github.com/vaskoz/dailycodingproblem-go/issues/346)
* [Day 167](https://github.com/vaskoz/dailycodingproblem-go/issues/347)
34 changes: 34 additions & 0 deletions day167/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package day167

// Pair represents indicies that correspond to words
// that when concatenated result in a palindrome.
type Pair struct {
First, Second int
}

// PairsPalindromes returns a slice of Pairs.
// Runs in O(N^2) time.
func PairsPalindromes(words []string) []Pair {
var result []Pair
for i, first := range words {
for j, second := range words {
if i == j {
continue
}
combined := first + second
if isPalindrome(combined) {
result = append(result, Pair{i, j})
}
}
}
return result
}

func isPalindrome(s string) bool {
for i := 0; i < len(s)/2; i++ {
if s[i] != s[len(s)-1-i] {
return false
}
}
return true
}
30 changes: 30 additions & 0 deletions day167/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package day167

import (
"reflect"
"testing"
)

var testcases = []struct {
words []string
expected []Pair
}{
{[]string{"code", "edoc", "da", "d"}, []Pair{{0, 1}, {1, 0}, {2, 3}}},
}

func TestPairsPalindromes(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := PairsPalindromes(tc.words); !reflect.DeepEqual(tc.expected, result) {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func BenchmarkPairsPalindromes(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
PairsPalindromes(tc.words)
}
}
}

0 comments on commit fa9395c

Please sign in to comment.