Skip to content
This repository was archived by the owner on Aug 22, 2025. It is now read-only.

Commit ae75d6f

Browse files
author
Holger Lösken
committed
Add task 4 in go
1 parent 566db28 commit ae75d6f

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/go/t4/s1.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func JumpOutOfArray(numbers []int) int {
6+
sum := 0
7+
jumps := 0
8+
9+
for index, number := range numbers {
10+
sum += numbers[sum]
11+
12+
// Jump out of array at the start of the array
13+
if (index + number) < 0 {
14+
jumps++
15+
break
16+
}
17+
18+
jumps++
19+
20+
// Jump out of array at the end of the array
21+
if sum > len(numbers) {
22+
break
23+
}
24+
25+
// End of array but do not jump out
26+
if (index + 1) == len(numbers) {
27+
jumps = -1
28+
}
29+
}
30+
31+
return jumps
32+
}
33+
34+
func main() {
35+
fmt.Println(JumpOutOfArray([]int { 2, 3, -1, 1, 6 }))
36+
}

src/go/t4/s1_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package main
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
func TestJumpOutOfArray(t *testing.T) {
9+
type test struct {
10+
input []int
11+
want int
12+
}
13+
14+
tests := []test{
15+
{input: []int {2, 3, -1, 1, 6}, want: 4},
16+
{input: []int {-1, 3, -1, 1, 6}, want: 1},
17+
{input: []int {1, 2, 1, 1, 1, 0}, want: -1},
18+
}
19+
20+
for _, tc := range tests {
21+
got := JumpOutOfArray(tc.input)
22+
if !reflect.DeepEqual(tc.want, got) {
23+
t.Fatalf("input: %v, expected: %v, got: %v", tc.input, tc.want, got)
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)