Wednesday, February 21, 2024
HomeSoftware EngineeringReturn the Shortest Phrases in Golang

Return the Shortest Phrases in Golang


The problem

Given a string of phrases, return the size of the shortest phrase(s).

The enter string won’t ever be empty and you don’t want to account for various information sorts.

The answer in Golang

Possibility 1:

bundle resolution
import "strings"

func FindShort(s string) int {
  shortest := len(s)
  for _, phrase := vary strings.Cut up(s, " ") {
    if len(phrase) < shortest {
      shortest = len(phrase)
    }
  }
  return shortest
}

Possibility 2:

bundle resolution
import "strings"

func FindShort(s string) (c int) {
  phrases := strings.Cut up(s," ");
  for _,phrase := vary phrases {
    if c == 0 || len(phrase) < c {
       c = len(phrase);
    }
  }
  return
}

Possibility 3:

bundle resolution
import "strings"

func FindShort(s string) (c int) {
  for _, phrase := vary strings.Fields(s) {
    if c == 0 || len(phrase) < c {
      c = len(phrase)
    }
  }
  return c
}

Take a look at instances to validate our resolution

bundle our_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Take a look at Instance", func() {
  It("ought to check that the answer returns the right worth", func() {
    Anticipate(FindShort("bitcoin take over the world possibly who is aware of maybe")).To(Equal(3))
    Anticipate(FindShort("seems random check instances are simpler than writing out fundamental ones")).To(Equal(3))
    Anticipate(FindShort("Let's journey overseas lets")).To(Equal(2))
  })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments