5
\$\begingroup\$

I have written code in the language Go. I wonder if anyone can do it in a very simple and effective way, because every language has its own way to solve this problem. My experience is in JavaScript. Please guide me how I can improve this solution. Thank you in advance.

What I'm doing here:

Input -

  • "I love dogs"
  • "fun&!! time"

Output :-

  • love
  • time

Here I return the longest word in the string. If there are two or more words that are of same length, return the first word from the string with that length.

package main

    import (
        "fmt"
        "regexp"
    )

    func main() {
        re := regexp.MustCompile(`[A-Za-z]+|[*?()$&.,!]`)
        matches := re.FindAllString("fun&!! time", -1)
        var count int
        for i := 0; i < len(matches); i++ {

            if (i+1)%len(matches) > 0 {

                if len(matches[(i+1)%len(matches)]) > len(matches[i]) {             
                    count = (i + 1) % len(matches)

                }

            }

        }
        fmt.Println(matches[count])
    }
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

The first thing to do is to incorporate some basic notions of organization and design into your program, for example, a maxWord function.

package main

import (
    "fmt"
    "regexp"
)

var re = regexp.MustCompile(`[A-Za-z]+|[*?()$&.,!]`)

func maxWord(s string) string {
    matches := re.FindAllString(s, -1)
    var count int
    for i := 0; i < len(matches); i++ {
        if (i+1)%len(matches) > 0 {
            if len(matches[(i+1)%len(matches)]) > len(matches[i]) {
                count = (i + 1) % len(matches)
            }
        }
    }
    return matches[count]
}

func main() {
    for _, s := range []string{
        "I love dogs",
        "fun&!! time",
        loremipsum,
    } {
        fmt.Printf("%q\n", maxWord(s))
    }
}

var loremipsum = `
Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
Excepteur sint occaecat cupidatat non proident, 
sunt in culpa qui officia deserunt mollit anim id est laborum.
`

Output:

"love"
"time"
"laborum"

Test your code. Your result for the loremipsum text doesn't look right.


Consider writing a simple, efficient word parser. For example,

package main

import (
    "fmt"
    "unicode"
)

func maxWord(s string) string {
    var word string
    inWord := false
    j, k := 0, 0
    for i, r := range s {
        if !unicode.IsLetter(r) {
            if inWord {
                k = i
                if k-j > len(word) {
                    word = s[j:k]
                }
            }
            inWord = false
        } else if !inWord {
            inWord = true
            j = i
        }
    }
    if inWord {
        k = len(s)
        if k-j > len(word) {
            word = s[j:k]
        }
    }
    return word
}

func main() {
    for _, s := range []string{
        "I love dogs",
        "fun&!! time",
        loremipsum,
    } {
        fmt.Printf("%q\n", maxWord(s))
    }
}

var loremipsum = `
Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
Excepteur sint occaecat cupidatat non proident, 
sunt in culpa qui officia deserunt mollit anim id est laborum.
`

Output:

"love"
"time"
"reprehenderit"

Go programmers often write reasonably efficient programs. The Go standard library testing package provides a benchmark facility.

For example,

$ go test maxword_test.go -bench=. -benchmem 
BenchmarkPeterSO-4    24316906      47.7 ns/op      0 B/op     0 allocs/op
BenchmarkMannu-4        557594    2022 ns/op      448 B/op    10 allocs/op

maxword_test.go:

package main

import (
    "regexp"
    "testing"
    "unicode"
)

func maxWordP(s string) string {
    var word string
    inWord := false
    j, k := 0, 0
    for i, r := range s {
        if !unicode.IsLetter(r) {
            if inWord {
                k = i
                if k-j > len(word) {
                    word = s[j:k]
                }
            }
            inWord = false
        } else if !inWord {
            inWord = true
            j = i
        }
    }
    if inWord {
        k = len(s)
        if k-j > len(word) {
            word = s[j:k]
        }
    }
    return word
}

func BenchmarkPeterSO(b *testing.B) {
    for N := 0; N < b.N; N++ {
        for _, s := range []string{"I love dogs", "fun&!! time"} {
            maxWordP(s)
        }
    }
}

var re = regexp.MustCompile(`[A-Za-z]+|[*?()$&.,!]`)

func maxWordM(s string) string {
    matches := re.FindAllString(s, -1)
    var count int
    for i := 0; i < len(matches); i++ {
        if (i+1)%len(matches) > 0 {
            if len(matches[(i+1)%len(matches)]) > len(matches[i]) {
                count = (i + 1) % len(matches)
            }
        }
    }
    return matches[count]
}

func BenchmarkMannu(b *testing.B) {
    for N := 0; N < b.N; N++ {
        for _, s := range []string{"I love dogs", "fun&!! time"} {
            maxWordM(s)
        }
    }
}

var benchTexts = []string{"I love dogs", "fun&!! time"}
\$\endgroup\$
1
  • \$\begingroup\$ Thank you so much, Peter, for your guidance. I will work on it and try to understand to write efficient code in Go. \$\endgroup\$
    – Mannu
    Jun 13, 2019 at 5:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.