Skip to content

Instantly share code, notes, and snippets.

@audrenbdb
Last active April 26, 2021 13:16
Show Gist options
  • Save audrenbdb/f5c1b212a023e59a657ac3b72893fcac to your computer and use it in GitHub Desktop.
Save audrenbdb/f5c1b212a023e59a657ac3b72893fcac to your computer and use it in GitHub Desktop.
package main
import "strconv"
//solveFizzBuzz solves Fizzbuzz algorithm with given rules below :
//https://en.wikipedia.org/wiki/Fizz_buzz
//Count incrementally up to n :
//when a number is divisible by 3 replace it with Fizz
//when its divisible by 5 replace it with Buzz
//when its divisible by 5 AND 3 replace it with FizzBuzz
func solveFizzBuzz(puzzleLength int) string {
return decodeEachFizzBuzzNumber(puzzleLength, "")
}
func decodeEachFizzBuzzNumber(currentNumber int, solution string) string {
if currentNumber == 0 {
return solution
}
decodedNumber := decodeFizzBuzzNumber(currentNumber)
return decodeEachFizzBuzzNumber(currentNumber - 1, decodedNumber+solution)
}
func decodeFizzBuzzNumber(n int) string {
if isDivisibleByThree(n) && isDivisibleByFive(n) {
return "FizzBuzz"
}
if isDivisibleByThree(n) {
return "Fizz"
}
if isDivisibleByFive(n) {
return "Buzz"
}
return strconv.Itoa(n)
}
func isDivisibleByThree(n int) bool {
return areNumbersDivisible(n, 3)
}
func isDivisibleByFive(n int) bool {
return areNumbersDivisible(n, 5)
}
func areNumbersDivisible(source int, n int) bool {
return source % n == 0
}
package main
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestSolveFizzBuzz(t *testing.T) {
var tests = []struct{
inputPuzzleLength int
outputSolution string
}{
{
inputPuzzleLength: 1,
outputSolution: "1",
},
{
inputPuzzleLength: 2,
outputSolution: "12",
},
{
inputPuzzleLength: 3,
outputSolution: "12Fizz",
},
{
inputPuzzleLength: 4,
outputSolution: "12Fizz4",
},
{
inputPuzzleLength: 5,
outputSolution: "12Fizz4Buzz",
},
{
inputPuzzleLength: 6,
outputSolution: "12Fizz4BuzzFizz",
},
{
inputPuzzleLength: 7,
outputSolution: "12Fizz4BuzzFizz7",
},
{
inputPuzzleLength: 8,
outputSolution: "12Fizz4BuzzFizz78",
},
{
inputPuzzleLength: 9,
outputSolution: "12Fizz4BuzzFizz78Fizz",
},
{
inputPuzzleLength: 10,
outputSolution: "12Fizz4BuzzFizz78FizzBuzz",
},
{
inputPuzzleLength: 11,
outputSolution: "12Fizz4BuzzFizz78FizzBuzz11",
},
{
inputPuzzleLength: 12,
outputSolution: "12Fizz4BuzzFizz78FizzBuzz11Fizz",
},
{
inputPuzzleLength: 13,
outputSolution: "12Fizz4BuzzFizz78FizzBuzz11Fizz13",
},
{
inputPuzzleLength: 15,
outputSolution: "12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzz",
},
}
for _, test := range tests {
solution := solveFizzBuzz(test.inputPuzzleLength)
assert.Equal(t, test.outputSolution, solution)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment