Skip to content

Commit

Permalink
Merge pull request #38 from vaskoz/day17
Browse files Browse the repository at this point in the history
Day 17 solution
  • Loading branch information
vaskoz authored Sep 7, 2018
2 parents 1984371 + 02971da commit 9bc3d1a
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ problems from
* [Day 14](https://github.com/vaskoz/dailycodingproblem-go/issues/31)
* [Day 15](https://github.com/vaskoz/dailycodingproblem-go/issues/33)
* [Day 16](https://github.com/vaskoz/dailycodingproblem-go/issues/35)
* [Day 17](https://github.com/vaskoz/dailycodingproblem-go/issues/37)
39 changes: 39 additions & 0 deletions day17/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package day17

import (
"strings"
)

// FindLongestAbsolutePathLength returns the length of the longest file path.
func FindLongestAbsolutePathLength(fs string) int {
var parts []string
var isFile bool
var partStart, tabCount, maxLength int
for i, r := range fs {
if isNewStart(i, r, fs) {
partStart = i
} else if r == '.' {
isFile = true
} else if r == '\t' {
tabCount++
} else if r == '\n' {
if pos := tabCount; len(parts) > pos {
parts = parts[:pos]
}
parts = append(parts, fs[partStart:i])
if len := len(strings.Join(parts, "/")); isFile && len > maxLength {
maxLength = len
}
isFile = false
tabCount = 0
}
}
if isFile {
parts = append(parts, fs[partStart:])
}
return len(strings.Join(parts, "/"))
}

func isNewStart(i int, r rune, fs string) bool {
return i-1 > 0 && fs[i-1] == '\t' && r != '\t' && r != '\n'
}
28 changes: 28 additions & 0 deletions day17/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package day17

import "testing"

var testcases = []struct {
fs string
expected int
}{
{"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext", 32},
{"root\n\tsubdir1\n\t\tfile1.ext", 22},
}

func TestFindLongestAbsolutePathLength(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := FindLongestAbsolutePathLength(tc.fs); result != tc.expected {
t.Errorf("Expected %v but got %v", tc.expected, result)
}
}
}

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

0 comments on commit 9bc3d1a

Please sign in to comment.