text:
Draw a big ASCII X
Problem
Inspired by a previous challenge doing something similar
Given positive integer input n output a shape that follows this pattern:
input n=1:
* *
 *
* *

input n=2:
**  **
 ****
  **
 ****
**  **

input n=3:
***   ***
 *** ***
  *****
   ***
  *****
 *** ***
***   ***

and so on...
It has these properties:
n*2+1 lines tall
the "arms" are n wide except when they merge
the center line is n wide
if n is even the lines above and below the center are n*2 wide
if n is odd the lines above and below the center are n*2-1 wide
Rules

Trailing newlines accepted
Standard loopholes apply
Shortest bytes win
Output may be print out or a string or array of strings

Edits

n=0 doesn't need to be handled
Trailing spaces allowed

Is it okay if the output has 1 instead of * and 0 instead of space?

Can our patterns be 0-indexed?

@JungHwanMin I will allow it but then you aren't allowed to win, might be swayed if you are most upvoted.

@LeakyNun 0 Indexed is fine

Charcoal, 13 12 bytes
Thanks to @ErikTheOutgolfer for a byte
ＦＮ«ＰX⁺*×*Ｉθ→

Try it online!
This is my first ever Charcoal answer, and I'm pretty sure it's not golfed as well as it could be, but I figured I'd start somewhere.
 ＦＮ«            # For input() (i in range(0,input()))
     Ｐ           # Print
       X          # In an 'X' shape
        ⁺*×*Ｉθ   # '*'+'*'*int(first_input)
               →  # Move the cursor right one

You can use Ｉ for -1.

@EriktheOutgolfer I knew there had to be a way to do that!  Thank you!

And yes it actually seems as golfed as it can be.

@EriktheOutgolfer It wasn't before you came along anyway :)

Correct me if I'm wrong, but you can't say that's 12 bytes, as some of those characters would require multiple bytes to represent them.

@thomasrutter Charcoal has it's own custom code-page with 256 bytes, where each of those characters is 1 byte. So it's not encoded in ASCII, where some of these characters would indeed be multiple bytes. nmjcman101 +1 btw. Was trying my first Charcoal answer as well yesterday, but it didn't really worked out in the few minutes I had before going home from work. So you've beat me to it. I did learn some things from your answer, so thanks for that.

MATL, 16 bytes
EQXyG:Y+tP+g42*c

Try it online!
Explanation
Consider input 2 as an example. Stack contents are shown with more recent ones below.
EQ    % Implicitly input n. Push 2*n+1
      %   STACK: 5
Xy    % Identity matrix of that size
      %   STACK: [1 0 0 0 0;
                  0 1 0 0 0;
                  0 0 1 0 0;
                  0 0 0 1 0;
                  0 0 0 0 1]
G:    % Push [1 2 ... n]
      %   STACK: [1 0 0 0 0;
                  0 1 0 0 0;
                  0 0 1 0 0;
                  0 0 0 1 0;
                  0 0 0 0 1],
                 [1 2]
Y+    % 2D convolution, extending size
      %   STACK: [1 2 0 0 0 0;
                  0 1 2 0 0 0;
                  0 0 1 2 0 0;
                  0 0 0 1 2 0;
                  0 0 0 0 1 2]
tP+   % Duplicate, flip vertically, add
      %   STACK: [1 2 0 0 2 1;
                  0 1 2 1 2 0;
                  0 0 1 4 0 0;
                  0 1 2 1 2 0;
                  1 2 0 0 1 2]
g     % Convert to logical
      %   STACK: [1 1 0 0 1 1;
                  0 1 1 1 1 0;
                  0 0 1 1 0 0;
                  0 1 1 1 1 0;
                  1 1 0 0 1 1]
42*   % Multiply by 42.
      %   STACK: [42 42  0  0 42 42;
                   0 42 42 42 42  0;
                   0  0 42 42  0  0;
                   0 42 42 42 42  0;
                  42 42  0  0 42 42]
c     % Convert to char. Char 42 is '*'. Char 0 is displayed as space
      %   STACK: ['**  **';
                  ' **** ';
                  '  **  ';
                  ' **** ';
                  '**  **']

You're faster than me...

@LeakyNun Very rarely :-)

I wish Jelly had 2D convolution... I had to append 0 in each row and then apply vectorized sum...

@LeakyNun You know what they say about convolution...

@LuisMendo In my heart you are the winner for using convolution, brings back such nice memories.

Jelly, 15 bytes
Ḥ‘Ḷ⁶ẋ;€”*ẋ$»Ṛ$Y

Try it online!

Very nice. 8 bytes short of me.

@LeakyNun The straightforward approach helps quite a bit.

A very nice approach

@JonathanAllan Yeah, especially tfw you learn » vectorizes...

I really like your username! But I wish you used "vi" or "vim" instead, so you could choose "Erik the vi King" ... (Monty Python fan here ...)

05AB1E, 18 bytes
Å4bS{I·ƒDÂ~„ *èJ,À

Try it online!
Explanation
Example for n=2
Å4                   # push a list of 4s with length as the input
                     # STACK: [4,4]
  b                  # convert each to binary
                     # STACK: [100, 100]
   S{                # split into digit list and sort
                     # STACK: [0, 0, 0, 0, 1, 1]
     I·ƒ             # input*2+1 times do
        D            # duplicate top of stack
                     # 1st iteration: [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1]
                     # 2nd iteration: [0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0]
                     # 3rd iteration: [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0]
         Â~          # or each item in the duplicate with its reverse
                     # 1st iteration: [0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1]
                     # 2nd iteration: [0, 0, 0, 1, 1, 0], [0, 1, 1, 1, 1, 0]
                     # 3rd iteration: [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0]
           „ *èJ     # use the resulting binary list to index into the string " *"
                     # 1st iteration: [0, 0, 0, 0, 1, 1], "**  **"
                     # 2nd iteration: [0, 0, 0, 1, 1, 0], " **** "
                     # 3rd iteration: [0, 0, 1, 1, 0, 0], "  **  "
                ,    # print
                 À   # rotate list left

V, 18 17 bytes
Saved a byte thanks to @DJMcMayhem's input trick.
Àé*ÄJÀälÀñ2ÙÀl2x>

Try it online!
Explanation
Àé*ÄJÀäl

This inserts [n]*'*'+[n]*' '+[n]*'*'
        Àñ        ' [arg] times
          2Ù      ' Duplicate the current line down twice
            Àl    ' Move right [arg] times
              2x  ' Delete two characters
                > ' Indent this line one space

Each iteration of the loop the buffer goes from
|**   ***

To
***   ***
 |** ***
***   ***

Where | is the cursor with a * under it

Wow. You waaay outgolfed me. Good job! A few tips: You could do Àé*ÄJÀäl instead of Àá*Àá Àá*, and you can do <M-c>, i.e. ã (mnemonic: center) to move to the middle of the line, which is a byte shorter than Àl. Try it online!

@DJMcMayhem I'm trying to talk to you in a bunch of different places.  I'm going to steal the first suggestion I think, but the <M-c> breaks for higher numbers

Haskell, 88 87 86 bytes
-1 thanks to @Laikoni

(!)=replicate
x n=[zipWith max(reverse m)m|m<-[i!' '++n!'*'++(n*2-i)!' '|i<-[0..n*2]]]

Try it online!

zipWith max m(reverse m) can be shortened to zipWith max(reverse m)m. This is the same as zipWith max=<<reverse$m, and then m can be inlined: Try it online!

V, 23 bytes
Àé*ÄJÀälÀñÙãlxx>ñyHæGVp

Try it online!
Hexdump:
00000000: c0e9 2ac4 4ac0 e46c c0f1 d9e3 6c78 783e  ..*.J..l....lxx>
00000010: f179 48e6 4756 70                        .yH.GVp

For whatever reason, this challenge is significantly harder in V than the last one. Since our general approach of n times, grow an 'x' won't work here, we'll instead construct the top of the X, copy it and flip it, then attaching the two parts together.
Explanation:
Àé*ÄJÀäl                " Insert ('*' * n) + (' ' * n) + ('*' * n)
                        " The obvious way would be 'Àé*ÀÁ ÀÁ*', but this
                        " non-obvious way saves us a byte
        Àñ      ñ       " 'n' times:
          Ù             "   Duplicate this line (below us)
           ãl           "   Move to the center of this line
             xx         "   Delete two characters
               >        "   And indent this line with one space.

Doing the indent at the end of the loop, allows us to take advantage of implicit endings. This also conveniently creates n+1 lines, which is exactly the top half of the 'X'. Let's say the input was 4. Then at this point, the buffer looks like this:
****    ****
 ****  ****
  ********
   ******
    ****

And we're on the last line. So then we:
                yH      " Copy the whole buffer and move to the first line
                  æG    " Reverse every line
                    Vp  " And paste what we just copied *over* the current
                        " line, deleting it in the process

I did the ãxx thing at first too, but I think it breaks for e.g. n = 8?

@nmjcman101 Ah, you're right. It's fine if you do ãl, or if you indent before centering though, but that doesn't actually save any bytes. I don't understand why it works for smaller numbers though.

C#, 139 130 115 bytes
-1 byte by creating a string and calling WriteLine, thus saving the check for the new line.
-6 bytes thanks to Kevin and his master golfing techniques!
-2 bytes by replacing n*3-n with n*2.
-15 bytes after Kevin kindly pointed me in the right direction: I can just return the string instead of printing it, thus saving the call to System.Console.WriteLine(). And some other tips also...
n=>{var s="";for(int i,j=0;j<=n*2;j++,s+='\n')for(i=0;i<n*3;)s+=i>=j&i<j+n|i<=n*3-j-1&i++>=n*2-j?'*':' ';return s;}

Try it online!
Ungolfed:
class Program
{
    static void Main(string[] args)
    {
        System.Func<int, string> g = n =>
        {
            var s = "";
            for (int i, j = 0; j <= n*2; j++, s += '\n')
                for (i = 0; i < n*3;)
                    s += i >= j & i < j+n | i <= n*3-j-1 & i++ >= n*2-j ? '*' : ' ';
            return s;
        };

        System.Console.Write(f(1));
        System.Console.Write(f(2));
        System.Console.Write(f(3));
        System.Console.Write(f(5));
        System.Console.Write(f(8));

        System.Console.ReadKey();
    }
}

It just iterates along the rows and columns of the space needed to print the big X and prints either a '*' or a ' ' depending on the condition.

+1! Some small things to golf. All the && can be & and || can be | in this case. for(int j=0; can be for(int j=0,i; and then you can remove the int  in front of the i in the inner loop. Also, after the first change of & and |, you can also remove the i++ inside the for-loop, and change i==n*3-1?... to i++==n*3-1?....

@KevinCruijssen thank you very much! I changed the inner loop and now I create a string so I can call WriteLine, saved just 1 byte. So now I'm not sure what to do with your last advice.

Well, with my advice for i++=n*3-1?... I simply put ++ at the last occurence of i. So you can still remove i++ in the for-loop, and change i>n*3-n-j-1? to i++>n*3-n-j-i. Hmm, btw, isn't n*3-n the same as n*2? :)

@KevinCruijssen yes, I have just realized that... ^__^U

Btw, why the System.Console.WriteLine? Returning the string: n=>{string s="";for(int i,j=0;j<n*2+1;j++,s+="\n")for(i=0;i<n*3;)s+=i>=j&i<j+n|i<=n*3-j-1&i++>n*2-j-1?'*':' ';return s;} is shorter [120 bytes] (and also gets rid of the brackets by putting everything inside the for-loop. Here is a TIO-link to show it works. Also, feel free to add this (or your own) TIO-link to your answer. :)

@KevinCruijssen I didn't know that TIO could handle C# code! I added the WriteLine in the code because the OP asked to output the big X, not just to return it, so I felt that the outputting of the X (by calling the WriteLine method) should be part of the code. Nonetheless, I'm still not used to the rules of code-golf, and I don't know what licenses I can take when writing code. I have just seen that some of the other answers here print the X in the code, and some others print it in the footer. What is the valid approach in this case?

Usually returning a string as well as using a function instead of a program is allowed by default, unless stated otherwise. Also, in the question it states "Output may be print out or a string or array of strings", so returning a string is allowed. :) Oh, and one last thing you can golf: j<n*2+1 can be j<=n*2. I've also created a Java 8 port of your answer with the same byte-count, crediting your amazing answer of course.

111 bytes Credit goes to @ceilingcat, since he suggested these golfs on my Java answer.

Jelly, 24 23 16 bytes
Ḥ‘Ḷ⁸+þṬ+Ṛ$a”*o⁶Y

Try it online!

Python 2, 93 90 89 83 bytes
-3 bytes thanks to Leaky Nun
-1 byte thanks to Zachary T
-6 bytes thanks to xnor

n=input()
x=n*'*'+n*'  '
exec"print`map(max,x,x[::-1])`[2::5];x=' '+x[:-1];"*(n-~n)

[Try it online!][TIO-j3xwsktf]
Starts with a string like '***      ' for n=3, applying map/max to pick the * over the spaces for each position, then append a space and remove the last character from the string and do this all again.

90 bytes

Can't you replace n*2*' ' with n*'  '?

The map(max can be done directly without a zip. Also, n*2+1 is n-~n.

MATLAB, 153 126 bytes (17.6%↓)
Thanks to @LuisMendo's comment, function disp() can output chars without single quotes, thus I could prevent using fprintf with formats and omit a few bytes. Besides, his comment reminds me that I need use char(32) to present a space rather than char(0) (null).
n=input('')
r=2*n+1
c=3*n
a=0
for i=0:n-1
a=a+[zeros(r,i),diag(1:r),zeros(r,c-r-i)];
end
a((a+flipud(a))>0)=10
disp([a+32 ''])

Try it online!
MATLAB, 153 bytes
n=input('')
r=2*n+1
c=3*n
a=0
for i=0:n-1
a=a+[zeros(r,i),diag(1:r),zeros(r,c-r-i)];
end
a((a+flipud(a))>0)=42
fprintf([repmat('%c',1,c),'\n'],char(a)')

Result example:
    n=10
**********          **********
 **********        **********
  **********      **********
   **********    **********
    **********  **********
     ********************
      ******************
       ****************
        **************
         ************
          **********
         ************
        **************
       ****************
      ******************
     ********************
    **********  **********
   **********    **********
  **********      **********
 **********        **********
**********          **********

Haskell, 70 bytes
f n=[[last$' ':['*'|y<-[1..n],(c-n-y)^2==r^2]|c<-[1..3*n]]|r<-[-n..n]]

Try it online!
Outputs a list of strings.
For each position of row r, column c, uses a formula to determine whether it falls in one of the two diagonal bands and so is *.

Javascript (ES2017), 155 157 bytes
n=>[...e=[...Array(n+1)].map((a,i)=>[...d=((b=''.padEnd(n))[c='slice'](i)+'*'.repeat(n)+b[c](0,i))[c](n/2)].reverse().join``+d[c](n%1)),...e.reverse()[c](1)]

Returns an array of strings. I perform operations on arrays then mirror it. This could probably be optimized with matrices like the other answers, but I wanted to be unique.
Edit: As pointed out by Neil, for even values of n, the center line was not n wide, so I added a modulus to detect even/odd when slicing the column.
n=5
['*****     *****',
 ' *****   ***** ',
 '  ***** *****  ',
 '   *********   ',
 '    *******    ',
 '     *****     ',
 '    *******    ',
 '   *********   ',
 '  ***** *****  ',
 ' *****   ***** ',
 '*****     *****']

Ungolfed
n => {
  e = [...Array(n+1)].map((a, i) => {   // Create and iterate over array with n+1 elements
    b = ''.padEnd(n)                    // String of n spaces
    d = (b.slice(i) + '*'.repeat(n) + b.slice(0, i)).slice(n/2) // Create row string
    return [...d].reverse().join`` + d.slice(1) // Mirror and combine row horizontally
  })
  return [...e,...e.reverse().slice(1)] // Mirror and combine vertically
}

Quadrant
n=5
   *****
  *****
 *****
*****
****
***

Mirrored Horizontally
n=5
*****     *****
 *****   *****
  ***** *****
   *********
    *******
     *****

Mirrored Vertically
n=5
*****     *****
 *****   *****
  ***** *****
   *********
    *******
     *****
    *******
   *********
  ***** *****
 *****   *****
*****     *****

This produces incorrect output for even n - the centre line is not n wide.

Java 10, 119 118 111 bytes
n->{var r="";for(int i=0,j;i<n-~n;i++,r+="\n")for(j=0;j<n*3;r+=j>=i&j<i+n|j<n*3-i&++j>n*2-i?"*":" ");return r;}

Port from @CarlosAlejo's amazing C# answer, after I helped him golf a few things. So make sure to upvote him as well!
-4 bytes thanks to @ceilingcat.
Try it here.

Mathematica, 148 bytes
T=Table;(a=Join[T[T["*",i],{i,(n=#)+2,2n,2}],T[Join[t=T["*",n],T[" ",y],t],{y,1,n,2}]];Column[Row/@Join[Reverse@a,{T["*",n]},a],Alignment->Center])&

R, 102 bytes
Code:
n=scan();x=matrix(" ",M<-3*n,N<-2*n+1);for(i in 1:N)x[c(i-1+1:n,M+2-i-1:n),i]="*";cat(x,sep="",fill=M)

Test:
> n=scan();x=matrix(" ",M<-3*n,N<-2*n+1);for(i in 1:N)x[c(i-1+1:n,M+2-i-1:n),i]="*";cat(x,sep="",fill=M)
1: 10
2:
Read 1 item
**********          **********
 **********        **********
  **********      **********
   **********    **********
    **********  **********
     ********************
      ******************
       ****************
        **************
         ************
          **********
         ************
        **************
       ****************
      ******************
     ********************
    **********  **********
   **********    **********
  **********      **********
 **********        **********
**********          **********

CJam, 24 bytes
{:T2*){S*T'**+}%_W%..e>}

This is a block that takes a number from the stack and outputs a list of lines to the stack.
Explanation:
{                        e# Stack:           | 2
 :T                      e# Store in T:      | 2, T=2
   2*                    e# Multiply by 2:   | 4
     )                   e# Increment:       | 5
      {                  e# Map over range:  | [0
       S                 e#   Push space:    | [0 " "
        *                e#   Repeat string: | [""
         T               e#   Push T:        | ["" 2
          '*             e#   Push char '*': | ["" 2 '*
            *            e#   Repeat char:   | ["" "**"
             +           e#   Concatenate:   | ["**"
              }%         e# End:             | ["**" " **" "  **" "   **" "    **"]
                _        e# Duplicate:       | ["**" " **" "  **" "   **" "    **"] ["**" " **" "  **" "   **" "    **"]
                 W%      e# Reverse:         | ["**" " **" "  **" "   **" "    **"] ["    **" "   **" "  **" " **" "**"]
                   ..e>  e# Overlay:         | ["**  **" " ****" "  **" " ****" "**  **"]
                       } e# End

Python 2, 110 bytes
x=a=0
n=c=input()
while x<2*n+1:
    print ' '*a+'*'*n+' '*c+'*'*(2*n-2*a-c)
    x+=1
    a=n-abs(n-x)
    c=max(0, n-2*a)

This program breaks each line into 4 parts, first spaces, first stars, second spaces and then second stars. For each horizontal line of the X it calculates how many stars or spaces are needed for each of the 4 sections of the line, then constructs and prints that string.

Retina, 144 bytes
.+
 $&$* $&$* $&

$`#$'¶
¶\d+$

( *)#( *)(\d+)
$1$3$**$2#$3$* #$2$3$**$1
( +)(\*+)( *)(# +#)\3\2\3 +
$3$2$1$4$1$2$3
+` (# +#)
$1
+` #...
#
##

Try it online! Explanation:
.+
 $&$* $&$* $&

Add 2n+1 spaces before the input value (one for each output line).
$`#$'¶

Replace each space with a # and collect the results. This gives a diagonal line of #s, space padded on both sides, with the input value suffixed.
¶\d+$

Delete the original input value, as we now have a copy on each line.
( *)#( *)(\d+)
$1$3$**$2#$3$* #$2$3$**$1

Build up two diagonal lines of n *s, with a separator column of n spaces wrapped in a pair of #s.
( +)(\*+)( *)(# +#)\3\2\3 +
$3$2$1$4$1$2$3

On those lines where the *s are nearer the middle, swap the two halves around. This gives an appearance resembling >  | |  <.
+` (# +#)
$1

Move the | |s as far left as they will go, giving a sort of >> >    < appearance.
+` #...
#

For each space between the #s, delete the three following characters. This joins the > < into an X.
##

Delete the now unnecessary #s.

05AB1E, 16 bytes
ENI>1})¦'*…×82SΛ

Try it online.
Explanation:
E      # Loop N in the range [1, (implicit) input]:
 N     #  Push loop-index N
  I>   #  Push the input, and increase it by 1
    1  #  Push 1
})     # After the loop: wrap all values on the stack into a list
  ¦    # And remove the very first 1
'*    '# Push "*"
…×82S  # Push "×82" as list: ["×",8,2]
Λ      # Use the Canvas builtin with these three arguments
       # (after which it is output implicitly)

Canvas explanation:
The Canvas builtin takes three arguments:
1. The lengths of the lines to 'draw', which in this case is the list we generate at the start with the loop. For an input \$n=3\$, the list will look like this: \$[4,1,2,4,1,3,4,1]\$ (or more in general: for sequence \$x_n\$ in \$[2,n]\$, the list will be \$[n+1,1,x_1,n+1,1,x_2,n+1,1,x_3,...]\$).
2. The string to 'draw', which in this case is "*".
3. The directions, which in this case is ["×",8,2]. These will be the directions [cross, reset-to-origin, →].
With these arguments, it will draw as follows (let's take the \$n=3\$ as example again):
Draw an X-shaped cross of character "*" with arms of length 4:
*     *
 *   *
  * *
   *
  * *
 *   *
*     *

Reset back to the origin (8), and draw 2-1 characters "*" in direction 2 (→):
(NOTE: The origin is the center of this first cross.)
*     *
 *   *
  * *
   **
  * *
 *   *
*     *

Draw an X-shaped cross of character "*" with arms of length 4 again:
**    **
 **  **
  ****
   **
  ****
 **  **
**    **

Reset back to the origin (8), and draw 3-1 characters "*" in direction 2 (→):
**    **
 **  **
  ****
   ***
  ****
 **  **
**    **

Draw an X-shaped cross of character "*" with arms of length 4 again:
***   ***
 *** ***
  *****
   ***
  *****
 *** ***
***   ***

See this 05AB1E tip of mine for a more in-depth explanation of the Canvas builtin.


text:
Group a List by Frequency
Given a list of integers, group the elements which occur most first, then group the next most and so on until each unique element in the list has been grouped once.

Examples:
Input: [1,2,3]
Output: [[1,2,3]]

Input: [1,1,1,2,2,3,3,4,5,6]
Output: [[1],[2,3],[4,5,6]]

Input: [1,1,1,4,5,6,6,6,7,7,8,8,8,8,8,8,8,9,5,6,5,6,5,6,5,6,-56]
Output: [[6, 8],[5],[1],[7],[9,4,-56]]

Input: []
Output: []

Input: (empty input)
Output: ERROR/Undefined/Doesn't matter

Rules

Groupings must go from maximal frequency to minimal frequency.
Internal order of the groupings are arbitrary (E.G. example 3 could have [8,6] instead).
This is code-golf, lowest byte-count wins.

Related

Sort the distinct elements of a list in descending order by frequency

Can the output be in string format? Ie. A list of lists, but each number represented by a character instead of an integer.

Pyth, 8 7 bytes
_{M.g/Q

Try it online!
1 byte thanks to FryAmTheEggman.

@DigitalTrauma you can't; it's in a lambda; the implicit variable there is k, which I have already omitted.

got it - thanks for the explanation!

Congratulations.

@MagicOctopusUrn thank you.

Mathematica, 43 bytes
Union/@SortBy[l=#,f=-l~Count~#&]~SplitBy~f&

Try it online! (Using Mathics.)
Alternatively:
SortBy[Union[l=#],f=-l~Count~#&]~SplitBy~f&

There's no built-in?

Is GatherBy an option, not sure because I don't know the language.

@carusocomputing It sorts the groups by the first occurrence of the elements in the original list, so I'd still have to sort the groups afterwards. By sorting the list first, I can save a byte with SplitBy (also the SortBy would actually be more complicated if I did GatherBy first).

Interesting, so the "must be in order from maximal to minimal" messes that up?

@carusocomputing Exactly.

JavaScript (ES6), 95 101 bytes
a=>a.map(x=>(o[a.map(y=>n+=x!=y,n=0)|n]=o[n]||[])[x*x+(x>0)]=x,o=[])&&(F=o=>o.filter(a=>a))(o).map(F)

How?
For each element x of the input array a, we compute the number n of elements of a that are different from x:
a.map(y => n += x != y, n = 0) | n

We use the indices n and x to fill the array o:
(o[n] = o[n] || [])[x * x + (x > 0)] = x

Edit: Because JS doesn't support negative array indices, we need the formula x * x + (x > 0) to force positive indices.
This gives us an array of arrays containing the unique elements of the original list, grouped by frequency and ordered from most frequent to least frequent.
However, both the outer array and the inner arrays potentially have many empty slots that we want to filter out. We do this with the function F, applied to o and each of its elements:
F = o => o.filter(a => a)

Test cases

let f =

a=>a.map(x=>(o[a.map(y=>n+=x!=y,n=0)|n]=o[n]||[])[x*x+(x>0)]=x,o=[])&&(F=o=>o.filter(a=>a))(o).map(F)

console.log(JSON.stringify(f([1,2,3]))) // [[1,2,3]]
console.log(JSON.stringify(f([1,1,1,2,2,3,3,4,5,6]))) // [[1],[2,3],[4,5,6]]
console.log(JSON.stringify(f([1,1,1,4,5,6,6,6,7,7,8,8,8,8,8,8,8,9,5,6,5,6,5,6,5,6,-56]))) // [[6, 8],[5],[1],[7],[9,4,-56]]
console.log(JSON.stringify(f([]))) // []

I think a Set saves you a byte: a=>a.map(e=>(r[n=0,a.map(f=>n+=e!=f),n]||(r[n]=new Set)).add(e),r=[])&&r.filter(s=>s).map(s=>[...s]).

@Neil This is quite different from my current approach. Maybe you should post it as a new answer?

I didn't think changing o[n] from an array to a set was that different, but I already golfed @RickHitchcock's answer anyway so there's not that much point.

Python 2, 145 141 bytes
import collections as c,itertools as i;o=lambda n:lambda l:l[n]
print[map(o(0),g)for _,g in i.groupby(c.Counter(input()).most_common(),o(1))]

Try it online!
This is my first submission after years of reading.

It basically it puts all the elements into a Counter (dictionary of how many of each element in the list) and .most_common() puts the items in decending frequency order. After that, it's just a matter of formatting the items into the right list.

Saved 4 bytes thanks to ovs.

Welcome to PPCG :). Don't get as addicted as I did.

Creating your own itemgetter function is 4 bytes shorter than importing it: o=lambda n:lambda l:l[n]

Jelly, 9 8 bytes
QɓċÐ€ĠṚị

Try it online!

Did... Pyth... beat... Jelly?

Jelly doesn't have group-by, so that shouldn't be surprising.

PHP, 85 bytes
<?$r=[];foreach(array_count_values($_GET)as$k=>$v)$r[$v][]=$k;krsort($r);print_r($r);

Try it online!

Clojure, 74 bytes
#(for[[_ g](sort-by(comp - key)(group-by val(frequencies %)))](map key g))

Looks quite verbose :/

Beat me to it (and beat me by a few bytes, clever use of comp - to reverse!). Not as short as other languages, but I thought it was amusing since Clojure has "group-by" and "frequencies" built in.

When I read the task description I was hoping for 50 or 60 bytes, but the actual implementation turned out to be a bit trickier.

Perl 6, 43 bytes
*.Bag.classify(-*.value).sort».value».key

Test it
Expanded:
*                   # WhateverCode lambda (this is the input)
                    # [1,1,1,2,2,3,3,4,5,6]

.Bag                # turn into a Bag
                    # (1=>3,5=>1,4=>1,3=>2,6=>1,2=>2).Bag

.classify(-*.value) # classify by how many times each was seen
                    # {-2=>[3=>2,2=>2],-3=>[1=>3],-1=>[5=>1,4=>1,6=>1]}

.sort\              # sort (this is why the above is negative)
                    # {-3=>[1=>3],-2=>[3=>2,2=>2],-1=>[5=>1,4=>1,6=>1]}

».value\            # throw out the classification
                    # ([1=>3],[3=>2,2=>2],[5=>1,4=>1,6=>1])

».key               # throw out the counts
                    # ([1],[3,2],[5,4,6])

Wow, I always forget about Bag, nice one!

Bash + GNU utilities, 71 61
sort|uniq -c|sort -nr|awk '{printf$1-a?"\n%d":",%d",$2;a=$1}'

Input as a newline-delimited list.  Output as a newline-delimited list of comma-separated values.
Try it online.

Mathematica, 79 bytes
Table[#&@@@f[[i]],{i,Length[f=GatherBy[Sort[Tally@#,#1[[2]]>#2[[2]]&],Last]]}]&

input

[{1, 1, 1, 4, 5, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 9, 5, 6, 5, 6, 5,
     6, 5, 6, -56}]

output

{{8, 6}, {5}, {1}, {7}, {-56, 9, 4}}

The GatherBy I mentioned to Martin! I wondered how this would be done :).

Sort[...,...&] is just SortBy[...,-Last@#&].

Length[f=...]. And First/@ is #&@@@.

fixed, fixed and fixed

MATL, 9 bytes
9B#uw3XQP

Input is a column vector, using ; as separator.
Try it online!
Explanation
9B#u   % Call 'unique' function with first and fourth outputs: unique entries and
       % number of occurrences
w      % Swap
3XQ    % Call 'accumarray' with anonymous function @(x){sort(x).'}. The output is
       % a cell array with the elements of the input grouped by their frequency.
       % Cells are sorted by increasing frequency. Some cells may be empty, but
       % those won't be displayed
P      % Flip cell array, so that groups with higher frequency appear first.
       % Implicitly display

R, 84 77 bytes
-7 bytes thanks to mb7744
unique(lapply(x<-sort(table(scan()),T),function(y)as.double(names(x[x==y]))))

Reads from stdin; returns a list with subvectors of integers in increasing order. If we could return strings instead of ints, then I could drop 11 bytes (removing the call to as.double), but that's about it. R's table function does the heavy lifting here, counting the occurrences of each member of its input; then it aggregates them by count (names). Of course, that's a string, so we have to coerce it to an integer/double.
Try it online!

You can lose 7 bytes by eliminating the "which", and using logical indexing

@mb7744 oh duh.

I took another stab at it with R. It's unfortunate how long the lambda syntax is, so I set out trying to avoid it. In exchange I had to use nested lapply's, but at least in that case I can assign a short variable to lapply. I can't seem to assign a variable to the the function function...

k, 22 bytes
{x@!x}{(>x)@=x@>x}#:'=

Try it online.
(AW's k seems to require an extra @ before the #, but oK does not.)
Explanation:
                     = /group identical numbers in a map/dict
                  #:'  /get number of times each number is repeated
                       /this is almost the answer, but without the inner lists
      {      x@>x}     /order "number of times" greatest to least
            =          /group them (to make the smaller groups)
       (>x)@           /get the actual numbers into place
{x@!x}                 /get values of the map/dict it's in

https://github.com/JohnEarnest/ok for anyone else wondering what k is, it's actually ok. Ba-dum-tssss...

Brachylog, 10 bytes
ọtᵒ¹tᵍhᵐ²|

Try it online!
Explanation
Example input: [2,1,1,3]

ọ            Occurences:            [[2,1],[1,2],[3,1]]
 tᵒ¹         Order desc. by tail:   [[1,2],[3,1],[2,1]]
    tᵍ       Group by tail:         [[[1,2]],[[3,1],[2,1]]]
      hᵐ²    Map twice head:        [[1],[3,2]]

         |   Else (Input = [])      Input = Output

JavaScript (ES6), 100 98 96 93 bytes
Saved 2 bytes thanks to @Neil (plus he fixed an edge-case bug in my code).  Saved 3 more bytes thanks to @TomasLangkaas.
a=>a.sort().map((_,n)=>a.filter((v,i)=>i-a.indexOf(v)==n&v!=a[i+1])).filter(a=>a+a).reverse()

Test cases

f=
a=>a.sort().map((_,n)=>a.filter((v,i)=>i-a.indexOf(v)==n&v!=a[i+1])).filter(a=>a+a).reverse()

console.log(JSON.stringify(f([1,2,3])))
console.log(JSON.stringify(f([1,1,1,2,2,3,3,4,5,6])))
console.log(JSON.stringify(f([1,1,1,4,5,6,6,6,7,7,8,8,8,8,8,8,8,9,5,6,5,6,5,6,5,6,-56])))
console.log(JSON.stringify(f([])))

Your test is flawed (doesn't work for zero) but I think you can still save bytes by filtering and reversing instead of unshifting: a=>a.sort().map((_,n)=>a.filter((v,i)=>i-a.indexOf(v)==n&v!=a[i+1])).filter(a=>1/a[0]).reverse().

Ahh, I should have known to test for 0!  Your code fixes it, plus it's shorter, so thank you for that : )

Save 3 more bytes by changing .filter(a=>1/a[0]) to .filter(a=>''+a).

Nice one, @TomasLangkaas, thanks.  (Saves 2 bytes.)

My bad (have trouble  with counting), but .filter(a=>a+a) would provide the extra byte.

Yes, that does it, thanks!

Husk, 6 5 bytes
↔k#¹u

Try it online!
-1 byte from Leo.
Explanation
↔k#¹u
    u uniquify the input
 k#¹  key on frequency in input
↔     reverse

You could save 1 byte by uniquifying the original list instead of the final groups https://tio.run/##yygtzv5flZpbfGhnbn7xo6bG/4/apmQrH9pZ@v///@hoQx0jHeNYHSANgkYgHhCa6JjqmMFFwTwwNAdCCxRoCZZDxrqmIJ2xsQA

05AB1E, 8 bytes
ÙΣ¢}R.γ¢

Try it online or verify all test cases.
Explanation:
Ù       # Uniquify the (implicit) input-list
 Σ      # Sort this uniquified list by:
  ¢     #  Get its count in the (implicit) input-list
 }R     # After the ascending sort: reverse it to make it descending
   .γ   # Then adjacently group each value by:
     ¢  #  Its count in the (implicit) input-list
        # (after which the result is output implicitly)

The .γ could have been .¡ for the same result. .¡ is the group-by builtin, and .γ is the adjacently group-by builtin. But since we use a sort first, the result ends up buying the same.
Unfortunately, 05AB1E lacks a sort & group-by as single builtin, so we'll have to do it in two steps instead (like most existing answers tbh).

Factor, 63 bytes
[ histogram unzip swap zip expand-keys-push-at values reverse ]

Explanation
                     ! { 1 1 1 2 2 3 3 4 5 6 }
histogram            ! H{ { 1 3 } { 2 2 } { 3 2 } { 4 1 } { 5 1 } { 6 1 } }
unzip                ! { 1 2 3 4 5 6 } { 3 2 2 1 1 1 }
swap                 ! { 3 2 2 1 1 1 } { 1 2 3 4 5 6 }
zip                  ! { { 3 1 } { 2 2 } { 2 3 } { 1 4 } { 1 5 } { 1 6 }
expand-keys-push-at  ! H{ { 1 V{ 4 5 6 } } { 2 V{ 2 3 } } { 3 V{ 1 } } }
values               ! { V{ 4 5 6 } V{ 2 3 } V{ 1 } }
reverse              ! { V{ 1 } V{ 2 3 } V{ 4 5 6 } }

Python 3, 85 bytes
def f(l):
 r=[[]for _ in l]
 for x in{*l}:r[-l.count(x)]+=x,
 return[*filter(bool,r)]

Try it online!
-12 thanks to tips from @ovs!

This will currently fail if all elements are the same, because r is too short. r=[[]for _ in s*2] would be a simple fix, but replacing r[l.count(x)] with r[-l.count(x)] fixes this as well, while removing the [::-1]

And a few golfing hints: The assignment to s is not worth it, the last line can be shorter with a filter and using tuples instead of lists for the inner containers can save a few bytes

@ovs thanks! your tips helped a lot. I used l instead of s*2 and removed s assignment.

V, 60, 54 bytes
ÚòÍ¨¼¾©î±/± ±òHòø
pkJjòú!
Ç¨^ƒ ©î±/o
Îf ld|;D
òV{Jk

Try it online!
Hexdump:
00000000: daf2 cda8 bc81 bea9 eeb1 2fb1 20b1 f248  ........../. ..H
00000010: f2f8 200a 706b 4a6a f2fa 210a c7a8 5e83  .. .pkJj..!...^.
00000020: 20a9 81ee b12f 6f0a ce66 206c 647c 3b44   ..../o..f ld|;D
00000030: 0af2 567b 4a6b                           ..V{Jk

As much as I love V, I'm pretty sure this is the worst possible language for the task. Especially considering it has no support for lists, and basically no support for numbers. Just string manipulation.

PowerShell, 77, 70 bytes
($a=$args)|group{($a-eq$_).count}|sort n* -Des|%{,($_.group|sort -u)}

NB: To see that these results are correctly grouped (since visually there's no deliniation between the contents of each array), you may wish to append | write-host to the end of the above line.
Acknowledgements
Thanks to:

TessellatingHeckler for saving 7 bytes by massively refactoring / rewriting to a way more golfed approach.

Previous
77 bytes
param($x)$x|group|sort count -desc|group count|%{,($_.group|%{$_.group[0]})}

Nice, thanks.  I had to inlclude the ,() for grouping (since output was just showing as one continuous array).  This is way more golfy than my original attempt; awesome work!

C#, 119 bytes
Just a quick stab at it:
using System.Linq;
a=>a.GroupBy(x=>x)
    .GroupBy(x=>x.Count(),x=>x.Key)
    .OrderBy(x=>-x.Key)
    .Select(x=>x.ToArray())
    .ToArray()

+1 You can remove the System.Func<int[],int[][]>F= and trailing ; though. That isn't part of the byte-count for these kind of lambdas.

@KevinCruijssen, I had no idea. Thanks!

Ruby, 62 bytes
->a{a.group_by{|e|a.count(e)}.sort_by{|x,_|-x}.map{|_,i|i|[]}}

Try it online!
There has got to be a shorter way to do this.

save one byte by removing the parentheses from a.count e

R, 66 bytes
(l=lapply)(l(split(x<-table(scan()),factor(-x)),names),as.integer)

Try it online!
If in the output the integers may be in string format, can drop to 48 bytes (as mentioned in @Giuseppe's answer).

Ungolfed:
input <- scan(); # read input
x <- table(input); # count how many times each integer appears, in a named vector
y <- split(x, factor(-x)) # split the count into lists in increasing order
z <- lapply(y, names) # access the the original values which are still
                      # attached via the names
lapply(z, as.integer) # convert the names back to integers

as.double is shorter by one byte, and it should work the same as as.integer

Well, it depends whether you want to return an integer or a double. If double is okay, maybe character would be as well, and we could both save some bytes.

50 bytes

Perl 5 -pa, 89 bytes
map$k{$_}++,@F;$_="@{[sort{$k{$b}-$k{$a}}keys%k]}";s/\S+ /$&.'| 'x($k{1*$&}!=$k{1*$'})/ge

Try it online!

Groovy, 71 bytes
{a->a.groupBy{a.count(it)}.sort{-it.key}.values().collect{it.unique()}}

I actually just learned about groupBy after creating this. I didn't know collect wasn't my only choice.

{
    a->                 // [1,2,1,2,3,3,3,6,5,4]
    a.groupBy{
        a.count(it)     // [2:[1,2,1,2],3:[3,3,3],1:[6,5,4]]
    }.sort{
        -it.key         // [3:[3,3,3],2:[1,2,1,2],1:[6,5,4]]
    }.values().collect{ // [[3,3,3],[1,2,1,2],[6,5,4]]
        it.unique()
    }                   // [[3],[1,2],[6,5,4]]
}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Create a binary ruler
Given a number n, generate the first n columns of this pattern:
                               #
               #               #
       #       #       #       #
   #   #   #   #   #   #   #   #
 # # # # # # # # # # # # # # # #
################################ ...

The height of the column at (1-indexed) n is the number of trailing 0 bits in n's binary representation, plus one. As a result, the bottom layer has every column filled in, the second layer every second column, the third layer every fourth column, etc.
Rules

You may input and output through any standard method.
You may assume the input is an integer between 1 and 999, inclusive.
The output may contain any amount of whitespace, as long as the pattern is intact.
The pattern must be 1-indexed, and in the same format as shown here.
You may use any single non-whitespace character in place of #, but you may not change the space character.

Test cases
1
#

2
 #
##

3
 #
###

4
   #
 # #
####

5
   #
 # #
#####

7
   #
 # # #
#######

32
                               #
               #               #
       #       #       #       #
   #   #   #   #   #   #   #   #
 # # # # # # # # # # # # # # # #
################################

A few larger test cases can be found here.
Scoring
This is code-golf, so the shortest code in bytes in each language wins.

Related.

Now I can measure distance in binary! Oh wait...

Does the ruler have to be horizontal? 2. Do the markings have to be #?

@JonathanAllan 1. Yes, and 2. No, they can be any single non-space character. I've added this to the rules.

The sequence at OEIS: A001511

Also related

Is it bugging anyone else how many response tallies are character counts, not byte counts?

@BrianRisk Many of the languages actually use an custom encoding. Jelly's, for example, can be found here.

Python 2, 54 bytes
i=n=input()
while i:i-=1;print((' '*~-2**i+'#')*n)[:n]

Try it online!
Prints with lots of leading whitespace. Each row i counting down from n repeats a pattern of 2**i-1 spaces followed by a #. This pattern is repeated up to the width of the ruler, which is the input n. This is done by multiplying the pattern string by n and taking the first n characters with [:n].
The pattern can be made by string formatting for an equal length alternative.
i=n=input()
while i:i-=1;print('%%%ds'%2**i%'#'*n)[:n]

A cute slicing method is longer.
n=input();s=~-2**n*' '+'#'
exec"s=s[1::2]*2;print s[:n];"*n

Is the ~ is -1 or +1?

Never mind, it's (-x) - 1

Python 3, 74 bytes
n=int(input())
a=1
while a<n:a*=2
while a:print(("%%%dd"%a%4*n)[:n]);a//=2

Try it online!

Wow, it took me a while to figure out how the rows are generated. Well done.

a=2**len(bin(n)) for 72 bytes

It will hit memory errors quickly, and print a bunch of extra white space (allowed) - but you can do 54 using Python 2.

V, 17, 16 bytes
é#Àñä}Är {ñÎÀlD

Try it online!
Hexdump:
00000000: e923 c0f1 e416 7dc4 7220 7bf1 cec0 6c44  .#....}.r {...lD

Thanks to @KritixiLithos for saving one byte!
This algorithm is horribly inefficient, but it should work in theory for any size input.
It works by generating the first n iterations of the following pattern:
#

 #
##

   #
 # #
####

       #
   #   #
 # # # #
########

               #
       #       #
   #   #   #   #
 # # # # # # # #
################

                               #
               #               #
       #       #       #       #
   #   #   #   #   #   #   #   #
 # # # # # # # # # # # # # # # #
################################

And then chopping off all but the first n columns. As such, this will produce a ton of leading whitespace, but the OP said:

The output may contain any amount of whitespace, as long as the pattern is intact

Explanation:
é#                      " Insert an '#'
  Àñ           ñ        " 'N' times:
    ä<C-v>}             "   Duplicate every line blockwise (duplicating horizontally instead of vertically)
           Ä            "   Duplicate the top line. This conveniently puts us on the first non-whitespace character (that is, '#')
            r           "   Replace this character with a space
              {         "   Move to the beginning of the buffer
                Î       " On every line:
                 Àl     "   Move 'N' characters to the right ('l' for right, makes sense, right?)
                   D    "   And delete everything after the cursor

I'm not entirely sure, but I think you can remove the |.

@KritixiLithos Aha! In hindsight, it's so obvious! Thanks for the tip. :)

APL (Dyalog), 21 bytes
'# '[1+⊖0⍪∨⍀⊖2⊥⍣¯1⍳⎕]

Try it online!
'# '[…`] index the string with
 ⎕ get input
 ⍳ that many integers
 2⊥⍣¯1 convert to binary, using as many digits as needed (one number in each column)
 ⊖ flip upside down
 ∨⍀ vertical cumulative OR reduction
 0⍪ concatenate zeros on top
 ⊖ flip upside down (i.e. back up again)
 1+ add one (for 1-based indexing)

JavaScript (ES6), 61 58 bytes
f=(n,c=n,s='')=>c?f(n,c>>1,s+s+' ')+`
`+(s+1).repeat(c):''

Saved 1 byte thanks to @ETHProductions, then 2 more bytes when I saw that any character could be used.
A recursive solution.
Test cases:

f=(n,c=n,s='')=>c?f(n,c>>1,s+s+' ')+`
`+(s+1).repeat(c):''

console.log(f(32));
console.log(f(1));
console.log(f(5));
console.log(f(7));

Animation:

f=(n,c=n,s='')=>c?f(n,c>>1,s+s+' ')+`
`+(s+1).repeat(c):''

for(let i = 1 ; i < 64 ; i++) {
  setTimeout(_=>document.querySelector('pre').textContent=f(i), i*40);
}
<pre>

Well done. You can change c/2|0 to c>>1 to save a byte.

Nice, I need to brush up on my bitwise operators.

Jelly, 11 10 bytes
Rọ2‘4ẋz⁶ṚY

Try it online!
1 byte saved after the OP added a relaxation that the character doesn't have to be #.

Japt, 20 17 bytes
Saved 3 bytes thanks to @Shaggy and @ETHproductions
õ_¤q1 o Ä çoÃ·z w

Try it online!
Explanation:
Input: 5
õ_¤q1 o Ä çoÃ·z w
õ           Ã       // Create a range [1...Input] [1,2,3,4,5]
 _                  // Map; At each item:
  ¤                 //   Convert to binary        ["1","10","11","100","101"]
   q1               //   Split on "1"             [["",""],["","0"],["","",""],["","00"],["","0",""]]
      o             //   Get the last item        ["","0","","00",""]
        Ä           //   Add 1                    [["1","01","1","001","1"]]
          ço        //   Fill with "o"            ["o","oo","o","ooo","o"]
             ·      // Join with new-lines        ["o\noo\no\nooo\no"]
              z     // Rotate 90 degrees          ["ooooo\n o o \n o   "]
                w   // Reverse                    ["   o \n o o \nooooo"]

20 bytes

@Shaggy Actually, you don't even need the l

@ETHproductions: yep, just figured that out. 18 bytes

17 bytes

A cool trick with bitwise operators is to do n&-n to capture only the final 1 and all trailing 0s in n. Not sure if this will help, but it's worth a shot...

Octave, 45 bytes
@(n)[[sort(cummin(de2bi(g=0:n)'));g|1]+32 '']

Try it on Octave Online!
Instead of '#' prints '!'.

PHP, 139 bytes
for($f=array_fill(0,$l=1+log($a=$argn,2)," ");$n++<$a;)for($h=1+strspn(strrev(decbin($n)),$i=0);$i<$h;)$f[$l-++$i][$n]=3;echo join("
",$f);

Try it online!

Pyth, 15 Bytes
j_.tm*Nhx_.Bd1S

Try it!
explanation
j_.tm*Nhx_.Bd1S
    m         SQ   # map over the numbers from 0 to the implicit input (lambda variable: d)
          .Bd      # Convert d to a binary string: (12 -> 1100)
         _         # reverse: (1100 -> 0011)
        x    1     # get the location of the first 1 ( 2 )
     *Nh           # make one more than that " quotation marks (""")
 _.t               # transpose the list of quotation mark strings and reverse it
j                  # join on newline

@JasonS It's a golfing language based on Python! I now linked pyth's github. I thought the Try it! link to the online Executor would be sufficient.

C, 84 74 bytes
f(i,l,m){putchar(32+3*!(i&m));i<l?f(i+1,l,m):m?putchar(10),f(1,l,m>>1):1;}

Ungolfed:
void f(int counter, int length, int mask) {
    putchar((counter&mask) ? ' ' : '#');
    if(counter<length) {
        f(counter+1, length, mask);
    } else if(mask) {
        putchar('\n');
        f(1, length, mask>>1);
    }
}

Test with:
int main() {
    f(1, 32, 1023);
    putchar('\n');
    f(1, 1, 1023);
    putchar('\n');
    f(1, 999, 1023);
    putchar('\n');
}

Explanation
Once again, recursion takes less characters in C than iteration, so the two loops are expressed as the two recursional invocations.
Also, C is a great language for playing tricks with boolean expressions, allowing the decision of whether to put a blank or a # to be expressed by the expression 32+3*!(i&m). A space has the ASCII value of 32, the # is ASCII 35, so we get a blank if any of the bits in the mask is set in i.

Do you even need the int i,l,m?

@ZacharyT No, turns out I didn't. Thanks for saving those 10 bytes :-)

Python 2, 47 bytes
f=lambda n:n and' '.join(f(n/2))+'\n'+n*'#'or''

Try it online!

JavaScript (ES8), 71 bytes
The padStart() function was introduced in ECMAScript 2017!
N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+'#'.padStart(n).repeat(N/n)+s`)

f=
N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+'#'.padStart(n).repeat(N/n)+s`)

console.log(f(+prompt()))

JavaScript (ES6), 77 bytes
N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+(' '.repeat(n-1)+'#').repeat(N/n)+s`)

f=
N=>eval(`for(s='',n=1;n<=N;n*=2)s='\\n'+(' '.repeat(n-1)+'#').repeat(N/n)+s`)

console.log(f(+prompt()))

@RickHitchcock Fixed.

Mathematica, 69 bytes
Rotate[Grid["#"~Table~#&/@(IntegerExponent[2*#,2]&/@Range[#])],Pi/2]&

(WESRRMICGSE): 237 bytes
IF(ROW()<=FLOOR(LOG(COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1,2),1)+2,LEFT(REPT(REPT(" ",FLOOR(POWER(2,LOG(COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1,2)-ROW()+2),1)-1) &"#",COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1),COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1),"")

Alright. 'splaining time.
First off, replace every COUNTA(R1C:R[-1]C,R[1]C:R[1024]C)+1 with simply [i], for input. the token counts the number of cells, not including itself, that contain a  formula, and then adds one, to include itself. Since WESRRMICGSE drags a formula according to the input you give it, this token always results in the input.
we have:
IF(ROW()<=FLOOR(LOG([i],2),1)+3,LEFT(REPT(REPT(" ",FLOOR(POWER(2,LOG([i],2)-ROW()+2),1)-1) &"#",[i]),[i]),"")

This is much more readable.
You're going to see the FLOOR(LOG([i],2),1) token a lot, which simply means take the nearest power of 2 which is less than the input ([i]) number. eg: 4->4, 5->4, 6->4, 7->4, 8->8 ...etc. I'll replace that with GS[[i]]
IF(ROW()<=GS[[i]]+3,LEFT(REPT(REPT(" ",,FLOOR(POWER(2,LOG([i],2)-ROW()+2),1),1)-1) &"#",[i]),[i]),"")

better. breaking down the if clause, we're testing if the row is less than or equal to GS[[i]]+3, because all rulers' height is equal to the GS[[i]]+1, this  selects the rows which are equal to the height of the ruler. +1 for 1-indexing rows, and +1 again for WESRRMICGSE offset.
The FALSE result yields an empty cell (""), and a true result yields LEFT(REPT(REPT(" ",,FLOOR(POWER(2,LOG([i],2)-ROW()+2),1),1)-1) &"#",[i]),[i])
currently still editing, stay tuned

Haskell, 64 62 bytes
l m=([2..2^m]>>" ")++'#':l m
f n=unlines$take n.l<$>[n,n-1..0]

Try it online! Example usage: f 10.

Charcoal, 27 23 bytes
↶Ｆ…·¹Ｎ«Ｊι⁰#Ｗ¬﹪ι²«Ａ÷ι²ι#

Try it online! Link is to verbose version of code. Edit: Saved 4 bytes by switching to JumpTo.

It's still absolute, just now it's called JumpTo (sorry)

@ASCII-only Ah, the wiki could do with an update. (Or I assume I could do it should you want to give me edit permission...)

@ASCII-only Huh, I should have remembered that from https://codegolf.stackexchange.com/a/119904 ...

Do you have a GitHub account?

@ASCII-only I have two... I can't decide which one is more appropriate...

@ASCII-only I could save another byte if \r worked after a PivotLeft()... assuming \r does what I'm guessing it does...

Oh, sorry, I'll fix \r as soon as I can.

Let us continue this discussion in chat.

FYI the 21-byte \r version is ↶Ｆ…·¹Ｎ«⸿#Ｗ¬﹪ι²«Ａ÷ι²ι#.

k, 33 bytes
`0:|" #"{(1+!x){~y!x}/:(x>)(2*)\1}

This only seems to work in AW's interpreter.

The oK version (which you can try online) seems to have a bug, requiring a slight change to make it work:
`0:|" #"{(1+!x){~y!x}/:{x>y}[x](2*)\1}

C#, 174 bytes
This method has two parameters, an input for the ruler length, and an output which is the ruler as string.
Golfed:
void R(int n,out string s){var l=new int[++n];int i,x=n,y=0;for(s="";x-->1;)for(i=0;0==(l[x]=(x>>i++&1)*i);y=y<i?i:y);for(y++;y-->0;s+='\n')for(x=0;++x<n;s+=y<l[x]?'#':' ');}

Indented:
void R(int n,out string s){                       // Return the result in an out parameter.
    var l=new int[++n];                           // Use a 1-based array.
    int i,x=n,y=0;                                //
    for(s="";x-->1;)                              // For each number x on the ruler
        for(i=0;0==(l[x]=(x>>i++&1)*i);y=y<i?i:y) // ... find lowest set bit of x, counting the maximum value.
            ;                                     //
    for(y++;y-->0;s+='\n')                        // Count down each line.
        for(x=0;++x<n;s+=y<l[x]?'#':' ')          // Output # for numbers that are tall enough.
            ;                                     //
}

Try it online!

Would converting to a Func<int, string> save you some bytes?

J, 38 bytes
3 :'|.|:''#''#~,.(1+|.i.1:)@#:"0>:i.y'

Not great. Lmk if the byte count is off -- I'm on my phone.

Looks like 38 to me, unless the 3 at the beginning is input...

@ETHproductions thanks, shame switching from a tacit definition didn't save any bytes...

28 bytes with 0|.@|:'#'#"0~1#.2~:/\i.#:@,]

Husk, 13 bytes
↔T' ↑moR'#→İr

Try it online!
I saw a ruler sequence builtin(İr), so I just went ahead and found a challenge I could cheat on.

Java (OpenJDK 8), 91 bytes
n->{int i=10,j;String s="";for(;i-->0;s+="\n")for(j=0;j++<n;)s+=j>>i<<i<j?' ':35;return s;}

Try it online!
Ungolfed:
n->{
    int i=10,j; // Since we are allowed extra whitespace, set columns always to 10
    String s = "";
    for(;i-->0;s+="\n")      // Every iteration add a newline, i=9..0
        for(j=0;j++<n;)      // j=1..n+1
            s+= j>>i<<i<j    // if j has less than i trailing 0s in binary form
                ?' '         // add a space else
                :35          // # (java handles ternary return types weirdly)
}

CJam, 34 bytes
ri{2bW%0+0#)}%_'#f*\:e>f{Se]}zW%N*

Meh.

C (gcc), 70 bytes
f(x,l,n){for(l=512;l/=2;)for(n=0;n++<=x;)putchar(n^x+1?n%l?32:35:10);}

Try it online!

Suggest n+~x instead of n^x+1

Perl 5, 60 + 1 (-n) = 61 bytes
$n=0|1+(log)/log 2;say(($"x(2**$n-1),X)x($_/2**$n))while$n--

Try it online!

Japt -R, 11 bytes
õ_&n)¤çTÃz3

Try it
õ_&n)¤çTÃz3     :Implicit input of integer U
õ               :Range [1,U]
 _              :Map each Z
  &n            :  Bitwise AND with -Z
    )           :  Group that operation
     ¤          :  Result to binary string
      ç         :  Fill with
       T        :    0
        Ã       :End map
         z3     :Rotate 90° clockwise 3 times
                :Implicit output joined with newlines

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Swep tha vowels!
Note: the title was misspelled intentionally.
Given a string s, swap the first vowel runs of every 2 words. For this challenge, y is considered a vowel.
For example, given an input of "great day sir":
1. Input: "great day sir"
2. Identify pairs of words: "[great day] [sir]" (No word for sir to pair with)
3. Identify the first vowel runs in each word: "[gr[ea]t d[ay]] [s[i]r]"
4. Swap the vowel runs in each pair: "[gr[ay]t d[ea]] [s[i]r]"
5. Return/print: "grayt dea sir"

When there are vowel runs of different lengths, you still swap the whole runs. When a word has more than one vowel runs, you still only swap the first one. When the first or second word of a pair of words does not have a vowel, then you do not swap the vowels for those words.
You may assume that the input only consists of one case of alphabetic letters and the literal space or another constant delimiter.
Standard methods of I/O, standard loopholes apply. Leading/trailing whatevers are okay.
Test cases:
Input -> Output

"great day sir" -> "grayt dea sir"
"ppcg is the best" -> "ppcg is the best" (When there is no vowel to swap, don't swap vowels."
"this is a test case" -> "this is e tast case"
"loooooooooooooong word" -> "long woooooooooooooord"
"great night" -> "grit neaght"
"anything goes" -> "oenything gas"
"qwrtpsdfghjklzxcvbnm aaaaaaaa hi there" -> "qwrtpsdfghjklzxcvbnm aaaaaaaa he thire"
"this is a long test case in case you could not tell" -> "this is o lang tast cese an cise ou cyould net toll"

For those who can see deleted posts, the sandbox post was here.

If the first word has no vowels, is it OK to swap the vowels of the second and third words? Or can vowels only swap between runs of two words? For example, should ppcg is awesome become ppcg is awesome or ppcg as iwesome?

@DJMcMayhem Vowels can only swap between runs of two words. I will edit.

I believe the output for this is a long test case in case you could not tell should be this is o lang tast cese an cise ou cyould net toll, since the vowel runs you and ou would be swapped.

@BashfulBeluga Yep, my mistake. I will fix.

Passing the test cases is easy enough but getting this right is trickier than it sounds: https://en.oxforddictionaries.com/explore/is-the-letter-y-a-vowel-or-a-consonant

I don't think you meant to have the brackets in 1. Input: "gr[ea]t day sir", that confused me when I reread it, since that's not part of the actual input.

V, 42, 41 bytes
ò2Eá
òÍ¨[aeiouy]«©¨ƒ ƒ©¨[aeiouy]«©/³²±
Íî

Try it online!
Hexdump:
00000000: f232 45e1 0af2 cda8 5b61 6569 6f75 795d  .2E.....[aeiouy]
00000010: aba9 a883 2083 a9a8 5b61 6569 6f75 795d  .... ...[aeiouy]
00000020: aba9 2fb3 b2b1 0acd ee                   ../......

Explanation:
ò       ò                                   " Recursively:
 2E                                         "   Move to the end of two words forward
   á<cr>                                    "   And append a newline

This will put all groups of two words on their own line, for example:
this is
a long
test case
in case
you could
not tell

Now we run some fancy regex-magic:
Í                                           " Globally substitute
 ¨[aeiouy]«©                                "   A vowel (capture group 1)
            ¨<131>                          "   Followed by as few characters as possible, then a space
                   <131>©                   "   Followed by as few characters as possible (capture group 2)
                         ¨[aeiouy]«©        "   Followed by a vowel again
                                    /       " With:
                                     ³²±    "   Capture groups '3', '2', '1'
Í                                           " Remove all:
 î                                          "   Newlines

Your regex doesn't require the end of a word between your two vowel groups.  Try it online!

@nmjcman101 Are you looking at my old revision? Because that's exactly what I have right now

My TIO link wasn't fixing anything, I just changed the input.  It swaps the letters oddly.

@nmjcman101 Ah, I see. Fixed now!

Japt, 39 37 bytes
They said it would be ugly, but I didn't listen... and it was:
¸ò ®efQ="%y+" ?Z£XrQZg°T fQP PÃ:ZÃc ¸

Test it online!
Explanation
 ¸  ò ® efQ="%y+" ?Z£    XrQ    Zg° T fQ    P PÃ :ZÃ c ¸
UqS ò mZ{Zef"%y+" ?ZmXYZ{Xr"%y+"Zg++T f"%y+"P P} :Z} c qS
             Implicit: U = input string, such as     "abc def ghi jkl mno"
UqS          Split on spaces, splitting into words.  ["abc","def","ghi","jkl","mno"]
ò            Group into runs of two items.           [["abc","def"],["ghi","jkl"],["mno"]]
mZ{          For each pair Z:
 Zef"%y+"?     If not every item contains a run of vowels (%y = [AEIOUYaeiouy]),
 :Z            return Z.                             [              ["ghi","jkl"]        ]
 ZmXYZ{        Otherwise, for each item X in Z:
  Xr"%y+"        Replace each run of vowels with
  Zg++T           the item at the next index in Z,   [["def","abc"]               ["mno"]]
  f"%y+"P         but only the first run of vowels.  [["e",  "a"  ]               ["o"  ]]
  P              Replace only for the first match.   [["ebc","daf"]               ["mno"]]
 }
}                                                    [["ebc","daf"],["ghi","jkl"],"mno"]]
c            Flatten back into a single array.       ["ebc","def","ghi","jkl","mno"]
qS           Re-join on spaces.                      "ebc daf ghi jkl mno"
             Implicit: output result of last expression

JavaScript (ES6), 62 106 98 101 bytes
s=>s.match(/(\w+)( (\w+))?/g).map(m=>m.replace(/([aeiouy]+)(\w* \w*?)([aeiouy]+)/g,'$3$2$1')).join` `

f=
s=>s.match(/(\w+)( (\w+))?/g).map(m=>m.replace(/([aeiouy]+)(\w* \w*?)([aeiouy]+)/g,'$3$2$1')).join` `
;

[
  "great day sir",
  "ppcg is the best",
  "this is a test case",
  "loooooooooooooong word",
  "great night",
  "anything goes",
  "qwrtpsdfghjklzxcvbnm aaaaaaaa hi there",
].map(f).map(s=>console.log(s))

Retina, 65 bytes
((\w*?)([aeiouy]+)(\w* \w*?)([aeiouy]+)|(\w+ ))(\w*)
$2$5$4$3$6$7

Try it online! Includes test cases. I wanted to use a conditional group reference but I couldn't get it to work in 66 bytes let alone 65 or less.

Retina, 50 bytes
\S+ \S+
$&¶
%O$^`(?<=\b[^aeiouy]*)[aeiouy]+
$`
¶

Try it online!
−2 bytes thanks to Martin.

First step is splitting each word pair to its own line (¶ is newline). This allows us to use .* within a pair of words.
Next, for each line we find the first vowel block in each word, and sort them by position in descending order.

I tried removing the double [aeiouy]+ but couldn't get something economic.

It's marginally shorter to swap the runs with a sort stage: https://tio.run/##VU0xDsIwDNz9Cg8tKvAFECMjA2OhatqGJBCSkrhAeRgP4GMhFRWCky37dPad46QMC2m2LsNuO8ehIZm8npBukqLMVovlrsoLxpXt@v1smo/bHJIS4lUIwnFG2LAevXLQtrVA5ZEkx4p7ApKRxWJIkWLNPAdt/2AE3qxr4ONklJAEzPTxMyrCcg@Xm6PWNwchjyf9uNfXypyRjUCphjjHf7L0YPoNRGU@s7cd1rbTDRpLUdf6DQ

@MartinEnder - Nice one! I couldn't get sorting to work. I tried another version that removed the [aeiouy] duplication, but I can't golf it down. I think It might work nicely with your suggestion: https://tio.run/##VU0xDsIwDNz9Cg8BFTrBXLEyMjBCUUMbkkBISuJSysN4AB8rqUAITras8@nuvCBteT9KlkW/Xac4LLDx8wHJhgvtmi5PJ8m2nU4gY7MFm8NoxXZFFj/ACtg8H9kih76XXnDCincYtIe6LiXqgKQE7kUgIBVZHI4UKZY8CDDuD1Zi63wF7ySrpSLgtovOqEgnAlxaT3WoDlIdT@Z@K697e0b@ASo91Hnx02WG0G8havu@nWuwdI2p0DqKujEv

Python 2, 148 bytes
from re import*
v="([aeiouy]+)"
print sub(r"(\w+)(?: (\w+))?",lambda m:sub(v+"(.* .*?)"+v,lambda g:''.join(g.groups()[::-1]),m.group()),raw_input())

Try it online!
Code Golfing is getting addictive!

Sections off pairs of words, then grabs the 2 groups of vowels and the string in between, reverses the order and uses that as the substitute.

Perl, 58 bytes
57 bytes code + 1 for -p.
$v="([aeiouy]+)";s!\w+ \w+!$&=~s/$v(.* .*?)$v/$3$2$1/r!ge

-2 bytes thanks to @Dada!
Try it online!

Just a couple of bytes to save by dropping a ? and storing ([aeiouy]+) in a variable: Try it online!

Haskell, 177 173 171 169 bytes
unwords.s.words
s(x:y:z)=maybe[x,y]id(do(a,b)<-k x;(c,d)<-k y;j[b c,d a])++s z
s x=x
v=(`elem`"aeiouy")
j=Just
k s=do(a,(x:y,r))<-j$span v<$>break v s;j(x:y,\n->a++n++r)

Try it online!
This is a direct shortening of the following naïve solution, so there should something much better around here:
swapvowels :: String -> String
swapvowels = unwords . swapPairs . words

swapPairs :: [String] -> [String]
swapPairs (word1:word2:rest) =
   case (,) <$> extractVowels word1 <*> extractVowels word2 of
     Just ((vowels1, rebuild1), (vowels2, rebuild2))
       -> [rebuild1 vowels2, rebuild2 vowels1] ++ swapPairs rest
     Nothing -> [word1,word2] ++ swapPairs rest
swapPairs rest = rest

extractVowels :: String -> Maybe (String, String -> String)
extractVowels s = do
    let isVowel l = l `elem` "aeiouy"
    (a,b) <- Just $ break isVowel s
    (w@(_:_),r) <- Just $ span isVowel b
    return (w, \n -> a ++ n ++ r)

Java (OpenJDK 8), 363 304+25 bytes
-34 bytes thanks to @KevinCruijssen
Golfed:
l->{String s[]=l.split(" "),a,b;Pattern p=Pattern.compile("[aeiouy]+");for(int i=0;i<s.length-1;i+=2){Matcher m=p.matcher(s[i]),n=p.matcher(s[i+1]);a=m.find()?m.group():null;b=n.find()?n.group():null;if(a!=null&b!=null){s[i]=s[i].replaceFirst(a,b);s[i+1]=s[i+1].replaceFirst(b,a);}}return l.join(" ",s);}

Try it online!
Ungolfed:
String swapVowels(String line) {
    String[] parts = line.split(" ");
    Pattern pattern = Pattern.compile("([aeiouy]+)");
    for (int i = 0; i < parts.length - 1; i += 2) {
        Matcher matcherL = pattern.matcher(parts[i]), matcherR = pattern.matcher(parts[i + 1]);
        String vowelRunL = matcherL.find() ? matcherL.group() : null, vowelRunR = matcherR.find() ? matcherR.group() : null;
        if (vowelRunL != null & vowelRunR != null) {
            parts[i] = parts[i].replaceFirst(vowelRunL, vowelRunR);
            parts[i + 1] = parts[i + 1].replaceFirst(vowelRunR, vowelRunL);
        }
    }
    return String.join(" ", parts);
}

You can remove the parenthesis around the input ((l)-> to l->). You can add import java.util.regex.*; to the byte-count, and remove all other java.util.regex.. You can remove the parenthesis in the regex ("([aeiouy]+)" -> "[aeiouy]+"). And you can change String[]s=l.split(" "); to String s[]=l.split(" "),a,b;, then you can remove the String inside the for-loop; And you can change String.join(" ",s); to l.join(" ",s);. Here is it all combined. [329 bytes]

@KevinCruijssen Indeed! Edited, thank you! :-)

Ruby, 87+1 = 88 bytes
Uses the -p flag.
gsub(/(\w+) (\w+)/){_,a,b=*$~;a[r=/[aeiouy]+/]&&b[r]?a.sub(r,b[r])+' '+b.sub(r,a[r]):_}

Try it online!

Python 3, 198 196 192 bytes

Saved 6 bytes: thanks to  Zachary T : if(m and n) to if m and n & removed unwanted r for regex string, index i starting from 1 instead of 0

from re import*
s=search
a=input().split()
v="[aeiouy]+"
j=1
while j<len(a):
 i=j-1;m=s(v,a[j]);n=s(v,a[i])
 if m and n:a[i]=sub(v,m[0],a[i],1);a[j]=sub(v,n[0],a[j],1)
 j+=2
print(' '.join(a))

Try it online!

I think you can shave three bytes off your program: one by removing the r before your string, another by changing i+1<len(a) to i<=len(a), and the third by changing if(m and n) to if m and n.

Thanks. But the i+1<len(a) cannot be changed to i<=len(a) or else it will try to evaluate a[j] i.e. a[i+1] for i=len(a) and cause index out of range error:

Sorry, I was reading that as i<len(a)+1, whoops!

Would this work? https://repl.it/IlX1

Yes, it works. You saved 2 bytes, Thank you!!

You have extraneous spaces at the end of some of your lines, I counted 192 bytes.

Yep, that and I had not even updated the tio link. Thanks.

Hey, would this work? https://repl.it/Iql5

Vyxal S, 33 bytes
⌈2ẇƛƛ≬k∪$cḊ:‡hAǑ";:vƒiṘ¨vJƛ÷Ȧṅ;;f

Try it Online!
Really really bad, I couldn't find a single good piece of this code


text:
Menger Sponge Generator
Challenge
My challenge, is for you to generate a Menger Sponge based on the level/iteration given. You need to draw it in 3d, anyway you can.
Examples
Inputs: 0, 1, 2, 3
Outputs:

Background Information
What is a Menger Sponge

In mathematics, the Menger sponge (also known as the Menger universal curve) is a fractal curve. It is a three-dimensional generalization of the Cantor set and Sierpinski carpet

Properties

See https://en.wikipedia.org/wiki/Menger_sponge#Properties (too long to copy and paste)

How do I construct the sponge?

Begin with a cube  (first image).

Divide every face of the cube into 9 squares, like a Rubik's Cube. This will sub-divide the cube into 27 smaller cubes.

Remove the smaller cube in the middle of each face, and remove the smaller cube in the very center of the larger cube, leaving 20 smaller cubes (second image). This is a level-1 Menger sponge (resembling a Void Cube).

Repeat steps 2 and 3 for each of the remaining smaller cubes, and continue to iterate ad infinitum.

The second iteration gives a level-2 sponge (third image), the third iteration gives a level-3 sponge (fourth image), and so on. The Menger sponge itself is the limit of this process after an infinite number of iterations.

Credit
Background info taken from this wikipedia page on Menger Sponges.

Good Luck!
Remember this is code-golf the shortest program wins!

@HyperNeutrino 3d is now required, so it's not a duplicate.

you shouldn't change the question when  2 of us answered

@Jenny_mathy I don't have a choice since doing it in 2d is already a question.

I'm voting to reopen simply because this is no longer a dupe. However, you will need to tighten up the spec to allow us to onow exactly what kind of 3d output you want

Since 3D is now required (invalidating existing answers), I think the question is now unclear.  There is a lot you need to specify for 3D including but not limited to viewing angle, projection, lighting, shading.

@DigitalTrauma I'm editing it right now!

@NoahCristino I think you'd do better to fix this one in the sandbox

I'm so sad this is a dupe :(. I'm already halfway done haha! This seemed like a fun one.

@DigitalTrauma Should I close this, and post in sandbox, or should I just leave it open?

@carusocomputing It's not now! With 3d it's not a duplicate, I just need to specify the 3d requirements

@NoahCristino right now its effectively closed (as dup).  Once you're done in the sandbox and have edited this question you may petition to the community (in comments, chat) to reopen.

@DigitalTrauma https://codegolf.meta.stackexchange.com/a/12867/61877

@NoahCristino please check out the sandbox man, it's not a dupe anymore, but you need to let this die and work out the kinks! I've actually posted a suggestion on the Meta site due to this question: https://codegolf.meta.stackexchange.com/questions/12869/resurrection-sandbox

@carusocomputing I'm working out the kinks here: https://codegolf.meta.stackexchange.com/a/12867/61877 But, I don't know what you mean about resurrecting, since I posted it today, and the other challenge is about 2d menger sponges (Sierpinski Carpets)

@NoahCristino your original question is the duplicate, and you already have 2 answers. Once an answer is posted, the question is "more-or-less" locked.

anyway.. here is the 3D answer
Mathematica, 15 bytes
#~MengerMesh~3&

new built-in in Mathematica 11.1
input

3

output

Can you add a try it link?

Why don't you just post it on https://codegolf.stackexchange.com/questions/40104/sierpinski-carpets since your code generates Sierpinski Carpets (2d menger sponges), not Menger Sponges, which my challenge is about.

I answered the 3D question ,too.Next time just ask "one" question in order to receive one answer

Why would you ever need a built-in function to do that either then now?

@NoahCristino Ask that to all 5000 of Mathematica's builtins :P

@HyperNeutrino lol