In the below examples I was playing with the languages using a simple method and/or trying to call a method from another method or within a class.
def fizzbuzz(n):
fzbz = []
for x in range(1, n+1):
if x % 15 == 0:
fzbz.append("Fizz Buzz")
elif x % 3 == 0:
fzbz.append('Fizz')
elif x % 5 == 0:
fzbz.append('Buzz')
else:
fzbz.append(str(x))
return fzbz
def print_fizzbuzz():
print(', '.join(fizzbuzz(20))
print_fizzbuzz()def fizz_buzz(num):
fzbz = []
for x in range(1,num+1):
if div_by_fifteen(x) == True:
fzbz.append("Fizz Buzz")
elif div_by_three(x):
fzbz.append("Fizz")
elif div_by_five(x):
fzbz.append("Buzz")
else:
fzbz.append(str(x))
for value in fzbz:
print(value)
def div_by_fifteen(n):
if n % 15 == 0:
return True
def div_by_five(n):
if n % 5 == 0:
return True
def div_by_three(n):
if n % 3 == 0:
return Truedef fizz_buzz(num)
fzbz = []
(1..num).each do |x|
if x % 15 == 0
fzbz << "Fizz Buzz"
elsif x % 3 == 0
fzbz << "Fizz"
elsif x % 5 == 0
fzbz << "Buzz"
else
fzbz << x
end
end
fzbz
end
print fizz_buzz(45)class FizzBuzz
def div_by_fifteen(n)
n % 15 == 0
end
def div_by_five(n)
n % 5 == 0
end
def div_by_three(n)
n % 3 == 0
end
def print_fizz_buzz(num)
fzbz = []
(1..num).each do |x|
if div_by_fifteen(x)
fzbz << "Fizz Buzz"
elsif div_by_three(x)
fzbz << "Fizz"
elsif div_by_five(x)
fzbz << "Buzz"
else
fzbz << x
end
end
fzbz
end
end
f = FizzBuzz.new
puts f.print_fizz_buzz(45)I refactored the above code, thinking about naming conventions.
class FizzBuzz
#dividend / divisor == quotient
def divide_by(dividend, divisor)
dividend % divisor == 0
end
def print_fizz_buzz(upper_bound)
fizzbuzz = []
(1..upper_bound).each do |dividend|
if divide_by(dividend,15)
fizzbuzz << "fizz buzz"
elsif divide_by(dividend,3)
fizzbuzz << "fizz"
elsif divide_by(dividend,5)
fizzbuzz << "buzz"
else
fizzbuzz << dividend
end
end
fizzbuzz
end
end
f = FizzBuzz.new
puts f.print_fizz_buzz(45)public class FizzBuzz
{
public static void main(String[] args)
{
for (int i = 1; i < 101; i++)
{
if (i % 3 != 0 && i % 5 != 0)
{
System.out.print(i);
}
else
{
if (i % 3 == 0)
{
System.out.print("Fizz");
}
if (i % 5 == 0)
{
System.out.print("Buzz");
}
}
System.out.print(' ');
}
}
}function fizzBuzz(){
for(var i = 1; i <= 100; i++){
if(i % 15 === 0){
print('Fizz Buzz');
} else if(i % 3 === 0){
print('Fizz');
} else if(i % 5 === 0){
print('Buzz');
} else {
print(i);
}
}
}package main
import "fmt"
func main() {
for i := 1; i <= 100; i++ {
if i % 15 == 0 {
fmt.Println("Fizz Buzz")
} else if i % 3 == 0 {
fmt.Println("Fizz")
} else if i % 5 == 0 {
fmt.Println("Buzz")
} else {
fmt.Println(i)
}
}
}