Thursday, December 7, 2023
HomeSoftware EngineeringMaking a Multiplication Desk for a Quantity in Golang

Making a Multiplication Desk for a Quantity in Golang


The problem

Your aim is to return multiplication desk for quantity that’s at all times an integer from 1 to 10.

For instance, a multiplication desk (string) for quantity == 5 seems like beneath:

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 should utilize n in string to leap to the following line.

Observe: newlines needs to be added between rows, however there needs to be no trailing newline on the finish.

The answer in Golang

Choice 1:

bundle answer

import (
  "fmt"
  "strings"
)

func MultiTable(quantity int) string {
  superstring := ""
  for i := 1; i < 11; i++ {
    superstring += fmt.Sprintf("%d * %d = %dn", i, quantity, quantity * i)
  }
  return strings.TrimRight(superstring, "n")
}

Choice 2:

bundle answer

import "fmt"

func MultiTable(quantity int) (res string) {
  for i := 1; i <= 10; i++ {
    res += fmt.Sprintf("%d * %d = %dn", i, quantity, quantity*i)
  }
  return res[:len(res)-1]
}

Choice 3:

bundle answer

import "fmt"
import "strings"

func MultiTable(quantity int) string {
  var s []string
  for i := 1; i <= 10; i++ {
    s = append(s, fmt.Sprintf("%d * %d = %d", i, quantity, i*quantity))
  }
  return strings.Be a part of(s[:],"n")
}

Check circumstances to validate our answer

bundle our_test

import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)

var _ = Describe("Check MultiTable", func() {
   It("ought to deal with fundamental circumstances", func() {
     Anticipate(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"))
     Anticipate(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"))
   })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments