🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of zhongwencool

zhongwencool's solution

to Series in the Go Track

Published at Apr 13 2021 · 0 comments
Instructions
Test suite
Solution

Given a string of digits, output all the contiguous substrings of length n in that string in the order that they appear.

For example, the string "49142" has the following 3-digit series:

  • "491"
  • "914"
  • "142"

And the following 4-digit series:

  • "4914"
  • "9142"

And if you ask for a 6-digit series from a 5-digit string, you deserve whatever you get.

Note that these series are only required to occupy adjacent positions in the input; the digits need not be numerically consecutive.

Implementation

Define two functions: (Two? Yes, sometimes we ask more out of Go.)

All returns a list of all substrings of s with length n.

All(n int, s string) []string

UnsafeFirst returns the first substring of s with length n.

UnsafeFirst(n int, s string) string

At this point you could consider this exercise complete and move on.

But wait, maybe you ask a reasonable question: Why is the function called Unsafe First? If you are interested, read on for a bonus exercise.

Bonus exercise:

Once you get go test passing, try go test -tags asktoomuch. This uses a build tag to enable a test that wasn't enabled before. Build tags allow for the selection of files to be used by the package. In our case it will control which test files are used. You can read more about those at the Go documentation.

You may notice that you can't make this asktoomuch test happy. We need a way to signal that in some cases you can't take the first N characters of the string. UnsafeFirst can't do that since it only returns a string.

To fix that, let's add another return value to the function. Define

First(int, string) (first string, ok bool)

and test with go test -tags first.

The ok bool second return argument is a common and idiomatic pattern in Go. For example you see it in Map lookups and type assertions.

Coding the solution

Look for a stub file having the name series.go and place your solution code in that file.

Running the tests

To run the tests run the command go test from within the exercise directory.

If the test suite contains benchmarks, you can run these with the --bench and --benchmem flags:

go test -v --bench . --benchmem

Keep in mind that each reviewer will run benchmarks on a different machine, with different specs, so the results from these benchmark tests may vary.

Further information

For more detailed information about the Go track, including how to get help if you're having trouble, please visit the exercism.io Go language page.

Source

A subset of the Problem 8 at Project Euler http://projecteuler.net/problem=8

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

asktoomuch_test.go

// +build asktoomuch

package series

import "testing"

func TestAskTooMuch(t *testing.T) {
	test := allTests[0]
	defer func() {
		if recover() != nil {
			t.Fatalf("Yikes, UnsafeFirst(%d, %q) panicked!", test.n, test.s)
		}
	}()
	for _, test = range allTests {
		switch res := UnsafeFirst(test.n, test.s); {
		case len(test.out) > 0: // well, this should work
			if res != test.out[0] {
				t.Fatalf("Yikes, UnsafeFirst(%d, %q) = %q, want %q.",
					test.n, test.s, res, test.out[0])
			}
		case len(res) != test.n:
			t.Fatalf("Yikes, UnsafeFirst(%d, %q) = %q, but %q doesn't have %d characters.",
				test.n, test.s, res, res, test.n)
		default:
			t.Fatalf("Yikes, UnsafeFirst(%d, %q) = %q, but %q isn't in %q",
				test.n, test.s, res, res, test.s)
		}
	}
}

first_test.go

// +build first

package series

import "testing"

func TestFirst(t *testing.T) {
	for _, test := range allTests {
		switch res, ok := First(test.n, test.s); {
		case !ok:
			if len(test.out) > 0 {
				t.Fatalf("First(%d, %q) returned !ok, want ok.",
					test.n, test.s)
			}
		case len(test.out) == 0:
			t.Fatalf("First(%d, %q) = %q, %t.  Expected ok == false",
				test.n, test.s, res, ok)
		case res != test.out[0]:
			t.Fatalf("First(%d, %q) = %q.  Want %q.",
				test.n, test.s, res, test.out[0])
		}
	}
}

series_test.go

// Define two functions:  (Two? Yes, sometimes we ask more out of Go.)
//
//    // All returns a list of all substrings of s with length n.
//    All(n int, s string) []string
//
//    // UnsafeFirst returns the first substring of s with length n.
//    UnsafeFirst(n int, s string) string
//
// At this point you could consider this exercise complete and move on.
// But wait, maybe you ask a reasonable question:
// Why is the function called **Unsafe** First?
// If you are interested, read on for a bonus exercise.
//
// Bonus exercise:
//
// Once you get `go test` passing, try `go test -tags asktoomuch`.
// This uses a *build tag* to enable a test that wasn't enabled before.
// You can read more about those at https://golang.org/pkg/go/build/#hdr-Build_Constraints
//
// You may notice that you can't make this asktoomuch test happy.
// We need a way to signal that in some cases you can't take the first N characters of the string.
// UnsafeFirst can't do that since it only returns a string.
//
// To fix that, let's add another return value to the function.  Define
//
//    First(int, string) (first string, ok bool)
//
// and test with `go test -tags first`.

package series

import (
	"reflect"
	"testing"
)

var allTests = []struct {
	n   int
	s   string
	out []string
}{
	{1, "01234",
		[]string{"0", "1", "2", "3", "4"}},
	{1, "92834",
		[]string{"9", "2", "8", "3", "4"}},
	{2, "01234",
		[]string{"01", "12", "23", "34"}},
	{2, "98273463",
		[]string{"98", "82", "27", "73", "34", "46", "63"}},
	{2, "37103",
		[]string{"37", "71", "10", "03"}},
	{3, "01234",
		[]string{"012", "123", "234"}},
	{3, "31001",
		[]string{"310", "100", "001"}},
	{3, "982347",
		[]string{"982", "823", "234", "347"}},
	{4, "01234",
		[]string{"0123", "1234"}},
	{4, "91274",
		[]string{"9127", "1274"}},
	{5, "01234",
		[]string{"01234"}},
	{5, "81228",
		[]string{"81228"}},
	{6, "01234", nil},
	{len(cx) + 1, cx, nil},
}

var cx = "01032987583"

func TestAll(t *testing.T) {
	for _, test := range allTests {
		switch res := All(test.n, test.s); {
		case len(res) == 0 && len(test.out) == 0:
		case reflect.DeepEqual(res, test.out):
		default:
			t.Fatalf("All(%d, %q) = %q, want %q.",
				test.n, test.s, res, test.out)
		}
	}
}

func TestUnsafeFirst(t *testing.T) {
	for _, test := range allTests {
		if len(test.out) == 0 {
			continue
		}
		if res := UnsafeFirst(test.n, test.s); res != test.out[0] {
			t.Fatalf("UnsafeFirst(%d, %q) = %q, want %q.",
				test.n, test.s, res, test.out[0])
		}
	}
}
package series

// All returns all strings of len(n)
// out of string s
func All(n int, s string) []string {
	parts := []string{}
	for i := range s[:len(s)-(n-1)] {
		parts = append(parts, s[i:i+n])
	}
	return parts
}

// UnsafeFirst returns the first string
// of len(n) out of string s, unsafely
func UnsafeFirst(n int, s string) string {
	return s[:n]
}

// First returns the first string of
// len(n) out of string s.  If s is too
// small, returns bool false, safely
func First(n int, s string) (string, bool) {
	if n > len(s) {
		return "", false
	}
	return s[:n], true
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?