title: Let's get Animated!

text:
# Question
Title: Let's get Animated!
# The Challenge

GIFs are the most common image format for animation, and are used pretty heavily in today's social media. For the purpose of this challenge, I'm going to redefine what a GIF can be. This challenge will require you to take in a 3D array containing some sort of representation of a 2D 'image' and iterate through them, displaying an animation. This animation can be done anywhere, in a GIF, in your console, in a GUI, etc; the delivery doesn't matter, so long as it is animated.

## The Input

* **A 3D array where the data inside somehow represents a 2D image.**
    + The array may contain RGB data, true/false data or anything else you see fit.
    + I'm also fine with you dumbing it down to a 2D array of strings or something similar, but the animation **must be a 2D animation**.
* **The time between each frame in a format of your choosing (Seconds, Milliseconds, etc...).**
    + *People have been asking me whether or not they HAVE to include the duration length. My answer is "meh", as long as you are able to show animation. I'm more concerned that you adhere to the "Array" parameter than this one, meaning no random animations.*

## The Output

* **A seamlessly iterated sequence of output that looks like a 2D animation with the correct delay on each transition based on the value input.**

# The Rules

* Output can be, but is not limited to:
    + GIF image.
    + GUI animation (my example).
    + In-console animation.
    + Honestly, any "animation" that you see fit, as long as it follows the below rules.
* When outputting your image you must clear the console before showing the next frame, you cannot just print them sequentially.
    + Emulating a console "clear" is also acceptable, as long as it looks like a seamless animation (see the hint under my example for more information on what I mean).
* Regardless of implementation, your animation should loop forever, or until stopped.
    + The "looping" can be as simple as `while(true){}` or infinite recursion, you may assume the user wants to view this masterpiece until they hit "ctrl+c".
* You must be able to handle any size 2D 'images', if your language is limited by buffer sizes, this is acceptable and you may state this in your explanation.
* Standard loopholes are disallowed.

# Example I/O

## Input (3D Array, Delay)

```
f([
  [[1,0,0],
   [0,0,0],
   [0,0,0]],
  [[0,0,0],
   [0,1,0],
   [0,0,0]],
  [[0,0,0],
   [0,0,0],
   [0,0,1]],
], 1)

```

## Output (Example, 2020 Bytes - Java)

```
import javax.swing.JFrame;
import javax.swing.JTextArea;

/**
 * Simple GIF class to animate a 3D integer array in a swing text area.
 * (Clearing the console in java isn't something you really do, so I chose
 * java on purpose to make it an extremely ungolf-able answer that someone
 * wouldn't bother to steal).
 */
public class Gif implements Runnable {
    /**
     * The output area.
     */
    private final JTextArea area;

    /**
     * The list of images.
     */
    private final int[][][] images;

    /**
     * The delay between image transitions.
     */
    private final long transitionDelay;

    /**
     * Main method, instantiates a GIF object and runs it.
     * @param args Does absolutely nothing.
     */
    public static void main(String[] args) {
        final int[][][] images = {{{1,0,0},{0,0,0},{0,0,0}},{{0,0,0},{0,1,0},{0,0,0}},{{0,0,0},{0,0,0},{0,0,1}}};
        final long transitionDelay = 1000L;
        new Thread(new Gif(images, transitionDelay)).start();
    }

    /**
     * Constructor for a GIF, takes in a 3D array of images and a transition
     * delay to wait between transitioning the images.
     * @param images The list of images.
     * @param delay The delay between each image.
     */
    public Gif(int[][][] images, long transitionDelay) {
        this.images = images;
        this.transitionDelay = transitionDelay;
        this.area = new JTextArea();
        final JFrame frame = new JFrame("It's a GIF!");
        frame.setSize(10,100);
        frame.add(area);
        frame.setVisible(true);
    }

    /**
     * When run, it will alter the area to imitate an animated GIF.
     */
    @Override
    public void run() {
        while (true) {
            for (int i = 0; i < images.length; i++) {
                final StringBuffer frame = new StringBuffer();
                for (int j = 0; j < images[i].length; j++) {
                    for (int k = 0; k < images[i][j].length; k++) {
                        frame.append("" + images[i][j][k]);
                    }
                    frame.append("\n");
                }
                this.area.setText(frame.toString());
                try{Thread.sleep(transitionDelay);}catch(Exception e){}
                this.area.setText("");
            }
        }
    }
}

```

This results in a swing GUI popping up, animating the array:

**HINT HINT:** Use a language where console clearing is possible, or specify why what you are doing will end up with a result that looks like an animation in the language you chose. I think some languages have default buffer sizes on their consoles, you may use this to your advantage, but I expect an explanation or example. Just because I output my animation as a string, you don't have to; I could've just as easily used 0 for black and 1 for white and made a real GIF.

## Judging

This is code-golf, lowest byte count wins (inputs excluded).
I'll +1 anyone who uses a language in a cool or unexpected way as well.

# Answer
> 3 votes
# MATL, ~~16~~ ~~12~~ 11 bytes

```
`G@)D1Y.XxT

```

Input is a cell array of 2D. For example:

```
{[1 0 0; 0 0 0; 0 0 0] [0 0 0; 0 1 0; 0 0 0] [0 0 0; 0 0 0; 0 0 1]}

```

The pause time is the `1` in the code. It can be changed to any real number, such as `.5` or \`.2 .

Try it at MATL Online! (If it doesn't work, refresh the page and press "Run" again.)

The input can also be a cell array of 2D char arrays. For example:

```
{['x...';'+...';'....';'....'] ['+x..';'....';'....';'....'] ['.+x.';'....';'....';'....'] ['..+x';'....';'....';'....'] ['...+';'...x';'....';'....'] ['....';'...+';'...x';'....'] ['....';'....';'...+';'...x'] ['....';'....';'....';'..x+'] ['....';'....';'....';'.x+.'] ['....';'....';'....';'x+..'] ['....';'....';'x...';'+...'] ['....';'x...';'+...';'....']}

```

Try this one too!

### Explanation

```
`       % Do...while
  G     %   Push input: cell array
  @     %   Push iteration index
  )     %   Index to obtain that cell. This uses modular indexing,
        %   so each cell is addressed cyclically
  D     %   Display
  1     %   Push 1: number of seconds to pause
  Y.    %   Pause for that many seconds
  Xx    %   Clear screen
  T     %   True. This is used as loop condition: infinite loop
        % End. Implicitly end do...while loop

```

# Answer
> 2 votes
# Octave, ~~56~~ ~~54~~ 47 bytes

Removed the possibility to input the pausing time as part of the input matrix. I was very satisfied with it, so have a look in the edit history if you want to have a look. This solution is 7 bytes shorter.

```
n=input('');while(any(n=~n))spy(n);pause(1);end

n=input('');  % Takes input as a matrix of zeros and ones

k=n(1);       % maximum of the input matrix is the desired pause time. Have to store
              % this, because n is soon to be messed with
              % NOTE: k=n(1); is not needed anymore, since the pause time can be hardcoded!

any(n=~n)     % Check if there are any truthy values in `n` (there is), and at the
              % same time negate it, thus creating a matrix where all elements
              % alternates between 1 and 0.
while(any(n=~n))   % Loop as long as there are any non-zero elements (always some)
spy(n)        % Create a spy-plot where all non-zero elements are shown as a dot
pause(1)      % Pauses for k seconds
end           % ends the loop (will never happen, since it's infinite).

```

The input will be something like this: `[4 0 0 4;0 4 4 0;4 0 0 0]`, where this will be a matrix of dimensions 3x4, and the desired pause time is 4 seconds.

It displays a plot like the one below, but alternates between showing the true and the false values of the input. So all the blue dots will become white in the next iteration, and all the white will become blue.

In the below plot, I used the input `rand(10,10)>0.6*2`. This means it will have dimensions 10x10, and all elements of the random matrix that are larger than 0.6 will be true. After that I multiply it by the desired pausing time, 2 seconds. I used a random matrix here, but I could have created the matrix manually too.

I don't have Octave installed on this computer, so I made a minor alteration to make this work in MATLAB. It's the exact same principle, but `n=~n` doesn't work in MATLAB.

# Answer
> 2 votes
# sed 141 134 90

-51 thanks to seshoumara

```
/^$/!{H;d}
:;/^$/g;s,^\n,,;s,$, ,;s,^,\d27[2J,p
:p;P;s,[^\n]*\n,,;/^ \n/!bp;N;s,[ \n]*,,;b

```

Input: First takes each frame separated by a line with a single space then display the next frame after each blank line is received (looks like a flipbook). Minimum 3 frames.

By default on my system (Windows 7) when I open cygwin it have 24 lines vertically. Between frames, there are always at least that many blank lines printed. This effectively clears the screen.

Over 1/3 of the bytes come from clearing the console. I'm sure there's a better way.

# Answer
> 2 votes
## GNU sed, ~~88~~ 84 + 1(n flag) = 85 bytes

**Edit:** 3 bytes less thanks to Riley

```
H;1h;${:
g;s:\n.*::;H;x;s:[^\n]*\n::;x;y:,:\n:;s:^:ESC[2J:;s:ESC:\d27:gp;esleep 1
b}

```

The input format is one animation frame per line. For multiple output lines in a frame, use comma as separator. Because I run the program in a Linux console, the maximum image size available (measured in rows and columns) is dependent on the size of the terminal window. The pause between two frames is accomplished by the *sleep* shell command; to get a faster animation call `esleep 0.4` (seconds).

```
100,000,000            # The timer could be read from the input as well, but that
000,010,000            #would require a lot more bytes and I understand I'm allowed
000,000,001            #to hardcode the value.

```

The best part is that I support color animation! To do this, I used the so called ANSI Escape Sequences to control the text font, foreground and background color, plus the position of the cursor, thus being able to clear the screen before each frame (code `ESC[2J`). To add color information, use the following format in the input, which is better explained here.

```
ESC[$FORMATm$textESC[0m     # 'ESC' is an actual string, it is then replaced
                            #in sed by the character with the ASCII value 27

```

**Run:**

```
sed -nf animate.sed input.txt

```

**Examples:** for each test, 2 animation cycles were screen-captured and saved in image GIF format (apologies for the low resolution)

0.4 seconds pause

1 second by default

**Explanation:**

```
H;1h                           # read each line/frame and store them in hold space
${:                            # when the input was read, start a loop
   g                           # copy hold space to pattern space
   s:\n.*::                    # remove all except the first/current frame
   H                           # append frame to hold space
   x;s:[^\n]*\n::;x            # delete first frame from hold space
   y:,:\n:                     # replace all commas with a newline
   s:^:ESC[2J:;s:ESC:\d27:gp   # use an ANSI Escape Sequence to clear the screen
                               #and print frame in color
   esleep 1                    # wait 1 second
b}                             # repeat

```

# Answer
> 1 votes
## Ruby, ~~89~~ 45 bytes

```
f=->h,t{h.cycle{|x|puts"^[[2J",x.map(&:join)}}

```

The `^[` is an escape character.

Hexdump:

```
00000000: 663d 2d3e 682c 747b 682e 6379 636c 657b  f=->h,t{h.cycle{
00000010: 7c78 7c70 7574 7322 1b5b 324a 222c 782e  |x|puts".[2J",x.
00000020: 6d61 7028 263a 6a6f 696e 297d 7d         map(&:join)}}

```

Saved a **lot** of bytes thanks to @Jordan

# Answer
> 1 votes
# Lua(LÖVE), ~~296~~ 287 bytes

```
c=0;f=1;t=10;l=love
function l.load()loadstring('i='..arg[2])()s=tonumber(arg[3])end
function l.update(d)if c>s then
c=0;f=f==#i and 1 or f+1
end;c=c+d;end
function l.draw()for K,V in pairs(i[f])do
for k,v in pairs(V)do if v>0 then l.graphics.rectangle('fill',k*t,K*t,t,t)end
end
end
end

```

**Usage Example**

```
love main.love '{{{1,0,0},{0,0,0},{0,0,0}},{{0,1,0},{0,0,0},{0,0,0}},{{0,0,1},{0,0,0},{0,0,0}},{{0,0,0},{0,0,1},{0,0,0}},{{0,0,0},{0,0,0},{0,0,1}},{{0,0,0},{0,0,0},{0,1,0}},{{0,0,0},{0,0,0},{1,0,0}},{{0,0,0},{1,0,0},{0,0,0}},{{1,0,0},{1,0,0},{0,0,0}},{{1,1,0},{1,0,0},{0,0,0}},{{1,1,1},{1,0,0},{0,0,0}},{{1,1,1},{1,0,1},{0,0,0}},{{1,1,1},{1,0,1},{0,0,1}},{{1,1,1},{1,0,1},{0,1,1}},{{1,1,1},{1,0,1},{1,1,1}},{{1,1,1},{1,1,1},{1,1,1}},{{0,0,0},{0,0,0},{0,0,0}}}' 1

```

**Output** : https://youtu.be/0kDhPbbyG9E

# Answer
> 1 votes
# SmallBasic, 167 bytes

As a parameter, define and set the global var i! Sadly, SmallBasic does not support parameters for own Sub-routines.

```
sub animate
for j=0 to Array.getItemCount(i)
for k=0 to Array.getItemCount(i[0])
TextWindow.writeLine(i[j][k])
endfor
Program.delay(9)
TextWindow.clear()
endfor
endsub

```

---
Tags: code-golf, ascii-art, animation
---


title: Hexagolf: Validagons

text:
# Question
Title: Hexagolf: Validagons
## Challenge

Given an ASCII art shape, you must find out whether the shape is a regular hexagon or not.

## Hexagons

A regular hexagon is defined using two rules:

* It has six sides
* Each side has equal numbers of characters

For example, the following shape is regular but it doesn't have six sides and so is not a regular *hexagon*:

```
B a a h
s a i d
y o u r
g a o t

```

Similarly, the following shape has six sides but has sides of different lengths and so is not a *regular* hexagon:

```
  * *
 * * *
* * * *
 * * *
  * *

```

However, the following shape has six sides and all of the sides have the same number of characters, so it is a regular hexagon:

```
  T h e
 h e x a
g o n s a
 r e c o
  m i n

```

## Rules

Output should be a truthy or a falsey value (truthy if the shape is a regular hexagon, falsey if not).

The shapes will only ever contain printable ASCII characters.

The border of the shape will never contain spaces. If it does, you can return falsey.

There can be arbitrary amounts of whitespace before and/or after the shape.

All angles in the shape may not be equal for example, the following shape is valid input:

```
  . . .
   . . .
. . . . .
 . . . .
  . . .

```

It will return a falsey value.

All shape inputs will be on a space separated grid. Hexagonal input will be on a staggered grid (each line is offset from the next).

## Examples

### Truthy

The following shapes should return truthy values:

```
 # _
+ + +
 9 :

```

---

```
  5 6 7
 8 9 0 1
2 3 4 5 6
 7 8 9 0
  1 2 3

```

---

```
    t h i s
   i       s
  a         h
 e           x
  a         g
   o       n
    ! ! ! !

```

---

```
    5 6 7
   8 9 0 1
  2 3 4 5 6
   7 8 9 0
    1 2 3

```

### Falsey

The following should return falsey values

```
r e c t a
n g l e s

```

---

```
  h e l l o
 w o r l d s
t h i s i s b
 e t a d e c
  a y n o w

```

---

```
  *
 * *
* * *

```

---

```
  .....
 .......
.........
 .......
  .....

```

This shape is not on a space separated grid and is not staggered.

---

```
   * * * *
  ---------
 * * * * * *
-------------
 * * * * * *
  ---------
   * * * *

```

---

```
5 6 7
8 9 0 1
2 3 4 5 6
7 8 9 0
1 2 3

```

---

For single character inputs, your program may output either truthy or falsey:

```
&

```

## Winning

The shortest program in bytes wins.

# Answer
> 2 votes
## R, 184 bytes

Golfed, could probably be golfed by a few bytes

```
function(m){e=min;f=max;l=length;v=which(m!=" ",T);a=v[,1];n=l(v[a==1,2]);u=(v[a==e(a),2]);all(u==v[a==f(a),2])&all(c(e(d<-v[a==ceiling(f(v[,1])/2),2]),f(d))==c(u[1]-n+1,u[l(u)]+n-1))}

```

Ungolfed, very messy, more like half way golfed

```
f=function(m) {
  v = which(m!=" ",T)
  a = v[,1]
  n = length(v[a==1,2])
  u=(v[a==min(a),2])
  c1 = all(u==v[a==max(a),2])
  d = v[a==ceiling(max(v[,1])/2),2]
  c2 = all(c(min(d), max(d))==c(u[1]-n+1,u[length(u)]+n-1))
  c1 & c2
}

```

Since the input format is unspecified, Input needs to be specified in an R array format, looking something like this.

```
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] " "  " "  "5"  " "  "6"  " "  "7"  " "  " "
[2,] " "  "8"  " "  "9"  " "  "0"  " "  "1"  " "
[3,] "2"  " "  "3"  " "  "4"  " "  "5"  " "  "6"
[4,] " "  "7"  " "  "8"  " "  "9"  " "  "0"  " "
[5,] " "  " "  "1"  " "  "2"  " "  "3"  " "  " "

```

Here is a generator function that generates the input. The generator doesn't generate an object that is fed into hexagon check function, but rather the code specifying the array (effectively the same thing). So this should not count as parsing the text. Remember that I'm not inputting text, but rather an array structure.

```
generate = function(x) {
  s = strsplit(strsplit(x, "\n")[[1]], "")
  m = max(sapply(s, length))
  dput(do.call(rbind, lapply(s, function(x) c(x, rep(" ", m-length(x))))))
}

```

For example, the generated code would be: `structure(c(" ", " ", "2", " ", " ", " ", "8", " ", "7", " ", "5", " ", "3", " ", "1", " ", "9", " ", "8", " ", "6", " ", "4", " ", "2", " ", "0", " ", "9", " ", "7", " ", "5", " ", "3", " ",
"1", " ", "0", " ", " ", " ", "6", " ", " "), .Dim = c(5L, 9L
))` which is identical to `array(c(" ", " ", "2", " ", " ", " ", "8", " ", "7", " ", "5", " ", "3", " ", "1", " ", "9", " ", "8", " ", "6", " ", "4", " ", "2", " ", "0", " ", "9", " ", "7", " ", "5", " ", "3", " ", "1", " ", "0", " ", " ", " ", "6", " ", " "), dim = c(5, 9))`

Hopefully this input method is in compliance with the rules.

Here are the test cases

```
x1 =
"  5 6 7
 8 9 0 1
2 3 4 5 6
 7 8 9 0
  1 2 3"

x2 =
" # _
+ + +
 9 :"

x3 =
"    t h i s
   i       s
  a         h
 e           x
  a         g
   o       n
    ! ! ! !"

x4 ="    5 6 7
   8 9 0 1
  2 3 4 5 6
   7 8 9 0
    1 2 3"

x5 = "r e c t a
n g l e s"

x6 = "  h e l l o
  w o r l d s
t h i s i s b
 e t a d e c
  a y n o w"

x7 ="  *
 * *
* * *"

x8 ="   .....
  .......
.........
  .......
   ....."

```

Generate input arrays

```
sapply(mget(paste("x", 1:8, sep = "")), generate)

```

Test for hexagon

```
sapply(.Last.value , f)

   x1    x2    x3    x4    x5    x6    x7    x8
 TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE

```

# Answer
> 1 votes
## JavaScript (ES6), 214 bytes

```
(s,a=s.split`\n`,n=a[l=a.length>>1].match(r=/(?=\S).*\S/),i=n.index)=>!/\S(  )*\S/.test(s)&&!a.some((s,j)=>(m=r.exec(s))&&(k=m.index)<i+(j<l?j=l-j:j-=l)|k+(m=m[0].length)+j>i+n[0].length|k+i+j&1|j%l<1&m+j+j!=l*4+1)

```

Where `\n` represents a literal newline character. Ungolfed:

```
function validhex(s) {
    if (/S(  )*/S/.test(s)) return false;
    var a = s.split("\n");
    var l = Math.floor(a.length / 2);
    var n = a[l].match(/(?=\S).*\S/);
    for (var j = -l; j <= l; j++) {
        var m = a[j+l].match(/(?=\S).*\S/);
        if (!m) continue;
        if (m.index < n.index + Math.abs(j)) return false;
        if (m.index + m[0].length + Math.abs(j) > n.index + n[0].length) return false;
        if ((m.index + n.index + j) % 2) return false;
        if (j % l) continue;
        if (m[0].length != l * 4 + 1 - 2 * Math.abs(j)) return false;
    }
    return true;
}

```

# Answer
> 1 votes
## SnakeEx, 200 bytes

The right language for the job... sort of.

```
m:{v<>}{r<RF>2P}{r<R>2P}{h<RF>1P}{w<>}{l<RF>2P}{l<R>2P}{h<.>1}
w:{u<>P}{v<>}
v:{e<L>}{u<R>1}
u:.*{e<>}
e:.$
r:[^ ]+
h:([^ ] )+
l:({c<.>}[^ ])+{c<.>}
c:{b<B>}(. )+{x<>LP}{s<>}
b:.{s<>}
s:[^\!-\~]*$
x:.

```

SnakeEx is a language from the 2-D Pattern Matching challenge. It ought to be really good at this task, but unfortunately all the corner cases really bloated the code. I also turned up a couple of interpreter bugs. Still, it was a fun challenge.

`m` is the main snake that calls all the others to do the actual work. It matches starting at the top right corner of the hexagon and going clockwise. Numbered groups are used to verify that the diagonal side lengths are all equal and that the horizontal side length matches the height of the whole figure. I could write a more detailed explanation, but I've spent the last two days dealing with corner cases, so just try it out for yourself here. :^)

# Answer
> 1 votes
# Perl, ~~127~~ ~~125~~ ~~124~~ 121 bytes

Includes +4 for `-0p`

Give input on STDIN

```
#!/usr/bin/perl -0p
/ *(.*\S)/;$a=join'\S *
\1',map$"x(abs).'\S '.(/$n/?'\S ':'. ')x(2*$n-1-abs),-($n=$1=~y/ //)..$n;$_=/^$`( *)$a\S\s*$/

```

---
Tags: code-golf, ascii-art, hexagonal-grid
---


title: Periodic Arrays

text:
# Question
Title: Periodic Arrays
# Challenge

The challenge is to write a function that prints the number of **repeats** a given array of integers has.

### What are repeats?

Repeats of a slice (as in a section of an array) `[ a1, a2, a3, ..., an]` are any other non-overlapping slices of the forms `[ a1+an, a2+an, a3+an, ..., an+an]`, `[ a1+2an, a2+2an, a3+2an, ..., an+2an]`, and so on. Incomplete repeats, e.g. `[ a1+3an, a2+3an]`, are not counted.

### Input and output

Inputs should be ordered collections of integers, e.g. arrays, lists, tuples, etc. The integers will be sorted and unique.

Output a single integer that is the number of repeats that covers the whole input. The output should correspond to the greatest possible number of repeats. E.g. certain inputs could be modeled to have 3 repeats of a 4-element slice, or 6 repeats of a 2-element slice; 6 should be the output because it is greater than 3.

# Examples

```
Input -> Output

[ 1,  3,  5,
  6,  8, 10,
 11, 13, 15,
 16, 18, 20]
-> 4

[ 3,  5, 7, 10,
 13, 15]
-> 1

[1,
 2,
 3]
-> 3

[1,2,4]
-> 1

[ 3, 5, 7, 9,
 12,14,16,18]
-> 2

```

This is a challenge, so the shortest code possible wins

If you have any questions related to the challenge feel free to ask.
I know that my attempts to explain something can be difficult to understand sometimes.

# Answer
> 3 votes
# 05AB1E, ~~21~~ 20 bytes

```
0)«¥©v®NôÙgi®Nôg}})Z

```

**Explanation**

```
0)«                   # prepend a 0 to the beginning of the list
   ¥©                 # calculate deltas and store in register
     v           }    # for each N in range(0, len(deltas))
      ®Nô             # split deltas into N chunks
         Ù            # uniquify list
          gi    }     # if length == 1
            ®Nôg      # push chunk length
                  )Z  # return max chunk length

```

Try it online!

Modified test suite

# Answer
> 4 votes
# Perl, ~~48~~ 47 bytes

Includes +3 for `-p`

Give input as a list of numbers on STDIN

```
repeats.pl <<< "3 5 7 9 12 14 16 18"

```

`repeats.pl`:

```
#!/usr/bin/perl -p
s//0 /;s/\d+/$'-$&/eg;/(.+?)\1*-/;$_=s/$1//g

```

Does not work if the input is a single 0 (not clear if that is a valid input). Fixing that takes 2 more bytes:

```
#!/usr/bin/perl -p
$_=s//0 /%s/\d+/$'-$&/eg-/^(.+?)\1*-/||s/$1//g

```

## Explanation

Adds a 0 in front of the sequence and then constructs a list of differences. The example input

```
3 5 7 9 12 14 16 18

```

becomes:

```
3 2 2 2 3 2 2 2 -18

```

The -18 is because the last difference is calculated relative to the end of the string which in perl will behave like 0. On this transformed list the problem is equivalent to finding the most often repeating substring before the `-` sign (this is why a single `0` as input does not work because only in that case there is no minus sign)

# Answer
> 3 votes
## Retina, 38 bytes

```
\d+
$*
(?<=(1*) )\1

(.+?)(| \1)+$
$#2

```

Input should be space-separated.

Try it online! (The first line enables a linefeed-separated test suite.)

### Explanation

```
\d+
$*

```

Convert input to unary by replacing each number `n` with `n` copies of `1`.

```
(?<=(1*) )\1

```

Compute consecutive differences, by removing from each number the previous number.

```
(.+?)(| \1)+$
$#2

```

Try to match the entire input as a repetition of difference (favouring more repetitions of fewer differences) and replace it with the number of repetitions.

---
Tags: code-golf, math
---


title: Make me a mooncake!

text:
# Question
Title: Make me a mooncake!
The mid-autumn festival has begun!

Unfortunately, all my mooncakes were stolen -- they're getting too expensive for small folk such as myself, and I fear I won't be able to eat any this year!

So I turn to you for help. Would you be able to make me some?

For those unaware, let me educate you on what a mooncake looks like.

---

Mooncakes come in many different sizes!
So I'm gonna give you my **input**, *n*, when I want one.

Here are some examples of the **output** I want:

Mooncake of size n = 3:

```
    (@@@@@)
    (@MAF@)
    (@@@@@)

```

Mooncake of size n = 6:

```
    (@@@@@@@@@@@)
    (@         @)
    (@    M    @)
    (@    F    @)
    (@         @)
    (@@@@@@@@@@@)

```

That is to say, a mooncake of size *n* is:

* *n* lines high
* *2n - 1* @s long
* *2n + 1* characters long (@s and brackets)

And you better not throw me your too-tiny practice mooncakes!
**Assume input will always be n \>= 3**.

Mooncakes also **contain one of the following decorations**:

* MF
* MAF
* HMF
* JCJ
* TTT
* ZJ
* LF
* RF
* CF

Which one, it doesn't matter - as long as it is **vertically and horizontally centered**.
It can be written vertically or horizontally too!

I want variety!
If you're really going to make me two of the same mooncake, the decoration better be different!

That is, **multiple executions of your program with the exact same input must not always yield the same decoration**.

I can't wait to eat your moon cakes, so the sooner I can receive them (**the shorter your code**) the better!

Good Luck!

---

For those wondering about the decorations:
They are the initials of all alternative names for the Mid-Autumn Festival.
A list can be found in the Wikipedia page linked at the top of this post.

---

**Clarifications:**

*There are no rules regarding leading and trailing whitespace*.
Have as much or as little as you like!

*The decorations must be in the very center of your mooncake!*
On horizontal decorations, this means it must be on the middle line of your cake, and the number of characters to the left and right of the decoration string must be equal.
On vertical decorations, this means it must reside in the middle column of your cake, and the number of characters above and below the decoration must be equal.

***Not all decorations must be used!***
The only requirement is that there must be more than one possibility for any given input *n*. The possibilities also do not need to be even.

*Functions are acceptable.*

# Answer
# Pyth, ~~71~~ ~~65~~ ~~59~~ 58 bytes

*Saved 1 byte thanks to @StevenH.*

```
jjRc"(@@)"2++J*KtytQ\@m.[Kd;.[ttQ@,,O"MC"\F]Oc"MAFHMF"3QkJ

```

Try it online. Test suite.

So much padding.
> 9 votes

# Answer
## JavaScript ES6, ~~206~~ ~~196~~ ~~192~~ ~~188~~ ~~187~~ ~~180~~ ~~176~~ ~~169~~ ~~165~~ 156 bytes

```
g=(n,r=new Date%2,a=(s,x,b=' @'[+!s].repeat(n-3+!x))=>`(@${b+(s||'@')+b}@)
`,l=a` `.repeat(n/2-2+n%2))=>a()+l+(n%2?a(r?'MAF':'HMF',1):a('RC'[r])+a`F`)+l+a()

```

### Breakdown

```
r=new Date%2                           // Sometimes 0, sometimes 1

// Function to create lines of the cake of the form `(@@@@@@@@@)` or `(@  ${s}  @)`
a=(s,x,b=' @'[+!s].repeat(n-3+!x))=>`(@${b+(s||'@')+b}@)
`

// Cake parts
a()                                    // Top of the cake.
l=a` `.repeat(n/2-2+n%2)               // Undecorated inner part.
a(r?'MAF':'HMF',1)                     // Decoration for uneven sized cakes.
a('RC'[r])+a`F`                        // Decoration for even sized cakes.
l                                      // Undecorated inner part.
a()                                    // Bottom part.

```

My first attempt at code-golf. This can probably be golfed more.

*saved 4 bytes thanks to @ETHProductions*

**Edit** I took the liberty of using ~~`Date.now()%2`~~ `new Date%2` to satisfy:

> multiple executions of your program with the exact same input must not always yield the same decoration

this allows me to save another 7 bytes over `+Math.random()>.5`

*saved another 4 bytes thanks to @Arnauld*
> 7 votes

# Answer
# Pyth, ~~99~~ ~~79~~ ~~71~~ ~~68~~ 64 bytes

Pyth is ~~very bad~~ all right at making strings. Or maybe I'm just ~~bad~~ getting better at golfing them.

```
jmj.[-yQ3@,k@,@,O"MC"\FgydQOc"MAFHMF"3Q>2ahydQ@" @"sIcdtQc2"(@@)

```

Can create the decorations `MAF` and `HMF` horizontally, and the decorations `MF` and `CF` vertically.

Try it online!
> 6 votes

# Answer
# Vim, 118 bytes

Takes input as a buffer (e.g. a file with the number *n* as its contents).

```
"aDi()<Esc>@ai@<Esc>.xY@apddll<C-v>G$k3hr @=@a/2-1
j@=@a-2-@a%2
l:let r=abs(reltime()[1])%2
@=@a%2?r?"RJCJ":"3rT":"rFkr"."ML"[r]
<Esc>

```

Here it is with the unprintable control characters in xxd format:

```
0000000: 2261 4469 2829 1b40 6169 401b 2e78 5940  "aDi().@ai@..xY@
0000010: 6170 6464 6c6c 1647 246b 3368 7220 403d  apddll.G$k3hr @=
0000020: 4061 2f32 2d31 0a6a 403d 4061 2d32 2d40  @a/2-1.j@=@a-2-@
0000030: 6125 320a 6c3a 6c65 7420 723d 6162 7328  a%2.l:let r=abs(
0000040: 7265 6c74 696d 6528 295b 315d 2925 320a  reltime()[1])%2.
0000050: 403d 4061 2532 3f72 3f22 524a 434a 223a  @=@a%2?r?"RJCJ":
0000060: 2233 7254 223a 2272 466b 7222 2e22 4d4c  "3rT":"rFkr"."ML
0000070: 225b 725d 0a1b                           "[r]..

```

Try it online! (As it turns out, the V interpreter works fine for normal Vim code, too.)

# Explanation

```
"aD                   " Delete the number and store it in @a
i()<Esc>              " Insert empty parentheses
@ai@<Esc>.x           " Insert @a '@' characters between the parentheses twice; delete 1
Y@apdd                " Copy the line and paste it @a times; delete 1
ll<C-v>G$k3hr<Space>  " Replace the inner area with spaces
@=@a/2-1<CR>j         " Go down @a/2-1 lines
@=@a-2-@a%2<CR>l      " Go right @a-2-@a%2 columns
:let r=reltime()[1]%2<CR>  " Get a random 1 or 0 based on the time (this may be OS-dependent)
@=@a%2?
   r?"RJCJ":"3rT"     " For odd @a, replace the next 3 characters with "JCJ" or "TTT"
  :"rFkr"."ML"[r]     " For even @a, replace this character with "F" and the above with "M" or "L"
<CR><Esc>

```
> 6 votes

# Answer
# PHP, ~~342~~ ~~292~~ ~~249~~ ~~185~~ ~~178~~ 176 bytes

```
for(;$i<$n=$argv[1];)$o.=str_pad("(@",2*$n-1," @"[$i++%($n-1)<1])."@)
";$p=F.[M,AM,R,MH][rand()&2|$d=$n&1];$f=$n*($n+$d)-2;for($i=2+$d;$i--;$f+=$d?:2*$n+2)$o[$f]=$p[$i];echo$o;

```

Call with `php -r '<code>' <size>`

**history**

Rev 1: initial version; all sizes (including tiny cakes), all decorations, all possible directions

Rev. 2: removed tiny cakes (-36 bytes), restructured decoration options, removed one decoration item (-21) and a single byte golf (-1).

Rev. 3: Down to four decorations; (-17), only horizontal for odd sizes (-18) plus minor golfing (-8).

Rev. 4: Thanks to Jörg for golfing down the "paint cake" part; he took off an amazing (-31).
Another -6 with my additional golfing, and -27 for using a single string instead of an array of strings.

Rev. 5: -7 bytes mostly thanks to Christallkeks

**breakdown**

This is getting slimmer by the hour. :)

```
// paint cake
for(;$i<$n=$argv[1];)$o.=str_pad("(@",2*$n-1," @"[$i++%($n-1)<1])."@)\n";

// add deco
$p=F.[M,AM,R,MH][rand()&2|$d=$n&1];
$f=$n*($n+$d)-2;
for($i=2+$d;$i--;$f+=$d?:2*$n+2)$o[$f]=$p[$i];

// output
echo$o;

```
> 5 votes

# Answer
# Java 7, ~~399~~ 349 bytes

Updated version with help from @Dodge and @Kevin Cruijssen:

```
void m(int n){int i=2,r=n%2,x=2*n,u=r+2,y=r*4+(int)(Math.random()*2)*u,z=y+u;String t="MFZJMAFHMF".substring(y,z);char[][]c=new char[n][x+1];while(i<x-1)c[0][i]=c[n-1][i++]=64;for(i=0;i<u;)c[(n-1)/2+(1-r)*i][r*(i-1)+n]=t.charAt(i++);for(i=0;i<n;){c[i][0]=40;c[i][1]=c[i][x-1]=64;c[i][x]=41;System.out.println(new String(c[i++]).replace('\0',' '));}}

```
~~```
void m(int n){String[]s={"MF","MAF","ZJ","HMF","LF","JCJ","RF","TTT","CF","MAF"};char[]d=s[((int)(Math.random()*5))*2+(n%2)].toCharArray(),c[]=new char[n][2*n+1];int i=2;while(i<2*n-1)c[0][i]=c[n-1][i++]='@';i=0;while(i<d.length)c[(n-1)/2+(1-(n%2))*i][(n%2)*(-1+i)+n]=d[i++];i=0;while(i<n){c[i][0]='(';c[i][1]=c[i][2*n-1]='@';c[i][2*n]=')';System.out.println(new String(c[i++]).replace('\0',' '));}}

```~~

Try it here!

The new version is much more optimized and got rid of the `String` array handling. Also as suggested, there are only 4 decorations now: 2 for even inputs (`MF`,`ZJ`) and 2 for odd inputs (`MAF`,`HMF`) which are combined into a single `String`.

**Ungolfed:**

```
void m(int n){
    int i=2,
    r=n%2,
    x=2*n,
    u=r+2, // length of the decoration string
    y=r*4+(int)(Math.random()*2)*u, // random starting index of string (0, 2, 4, 7)
    z=y+u; // exclusive end index of string (2, 4, 7, 10)
    String t="MFZJMAFHMF".substring(y,z);
    char[][]c=new char[n][x+1];
    while(i < x-1) {
        c[0][i]=c[n-1][i++]=64; // '@'
    }
    for(i=0; i<u;) {
        c[(n-1)/2+(1-r)*i][r*(i-1)+n]=t.charAt(i++); // Depending on even/odd, fills the center column/row respectively with the decoration
    }
    for(i=0; i<n;) {
        c[i][0]=40; // '('
        c[i][1]=c[i][x-1]=64; // '@'
        c[i][x]=41; // ')'
        System.out.println(new String(c[i++]).replace('\0',' ')); // Print all
    }
}

```
> 4 votes

# Answer
# C, 233 Bytes

Should be able to golf this down a bit from here...

```
A="HMFMAFCF";i,j,k,t;f(n){t=time();char*S=n&1?t&1?A:A+3:t&1?A+1:A+6;for(;i<n;i++,puts(")"))for(j=0,k=2*n-1,putchar(40);j<k;putchar(0==i*j|i==n-1|j==k-1?64:n&1&i==n/2&j>n-3&j<n+1?*S++:n&1?32:(i==n/2-1|i==n/2)&j>n-2&j<n?*S++:32),j++);}

```

Great challenge, this was difficult and ugly to code.

Run with this main func;

```
main(c,v)char**v;
{
    f(atoi(v[1]));
}

```
> 3 votes

# Answer
## Batch, 386 bytes

```
@echo off
set/pn=
set f=HMAC
set/ao=n%%2,u=n/2,l=h=u+1,d=%random%%%2*2+1
if %o%==1 set/al=u=0,d/=2
set c=
for /l %%i in (4,1,%n%) do call set c= %%c%%
call:l %n%
for /l %%i in (2,1,%n%) do call:l %%i
exit/b
:l
set s=
if %1==%h% call set s=%%f:~%d%,2%%F
if %1==%u% call set s= %%f:~%d%,1%%
if %1==%l% set s= F
set s=(@%c%%s%%c%@)
if %1==%n% set s=%s: =@%
echo %s%

```

Will only output HMF, MAF, MF or CF as appropriate. Note: certain lines end in white space. Variables:

* `n` Input parameter (read from STDIN)
* `f` Decoration prefixes (suffix `F` is implied)
* `o` Oddness of `n` (only used once, but `if` statements don't accept expressions)
* `l` Row of the upper vertical character, or `0` for a horizontal decoration
* `u` Row of the lower vertical character, or `0` for a horizontal decoration
* `h` Row of the horizontal decoration (gets overwritten by a vertical decoration)
* `d` Index of decoration in decoration prefix (0/1 for horizontal or 1/3 for vertical)
* `c` String of `n-3` spaces
* `s` Output string for each row
* `%1` Row number, but set to `n` for the first row too, so that both first and last rows use `@`s instead of spaces.
> 3 votes

# Answer
# Ruby 2.3.1, ~~449~~ ~~265~~ ~~245~~ ~~233~~ 230 characters

Seems like there should be a ruby answer, so here is a ruby answer. It's really not that clever, Hopefully someone else here will be more clever ;)

Golfed version:

```
def m(n)
d,s=n.odd?? [[%w{MAF HMF}.sample],n/2]:[%w{RF LF}.sample.chars,(n-2)/2]
r=->f{l=f.size;q=($i-l)/2;($c=' '*$i)[q...l+q]=f;puts "(@#$c@)"}
$i=2*n-1;a='@'*$i
r[a]
(1..n-2).map{|x|(s...s+d.size)===x ?r[d[x-s]]:r['']}
r[a]
end

```

Golfing tricks:

* replace method declaration with a stabby string interpolation of
* $globals doesn't need #{global}, only #$global
* === for ranges is shorter than .covers?

Readable version

```
def row(inner_width, fillchar='')
  padding = ( inner_width - fillchar.size) / 2
  (center =(' ' * inner_width))[padding...fillchar.size+padding]=fillchar
  puts "(@"+center+"@)"
end

def mooncake(n)
  decoration = n.odd?? [%w{ MAF HMF JCJ TTT }.sample] : %w{ ZJ LF RF CF }.sample.chars
  start_row = n.odd?? (n/2) : (n - 2) / 2
  inner_width = 2 * n - 1
  row(inner_width,'@'*inner_width)
  (1...(n-1)).each do |row|
    if (start_row ... start_row + decoration.size).include? row
      row(inner_width,decoration[row - start_row])
    else
      row(inner_width)
    end
  end
  row(inner_width,'@'*inner_width)
end

```

Testing

```
mooncake(3)
mooncake(4)
mooncake(5)
mooncake(6)

```
> 2 votes

# Answer
I was bored ... here are two more versions:

# PHP, 193 bytes

```
function p($s){global$n;return"(@".str_pad($s,2*$n-3,$s?" ":"@",2)."@)
";}$p=[M,MA,R,HM][rand()&2|1&$n=$argv[1]];echo p(""),$e=str_repeat(p(" "),($n+$n%2)/2-2),$n&1?p($p.F):p($p).p(F),$e,p("");

```

a port of Lmis´ answer

# PHP, 191 bytes

```
for($p=[M,MA,R,HM][rand()&2|1&$n=$argv[1]].F;$i<$n*$w=2*$n+1;$i++)echo($x=$i%$w)?$w-1-$x?($y=$i/$w|0)%($n-1)&&1-$x&&$w-2-$x?$p[$n&1?$n>>1!=$y?9:$x-$n+1:($n-$x?9:$y-$n/2+1)]?:" ":"@":")
":"(";

```

printing the cake character by character in a single loop

**breakdown**

```
for(
    $p=[M,MA,R,HM][rand()&2|1&$n=$argv[1]].F;   // pick decoration
    $i<$n*$w=2*$n+1;$i++)       // loop $i from 0 to $n*width-1:
echo                                // print ...
    $w-1-($x=$i%$w)                 // 1. not last column
        ?$x                         // 2. not first column
            ?
                ($y=$i/$w|0)%($n-1) // 3. not first or last line
                && 1-$x%($w-3)      // and not second or (width-2)th column
                ?$p[$n&1
                    ?$n>>1!=$y?3:1+$x-$n
                    :($n-$x?3:1+$y-$n/2)
                ]   ?               // 4. decoration character
                    :" "            // 4. else: blank
                :"@"                // 3. else: "@"
            :"("                    // 2. else: "("
        :")\n"                      // 1. else: ")"+newline
    ;

```
> 1 votes

# Answer
# Python 3, ~~318~~ ~~301~~ ~~297~~ ~~285~~ 272 bytes

**Knocked off 17 bytes with the help of DJMcMayhem**

**Knocked off 4 bytes thanks to mbomb007**

**Knocked off another 12 bytes thanks to DJMcMayhem**

**Knocked off another 13 bytes thanks to mbomb007**

My first golf ever, so it's not all that great. I used: aliasing math.ceil as y and str.format as z, nesting formats, single line imports, lambda, and bitwise operation plus some other things to get this like it is.

```
def f(n):import random,math;y=math.ceil;z=str.format;i=y(2*n-5>>1);j=y(n-3>>1);return z("{a}{}{a}",z("{d}(@{}{b}F{c}@)\n{e}"," "*i,b=random.sample(["L","R"],1)[0],c=" "*(2*n-5-i),d=z("(@{}@)\n"," "*(2*n-3))*j,e=z("(@{}@)\n"," "*(2*n-3))*(n-3-j)),a=z("({})\n","@"*(2*n-1)))

```

Ungolfed version (separated imports, no aliases, and no bitwise operation):

```
def f(n):
    import random;
    import math;
    return "{a}{}{a}".format(
        "{d}(@{}{b}F{c}@)\n{e}".format(
            " "*(math.ceil((2*n-5)/2)),
            b=random.sample(["L","R"],1)[0],
            c=" "*((2*n)-(5+math.ceil((2*n-5)/2))),
            d="(@{}@)\n".format(" "*(2*n-3))*math.ceil((n-3)/2),
            e="(@{}@)\n".format(" "*(2*n-3))*(n-(3+(math.ceil((n-3)/2))))),
        a="({})\n".format("@"*(2*n-1)))

```

Interestingly, using the non-bitwise version of this still produces correct output, however, the output is different:

Non-Bitwise:

```
(@@@@@@@)
(@     @)
(@  LF @)
(@@@@@@@)

```

Bitwise:

```
(@@@@@@@)
(@ LF  @)
(@     @)
(@@@@@@@)

```
> 0 votes

# Answer
# C# 448 bytes

Golfed:

```
var v=n%2==0;int l=n+n-3,h=n-2,e=v?0:1,c=e+2;var c2=v?"MFZJLFRFCF":"MAFHMFJCJTTT";var r=new Random().Next(3+e);var f=new String(c2.Skip(c*r).Take(c).ToArray());var mc="";for (var i=0;i < h;i++) {var x="";if (!v && i==((h / 2))) { x=f;} else if (v && ((i==h / 2) || (i==(h/2)-1))) { x +=f[i%2==1?0:1];} var es=x.PadLeft((l/2)+1+e,' ').PadRight(l,' ');mc +="(@"+es+"@)\n";}var b="("+"".PadLeft(l+2, '@')+")";mc=b+"\n"+mc+ b; Console.WriteLine(mc);

```

Test it here

Ungolfed:

```
        var v = n % 2 == 0;
        int l = n + n - 3, h = n - 2, e = v ? 0 : 1, c = e + 2;
        var c2 = v ? "MFZJLFRFCF" : "MAFHMFJCJTTT";
        var r = new Random().Next(3 + e);
        var f = new String(c2.Skip(c * r).Take(c).ToArray());
        var mc = "";
        for (var i = 0; i < h; i++)
        {
            var x = "";
            if (!v && i == ((h / 2)))
            {
                x = f;
            }
            else if (v && ((i == h / 2) || (i == (h / 2) - 1)))
            {
                x += f[i % 2 == 1 ? 0 : 1];
            }
            var emptySpace = x.PadLeft((l / 2) + 1 + e, ' ').PadRight(l, ' ');
            mc += "(@" + emptySpace + "@)\n";
        }
        var b = "(" + "".PadLeft(l + 2, '@') + ")";
        mc = b + "\n" + mc + b;
        Console.WriteLine(mc);

```
> 0 votes

---
Tags: code-golf, ascii-art
---


title: Obfuscated FizzBuzz Golf

text:
# Question
Title: Obfuscated FizzBuzz Golf
Create the shortest possible obfuscated FizzBuzz implementation.

To be considered obfuscated, it should satisfy at least one of the following:

1. Does not contain any of the words "Fizz", "Buzz", or "FizzBuzz"
2. Does not contain the numbers 3, 5, or 15.
3. Use any of the above in a misleading way.

Remember: The goal is to be short *and* hard to follow.

The code sample which inspired this question follows:

```
public class Default
{
        enum FizzBuzz
        {
            Buzz = 1,
            Fizz,
            FizzBuzz
        }
        public static void Main(string[] args)
        {
            byte[] foo =
              Convert.FromBase64String("IAmGMEiCIQySYAiDJBjCIAmGMEiCIQySYA==");
            MemoryStream ms = new MemoryStream(foo);
            byte[] myByte = new byte[1];
            do
            {
                FizzBuzz fb;
                ms.Read(myByte, 0, 1);
                for (int i = 0; i < 4; i++)
                {
                    fb = (FizzBuzz)(myByte[0] >> (2 * i)
                         & (int)FizzBuzz.FizzBuzz);
                    Console.Out.WriteLine( (((int)fb > 0) ? "" + fb : ""
                         + ((ms.Position - 1) * 4 + i + 1)));
                }
            } while (ms.Position < ms.Length);
        }
}

```

# Answer
> 25 votes
## GolfScript, ~~75~~ ~~69~~ ~~65~~ ~~60~~ 59 chars

```
100,{)6,{.(&},{1$1$%{;}{4*35+6875*25base{90\-}%}if}%\or}%n*

```

So, you'd think GolfScript by itself is already obfuscated, right? Well, just to follow the spec, I decided to have the program not contain "fizz", "buzz", nor the numbers 3, 5, nor 15. :-)

Yes, there are some numbers with multiples of 5, like 25, 35, 90, 100, and 6875. Are they red herrings? You decide. ;-)

# Answer
> 65 votes
## Javascript 97 chars - no numbers at all

Numbers ? Who needs number when you have Javascript !

```
a=b=!![]+![],a--,c=b+b;while(++a)e=!(a%(c+c+b)),alert(!(a%(c+b))?e?"FizzBuzz":"Fizz":e?"Buzz":a);

```

Note: There is an infinite loop that will alert you the sequence.

**Bonus** (666 chars)

* No number
* No letter (only `zfor` has been use in the whole script)

.

```
_=$=+!![];$__=((_$={})+'')[_+$+_+$+_];__$=((![])+'')[$];_$_=((_$={})+'')
[_+$+_+$+_+$];____=[][$__+((_$={})+'')[$]+(($)/(![])+'')[$]+$__+__$+_$_];$__$=(!![]+"")
[$+$+$]+([][(![]+"")[$+$+$]+(+[]+{})[$+$]+(!![]+"")[$]+(!![]+"")[+[]]]+"")[($+$)+""+
($+$+$)]+(![]+"")[$]+(![]+"")[$+$];$_$_=____()[$-$][$__$]("\"\\"+($)+($+$+$+$+$+$+$)+
($+$)+"\"");_$=(![]+'')[$-$]+([][[]]+[])[$+$+$+$+$]+$_$_+$_$_;$_=(_+{})[$+$+$]+(!![]+'')
[_+$]+$_$_+$_$_;_--,$$=$+$;____()[$-$][$__$]((![]+"")[+[]]+(+[]+{})[$+$]+(!![]+"")[$]+
"(;++_;)$$$=!(_%("+($$+$$+$)+")),____()[+[]][__$+((![])+'')["+($+$)+"]+((!![])+'')["+
($+$+$)+"]+((!![])+'')[+!![]]+_$_](!(_%("+($$+$)+"))?$$$?_$+$_:_$:$$$?$_:_);");

```

# Answer
> 25 votes
## Python - 78 chars

```
i=0
while 1:i+=1;print"".join("BzuzzizF"[::2*j]for j in(-1,1)if 1>i%(4+j))or i

```

# Answer
> 23 votes
# PostScript, 96 bytes

So obfuscated it looks like random garbage.

```
1<~0o0@eOuP7\C+tf6HS7j&H?t`<0f>,/0TnSG01KZ%H9ub#H@9L>I=%,:23M].P!+.F6?RU#I;*;AP#XYnP"5~>cvx exec

```

Usage: `$ gs -q -dNODISPLAY -dNOPROMPT file.ps`

# Answer
> 22 votes
## C++: 886 chars

I've tried to hide the 'fizz' and the 'buzz'. Can you spot them?

```
#include <iostream>
#define d(a,b) a b
#define _(a,b) d(#b,#a)
#define b(b) _(b,b)
#define y _(i,f)c
#define x _(u,b)c
#define c b(z)
#define i int
#define p main
#define s char
#define q 810092048
#define h for
#define m 48
#define a ++
#define e ==
#define g 58
#define n 49
#define l <<
#define oe std::cout<<
#define v '\n'

int  p   (i,  s*t     ){i   j  =   q;h   (*(
i    *     )    t     =  m  ;  2     [     t
]?   0    :    1      ??(   t  ]    ?     a
1    [   t    ]       e  g  ?  1   [     t
]    =   48,  ++0     ??(    t]e   g?0   ??(

t]=  n   ,1[  t]=
2    [     t    ]
=m   :    1    :
1    :   a    0
[    t   ??)  ==g

?0[   t  ]   =49   ,1[
t  ]  =  m     :     1
;j=   (  j    /     4
)  |  (  (   j     &
3)l    28)   )oe   (j&

3?j  &   1?j  &2?
y    x     :    y
:x   :    t    )
l    v   ;    }
i    f   =m&  ~g;

```

# Answer
> 16 votes
## DC (256 255 bytes)

Here it is, I tried (rather successfully, if I may say so myself) to hide anything except for letters, and `+-[];:=` (which are vital and impossible to obfuscate). It does segfault after getting to about 8482 or so on my machine, but that is to do with stack issues related to the way the recursion is implemented. The solution *itself* is correct. 255 bytes if you remove the whitespace (included for ease of reading) Enjoy:

```
Izzzdsa+dsbrsc+dsdd+sozdsezzsm+s
nloddd++splbz++ddaso+dln-dstsqlm
d+-sr[PPPP]ss[IP]su[lpdlqlrlsxlu
x]lm:f[lpdltdI+lm+rlblm+-lsxlux]
ln:f[[]sulm;fxln;f[IP]sux]la:f[;
fsk]sg[lmlgx]sh[lnlgx]si[lalgx]s
j[lc[lcp]sklerldlolclerlblolcler
lalox=hx=ix=jlkxclcz+scllx]dslx

```

# Answer
> 11 votes
## Brainfuck - 626 656

```
+[[>+>+<<-]>>>+++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]<[<+>>+<-]>>[-]+++>[
<<<+>>>-]>[-]<<<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]<<<<[>+<-]>>>[<
<<+>>>-]<<[>>+<<-]<[>+>+<<-]>[<+>-]+>[<->[-]]<[>>>[-]>[-]<>+++++++[<++
++++++++>-]<.>+++++[<+++++++>-]<.+++++++++++++++++..[-]+<<<-]<[-]>>>[<
+<+>>-]<[>+<-]+<[>-<[-]]>[>>>[-]>[-]<>++++++[<+++++++++++>-]<.>+++++[<
++++++++++>-]<+.+++++..[-]<+<<-]>[-]>[<+<+>>-]<[>+<-]+<[>-<[-]]>[<<<<[
>+>>>>+<<<<<-]>[<+>-]>>>>>>--[<->+++++]<--<[->-[>+>>]>[+[-<+>]>+>>]<<<
<<]>[-]<-[>-<+++++]>--->>[<<[<+>>>+<<-]<[>+<-]>>>.[-]]++++++++++<[->-[
>+>>]>[+[-<+>]>+>>]<<<<<]>[-]<<[>+>>>+<<<<-]>>>>.[-]<<<[>>+<<-]>>.[-]<
<<<<-]<<<++++++++++.[-]<+]

```

Goes from 1 to 255

# Answer
> 11 votes
This was a bit tricky to embed using the indentation so a gist:

# Ruby, 4312 chars

https://gist.github.com/dzucconi/1f88a6dffa2f145f370f

```
eval("

                                                                                ".split(/\n/).map(&:size).pack("C*"))

```

# Answer
> 10 votes
Brainfuck, 708 characters

```
++++++++++[>++++++++++<-]>>++++++++++>->>>>>>>>>>>>>>>>-->+++++++[->++
++++++++<]>[->+>+>+>+<<<<]+++>>+++>>>++++++++[-<++++<++++<++++>>>]++++
+[-<++++<++++>>]>>-->++++++[->+++++++++++<]>[->+>+>+>+<<<<]+++++>>+>++
++++>++++++>++++++++[-<++++<++++<++++>>>]++++++[-<+++<+++<+++>>>]>>-->
---+[-<+]-<[+[->+]-<<->>>+>[-]++[-->++]-->+++[---++[--<++]---->>-<+>[+
+++[----<++++]--[>]++[-->++]--<]>++[--+[-<+]->>[-]+++++[---->++++]-->[
->+<]>>[.>]++[-->++]]-->+++]---+[-<+]->>-[+>>>+[-<+]->>>++++++++++<<[-
>+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>
+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->+++
+++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]+[-<+]->>]+[-]<<<.>>>+[
-<+]-<<]

```

Description of how it works is available in my Code Review question

# Answer
> 9 votes
## Haskell - 147 142 138 characters

```
fi=zz.bu
bu=zz.(:).(++"zz")
[]#zz=zz;zz#__=zz
zZ%zz=zZ zz$zZ%zz
zz=(([[],[]]++).)
z=zipWith3(((#).).(++))(bu%"Fi")(fi%"Bu")$map show[1..]

```

The code is 19 characters longer than it needs to be, but I thought the aesthetics were worth it! I believe all three "objectives" are satisfied.

```
> take 20 z
["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14",
"FizzBuzz","16","17","Fizz","19","Buzz"]

```

# Answer
> 8 votes
# , 33 chars / 92 bytes (noncompetitive)

```
ѨŃ(1,ṥ)ć⇀ᵖɘƃ႖סР깜 #ē($%3⅋4,$%5?4:8)⋎$⸩

```

`Try it here (Firefox only).`

This language is way too OP for restricted source challenges.

# Answer
> 5 votes
# Javascript, 469 bytes

This was probably the most fun I've ever had.

```
z=0;_=(function(){b=0;window[0xA95ED.toString(36)]((function(){yay="&F bottles of beer on the wall, &F bottles of beer. Take one down, pass it around, &z Bottles of beer on the wall.";return atob("eisrOyAg") + "console.log(((function(y){if((y%0xf)==0){return [1,72,84,84,86,78,84,84]}else if(y%0b11==0){return [1,72,84,84]}else if(y%0b101==0){return [86,78,84,84]}else{b=1;return [y]}})(z).map(function(x){return b==0?yay[x]:x}) ).join(''))"})())});setInterval(_,1000);

```

Try it here

# Answer
> 4 votes
## Ruby - 165 characters

```
(1..100).each{|i|i%0xF==0? puts(["46697A7A42757A7A"].pack("H*")):i%(0xD-0xA)==0? puts(["46697A7A"].pack("H*")):i%(0xF-0xA)==0? puts(["42757A7A"].pack("H*")):puts(i)}

```

This was my first attempt at code golf. I had a lot of fun. =)

# Answer
> 4 votes
# Perl 6 (52 bytes)

```
say "Fizz"x$_%%(2+1)~"Buzz"x$_%%(4+1)||$_ for 1..100

```

Let me put an explanation here. It's the worst rule abuse I've done in such task. I know what you are saying - there is obvious `Fizz` and `Buzz` here. But let's take a look at the rules.

> To be considered obfuscated, it should satisfy *at least one* of the following:

This avoids `3`, `5` and `15`. Therefore, it's valid and really short solution.

# Answer
> 3 votes
# C (~~237~~ 209 characters)

```
#include<stdlib.h>
#define e printf
a=50358598,b=83916098,c=1862302330;_(m,n){return(m%((c&n)>>24))
||!(e(&n)|e(&c));}main(_);(*__[])(_)={main,exit};main(i){_(i,a)
&_(i,b)&&e("%i",i);e("\n");__[i>=100](++i);}

```

Though I'm not sure this conforms to the C standard :)
It works, though. On Linux using GCC, that is.

# Answer
> 3 votes
## Scala, 295 characters

```
object F extends Application{var(f,i,z)=("",('z'/'z'),"FBiuzzzz");while(i<(-'b'+'u'+'z'/'z')*('¥'/'!')){if(i%(-'f'+'i'/('z'/'z'))==0)f+=z.sliding(1,2).mkString;if(i%((-'b'+'u'+'z'/'z')/('f'/'f'+'i'/'i'+'z'/'z'+'z'/'z'))==0)f+=z.drop(1).sliding(1,2).mkString;if(f=="")f+=i;println(f);i+=1;f="";}}

```

# Answer
> 3 votes
# Python 3 - 338

```
import sys
def fibu():
        (F,I,B,U),i,u,z=sys._getframe(0).f_code.co_name,0xf,0xb,lambda x,y:x%((i//u)+(i^u))==u>>i if y>u else x%(((u<<(u>>2))&i)>>(u>>2))==i>>u
        A,RP = "",chr(ord(U)+((i//u)+(i^u)))*2
        for x in range(100):print(x if not (z(x,u)or z(x,i))else A.join((F+I+RP if z(x,u)else A,B+U+RP if z(x,i)else A)))
fibu()

```

This is my first golf. Not the shortest, but it's pretty ugly! None of the forbidden numbers or string literals. Firp, Burp!

# Answer
> 3 votes
# Python - 157

```
from itertools import cycle as r
c=str.replace
[c(c(c(z+y,'x','fix'),'y','bux'),'x','zz').strip() or x for z,y,x in zip(r('  y'),r('    x'),range(1,101))]

```

Not quite the shortest, but I hope the reader will appreciate the pure functional style and extensibility to arbitrarily long counts.

# Answer
> 3 votes
# K, 155

```
{m:{x-y*x div y};s:{"c"$(10-!#x)+"i"$x};$[&/0=m[x]'(2+"I"$"c"$49;4+"I"$"c"$49);s"<`rs<pvw";0=m[x;2+"I"$"c"$49];s"<`rs";0=m[x;4+"I"$"c"$49];s"8lrs";x]}'!100

```

I could golf it quite a bit but I'd rather it be more obfuscated.

# Answer
> 2 votes
# JavaScript 111 chars - no key numbers

`a=b=c=0;while(a++<99)document.write((b>1?(b=0,"Fizz"):(b++,""))+(c==4?(c=0,"Buzz"):(c++,""))+(b*c?a:"")+"<br>")`

# Answer
> 2 votes
## C# - 218 characters

```
using System;class D{static void Main(){int l,i,O=1;l++;string c="zz",a="fi",b="bu";l++;l++;i=l;i++;i++;for(;O<101;O++)Console.WriteLine(((O%l)>0&&1>(O%i))?a+c:(1>(O%l)&&(O%i)>0)?b+c:(1>(O%l)&&1>(O%i))?a+c+b+c:O+"");}}

```

**Could be shortened if I introduced other numbers like so: (210 characters total)**

```
using System;class D{static void Main(){int l=1,i,O=1;string c="zz",a="fi",b="bu";l+=2;i=l;i+=2;for(;O<101;O++)Console.WriteLine(((O%l)>0&&1>(O%i))?a+c:(1>(O%l)&&(O%i)>0)?b+c:(1>(O%l)&&1>(O%i))?a+c+b+c:O+"");}}

```

Decided to remove the obvious word fizz and buzz and go for slightly more obfuscation. Second one is shorter than the first one but is slightly more direct on what's occurring in the addition.

# Answer
> 2 votes
This isn't exactly golfed, its about 120 lines.

I thought I'd do something that took advantage of all the fun potential for undefined behavior with C++ memory management.

```
#include <iostream>
#include <string>

using namespace std;

class Weh;
class HelloWorld;

class Weh
{
public:

    string value1;
    string value2;
    void (*method)(void * obj);

    Weh();

    string getV1();

    static void doNothing(void * obj);
};

class HelloWorld
{
public:
    static const int FOO = 1;
    static const int BAR = 2;
    static const int BAZ = 4;
    static const int WUG = 8;

    string hello;
    string world;
    void (*doHello)(HelloWorld * obj);

    HelloWorld();

    void * operator new(size_t size);

    void tower(int i);
    const char * doTower(int i, int j, int k);

    static void doHe1lo(HelloWorld * obj);
};

Weh::Weh()
{
    method = &doNothing;
}

void Weh::doNothing(void * obj)
{
    string s = ((Weh *) obj)->getV1();
    ((HelloWorld *) obj)->tower(1);
}

string Weh::getV1()
{
    value1[0] += 'h' - 'j' - 32;
    value1[1] += 'k' - 'g';
    value1[2] += 'u' - 'g';
    value1[3] = value1[2];
    value2 = value1 = value1.substr(0, 4);

    value2[0] += 'd' - 'h';
    value2[1] += 'w' - 'k';
    value2[2] = value1[2];
    value2[3] = value1[3];

    return "hello";
}

void * HelloWorld::operator new(size_t size)
{
    return (void *) new Weh;
}

HelloWorld::HelloWorld()
{
    hello = "hello";
    world = "world";
}

void HelloWorld::doHe1lo(HelloWorld * obj)
{
    cout << obj->hello << " " << obj->world << "!" << endl;
}

void HelloWorld::tower(int i)
{
    doTower(0, 0, i);
    tower(i + (FOO | BAR | BAZ | WUG));
}

const char * HelloWorld::doTower(int i, int j, int k)
{
    static const char * NOTHING = "";
    int hello = BAR;
    int world = BAZ;
    int helloworld = FOO | BAR | BAZ | WUG;

    if ((hello & i) && (world & j))
        cout << this->hello << this->world << endl;
    else if (hello & i)
    {
        cout << this->hello << endl;
        cout << doTower(0, j + 1, k + 1);
    }
    else if (world & j)
    {
        cout << this->world << endl;
        cout << doTower(i + 1, 0, k + 1);
    }
    else
    {
        cout << k << endl;
        cout << doTower(i + 1, j + 1, k + 1);
    }

    return NOTHING;
}

int main()
{
    HelloWorld * h = new HelloWorld;
    h->doHello(h);
}

```

# Answer
> 2 votes
# Ruby - 89 chars

```
puts (0..99).map{|i|srand(1781773465)if(i%15==0);[i+1,"Fizz","Buzz","FizzBuzz"][rand(4)]}

```

I can't take credit for this piece of brilliance, but I couldn't leave this question without my favorite obfuscated implementation :)

The implementation above was written by David Brady and is from the fizzbuzz ruby gem. Here is the explanation from the source code:

> Uses the fact that seed 1781773465 in Ruby's rand will generate the 15-digit sequence that repeats in the FizzBuzz progression. The premise here is that we want to cleverly trick rand into delivering a predictable sequence. (It is interesting to note that we don't actually gain a reduction in information size. The 15-digit sequence can be encoded as bit pairs and stored in a 30-bit number. Since 1781773465 requires 31 bits of storage, our cleverness has actually cost us a bit of storage efficiency. BUT THAT'S NOT THE POINT!

# Ruby - 87 chars

```
puts (0..99).map{|i|srand(46308667)if(i%15==0);["FizzBuzz","Buzz",i+1,"Fizz"][rand(4)]}

```

Here's a different version which uses a shorter seed but the lookup table is in a different order. Here is the explanation from the source code:

> The first implementation (89 chars) adheres to the specific ordering of 0=int, 1=Fizz, 2=Buzz, 3=FizzBuzz. It may be possible to find a smaller key if the ordering is changed. There are 24 possible permutations. If we assume that the permutations are evenly distributed throughout 2\**31 space, and about a 50% probability that this one is "about halfway through", then we can assume with a decent confidence (say 20-50%) that there is a key somewhere around 1.4e+9 (below 2*\*28). It's not much gain but it DOES demonstrate leveraging rand's predefined sequence to "hide" 30 bits of information in less that 30 bits of space.
>
> Result: The permutation \[3,2,0,1\] appears at seed 46308667, which can be stored in 26 bits.

# Answer
> 2 votes
# Python, 1 line, 376 characters

pep8-E501 ignored. Only works in python3.

```
print(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\n' if x % (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (10 >> 1) == 0 else str(x) + '\n')() for x in range(1, 101)))

```

# Answer
> 2 votes
**Alternative Ruby (126 characters)**

```
(1..100).map{|i|(x="\xF\3\5\1Rml6ekJ1eno=".unpack('C4m'))[-1]=~/(.*)(B.*)/
[*$~,i].zip(x).map{|o,d|i%d>0||(break $><<o<<?\n)}}

```

Short and obscure, just how we like it. The 3 and the 5 are actually in there but not as integer literals so I think that still counts.

Note that the this is the shortest Ruby version without literal 'Fizz', 'Buzz', 'FizzBuzz' on here.

# Answer
> 2 votes
## Python 2 - 54 chars

```
i=0
while 1:i+=1;print'FizzBuzz'[i%~2&4:12&8+i%~4]or i

```

## Python 3 - 56 chars

```
i=0
while 1:i+=1;print('FizzBuzz'[i%~2&4:12&8+i%~4]or i)

```

If you do not want 'FizzBuzz' to appear :

## Python 2 - 58 chars

```
i=0
while 1:i+=1;print' zzuBzziF'[12&8+i%~2:i%~4&4:-1]or i

```

## Python 3 - 60 chars

```
i=0
while 1:i+=1;print(' zzuBzziF'[12&8+i%~2:i%~4&4:-1]or i)

```

Or how to beat GolfScript with Python ;)

# Answer
> 1 votes
**Squeak (4.4) Smalltalk 206 bytes**

```
|f i zz b u z|z:=''.b:=28r1J8D0LK. 1to:100do:[:o|0<(f:=(i:=(zz:=b\\4)//2*4)+(u:=zz\\2*4))or:[z:=z,o].b:=zz<<28+(b//4).z:=z,((z first:f)replaceFrom:1to:f with:28r1A041FHQIC7EJI>>(4-i*u*2)startingAt:1),'
'].z

```

Or same algorithm with less explicit messages, same number of characters

```
|l f i zz b u z|z:=#[].b:=36rDEB30W. 1to:100do:[:o|0<(f:=(i:=(zz:=b\\4)//2)+(u:=zz\\2)*4)or:[z:=z,('',o)].b:=zz<<28+(b//4).l:=36r2JUQE92ONA>>(1-u*i*24).1to:f do:[:k|z:=z,{l-((l:=l>>6)-1<<6)}].z:=z,'
'].'',z

```

My apologizes to Alan Kay for what I did to Smalltalk.
Some of these hacks are portable across Smalltalk dialects, some would require a Squeak compatibility layer...

Note that if you execute in a Workspace, you can omit declarations |f i zz b u z| and gain 14 characters.

If we can afford 357 characters (315 with single letter vars), then it's better to avoid trivial #to:do: loop:

```
|fizz buzz if f fi zz b u bu z|f:=fizz:=buzz:=0.z:=#[].b:=814090528.if:=[:i|i=0or:[fi:=28.zz:=27<<7+i.u:=26.(fizz:=[zz=0or:[z:=z,{(u:=u//2)\\2+1+(zz+((fi:=fi//2)\\2+2-(zz:=zz//8)*8)*4)}.fizz value]])value]].(buzz:=[(f:=f+1)>100or:[(fi:=(zz:=b\\4)//2*17)+(bu:=zz\\2*40)>0or:[z:=z,('',f)].b:=zz<<28+(b//4).if value:fi;value:bu.z:=z,'
'.buzz value]])value.'',z

```

# Answer
> 1 votes
## Haskell 226 bytes, including the whitespace for layout ;)

```
z=[fI$ (++)            \
(fi zz 1 "Fi" )        \
(fi zz 2 "Bu" )        \
:[show zz]  | zz<-[1..]]
fI (zZ:zz)  | zZ==[]   \
= concat zz | 1==1=zZ
fi zZ bu zz | zZ%bu=   \
(zz++"zz")  | 1==1=[]
bu%zz=mod bu (zz*2+1)==0

```

The 'real' code is 160 bytes and can be compressed, but loses fizz-buzz-ness then.

Run it (for nice output):

```
putStrLn (unwords (take 20 z ))

```

Output:

```
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz

```

# Answer
> 0 votes
# Perl

```
use MIME::Base64;print map{map{(++$i,'Fizz','Buzz','FizzBuzz')[$_]."\n"}(3&ord,3&ord>>2,3&ord>>4,3&ord>>6)}split//,decode_base64"EAZJMIRBEgxhkARDGCTBEAZJMIRBEgxhkA"

```

One I made in 2009. It's pretty easy to figure out, though.

Edit: Darn, it uses "Fizz" and "Buzz!" :( I thought I changed that. Nevermind then.

# Answer
> 0 votes
# C 216 bytes

```
#define t(b) putchar(p+=b);
main(p,v,c){p=70;for(v=c=1;v<=p*2-40&&!(c=0);++v){if(!(v%(p/23))){t(0)t(35)t(17)t(0)++c;}if(!(v%(p/(14+c*9)))){t(-56+!c*52)t(51)t(5)t(0);++c;}if(c){t(-112)p+=60;}else printf("%i\n",v);}}

```

# Answer
> 0 votes
**PHP - 157 154 95 chars**

```
<?$x="zz";for(;++$i<=100;){?> <?$j=$i%(4-1)^0?"":"Fi$x";$j.=$i%(4+1)^0?"":"Bu$x";echo$j?$j:$i;}

```

And no whitespace! Only one space!

# Answer
> 0 votes
## Python, 180 chars

```
from random import*;seed(0);_,y=''.join(sample('zzzzuiFB',8)),5**2<<2
print chr(int(`y`[::2])).join(filter(bool,map(lambda z:(not z%(y>>5))*_[:1<<2:]+(1>z%5)*_[1<<2::],range(1,y))))

```

# Answer
> 0 votes
## C Solution

```
    #include  <stdio.h>
    #define a b b b b b
    #define b c c c c c
    #define c d d d d d
   #define  h(k,s)k?s:""
  #define x !(n%('0'>>4))
  #define y !(n%('P'>>4))
  #define d if(100>=++n)\
printf("%s%s%s",h(x,"Fizz"\
),h(y,"Buzz"),h(x|y,"\n"));
int main(){static int n; a}

```

# Answer
> 0 votes
## K

```
-1',/'$(+`fizz`buzz,,1+!100)@'&:'+(a,,~|/[a:100#'(001b;00001b)])

```

# Answer
> 0 votes
Here's a fun one in C. It can be shorter, but then it won't be as much fun!

```
#define i(bu,zz,fi) printf("?"[1]|""[0]?"fi":"%"#zz"\n",bu)
#define x(a,i,p) {-0xf##i&(3+5-1),{z(z,a,p,),""}}
#define z(b,f,z,l) #z#f""#b""#l#b
main(b){struct{char z;char*u[2];}u[]={x(i,d,f),x(u,b,b),{0}};for(b=1;b<'e';b++)
{int z=0;char f[3+5+1]={0};for(b;u[z].z;z++)strcat(f,u[z].u[!!(b%u[z].z)]);*f&&
i(f,s,3)||i(b,d,5);}}

```

# Answer
> 0 votes
# JavaScript, 80 characters

```
for(i=0;i<100;a=++i%3,b=i%5,alert(i+"FizzBuzz".slice(t=a&&!b*4,t?8:!a*4+!b*4)));

```

# Answer
> 0 votes
# C, 283 bytes

```
#include "stdio.h"
#include "string.h"
#define z 122
int main(){char f[]={70,105,z,z,0},b[]={66,117,z,z,0},i=1,B[z],g;for(i=1;i<=100;i++){g=0;if(i%3<1)strcpy(B,f),g=1;if(i%5<1){if(g>0)strcat(B,b);else if(g<1)strcpy(B,b),g=1;}if(g<1)printf("%d\n",i);else printf("%s\n",B);}return 0;}

```

Obscure? Maybe. Golfed? A little more so than it is obscure. Ugly? **YES**.

# Answer
> 0 votes
# C 213 Bytes

```
int c=1,m,n,O,z='z';void main(){O=0;m=c%5-c%3;if(c>2){O=!m&&n?printf("Fiz%cBuz%c",z,z):O;O=m<0&&n+1?printf("Buz%c",z):O;O=m!=n&&m+1&&!O?printf("Fiz%c",z):O;}n=m;O?0:printf("%i",c);putchar(10);c++;if(c<101)main();}

```

Everything is based on `counter % 5 - counter % 3`.

# Answer
> 0 votes
# C++ (478 Bytes)

It beats the previous C++ code easily.

```
#include<iostream>
#include<string>
using namespace std;int main() {string K = "FBiuzzzz";for (int i = 1; i <= 100; i++) {if (i % ((35 / 10)*(35 % 10))==0) {for (int j = 0; j < 8; j += 2)cout << K.at(j);for (int j = 1; j < 8; j += 2)cout << K.at(j);cout << endl;}else if (i % (35 / 10) == 0) {for (int j = 0; j < 8; j += 2)cout << K.at(j);cout << endl;}else if (i % (35 % 10) == 0) {for (int j = 1; j < 8; j += 2)cout << K.at(j);cout << endl;} else cout << i << endl;}return 0;}

```

# Answer
> 0 votes
# gs2, 1 byte

```
f

```

prints fizzbuzz, gs2 has a very simple function

# Answer
> 0 votes
# JavaScript - 166 chars

Here's another JavaScript solution which uses an encoded `for` loop body to hide 3, 5, Fizz, and Buzz. It's relatively terse, but you can still kind of see what's going on.

```
for(i=0;++i<101;)console.log(eval(String.fromCharCode(...'286925333f27273a2746697a7a27292b286925353f27273a2742757a7a27297c7c69'.match(/../g).map(n=>parseInt(n,16)))))
```

For something a bit more interesting, we can encode *all* the programming logic in zero-width whitespace characters and have something that *looks* concise but is actually not at all. This is similar to dzuc's Ruby solution.

```
eval(''.split('').map(=>String.fromCharCode(.length)).join(''))
```

Personally, I like playing with fire.

```
Function('ಠ_ಠ',''.split('').map(ಠ_ಠ=>String.fromCharCode(ಠ_ಠ.length)).join(''))(100)
```

---
Tags: code-golf, obfuscation, restricted-source
---


title: Draw some ASCII-boxes

text:
# Question
Title: Draw some ASCII-boxes
Take two lists of non-negative integers, and output an ASCII-box as it's defined below.

* Corners and intersections are pluses: `+` (ASCII-code 43)
* Vertical lines are bars `|` (ASCII-code 124)
* Horizontal lines are minuses `-` (ASCII-code 45)

The first input list specifies the number of minuses between each plus sign, in the horizontal direction.

The second input list specifies the number of bars between each plus sign, in the vertical direction.

It's easier to explain with a few examples:

```
0    // No minuses between each + sign
0    // No bars between + signs

++
++

------------------
1 2   // First a single minus, then two minuses
1 2   // First  one bar, then two bars

+-+--+
| |  |
+-+--+
| |  |
| |  |
+-+--+

------------------
1 0 3 0 2 0
2 1 0 0

+-++---++--++
| ||   ||  ||
| ||   ||  ||
+-++---++--++
| ||   ||  ||
+-++---++--++
+-++---++--++
+-++---++--++

```

Clarifications:

* Input order and format are optional
* Only the boxes should be printed/displayed, but a trailing space or newlines are accepted.
* You may optionally add 1 to all input values if that's more convenient. The second example would then be: `2 3; 2 3`.

This is code golf, so the shortest code in bytes win.

# Answer
# MATL, ~~25~~ ~~22~~ 21 bytes

```
'|-+ '2:"1tiYsQ(]E!+)

```

Uses inputs with `1` added (allowed by the challenge).

Try it online!

### Explanation

The code initially builds an array containing `1` for the column indices of non-space characters in the final result, and `0` otherwise. So if the first input is `[2 1 4 1 3 1]` (would be `[1 0 3 0 2 0]` in the 0-based format) this array will be

```
1 0 1 1 0 0 0 1 1 0 0 1 1

```

Note how the length of runs of zeros is related to the input. Specifically, this array is built as follows:

1. Initiallize the array to a single `1`.
2. Compute the cumulative sum of the input and add `1`. In the example this gives `[3 4 8 9 12 13]`.
3. Extend the array from step 1 by assigning `1` to the entries with (1-based) indices given by step 2. Intermediate entries are automatically set to `0`.

A similar array is built for the rows. Second input `[3 2 1 1]` (or `[2 1 0 0 ]`) gives

```
1 0 0 1 0 1 1 1

```

Now the second array is multiplied by `2`, transposed and added with broadcast to the first. This gives the 2D array

```
3 2 3 3 2 2 2 3 3 2 2 3 3
1 0 1 1 0 0 0 1 1 0 0 1 1
1 0 1 1 0 0 0 1 1 0 0 1 1
3 2 3 3 2 2 2 3 3 2 2 3 3
1 0 1 1 0 0 0 1 1 0 0 1 1
3 2 3 3 2 2 2 3 3 2 2 3 3
3 2 3 3 2 2 2 3 3 2 2 3 3
3 2 3 3 2 2 2 3 3 2 2 3 3

```

Indexing into the string `'|-+ '` gives the final result as a 2D char array. Since indexing is modular and 1-based, index `0` corresponds to the last element (space).

```
'|-+ '                   % Push this string
      2:"       ]        % Do this twice
         1               % Push 1 (initial array)
          t              % Push another 1 (contents to be filled in)
           i             % Take input
            Ys           % Cumulative sum
              Q          % Add 1
               (         % Fill 1 into those entries of the array
                 E       % Multiply by 2
                  !      % Transpose
                   +     % Add, with broadcast
                    )    % Index (modular, 1-based) into the string

```
> 5 votes

# Answer
# Python 2, 117 Bytes

```
def f(h,v):r="+"+"+".join("-"*i for i in h)+"+\n";print r+r.join(("|"+"|".join(" "*i for i in h)+"|\n")*i for i in v)+r

```

Try it on ideone.

Not expecting too much from this. Really simple, just uses python joins and string multiplication to pull everything together.
> 6 votes

# Answer
## JavaScript (ES6), 83 bytes

```
(a,b,g=(a,[s,t])=>t+a.map(n=>s.repeat(n)+t).join``+`
`)=>g(b,[g(a,` |`),g(a,`-+`)])

```

Output includes two trailing newlines.
> 6 votes

# Answer
# CJam, 50 Bytes

```
0lS/:i0++:H;lS/:i0+{H{'-*}%'+*N+o{H{S*}%'|*N+o}*}%

```

Try it online!
> 2 votes

# Answer
# Pyth, 45 bytes

```
AQj.i*hlH]Js.i*hlG\+m*d\-G-mjb*d]XJ"+-""| "Hk

```

A program that takes input of two comma-separated lists on STDIN and prints the result.

There is probably still some golfing to be done here.

Try it online

*Explanation coming later*
> 1 votes

# Answer
# Haskell, 55 bytes

```
f[a,b]x=a:do n<-x;(b<$[1..n])++[a]
g x=f[f"+-"x,f"| "x]

```

Defines a function `g` which takes the two input lists and returns a list containing the lines of the output
> 1 votes

# Answer
## PowerShell v2+, 89 bytes

```
param($a,$b)($x="+$(($a|%{'-'*$_})-join'+')+")
$b|%{,"|$(($a|%{' '*$_})-join'|')|"*$_;$x}

```

Dang, don't think I can quite catch JavaScript.

Takes input `$a` and `$b` as explicit arrays. Sets variable `$x` to be the top row of the boxes based on looping through `$a` and some string concatenation. That's encapsulated in parens so it's placed on the pipeline. Then, we loop through `$b`, each iteration putting two strings on the pipeline -- the same style string but with spaces and `|` instead of hyphens and `+`, and `$x`. Those strings are all gathered from the pipeline with an implicit `Write-Output` at program completion, with default newline between them.

### Examples

```
PS C:\Tools\Scripts\golfing> .\make-some-ascii-boxes.ps1 @(0) @(0)
++
++

PS C:\Tools\Scripts\golfing> .\make-some-ascii-boxes.ps1 @(1,0,3,0,2,0) @(2,1,0,0)
+-++---++--++
| ||   ||  ||
| ||   ||  ||
+-++---++--++
| ||   ||  ||
+-++---++--++
+-++---++--++
+-++---++--++

PS C:\Tools\Scripts\golfing> .\make-some-ascii-boxes.ps1 @(1,4,1) @(1,2,1)
+-+----+-+
| |    | |
+-+----+-+
| |    | |
| |    | |
+-+----+-+
| |    | |
+-+----+-+

```
> 0 votes

# Answer
# Ruby, 66 bytes

```
->x,y{d=->c,m,z=x{c+z.map{|w|m*w}*c+c+$/}
d[d[?+,?-],d[?|,' '],y]}

```
> 0 votes

# Answer
# Jelly, ~~30~~ 26 bytes

```
Ḣị“+-“| ”ị@
1;+\Ṭ
Ç€,€/Ñ€Y

```

Test it at **TryItOnline**

How?

The input taken is a list of the two lists, `[vertical, horizontal]`, and uses the incremented option
\- so example 3 takes `[[3,2,1,1], [2,1,4,1,3,1]]`
Each of these is then converted to a boolean array indicating the rowType or rowCharacterType respectively, e.g. `[[1,0,0,1,0,1,1,1], [1,0,1,1,0,0,0,1,1,0,0,1,1]]`
The boxes are then constructed by making the rows from the characters identified by the rowType and rowCharacterType combinations - i.e. a rowType identifies either `"+-"` or `"| "` and a rowCharacterType identifies one of those two characters.

```
Ḣị“+-“| ”ị@ - Link 1, create a row: [rowType, [rowCharaterTypes]]
Ḣ           - head - get the rowType
  “+-“| ”   - list of strings ["+-", "| "]
 ị          - index into (if rowType is 1 "+-"; if rowType is 0 "| ")
         ị@ - index into with reversed operands (index into that from rowCharaterTypes)
                (replace each 1 in rowCharaters with "+" or "|" and each 0 with "-" or " ")

1;+\Ṭ - Link 2, create the Type lists from the inputs: int[] nCharacters
1;    - 1 concatenated with the input
  +\  - reduce with addition (accumulation provides the indices)
    Ṭ - boolean array with 1s at those indices
            As an example take the vertical of example 3:
            [3,2,1,1] -> [1,3,2,1,1] -> [1,4,6,7,8] -> [1,0,0,1,0,1,1,1]
            each of which will be passed as a rowType for Link 1

Ç€,€/Ñ€Y - Main link, takes one argument: [Vertical, Horizontal] (incremented option)
Ç€       - call the last link (2) for each of the two lists in the input
  ,€/    - pair each and reduce (making a list of [rowtype [rowCharacterTypes]])
     Ñ€  - call the next link (1) for each
       Y - join on line feeds

```
> 0 votes

---
Tags: code-golf, ascii-art
---