"How to identify programmer applicants who can't write code" (Wikipedia The FizzBuzz problem, known as% 95% 8F% E9% A1% 8C)), is a problem that makes you want to think about how short and simple it can be written in various languages (bias). I thought about it myself.
If you write it honestly, it looks like this. Check with Gauche.
fizzbuzz1.scm
(define FizzBuzz
(lambda (n)
(let loop ((x 1) (r '()))
(cond ((> x n) (reverse r))
((and (zero? (modulo x 3)) (zero? (modulo x 5)))
(loop (+ x 1) (cons 'FizzBuzz r)))
((zero? (modulo x 3))
(loop (+ x 1) (cons 'Fizz r)))
((zero? (modulo x 5))
(loop (+ x 1) (cons 'Buzz r)))
(else
(loop (+ x 1) (cons x r)))))))
(display (FizzBuzz 100))
No, it's too straightforward, so I rewrote it.
fizzbuzz2.scm
(define (ch x)
(define (p? n) (zero? (modulo x n)))
(cond ((p? 15) 'FizzBuzz) ((p? 3) 'Fizz) ((p? 5) 'Buzz) (else x)))
(display (map ch (cdr (iota 101))))
Was it too sharp this time?
First of all, honestly.
fizzbuzz1.py
def FizzBuzz(n):
for x in range(1, n+1):
if x % 3 == 0 and x % 5 == 0:
print('FizzBuzz')
elif x % 3 == 0:
print('Fizz')
elif x % 5 == 0:
print('Buzz')
else:
print(x)
FizzBuzz(100)
Let's rewrite this with the glue in the case of Scheme.
fizzbuzz2.py
def ch(x):
def p(n):
return (x % n == 0)
return ('FizzBuzz' if p(15) else 'Fizz' if p(3) else 'Buzz' if p(5) else x)
print(list(map(ch, range(1,101))))
Alright. If you think, If you use the list comprehension notation, you only need one line?
Check with SWI-Prolog and GNU Prolog. I wonder if the combination of between and fail is a bad idea.
fizzbuzz.pl
fb(X,'FizzBuzz') :- X mod 15 =:= 0, !.
fb(X,'Fizz') :- X mod 3 =:= 0, !.
fb(X,'Buzz') :- X mod 5 =:= 0, !.
fb(X,X).
fizzbuzz(N) :- between(1,N,X), fb(X,R), write(R), write(' '), fail.
% ?- fizzbuzz(100).
A straightforward version for the time being.
fizzbuzz1.c
#include <stdio.h>
int main(void)
{
for (int n = 1; n <= 100; n++)
if (n % 3 == 0 && n % 5 == 0) printf("FizzBuzz ");
else if (n % 3 == 0) printf("Fizz ");
else if (n % 5 == 0) printf("Buzz ");
else printf("%d ", n);
return (0);
}
Rewritten using the ternary operator. It's not used as an operator, but it's a little shorter.
fizzbuzz2.c
#include <stdio.h>
int main(void)
{
for (int n = 1; n <= 100; n++)
n % 3 == 0 && n % 5 == 0 ? printf("FizzBuzz ") :
n % 3 == 0 ? printf("Fizz ") :
n % 5 == 0 ? printf("Buzz ") :
printf("%d ", n);
return (0);
}
If you generate a sequence of numbers from 1 to 100 and apply processing to each element, or if you can write multiple judgment expressions in one line, it seems that you can make a short and simple code.