Skip to content

Commit

Permalink
Merge a7b94a5 into 421fffa
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz authored Jan 23, 2019
2 parents 421fffa + a7b94a5 commit 6ff0573
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,4 @@ problems from
* [Day 149](https://github.com/vaskoz/dailycodingproblem-go/issues/311)
* [Day 150](https://github.com/vaskoz/dailycodingproblem-go/issues/312)
* [Day 151](https://github.com/vaskoz/dailycodingproblem-go/issues/313)
* [Day 153](https://github.com/vaskoz/dailycodingproblem-go/issues/316)
45 changes: 45 additions & 0 deletions day153/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package day153

import (
"strings"
)

// SmallestDistanceBetweenWords returns the smallest number of words
// between the two given words in the text provided.
// Returns -1 if one or both of the words don't exist in the text.
func SmallestDistanceBetweenWords(text, one, two string) int {
words := strings.Split(text, " ")
oneI := getIndex(words, one, 0)
twoI := getIndex(words, two, 0)
if oneI == -1 || twoI == -1 {
return -1
}
smallest := len(words)
for oneI != -1 && twoI != -1 {
if dist := abs(oneI - twoI); dist < smallest {
smallest = dist
}
if oneI < twoI {
oneI = getIndex(words, one, oneI+1)
} else {
twoI = getIndex(words, two, twoI+1)
}
}
return smallest - 1
}

func getIndex(s []string, target string, start int) int {
for i := start; i < len(s); i++ {
if s[i] == target {
return i
}
}
return -1
}

func abs(a int) int {
if a < 0 {
return -a
}
return a
}
29 changes: 29 additions & 0 deletions day153/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package day153

import "testing"

var testcases = []struct {
text, one, two string
expected int
}{
{"dog cat hello cat dog dog hello cat world", "hello", "world", 1},
{"dog cat hello cat dog dog hello cat world", "hello", "cat", 0},
{"dog cat hello cat dog dog hello cat world", "wat?", "cat", -1},
}

func TestSmallestDistanceBetweenWords(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := SmallestDistanceBetweenWords(tc.text, tc.one, tc.two); result != tc.expected {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func BenchmarkSmallestDistanceBetweenWords(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
SmallestDistanceBetweenWords(tc.text, tc.one, tc.two)
}
}
}

0 comments on commit 6ff0573

Please sign in to comment.