How did I end up with this FizzBuzz?
C, 81 78 bytes
l,i;f(n){for(l=i=0;l<n;l+=++i%3?i%5?snprintf(0,0,"%d",i):4:i%5?4:8);return i;}
68 bytes if you don't mind converting to double
and back:
l,i;f(n){for(l=i=0;l<n;l+=++i%3?i%5?log10(i)+1:4:i%5?4:8);return i;}
Jelly, 16 14 bytes
2 bytes saved using more recent language features )
for µ€
and Ä
for +\
3,5ḍS×4oDL$)Äi
Try it online! or see the test cases.
How?
Builds a list of the lengths of every item from 1
to the input, reduces by addition and then finds the one-based index of the input in the list. (This also means an invalid input results in 0
, "not in list").
3,5ḍS×4oDL$)Äi - Main link: theLength
) - perform the chain to the left for each (€) in
implicit range from 1 to the input and
pass the result into the monadic chain (µ) to the right
3,5 - 3 paired with 5: [3,5]
ḍ - divides? for a multiple of 15 [1,1]; sum = 2; times 4 = 8
S - sum for a multiple of 5 [0,1]; sum = 1; times 4 = 4
×4 - times 4 for a multiple of 3 [1,0]; sum = 1; times 4 = 4
for none of those [0,0]; sum = 0; times 4 = 0
$ - last two links as a monad
D - to decimal digit list
L - length - e.g. 313 -> [3,1,3] -> 3
o - logical or: replace a 0 with the decimal length, keep the 4s and 8s
Ä - reduce with addition: e.g. [1,1,4,1, 4, 4, 1, 1, 4, 4, 2, 4, 2 ,2, 8]
-> [1,2,6,7,11,15,16,17,21,25,27,31,33,35,43]
i - index of theLength in that list (e.g. 15 is at index 6)
MATL, 31 28 27 bytes
`@:tI5h!\XJA)VXznJ~z4*+G-}@
Try it online!
Explanation
` % Do...while
@: % Push array [1 2 ...k], where k is iteration index
t % Duplicate
I5h! % Push column vector [3; 5]
\ % Modulo, with broadcast. Gives 2 × k matrix
XJ % Copy into clipboard J
A % Row vector that contains true for columns that contain two nonzeros
) % Index with that vector. This keeps numbers that are non-fizz/buzz
V % Convert to string. This inserts spaces between numbers
Xzn % Number of nonspace characters
J % Push 2 × k matrix resulting from modulo operation again
~z % Number of zeros
4* % Multiply by 4. Gives number of characters corresponding to fizz/buzz
+ % Add
G- % Subtract input. This is the loop condition: exit if 0
} % Finally (execute right before exiting loop)
@ % Push current iteration index
% End (implicit)
% Display (implicit)