-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #350 from vaskoz/day167
Day167
- Loading branch information
Showing
3 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |