[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
Fizz Buzz Time
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 93
Thread images: 9
File: fizzbuzz.png (6 KB, 160x160) Image search: [Google]
fizzbuzz.png
6 KB, 160x160
So, this time you are only allowed to use 2 if blocks with optional else.
Every variable you declare should be final / immutable.
The only exception is the outer loop.

If you wish extra difficulty: no arrays allowed.

Just a reminder:
Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Syntactic sugar to avoid the restrictions is NOT allowed. Examples of what is not allowed:
import fizzbuzz
test ? if_true : if_false
del varname
>>
>>55325748
Easy.
Print ("1")
Print ("2")
Print ("Fizz")
Etc
>>
>>55325811
Wonder if that would take more or less CPU cycles than an algorithm that goes through a loop with nested if statements.
>>
>>55325748
why would you ever need more than 2 ifs ?
>>
>>55325836
less obviously, are you retarded ?
>>
>>55325836

Nah it will not. Unless you execute it on an ancient CPU with an extremely limited cache.
>>
>>55325860
Yes. Explain pls.
>>
>>55325842
Final variables only. You are not allowed to change the value of the existing variable. It is getting challenging with only 2 ifs.
>>
>>55325880
how could it possibly take more cpu cycles ? it's just print, no conditionals, no incrementation of counter variables and most likely (depends on if the compiler/interpreter unrolls the loops) no loop (cmp/test + jmp)
>>
[source]
#include <stdio.h>

int main(int argc, char **argv)
{
for (int i = 1; i <= 100; i++)
{
printf("\n");
if ((i % 3) == 0)
if ((i % 5) == 0)
printf("FizzBuzz");
else
printf("Fizz");
else if ((i % 5) == 0)
printf("Buzz");
else
printf("%d", i);
}
printf("\n\n");
}
[/source]
>>
>>55325924
So if you wanted to write the most efficient fizzbuzz on an interview you should just do >>55325811?
>>
>>55325903
so i just use a pointer (whichs value doesn't change) and change the memory it points to ?
but i guess thats not what you meant
so by final variables you mean only constants + no arrays ?
i assume strings are considered char arrays ?
>>
>>55325924
Talking to and waiting for the slow RAM on your [pseudo-] von neumann CPU.
>>
>>55325960
I'm new around here.

<source>
#include <stdio.h>

int main(int argc, char **argv)
{
for (int i = 1; i <= 100; i++)
{
printf("\n");
if ((i % 3) == 0)
if ((i % 5) == 0)
printf("FizzBuzz");
else
printf("Fizz");
else if ((i % 5) == 0)
printf("Buzz");
else
printf("%d", i);
}
printf("\n\n");
}
</source>
>>
>>55325960
>Three if statements in a challenge that limits you to two if statements
Really?
>>
>>55325965
cpu efficient? yes. but the binary would be much bigger e.g.
on an interview? nope. but fizzbuzz won't be used for interviews anyway.
>>
>>55325986
{
like this
}
>>
>>55325960
>>55325986
fml
>>
>>55325748
A[I]←1+I←(0⍷A)/⍳⍴A←('FizzBuzz' 'Fizz’ 'Buzz' 0)[2⊥¨×(⊂3 5)|¨1+⍳100]
>>
>>55325967
Consider it to be a pointer on a variable that changes. Forgot to mention it for the c/cpp world, was too long ago...
Though strings technically are, you still need to output something.
Don't get too captious, I bet you understood the idea of the task, and cheating is no go ;) Did not want to write poems in the first post, readability and shit.

>>55325960
Too many IF-s. Busted.
>>
>>55325748
import time
__ = time.time()
while True:
time.sleep(1)
_ = int(time.time() - __)
print('Fizz'[0:int(_%3==0)*4]+'Buzz'[0:int(_%5==0)*4] or _)
if _ >= 100:
break
>>
>>55326063
if you can't change any value or do any pointer arithmetic and arrays are forbidden, the only option would be >>55325811
but i'm probably missing something.
>>
File: rocketscience.jpg (128 KB, 454x264) Image search: [Google]
rocketscience.jpg
128 KB, 454x264
>>55326017
Dude you exploded my brain.

>>55326110
Now we have a winner in the easy difficulty using arrays (lists). Nice use of if btw.
And go make
import this
>>
File: ComputerRTFM.jpg (17 KB, 370x270) Image search: [Google]
ComputerRTFM.jpg
17 KB, 370x270
>>55326125

You are missing something.

Still waiting for a solution without arrays/lists and other crazy shit stuff. It exists.
>>
>>55326181
now i'm really curious how it's possible with immutable variables. i mean it's possible without using any variables at all just writing/reading from the stack directly wie bp/sp but thats kinda language specific so i'd say it counts as "cheating"
>>
File: good_code.png (38 KB, 455x695) Image search: [Google]
good_code.png
38 KB, 455x695
>>55325986
Welcome.
And, no, my bio-grep-eye shows you have used 3 IFs.

>>55326233
I will post the solution if I don't fall asleep earlier. Otherwise make a disposable email box and I send it.
>>
lul

<html>
<body>
<style>
li{
list-style-type: none
}
li:nth-child(3n+1), li:nth-child(5n+1){
font-size: 0;
}
li:nth-child(3n+1):before{
content: 'fizz';
font-size: initial;
}
li:nth-child(5n+1):after{
content: 'buzz';
font-size: initial;
}
</style>
<li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li><li>52</li><li>53</li><li>54</li><li>55</li><li>56</li><li>57</li><li>58</li><li>59</li><li>60</li><li>61</li><li>62</li><li>63</li><li>64</li><li>65</li><li>66</li><li>67</li><li>68</li><li>69</li><li>70</li><li>71</li><li>72</li><li>73</li><li>74</li><li>75</li><li>76</li><li>77</li><li>78</li><li>79</li><li>80</li><li>81</li><li>82</li><li>83</li><li>84</li><li>85</li><li>86</li><li>87</li><li>88</li><li>89</li><li>90</li><li>91</li><li>92</li><li>93</li><li>94</li><li>95</li><li>96</li><li>97</li><li>98</li><li>99</li><li>100</li>
</body>
</html>
>>
>>55326162
import time
__ = time.time()
while (time.time() - __ <= 100):
_ = int(time.time() - __)
print(((_%3==0 and 'Fizz') or '')+((_%5==0 and 'Buzz') or '') or _)
time.sleep(1)


I guess this fits the requirements
>>
>>55325748
What the fuck is that image?
>>
I figure if you're gonna go janky, go for broke:

function f0(x) { document.write("FizzBuzz") }
function f1(x) { document.write(x) }
function f2(x) { document.write(x) }
function f3(x) { document.write("Fizz") }
function f4(x) { document.write(x) }
function f5(x) { document.write("Buzz") }
function f6(x) { document.write("Fizz") }
function f7(x) { document.write(x) }
function f8(x) { document.write(x) }
function f9(x) { document.write("Fizz") }
function f10(x) { document.write("Buzz") }
function f11(x) { document.write(x) }
function f12(x) { document.write("Fizz") }
function f13(x) { document.write(x) }
function f14(x) { document.write(x) }
for(var i = 1; i <= 100; i++) {
eval("f" + (i % 15) + "(" + i + ")")
document.write("<br>")
}
>>
File: behold-the-kickmen.png (318 KB, 1280x720) Image search: [Google]
behold-the-kickmen.png
318 KB, 1280x720
import time

sleep(3153600000)

print('fizzbuzz :^)')

sleep(1)




Job offer when
>>
>>55326660
FizzBuzz, what the fuck else would it be?
>>
>>55326530
What is up with that padding? That a faggot thing?
>>
>>55326676
I like this for thinking outside the box.>>55326717
>>
>>55326717
default html padding is 8px
>>
>>55326701
Shit son, what's got your panties all tied up in a bunch?
>>
>>55326734
The image.
>>
>>55325748
I was really overthinking it

def fizzbuzz(start, end):
print(((start%3==0 and 'Fizz') or '')+((start%5==0 and 'Buzz') or '') or start)
if start < end:
fizzbuzz(start + 1, end)

fizzbuzz(1, 100)
>>
>>55326762
oh, that's a shadow default osx's window screenshot tool makes

can't be bothered to disable it
>>
>>55326750
Mostly reading retarded questions.
>>
>>55326628
Sorry, not at all. Cheating. Here you are using extra conditions hidden behind logical functions.
x % 3 == 0 and 'fizz' or 'buzz'
if (x % 3 == 0) fizz; else buzz;

But I'm glad you find it interesting to explore new features. Check checkio.org

>>55326676
I am not sure whether I hate you or fascinated of the enterprise creativity.
>>
>>55325748
Look ma, no if blocks!
;Boolean short-circuiting
(for ([n (in-range 100)])
(or (and (remainder n 3) (~a "Fizz"))
(and (remainder n 5) (~a "Buzz"))
(void n))
>>
>>55326784
Hidden conditions, same as >>55326628
Also
fizzbuzz(1, 9000)
just realized it's recursive, maniac.

Come one, I want to see here a nice algorithm driven solution finally!
>>
>>55326902
>or
>and
>and

That's one if-statement too many.

>inb4 you don't know that 'and' and 'or' are semantic sugar
>>
File: moonman.png (377 KB, 498x497) Image search: [Google]
moonman.png
377 KB, 498x497
Sure is pleb in here.

print("\n".join(("Fizz"*(i%3==0)+"Buzz"*(i%5==0)) or str(i) for i in range(1,101)))
>>
>>55326835
>I am not sure whether I hate you or fascinated of the enterprise creativity.
Strictly speaking, my solution is dictionary-based, but this gets into why it's so tricky to impose restrictions like "only two 'if' blocks" (what about languages that use pattern-matching?) and "no arrays" (what about compiler/interpreter internal arrays?). Because if you try restricting symbol table usage, then these modern interpreted languages are straight out, and we'd be writing x86 assembly with restrictions on which/how many instructions we can use.
>>
>>55325748
Do conditions in for loops count as ifs?
>>
#include <stdio.h>

int main(int argc, char *argv[]) {
for (int i = 1; i <= 100; i++) {
printf("%d", i);
if (i % 3 == 0)
printf("\b\b\bFizz ");
if (i % 5 == 0)
printf("\b\b\bBuzz");
printf("\n");
}
}


do I win?
>>
>>55327043
What do you believe this prints at numbers 3, 5 and 15
>>
>>55326983

No, no, I seen solutions with the same idea before. But not with functions and eval(). It's actually enough to form a 15-element iterable of any type. That's why I put the "no arrays for extra difficulty" part. Since it is not possible to explain or even find each detail for each possible implementation in each existing programming language, I kept the conditions minimalisting hoping everyone will understand the idea of not using iterables solving the task itself. Otherwise anyone would be disqualified by using array of characters to store the source code.
>>
>>55327043
In a way, you do. This way to solve it I never seen before. And you are surprisingly close to a clean one, without manipulating the actual output or other language/compiler/environment specific stuff.
>>
>>55325748
>>55326902
look ma, no macros!
[CODE]
(doseq [t (range 1 101)]
(println
(match [(mod t 3) (mod t 5)]
[0 0] "FizzBuzz"
[0 _] "Fizz"
[_ 0] "Buzz"
:else t)))
[/CODE]
using clojure with core.match here
>>
>>55327303
This solution violates all the restrictions, but it hoists them to the terminal implementation. The '\b' character relies on having a mutable character array (called the terminal buffer), and the terminal's implementation of '\b' requires a condition (to make sure it doesn't backspace past the beginning of the line).
It's clever and funny, but it's a more exotic version of "import fizzbuzz."
>>
>>55327035
As for me, it would fall under
>Syntactic sugar
and other cheating solutions.

Reminder: there actually IS a clean solution, implementable in (nearly?) any popular programming language.

Sorry for multiposting.
>>
>>55327347

Unfortunately I don't speak Clojure, care to explain the code?
Also, you seem to use arrays. Easy difficulty level solved for you.
>>
>>55327357
Then >>55327043 would be considered wrong, right?
>>
>>55327380
Fuck wikipedia links, if you wanted that you'd google. Pattern matching is a technique used in functional programming to trick a function into doing a different thing based on the parameters it receives, like in a "switch" instruction, but not really.

Not using arrays here - (doseq [t (range 1 101)] ... ) means do something for every t in a sequence obtained by taking a range 1...100. This data structure is immutable, so if it's not returned it'll be garbage collected. If you are willing to consider it like "using an array or a list" anyways, then this instruction may be substituted by (dotimes [t 101] ...) - yields the same result without creating any data structure.
>>
File: Beret_Guy.png (3 KB, 40x127) Image search: [Google]
Beret_Guy.png
3 KB, 40x127
>>55327418
Right, wrong. But a very beret guy way of thinking I should admit.
>>
>>55327380
The "match" is where all the conditions are buried. It's the standard solution, but with a four-clause match instead of if/else if/else if/else. If you speak Haskell, it's like,

data Result = StrRes String | IntRes Int
deriving Show

solve :: Int -> Int -> Int -> Result
solve 0 0 _ = StrRes "FizzBuzz"
solve 0 _ _ = StrRes "Fizz"
solve _ 0 _ = StrRes "Buzz"
solve _ _ x = IntRes x

massage :: Int -> Result
massage x = solve (mod x 3) (mod x 5) x

main :: IO ()
main = print (map massage [1..100])
>>
>>55327474
Okay, thanks for explaining, stay calm. Maybe today I find a nice reason to finally try out some functional languages.
>>
>>55327500
Oh well, this is a kind of problem that is not solvable without conditional constructs. Strictly speaking, (match ...) in clojure is not syntactic sugar for IF, and neither is the macro of the lisp guy before me >>55326902
P.S. for pythonfags, here's your python of the christ:
for i in range(1,101):
print("FizzBuzz"[i*i%3*4:8--i**4%5] or i)
>>55327593
sorry if i seemed angry, I was not
>>
>>55327500
So effectively there are 4 mutually exclusive branches, which is impossible using 2 ifs (you always get 3 branches).
>>
>>55327612
>Strictly speaking, (match ...) in clojure is not syntactic sugar for IF
Sort of, but I think what OP was going for is that "if" really means "conditional branch." In general for functional languages, match is a very heavyweight conditional branch (heavyweight because they often include safe downcasting). Certainly building this as a pattern-match problem with more than three clauses violates the spirit of OP's restrictions.
Indeed, in a nonstrict functional language like Haskell, you can do away with if entirely:

if' :: Bool -> a -> a -> a
if' True r _ = r
if' _ _ r = r


But note that does rely on nonstrict evaluation.
>>
File: n-BAD-SLEEP-628x314.jpg (32 KB, 628x314) Image search: [Google]
n-BAD-SLEEP-628x314.jpg
32 KB, 628x314
My favorite solution in Python
(SPOILERS if you still want to try yourself) pastebin.com/hFfSNa7a

I want to apologize if it became "guess my code" kind of party. Hope still had some fun & g'nite.
>>
>>55326010
That's wrong. If your code is short, the pc is maybe able to work almost only on the cache without using the ram that much. Which is a lot faster.
>>
>>55327852
yeah, worded it wrong, the original question was about cpu cycles, not actual efficiency
>>
>>55327357
>>55327822
>implementable in (nearly?) any popular programming language.
then what you did contains a for (which uses an if to check the end of the range) and two other ifs, making 3.
>>
def fb(x):
return ( 'Fizz'*len('x'[x%3:] )
+ 'Buzz'*len('x'[x%5:] ) ) or str(x)

print(*map(fb, range(1, 101)))
>>
Here's an array one in JS:

for (var i = 1; i < 101; i++) print((["Fizz", "" ,""][(i % 3)] + ["Buzz", "", "", "", ""][(i % 5)]) || i);
>>
>>55328121
I'm pretty sure map has two if statements in it
>>
>>55327946
Without a loop it would not make any sense therefore >>55325748
>The only exception is the outer loop.
not to call the goddamn function a hundred of times.
>>
>>55328478
If you're already using arrays, why not to implement a single one
["FizzBuzz", 1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14]
and reference it by
 array[i % 15]
replacing integers with i? Nah, nevermimd, just asking.
>>
>>55328675
>hiding conditions in the inner loop

fail
>>
>>55328660
less fun ;)
>>
#include <stdio.h>

const char* fizzbuzz[] = {
"%d\n",
"%d\n",
"Fizz\n",
"%d\n",
"Buzz\n",
"Fizz\n",
"%d\n",
"%d\n",
"Fizz\n",
"Buzz\n",
"%d\n",
"Fizz\n",
"%d\n",
"%d\n",
"FizzBuzz\n"
};

int main(const int argc, const char **argv) {
for (int i = 1; i<= 100; i++) {
printf(fizzbuzz[(i-1) % 15], i);
}
}
>>
public class fb {
public static void main (String args[]) {
for(int i=0;i<=100;i++) {
System.out.print(" "+i+":");
if (i%3==0) System.out.print("Fizz");
if (i%5==0) System.out.print("Buzz");
}}}

hello from india
>>
_.range(1,100).map(n => n%3===0?n%5===0?"FizzBuzz":"Fizz":n%5===0?"Buzz":n)
>>
>>55325748
here u go

#include <stdio.h>
int main(void)
{
for(int i=1; i<101; ++i)
printf("%d\r%s%s\n", i, "Fizz"+4*!!(i%3), "Buzz"+4*!!(i%5));
return 0;
}
>>
>>55328782
>>55328782
> India
Trolling?
P.S. check the output, compare with FizzBuzz task definition.
>>
>>55328844
I think we have a real wiener here.
>>
>>55328844
>>55328980
Abusing the output again. \r overwriting the output plus conditionals hidden using operators. Soz.
>>
>>55329000
A better solution would be a solution with the correct output
>>
>>55329000
>stringBuilder
explicitly violates
> Every variable you declare should be final / immutable.
Under the hood Sting operations return new object every time effectively changing the reference variable is. StringBuilder is just a nice wrapper around it with some optimizations.
>Let me know
>>55327822
Why not this? Cannot see anything wrong with it.
>>
I know a solution! It's called brain and hand. It can be implementable in almost any language as an AI, as it is possible to simulate a miniscule portion of a brain at mathematical terms, and the brain does not do conditions! Just pure simple conversions however you imagine it. The hand does most of the outer work for you.

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Tada.
>>
>>55327822
I feel sort of obligated to point out that any solution dependent on nonliteral strings is array-based. The requirement of immutability is a false constraint, because of course any mutation can be replaced by a looping copy. And since you're doing string concatenation as a supposedly primitive operation, you're implicitly allowing looping copies.

Given that, the \b and \r solutions could be reimplemented in ways that follow the rules as much as your version does. I wrote this version in Haskell just to be clear that these are all immutable operations:

solve :: Int -> String
solve i =
let res = show i in
let res2 = if mod i 3 == 0 then "Fizz " else res in
let res3 = if mod i 5 == 0 then take (length res2 - 3) res2 ++ "Buzz" else res2 in
res3

main :: IO ()
main = mapM_ putStrLn (map solve [1..100])


The "problem" with this is that the take function contains a condition:

take :: Int -> [a] -> [a]
take 0 xs = []
take n (x:xs) = x : take (n - 1) xs


But at the same time, list concatenation contains nearly the same condition:

(++) :: [a] -> [a] -> [a]
(++) [] ys = ys
(++) (x:xs) ys = x : xs ++ ys


This is all to say, you violated your own rules, but the ways in which you did so are quite obscure.
>>
Woops, didn't read properly last time. This one has proper output.


private static void gFizzbuzz() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 1; i <= 100; i++) {
int positionCheck = String.valueOf(i).length();
stringBuilder.append(i);
if (i % 3 == 0) {
stringBuilder.delete(0, positionCheck);
stringBuilder.append("Fizz");
positionCheck = 0;
}
if (i % 5 == 0) {
stringBuilder.delete(0, positionCheck);
stringBuilder.append("Buzz");
}
System.out.println(stringBuilder);
stringBuilder.setLength(0);
}
}
>>
>>55329421
Just agree there could stand 3 print operators instead: to print var1, to print var3 and to print \n and no string operations would be involved.
>>
for i in range(1, 101):
start = 0 + (i % 3 != 0) * 4
end = 8 - (i % 5 != 0) * 4
if (i % 3 == 0) or (i % 5 == 0):
print('FizzBuzz'[start:end])
else:
print(i)
>>
>2016
>using if or conditionals on a fizzbuzz ever
how is unemployment gıing for you?

#include<stdio.h>
#include<stdlib.h>

int fizz(int i){
int (*f[])(int) = {fizz, exit};
static char* s[] = {"%d\n", "fizz\n", "buzz\n", "fizzbuzz\n"};
printf(s[!(i%3) + !(i%5)*2], i);
f[i/100]((i+1)%101);
}

int main(){
fizz(1);
}
>>
>>55329800
cleaner
for i in range(1, 101):
start = 0 + (i % 3 > 0) * 4
end = 8 - (i % 5 > 0) * 4
if (start - end) == 0:
print(i)
else:
print('FizzBuzz'[start:end])
>>
>>55326701
Yes, but it's clearly implemented incorrectly
>>
>>55325748
Just declare the function outside the main program

>import FizzBuzz
>mainFunction()
>print("OP is still a fucking faggot")

there 2 lines you autistic faggots
>>
>>55330120
and here version without arrays. almost. if you count that string literal as array then fuck you

#include<stdio.h>
#include<stdlib.h>

int fizz(int i){
printf("%d\n\0fizz\n\0fizzbuzz\n"+!(i%3)*4+!(i%5)*14-!(i%15)*8, i);
(fizz+((int(*)(int))exit-fizz)*(i/100))((i+1)%101);
}

int main(void){
fizz(1);
}
Thread replies: 93
Thread images: 9

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.