[ad_1]
The challenge
Your goal is to return multiplication table for number
that is always an integer from 1 to 10.
For example, a multiplication table (string) for number == 5
looks like below:
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
P. S. You can use n
in string to jump to the next line.
Note: newlines should be added between rows, but there should be no trailing newline at the end.
The solution in Golang
Option 1:
package solution
import (
"fmt"
"strings"
)
func MultiTable(number int) string {
superstring := ""
for i := 1; i < 11; i++ {
superstring += fmt.Sprintf("%d * %d = %dn", i, number, number * i)
}
return strings.TrimRight(superstring, "n")
}
Option 2:
package solution
import "fmt"
func MultiTable(number int) (res string) {
for i := 1; i <= 10; i++ {
res += fmt.Sprintf("%d * %d = %dn", i, number, number*i)
}
return res[:len(res)-1]
}
Option 3:
package solution
import "fmt"
import "strings"
func MultiTable(number int) string {
var s []string
for i := 1; i <= 10; i++ {
s = append(s, fmt.Sprintf("%d * %d = %d", i, number, i*number))
}
return strings.Join(s[:],"n")
}
Test cases to validate our solution
package our_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Test MultiTable", func() {
It("should handle basic cases", func() {
Expect(MultiTable(5)).To(Equal("1 * 5 = 5n2 * 5 = 10n3 * 5 = 15n4 * 5 = 20n5 * 5 = 25n6 * 5 = 30n7 * 5 = 35n8 * 5 = 40n9 * 5 = 45n10 * 5 = 50"))
Expect(MultiTable(1)).To(Equal("1 * 1 = 1n2 * 1 = 2n3 * 1 = 3n4 * 1 = 4n5 * 1 = 5n6 * 1 = 6n7 * 1 = 7n8 * 1 = 8n9 * 1 = 9n10 * 1 = 10"))
})
})
[ad_2]