How to Dry Potatoes in Golang

1 min read 280 words

The challenge

All we eat is water and dry matter.

John bought potatoes: their weight is 100 kilograms. Potatoes contain water and dry matter.

The water content is 99 percent of the total weight. He thinks they are too wet and puts them in an oven – at low temperature – for them to lose some water.

At the output the water content is only 98%.

What is the total weight in kilograms (water content plus dry matter) coming out of the oven?

He finds 50 kilograms and he thinks he made a mistake: “So much weight lost for such a small change in water content!”

Can you help him?

Write function potatoes with

  • int parameter p0 – initial percent of water-
  • int parameter w0 – initial weight –
  • int parameter p1 – final percent of water –

potatoesshould return the final weight coming out of the oven w1 truncated as an int.

Example:

potatoes(99, 100, 98) --> 50

The solution in Golang

Option 1:

package solution

func Potatoes(p0, w0, p1 int) int {
    return w0 * (100 - p0) / (100 - p1)
}

Option 2:

package solution

const percent = 100

func Potatoes(p0, w0, p1 int) int {
  return int(float64(w0) * (float64(percent-p0) / float64(percent-p1)))
}

Option 3:

package solution

func Potatoes(p0, w0, p1 int) int {
  
  weight := w0 * (100-p0)/(100-p1)

  return int(weight)
}

Test cases to validate our solution

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

func dotest(p0, w0, p1 int, exp int) {
    var ans = Potatoes(p0, w0, p1)
    Expect(ans).To(Equal(exp))
}

var _ = Describe("Test Example", func() {

    It("should handle basic cases", func() {
        dotest(99, 100, 98, 50)
        dotest(82, 127, 80, 114)
    })
})
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags