Created
January 12, 2017 16:16
-
-
Save fenimore/1dc053de0b3d762a2e0a6fd19eeaa5bd to your computer and use it in GitHub Desktop.
FizzBuzz iteratively and recursively https://play.golang.org/p/NAl_rTcCxe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// fizzbuzz see the goplayground for output | |
// https://play.golang.org/p/NAl_rTcCxe | |
package main | |
import ( | |
"fmt" | |
) | |
// recursiveFizzBuzz returns a string | |
// of every FizzBuzz output from the original | |
// input until 100 (which is Buzz) | |
func recursiveFizzBuzz(num int) string { | |
if num > 100 { | |
return "" // terminal condition | |
} | |
if num % 3 == 0 { | |
fmt.Print("Fizz") // no newline | |
} | |
if num % 5 == 0 { | |
fmt.Println("Buzz") | |
return recursiveFizzBuzz(num+1) | |
} | |
if num % 3 == 0 { // if Fizz was printed | |
fmt.Println() // there won't be a newline | |
return recursiveFizzBuzz(num+1) | |
} | |
fmt.Println(num) // neither fizz nor buzz | |
return recursiveFizzBuzz(num+1) | |
} | |
// iterativeFizzBuzz returns a string | |
// of line seperated FizzBuzz values | |
// from 1 to 100. | |
func iterativeFizzBuzz() string { | |
var result string // init empty string | |
for i := 1; i < 101; i++ { | |
fizz := i % 3 == 0 | |
buzz := i % 5 == 0 | |
if fizz { | |
result += fmt.Sprint("Fizz") | |
} | |
if buzz { | |
result += fmt.Sprintln("Buzz") | |
} else if !fizz { | |
result += fmt.Sprintln(i) // just the number | |
} else { | |
// Fizz was printed without \n | |
result += fmt.Sprint("\n") | |
} | |
} | |
return result | |
} | |
func main() { | |
fmt.Println(iterativeFizzBuzz()) | |
fmt.Println(recursiveFizzBuzz(1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment