Last active
November 4, 2021 15:51
-
-
Save alexandru-dinu/ce840ece857e7ad4a6a4e7044adb9a84 to your computer and use it in GitHub Desktop.
FizzBuzz
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
// adapted from | |
// https://wiki.haskell.org/Haskell_Quiz/FizzBuzz/Solution_Acontorer | |
#include <bits/stdc++.h> | |
#include <iostream> | |
using namespace std; | |
const vector<pair<int, string>> tags = { { 3, "Fizz" }, | |
{ 5, "Buzz" }, | |
{ 7, "Bazz" } }; | |
string fizz_buzz(int x) | |
{ | |
string out = ""; | |
for (auto &it : tags) | |
if (x % it.first == 0) | |
out += it.second; | |
return out.empty() ? to_string(x) : out; | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
for (int i = 1; i <= stoi(argv[1]); i++) | |
cout << fizz_buzz(i) << endl; | |
return 0; | |
} |
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
-- adapted from | |
-- https://wiki.haskell.org/Haskell_Quiz/FizzBuzz/Solution_Acontorer | |
import Data.Bool (bool) | |
tags :: [(Int, String)] | |
tags = [(3, "Fizz"), (5, "Buzz"), (7, "Bazz")] | |
desc :: Int -> String | |
desc i = concat [label | (q, label) <- tags, mod i q == 0] | |
fizzBuzz :: Int -> String | |
fizzBuzz i = bool str (show i) (null str) where str = desc i | |
example :: [String] | |
example = map fizzBuzz [1..120] |
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
# adapted from | |
# https://wiki.haskell.org/Haskell_Quiz/FizzBuzz/Solution_Acontorer | |
import functools | |
from typing import List, NewType, Tuple | |
Description = List[Tuple[int, str]] | |
def once(i: int, desc: Description) -> str: | |
return "-".join([m for (k, m) in desc if i % k == 0]) or str(i) | |
description = [(3, "fizz"), (5, "buzz"), (7, "quux")] | |
closure = functools.partial(once, desc=description) | |
res = map(closure, range(128)) | |
for r in res: | |
print(r) | |
# or use nested functions to achieve the same effect | |
def once(desc: Description): | |
def _inner(i: int) -> str: | |
return "-".join([m for (k, m) in desc if i % k == 0]) or str(i) | |
return _inner | |
# but this hides the fact that "closure" is now a function from (int -> str) | |
closure = once(description) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment