DEV Community

Discussion on: Daily Challenge #64- Drying Potatoes

Collapse
 
dak425 profile image
Donald Feury • Edited

All this talk of potatoes makes me want to Go get some french fries.

I added some error checking for a few cases that made sense to me, such as:

  • No passing in 0 for the mass, since that means you don't have any spuds!
  • No passing in a greater water ratio for p1. I don't think you can increase water ratio by drying potatoes.

I also changed the inputs and outputs to specifically be unsigned integers, since it seems like negative numbers were not meant to be used here and this avoids having to do error checking for things like:

if p0 < 0 || p1 < 0 || w0 < 0 {
    return 0, errors.New("cannot use negative values")
}

Want to see my solutions to the other challenges? Go check them out on my Github! github.com/Dak425/dev-to-challenges

potato.go

package potato

import "errors"

// Dry determines the weight of a mass of potatoes by reducing the current water ratio to the desired ratio
func Dry(p0, w0, p1 uint) (uint, error) {
    if p1 > p0 {
        return 0, errors.New("p1 cannot be greater than p0")
    }
    if w0 == 0 {
        return 0, errors.New("w0 cannot be zero")
    }
    if p0 == p1 {
        return w0, nil
    }
    return w0 * (100 - p0) / (100 - p1), nil
}

potato_test.go

package potato

import "testing"

type testCase struct {
    description string
    input       []uint
    expected    uint
    expectErr   bool
}

func TestDry(t *testing.T) {
    testCases := []testCase{
        {
            "example test",
            []uint{99, 100, 98},
            50,
            false,
        },
        {
            "bigger change in water ratio",
            []uint{99, 100, 95},
            20,
            false,
        },
        {
            "no change in water ratio",
            []uint{87, 120, 87},
            120,
            false,
        },
        {
            "cannot use a zero mass of potatoes",
            []uint{56, 0, 54},
            0,
            true,
        },
        {
            "cannot increase the water ratio",
            []uint{42, 50, 50},
            0,
            true,
        },
    }
    for _, test := range testCases {
        result, err := Dry(test.input[0], test.input[1], test.input[2])
        if err == nil && test.expectErr {
            t.Fatalf("FAIL: %s - Dry(%d, %d, %d): expected error but nil was returned", test.description, test.input[0], test.input[1], test.input[2])
        }
        if result != test.expected {
            t.Fatalf("FAIL: %s - Dry(%d, %d, %d): %d - expected: %d", test.description, test.input[0], test.input[1], test.input[2], result, test.expected)
        }
        t.Logf("PASS: %s", test.description)
    }
}