title: Fake Marquee Text

text:
# Question
Title: Fake Marquee Text
In this challenge fake marquee text is text that is shown part by part, in a scrolling-like fashion.

Some examples:

```
testing 4

   t
  te
 tes
test
esti
stin
ting
ing
ng
g

hello 2

 h
he
el
ll
lo
o

foobarz 3

  f
 fo
foo
oob
oba
bar
arz
rz
z

Something a bit longer 10

         S
        So
       Som
      Some
     Somet
    Someth
   Somethi
  Somethin
 Something
Something
omething a
mething a
ething a b
thing a bi
hing a bit
ing a bit
ng a bit l
g a bit lo
 a bit lon
a bit long
 bit longe
bit longer
it longer
t longer
 longer
longer
onger
nger
ger
er
r

small 15

              s
             sm
            sma
           smal
          small
         small
        small
       small
      small
     small
    small
   small
  small
 small
small
mall
all
ll
l

aaa 3

  a
 aa
aaa
aa
a

brace yourself 6

     b
    br
   bra
  brac
 brace
brace
race y
ace yo
ce you
e your
 yours
yourse
oursel
urself
rself
self
elf
lf
f

```

You have to write a program or a function that takes in two input and prints the output as described above. You may or may not output trailing spaces in your output. This is code-golf so shortest code in bytes wins.

If your program is standalone (i.e. when run actually prints the lines) (Input can be hard-coded but easy to change) and sleeps a bit between each line of output you get a -10 bonus.

# Answer
> 24 votes
# CJam, ~~12~~ 11 bytes

*1 byte saved by Dennis.*

```
,Sf*\f+$zN*

```

I'm making use of "Input can be hard-coded but easy to change": this expects the input to be already on the stack, so you can prepend `"testing" 4` to the above, for instance.

Test it here.

## Explanation

Notice that the transpose of the desired output is much simpler:

```
   testing
  testing
 testing
testing

```

So we just need to create `n` lines, prepending `i` spaces for `i` from `n-1` down to `0`. That's what the code does:

```
,            e# Turn n into a range [0 1 .. n-1]
 Sf*         e# Turn each i into a string of i spaces.
    \f+      e# Swap this array with the input string and append it to each of the
             e# strings of spaces.
       $     e# Sort the array to have the string with n-1 spaces first.
        z    e# Transpose the grid.
         N*  e# Join the lines with newline characters.

```

## 19 - 10 = 9?

I find the "sleeps a bit between each line" bonus a bit vague and dodgy, but here is a 19 byte version that simply stalls after each line by computing all permutations of the array `[0 1 .. 7]`. In the online interpreter this simply leads to the final result being shown a bit later, but if you use the Java interpreter this will actually print each line after "sleeping a bit":

```
,Sf*\f+$z{oNo8e!;}/

```

# Answer
> 16 votes
# C, 69 bytes

printf magic!

```
f(s,n,i)char*s;{for(i=n;*s;i?i--:s++)printf("%*s%.*s\n",i,"",n-i,s);}

```

Expanded version with some explanation:

```
f(s,n,i)char*s;{       /* s is the string, n is the width of the grid. */
  for(i=n;             /* i is the number of preceding spaces. */
      *s;              /* Stop once we reach the end of the string. */
      i?i--:s++)       /* Decrease the number of spaces, and when there's
                          none left start truncating the string itself. */
  printf("%*s          /* The first argument is the minimum width to print the
                          string (left padded with spaces) and the second
                          argument is the string to print. We use the empty
                          string just to print the i spaces. */
    %.*s              /* The third argument is the maximum number of
                         characters from the string (which is the fourth
                         argument) to print. */
    \n",i,"",n-i,s);
}

```

And here's an example:

```
$ ./marquee stackoverflow 12

           s
          st
         sta
        stac
       stack
      stacko
     stackov
    stackove
   stackover
  stackoverf
 stackoverfl
stackoverflo
tackoverflow
ackoverflow
ckoverflow
koverflow
overflow
verflow
erflow
rflow
flow
low
ow
w

```

# Answer
> 14 votes
# Pyth, 13 bytes

```
jb.:++K*dQzKQ

```

Try it online: Pyth Compiler/Executor

### Explanation

```
                 implicit: z = input string, Q = input number
      K*dQ       K = " " * Q
    ++K   zK     K + z + K
  .:        Q    all substrings of length Q
jb               join by newlines and print

```

# Answer
> 6 votes
## Python 65 63

```
s=lambda t,s:'\n'.join((' '*s+t)[i:s+i]for i in range(len(t)+s))

```

This was actually used to write the examples. Baseline solution.

```
>>> print(s("foobarz", 3))

  f
 fo
foo
oob
oba
bar
arz
rz
z

```

# Answer
> 6 votes
# Javascript (*ES7 Draft*), 61 bytes

```
f=(s,l)=>[x.substr(i,l)for(i in x=' '.repeat(l)+s)].join(`
`)
```

```
<input id="str" value="Some String" />
<input id="num" value="5" />
<button onclick="out.innerHTML=f(str.value, +num.value)">Run</button>
<br /><pre id="out"></pre>
```

# Javascript (*ES6*) Hardcoded Inputs, 47 bytes

Assuming hard-coded inputs in variables `s` (string) and `l` (length), it can be reduced to **47** bytes printing with an alert for each line:

```
for(i in x=' '.repeat(l)+s)alert(x.substr(i,l))

```

# Answer
> 5 votes
# K, 19 bytes

```
{x#'![1]\(x#" "),y}

```

Tack `x` spaces (`x#" "`) onto the beginning of the string `y`. Then use the "fixed-point scan" form of the operator `\` to create the set of rotated strings. A fixed-point in K stops iterating if the result of applying the function returns a repeated result or if the initial input is revisited. Since `![1]` will rotate a string one step at a time, `![1]\` is a nice idiom for cyclic permutations. Then we just trim the results with `x#'`.

A sample run:

```
  {x#'![1]\(x#" "),y}[4;"some text"]
("    "
 "   s"
 "  so"
 " som"
 "some"
 "ome "
 "me t"
 "e te"
 " tex"
 "text"
 "ext "
 "xt  "
 "t   ")

```

# Answer
> 5 votes
# Julia, 75 bytes

```
(s,n)->(n-=1;print(join([(" "^n*s*" "^n)[i:n+i]for i=1:length(s)+n],"\n")))

```

This creates an unnamed function that accepts a string and integer as input and prints the output. To call it, give it a name, e.g. `f=(s,n)->(...)`.

Ungolfed + explanation:

```
function f(s, n)
    # Decrement n by 1
    n -= 1

    # Construct the lines as an array using comprehension by repeatedly
    # extracting subsets of the input string padded with spaces
    lines = [(" "^n * s * " "^n)[i:n+i] for i = 1:length(s)+n]

    # Print the array elements separated by a newline
    print(join(lines, "\n"))
end

```

Examples:

```
julia> f("banana", 3)
  b
 ba
ban
ana
nan
ana
na
a

julia> f("Julia", 6)
     J
    Ju
   Jul
  Juli
 Julia
Julia
ulia
lia
ia
a

```

Note that this solution is 66 bytes if `s` and `n` are assumed to already exist in the program.

# Answer
> 5 votes
# J (22)

This ended up longer than I anticipated, but I guess it is not too bad.

```
[{."0 1[:]\.(' '#~[),]

```

Fun fact: non of the `[` and `]` are actually matched, or have anything to do with each other.

# Answer
> 5 votes
# QBasic, 56 - 10 = 46

This is golfed QBasic--the autoformatter will expand `?` into `PRINT` and add some spaces. Tested with QB64, though there shouldn't be anything in here that won't work with DOS QBasic.

```
s=SPACE$(n)+s
FOR i=1TO LEN(s)
?MID$(s,i,n)
SLEEP 1
NEXT

```

QBasic generally isn't good with string operations, but there very conveniently *is* a function that returns a given number of spaces!

Taking some liberties with "input may be hard-coded," this code expects the variable `s` to be `DIM`'d `AS STRING`, in order to avoid the `$` type suffix, as well as the string being assigned to `s` and the number to `n`.

Example preamble:

```
DIM s AS STRING
s="string"
n=4

```

Output:

```

   s
  st
 str
stri
trin
ring
ing
ng
g

```

The top blank row may be eliminated by starting the `FOR` loop at 2 instead of 1.

**Bonus:** Adding `CLS` right before `NEXT` for a paltry four bytes turns this into... a *real marquee*!

I `PRINT CHR$(3)` QBasic. :^D

# Answer
> 5 votes
# Ruby, 68, 55 bytes

```
a=" "*$*[1].to_i+$*[0]+" ";a.size.times{|b|puts a[b...b+$*[1].to_i]}

```

After an update from @blutorange:

```
a=" "*(z=$*[1].to_i)+$*[0];a.size.times{|b|puts a[b,z]}

```

Output:

```
         S
        So
       Som
      Some
     Somet
    Someth
   Somethi
  Somethin
 Something
Something
omething a
mething a
ething a b
thing a bi
hing a bit
ing a bit
ng a bit l
g a bit lo
 a bit lon
a bit long
 bit longe
bit longer
it longer
t longer
 longer
longer
onger
nger
ger
er
r

```

`ruby marquee.rb "Something a bit longer" 10`

First submission so asking for criticism.

# Answer
> 4 votes
# Haskell, ~~61~~ ~~59~~ 54 bytes

```
m n=unlines.scanr((take n.).(:))[].(replicate n ' '++)

```

Usage example:

```
*Main> putStr $ m 6 "stackoverflow"

     s
    st
   sta
  stac
 stack
stacko
tackov
ackove
ckover
koverf
overfl
verflo
erflow
rflow
flow
low
ow
w

*Main>

```

Edit: an empty line at the beginning / end is allowed

# Answer
> 4 votes
# Bash, 109 - 10 = 99 bytes

I see that in the time it took me to write my solution, I have been soundly beaten. Nevertheless, I spent too long writing it to not post it...

Besides which, it has some unique features, like the time between lines printing being user-adjustable based on how much is in the current directory! (Also somewhat inconsistent, depending on how your disk feels)

```
l=${#1};s=$1;for j in `seq 1 $2`;do s=" $s";done;for i in `seq 0 $((l+$2))`;do echo "${s:i:$2}";find 1>2;done

```

Example:

```
cd <some directory in which you own everything recursively>
Marquee.sh "Test Case" 4

   T
  Te
 Tes
Test
est
st C
t Ca
 Cas
Case
ase
se
e

```

Ungolfed and commented:

```
l=${#1} #Length of the incoming string
s=$1 #Can't reassign to the parameter variables, so give it another name
for j in `seq 1 $2`; do
    s=" $s" # Put on the padding spaces
done

for i in `seq 0 $((l+$2))`; do
    #Cut the string and print it. I wish I could lose "padding" that easily!
    echo "${s:i:$2}" #Format is ${string:index:length}, so always the same
    # length, with the index moving into the string as the loop advances
    find 1>2  #Wait "a bit". From ~/, about 6 minutes per line on my junky
    # computer with a huge home directory. Probably in the <1 sec range for
    # most people.
    #This actually has the same character count as sleep(X), but is much
    # more fun!
done

```

I've never really tried this before. Suggestions and comments welcome!

# Answer
> 4 votes
# Pure Bash, 61 bytes

```
printf -vs %$2s"$1"
for((;++i<${#1}+$2;)){
echo "${s:i:$2}"
}

```

### Output:

```
$ ./marquee.sh testing 4
   t
  te
 tes
test
esti
stin
ting
ing
ng
g
$

```

# Answer
> 3 votes
# Perl, 50

```
$c=$" x$^I;$_="$c$_$c";sleep say$1while(/(?<=(.{$^I}))/g)

```

`57` characters `+3` for `-i`, `-n` and `-l`. `-10` characters for the sleep.

`-i` is used for the numeric input, which is stored in `$^I`. Basically, we add `i` spaces to the front and end of the input, and then search for every `i` characters and loop through them with `while`. `say` conveniently returns `1` which we can input to `sleep`.

```
echo "testing" | perl -i4 -nlE'$c=$" x$^I;$_="$c$_$c";sleep say$1while(/(?<=(.{$^I}))/g)'

```

# Answer
> 3 votes
# Java, 133 ~~119~~ 115

```
int i;void f(String s,int n){for(;++i<n;)s=" "+s+" ";for(;i<=s.length();)System.out.println(s.substring(i-n,i++));}

```

Long version:

```
int i;
void f(String s, int n) {
    for(; ++i < n;)
        s = " " + s + " ";
    for(; i<=s.length();)
        System.out.println(s.substring(i-n, i++));
}

```

Padding is applied to the string, and then substrings of the padded string are printed to the console.

*-4 bytes thanks to @KevinCruijssen.*

# Answer
> 3 votes
# Python 2, (52 bytes - 10 = 42) ~~64~~ ~~62~~ ~~60~~ ~~46~~ ~~44~~

(I assumed the line for hard-coded input doesn't add to byte count.)

I didn't see a program yet that actually sleeps between printing lines, so I made one that does, since it looks more like a marquee that way. This program is 2 more bytes in Python 3.

EDIT: The program now does a computation instead of sleeping. I used `i` in the calculation so that the program doesn't store it as a constant, but must compute it each time.

**Try It Online!**

```
i=0
while s[i-n:]:print(' '*n+s)[i:n+i];i+=1;i**7**7

```

# Answer
> 3 votes
# POSIX shell, 94

```
[ $3 ]||set "`printf "%${2}s"`$1" $2 t
[ "$1" ]&&printf "%-.${2}s" "$1" "
"&&$0 "${1#?}" $2 t

```

I know it looks closer to perl, but this really is shell!

The first line adds the necessary leading spaces, only on the first time through the loop. It sets $3 to indicate that it has done so.

The second line (N.B. embedded newline) recurses until input is exhausted, printing the first *n* characters of the string, then invoking itself with the first character removed from $1.

Tested with Debian `/bin/dash` \- sample outputs follow:

./marquee "testing" 4

```
   t
  te
 tes
test
esti
stin
ting
ing
ng
g

```

./marquee "Something a bit longer" 10

```
         S
        So
       Som
      Some
     Somet
    Someth
   Somethi
  Somethin
 Something
Something
omething a
mething a
ething a b
thing a bi
hing a bit
ing a bit
ng a bit l
g a bit lo
 a bit lon
a bit long
 bit longe
bit longer
it longer
t longer
 longer
longer
onger
nger
ger
er
r

```

./marquee "small" 15

```
              s
             sm
            sma
           smal
          small
         small
        small
       small
      small
     small
    small
   small
  small
 small
small
mall
all
ll
l

```

# Answer
> 3 votes
# Python 2, 51 bytes / 37 bytes

**Without hardcoded input (51 bytes):**

```
def f(s,n):
 s=" "*n+s
 while s:print s[:n];s=s[1:]

```

Call like `f("testing", 4)`.

**With hardcoded input (37 bytes):**

```
s="testing";n=4

s=" "*n+s
while s:print s[:n];s=s[1:]

```

Both versions output an initial line of spaces.

# Answer
> 3 votes
# Pyth, 12 bytes

```
jb.:X*dyQQzQ

```

Demonstration.

---

# Pyth, 17 - 10 = 7 bytes

```
FN.:X*dyQQzQ&.p9N

```

This version employs a delay between line prints. This can be seen on the command line compiler, which you can get here.

Run the following:

```
pyth -c 'FN.:X*dyQQzQ&.p9N' <<< 'testing
4'

```

This has a delay of about 0.3 seconds before each print. If you prefer a longer delay, you can use:

```
FN.:X*dyQQzQ&.pTN

```

This has about a 4 second delay.

# Answer
> 3 votes
# Canvas, 3 bytes

```
＊／⤢

```

Try it here!

Input is string and integer (in either order) separated by a newline.

---

Explanation:

```
＊     | Repeat a b times vertically (a=string input, b=int input)
  ／   | Make antidiagonal (add one extra space to each line bottom up)
    ⤢　| Transpose (reflect along top-left to bottom-right diagonal)

```

# Answer
> 2 votes
# Matlab, 95

As always, it is a manipulation of matrices. The core here is the command `spdiags` which lets you create diagonal matrices very easily.

```
t=input('');
n=numel(t);
k=input('');
flipud(char(full(spdiags(repmat(t,n+k-1,1),1-n:0,n+k-1,k))))

```

With hardcoding 71 bytes (expected string stored in `t` and the number in `k`)

```
n=numel(t);flipud(char(full(spdiags(repmat(t,n+k-1,1),1-n:0,n+k-1,k))))

```

# Answer
> 2 votes
# APL, 50 - 10 = 40 chars

I'm sure it could be shorter. 50 is the length of the program without the two constants.

```
{⍵≡⍬:⍬⋄⎕←↑⍵⋄⎕DL 99⋄∇1↓⍵}⊂[0]⊖s⍴⍨n,¯1+⍴s←'brace yourself',' '⍴⍨n←6

```

Explanation:

```
                               ' '⍴⍨n←6   call the number 'n' and make n spaces
            s←'brace yourself',           append them to the string and call it 's'
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
                             s⍴⍨n,¯1+⍴s   make a len(s)-1 by n matrix by repeating s
                        ⊂[0]⊖             reflect the matrix and extract the columns
{                      }                  pass the list of columns to this function
 ⍵≡⍬:⍬⋄                                   return if the list is empty
       ⎕←↑⍵⋄                              print the first column (as a row)
            ⎕DL 99⋄                       wait for 99ms
                   ∇1↓⍵                   recurse with the rest of the columns

```

Developed for ngn APL on the terminal.

# Answer
> 2 votes
# Powershell - 85 83 bytes

It's late, it's not going to win :-) But I thought I'd throw in a Powershell one for completeness:

`function m($s,$n){1..$($n+$s.length)|%{-join(" "*$n+$s+" "*$n)[$_-1..$($n+$_-1)]}}`

# Answer
> 2 votes
# , ~~15~~ 14 bytes

```
,.~/@(' '&,~<)

```

Try it online!

# Answer
> 2 votes
# Add++, 38 bytes

```
L#,b]*ApR1€Ω_32C€*dbR@$BcB]€¦+bU@BcBJn

```

Try it online!

# Answer
> 2 votes
# Thunno 2 `N`, 8 bytes

```
L€ṣs+rðƬ

```

Try it online!

#### Explanation

```
L€ṣs+rðƬ  # Implicit input
L€ṣ       # Push [" " * 0, " " * 1, ..., " " * (n-1)]
   s+     # Prepend each to the input
     rðƬ  # Reverse and transpose with filler space
          # Implicit output, joined on newlines

```

# Answer
> 1 votes
# PHP4.1, 85-10=75 bytes

Yes, this is a **very** old version, but it has a functionality I need.
You can still run it in any more recent versions of PHP, but you need to set the variables yourself before running the code below.

That helps me to reduce the size of my code a lot!

It is really basic:

```
<?for($s=str_repeat(' ',$n).$s;$i++<strlen($s)+$n;sleep(1))echo substr($s,$i,$n),'
';

```

I ran for the bonus due to this, quoting O.P.:

> If your program is standalone (i.e. when run actually prints the lines) (Input can be hard-coded but easy to change) and sleeps a bit between each line of output you get a -10 bonus.

As you can obviously see, it has a sleep.

This assumes that you have `register_globals` enabled by default, which were the default settings for this version.

---

You can easily test in your browser, with ~~minimal~~ some changes:

```
//detects if it is running in js or php
//true for js, false for php
if('\0'=="\0")
{
 function strlen($s){
  return $s.length;
 }

 function str_repeat($s,$n){
  return Array($n+1).join($s);
 }

 function substr($s,$n,$m){
  return $s.substr($n,$m);
 }

 function printf($s){
  document.write($s);
 }

 function concat($a,$b){
  return $a+$b;
 }
}
else
{
 function concat($a,$b){
  return $a.$b;
 }
}

//sets the variables, not required for PHP if you pass the values by GET or POST
$i=0;
$s='example';
$n=6;

for($s=concat(str_repeat('-',$n),$s);$i++<strlen($s)+$n;)printf(concat(substr($s,$i,$n),'<br>'));
```

```
*{font-family:monospace}
```

The above code is a polyglot and you can run in your browser or in a PHP interpreter. Shouldn't I get a prize for this? A cookie, perhaps?

List of changes:

* Removed the `sleep(1)` in this test
* Created 2 versions of the function `concat`
The goal is to overcome PHP and JS differences in concatenating strings.
* Instead of a space, a `-` is used to fill the space
* Instead of `echo`, `printf` is uses instead (PHP limitation)
* Instead or a 'real' newline, `<br>` is uses instead

# Answer
> 1 votes
# Cobra - 60

```
def f(n,s)
    s=' '.repeat(n)+s
    while''<s,print (s=s[1:])[:n]

```

# Answer
> 1 votes
# Groovy - 82

```
n=args[1]as int;t=" "*n+args[0]+" "*n;(0..t.size()-n).each{println t[it..it+n-1]}

```

# Answer
> 1 votes
# Lua, 79 bytes

```
r=io.read;t=r()w=r()s=" "t=s:rep(w)..t;for i=1,t:len()do print(t:sub(i,i+w))end

```

# Answer
> 1 votes
# C#, 112 bytes

```
s=>n=>{var r=new string(' ',n-1);s=r+s+r;r="";for(int i=0;i<s.Length-n+1;)r+=s.Substring(i++,n)+"\n";return r;};

```

Full program with ungolfed method and test cases:

```
using System;

namespace FakeMarqueeText
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,Func<int,string>>f= s=>n=>
            {
                var r=new string(' ',n-1);
                s=r+s+r;
                r="";
                for(int i=0;i<s.Length-n+1;)
                    r+=s.Substring(i++,n)+"\n";

                return r;
            };

            // test cases:
            Console.WriteLine(f("testing")(4));
            Console.WriteLine(f("hello")(2));
            Console.WriteLine(f("foobarz")(3));
            Console.WriteLine(f("Something a bit longer")(10));
            Console.WriteLine(f("small")(15));
            Console.WriteLine(f("aaa")(3));
            Console.WriteLine(f("brace yourself")(6));

        }
    }
}

```

# Answer
> 1 votes
# Charcoal, 7 bytes

```
ＦＮ«Ｐ↓η↗

```

Try it online!

# Answer
> 1 votes
# Jelly, 15 bytes - 10 = 5 (non-competing?)

```
ḶṚ⁶ẋ;€⁹ZṄœS$€ṛ“

```

Try it online!

Sleeps for a second between each line. Prints a trailing newline, if that's acceptable.

<sup>yay Jelly beats Charcoal</sup>

# Answer
> 1 votes
# APL (Dyalog), 17 bytes

```
⌽⍉↑(⎕,⍨' '/⍨⊢)¨⍳⎕

```

Try it online!

(the program assumes `⎕IO←0` which is default on many machines)

### Explanation

```
⍳⎕               Create a range 0 .. input-1
¨                For each element in this range do:
 ' '/⍨⊢           A space duplicated right argument (which is the element in  the range) times
 ⎕,⍨              Concatenated with the input string to its right
⌽⍉               Transpose and reflect horizontally

```

# Answer
> 1 votes
# Python 3, 62 bytes

Definitely think it can be golfed further, particularly with the for loop notation.

Unfortunately I'm not that fluent with Python yet, maybe someone here can help.

```
def f(s,n):
 s=n*" "+s
 for i in range(len(s)):print(s[i:i+n])

```

Try it online!

I hope leading spaces are allowed.

# Answer
> 1 votes
# PowerShell, 60 bytes

```
param($s,$n)($t=' '*--$n+$s)|% t*y|%{-join$t[$i..($i+++$n)]}

```

Try it online!

# Answer
> 1 votes
# Japt `-R`, 7 bytes

```
VÆiYîÃz

```

Run it online

# Answer
> 1 votes
# Nibbles, 6.5 bytes (13 nibbles)

```
`'.\`,$:^$" "_

```

Transpose approach copied from The Thonnu's Thunno 2 answer.

```
    `,          # list of 0..
                #   arg1-1
   \            # reversed
  .             # map over this
       :        # append
             _  # arg2 onto
        ^$      # that many
          " "   # spaces
`'              # and then transpose it all

```

# Answer
> 0 votes
# Google Sheets, 79 bytes

```
=ARRAYFORMULA(JOIN("
",MID(REPT(" ",A2)&A1,ROW(OFFSET(A2,0,0,LEN(A1)+A2)),A2)))

```

Text is input in cell `A1` and the marquee width is in cell `A2`.
`ARRARYFORMULA` \+ `ROW(OFFSET())` lets us return multiple values into the `MID` function.
After that, all we do is return `A2` characters from the middle of the text prepended with spaces as needed.
`JOIN` combines them all with a line break in between each.

Sample outputs:

<sub>I expected this challenge to require clearing the screen so it looks like a marquee in place but, as it (currently) doesn't, I think this answer is valid.</sub>

# Answer
> 0 votes
# T-SQL, 110 bytes

```
DECLARE @n INT,@ CHAR(99)SELECT @n=n,@=space(@n)+s FROM t
L:SET @=RIGHT(@,98)PRINT LEFT(@,@n)IF LEN(@)>0GOTO L

```

Input is via pre-existing table **t** with columns **n** (INT) and **s** (CHAR), per our IO standards.

Formatted:

```
DECLARE @n INT, @ CHAR(99)
SELECT @n=n, @=space(@n)+s FROM t
L:
    SET @=RIGHT(@,98)
    PRINT LEFT(@,@n)
IF LEN(@)>0 GOTO L

```

The question didn't specify the range of values my code had to handle; it works for all given samples, but will cut off the text if `n + len(s)` exceeds 99. To handle huge values of `n` and much longer strings without cutting off, add two bytes by changing `99` to `999` and `98` to `998`.

# Answer
> 0 votes
# Perl 5, 43

53 bytes - 10 bonus

```
push@F,($")x($t=<>);sleep say@F[$_-$t..$_-1]for 1..@F

```

Try it online!

# Answer
> 0 votes
# GolfScript, 20 bytes

```
~.' '*@+{.2$<p(;.}do

```

Try it online!

It prints the length at the end, due to it still being on the stack and implicit printing. I like to think of it as a feature, sort of like its a spelling bee ;)

Really taking the "input can be hardcoded but easy to change" to heart, I managed to get it down to only 17 bytes:

```
' '*\+{.b<p(;.}do

```

Try it online!

Input is appended to the stack, in addition to the size being stored in a variable. The main issue was organizing the stack because the length is needed once to create a string of spaces, then it is also needed every loop cycle in order to truncate the string to the correct length. This adds 1 char for duplicating it, one to rotate the stack, and another to duplicate the length every loop cycle.

# Answer
> 0 votes
# Zsh, 42 bytes

```
s=${(l:$2:)}$1;eval '<<<${s:'{1..$#s}:$2\}

```

Try it online!

# Answer
> 0 votes
# Vyxal `L`, 5 bytes

```
*/¹ɾ꘍

```

Try it Online!

Wow it's been way too long since I last used vertical join. Takes n then the string.

## Explained

```
*/¹ɾ꘍
*      # Repeat the string n times
 /     # And split into n chunks
  ¹ɾ꘍  # append [1, n] spaces to each chunk (pairwise vectorised)
# The L flag transposes then joins on newlines.

```

Created with the help of Luminespire.

Now you're probably wondering why there's such a specific flag. Well that's because it's a shortcut for having `§` at the end of the program. `§` is a built-in that transposes then joins on newlines.

Now you're probably wondering why there's such a specific built-in. Well that's because back in 2020 when I first added it, apparently I thought it was a useful enough thing that it was worth adding.

---
Tags: code-golf, string
---


title: Efficient censorship

text:
# Question
Title: Efficient censorship
*This challenge was originally posted on codidact.*

---

You are a low-level censor working for the *Ministry of Media Accuracy*. Part of your job is to make sure that certain words don't appear in publications. Every morning you get a fresh stack of next week's newspapers and its your job to comb through them and fix any of the words that were mistakenly included. A naive censor might simply remove the entire word completely, but you know that if you remove part of the word that still prevents the word from appearing in print. So for you it is a point of pride to remove as little of the offending word as possible while still ensuring it does not appear in print.

## Task

Given non-empty strings \\$X\\$ and \\$Y\\$ output the longest substring of \\$X\\$ which does not contain \\$Y\\$ as a *contiguous* substring

This is code-golf so the goal is to minimize the size of your source code as measured in bytes.

## Test cases

For each input output pair a *possible* correct output is given, your output should always be the same length, but it is not necessary to reproduce these outputs exactly.

```
chat, cat -> chat
escathe, cat -> esathe
homology, o -> hmlgy
ccatt, cat -> cctt
aababbabab, abab -> aaabbbab
ababab, abab -> abbab
aaaaaaaa, aaa -> aa
a, a ->

```

# Answer
> 5 votes
# Python 3, 86 bytes

```
f=lambda s,t,i=0:s if t not in s else max([f(s[:i]+s[(i:=i+1):],t)for x in s],key=len)

```

Attempt This Online!

## Ungolfed and commented

```
def f(s, t):
    if t not in s: # return s if it's valid (ie. doesn't contain t)
        return s
    return max([ # recurse on all substrings with 1 character removed
        f(
            s[:i] + s[i+1:], # s without the character at index i
            t
        )
        for i in range(len(s))
    ], key=len) # find the longest valid substring

```

# Answer
> 5 votes
# Jelly, 6 bytes

```
ŒPwÐḟṪ

```

Try It Online!

## Explanation

```
ŒPwÐḟṪ    Main Link
ŒP        Powerset (all subsequences) of the left argument
   Ðḟ     Filter where falsy:
  w       The sublist index of the right argument (0 if not found)
     Ṫ    Tail (Last Element) - powerset generates in increasing order of length

```

# Answer
> 3 votes
# Vyxal, 8 bytes

```
ṗ'⁰c¬;ÞG

```

Try it Online!

```
      ÞG # Longest
ṗ        # Subsequence of input
 '   ;   # Which
    ¬    # Does not
   c     # Contain
  ⁰      # The other input

```

# Answer
> 1 votes
# Python3, 108 bytes

```
lambda x,y:max(f(x,y),key=len)
f=lambda x,y,r='':[r]*(y not in r)if''==x else f(x[1:],y,r)+f(x[1:],y,r+x[0])

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 52 bytes

```
+%`(.),
,$'¶$`,$1
Ar`\1.* (.+)$
O^#$`
$.&
,| .+

1G`

```

Try it online! Link includes test cases. Assumes that the strings don't contain commas or spaces. Explanation:

```
+%`(.),
,$'¶$`,$1

```

Generate all subsequences of the first input.

```
Ar`\1.* (.+)$

```

Delete those that contain the second input.

```
O^#$`
$.&

```

Sort the remainder in descending order of length.

```
,| .+

```

Delete the second input.

```
1G`

```

Keep only the longest subsequence.

# Answer
> 1 votes
# Scala 3, 141 bytes

Port of @SuperStormer's Python answer in Scala.

---

Golfed version. Attempt this online!

```
def f(s:String,t:String):String={if(!s.contains(t))s;else{(0 until s.length).map{i=>f(s.substring(0,i)+s.substring(i+1),t)}.maxBy(_.length)}}

```

Ungolfed version. Attempt this online!

```
object Main extends App {

  def removeLongestSubstring(s: String, t: String): String = {
    if (!s.contains(t)) s
    else {
      (0 until s.length).map { i =>
        removeLongestSubstring(s.substring(0, i) + s.substring(i + 1), t)
      }.maxBy(_.length)
    }
  }

  val testCases = List(
    ("chat", "cat", "chat"),
    ("escathe", "cat", "esathe"),
    ("homology", "o", "hmlgy"),
    ("ccatt", "cat", "cctt"),
    ("aababbabab", "abab", "aaabbbab"),
    ("ababab", "abab", "abbab"),
    ("aaaaaaaa", "aaa", "aa")
  )

  for ((s, t, o) <- testCases) {
    println(s"$s $t ${removeLongestSubstring(s, t)} $o")
  }
}

```

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
æéR.ΔIå≠

```

Try it online or verify all test cases.

**Explanation:**

```
æ         # Get the powerset of the first (implicit) input-string
 é        # Sort it by length (shortest to longest)
  R       # Reverse it, so it's sorted from longest to shortest
   .Δ     # Find the first string that's truthy for:
       ≠  #  Check that the current powerset-string does NOT
      å   #  contain
     I    #  the second input-string
          # (after which the found result is output implicitly)

```

The `R.Δ...` could alternatively be `ʒ...}θ` (filter, and keep last item after the filter) for the same byte-count.

# Answer
> 0 votes
# Charcoal, 26 bytes

```
⊟⌈ＥΦＥＸ²ＬθΦθ﹪÷ιＸ²μ²¬№ιη⟦Ｌιι

```

Try it online! Link is to verbose version of code. Explanation:

```
      ²                     Literal integer `2`
     Ｘ                      Raised to power
        θ                   First input
       Ｌ                    Length
    Ｅ                       Map over implicit range
          θ                 First input
         Φ                  Filtered where
             ι              Outer value
            ÷               Integer divided by
               ²            Literal integer `2`
              Ｘ             Raised to power
                μ           Inner index
           ﹪     ²          Is odd
   Φ                        Filter over subsequences where
                    ι       Current subsequence
                  ¬№        Does not include
                     η      Second input
  Ｅ                         Map over remaining subsequences
                        ι   Current subsequence
                       Ｌ    Length
                         ι  Current subsequence
                      ⟦     Make into list
 ⌈                          Get a subsequence with the longest length
⊟                           Get the subsequence
                            Implicitly print

```

# Answer
> 0 votes
# JavaScript (ES12), 76 bytes

Expects `(Y)(X)`.

```
y=>o=g=([c,...x],s='')=>c?g(x,s+c)|g(x,s)||o:o=s.match(y)||o?.[s.length]?o:s

```

Attempt This Online!

### Commented

```
y =>                // y = forbidden word
o =                 // o = output, initially not a string
g = (               // g is a recursive function taking:
  [ c,              //   c = next character from the input text
       ...x ],      //   x[] = remaining characters
  s = ''            //   s = censored text
) =>                //
c ?                 // if c is defined:
  g(x, s + c) |     //   do a 1st recursive call with c added to s
  g(x, s) ||        //   do a 2nd recursive call with s unchanged
  o                 //   eventually return o
:                   // else:
  o =               //   update o:
    s.match(y) ||   //     if s contains y
    o?.[s.length] ? //     or o is a string longer than s:
      o             //       leave o unchanged
    :               //     else:
      s             //       update o to s

```

# Answer
> 0 votes
# Haskell, 161 bytes

```
c=concatMap
l=length
[]%y=y/=[]
x%y=(l x<l y||or(zipWith(/=)x y))&&tail x%y
r[]=[]
r(x:y)=y:map(x:)(r y)
x#0=[x]
x#n=c r$x#(n-1)
x!y=head$c(filter(%y).(x#))[0..]

```

Attempt This Online!

# Answer
> 0 votes
# JavaScript (Node.js), 74 bytes

```
y=>g=([c,...x],s=o='')=>c?g(x,s+c)|g(x,s)||o:o=s[s.match(y)||o.length]?s:o

```

Attempt This Online!

Optimized from Arnauld's

# JavaScript (Node.js), 76 bytes

```
S=>g=(T,...U)=>T.join``.match(S)?g(...U,...T.map((_,i)=>T.filter(_=>i--))):T

```

Try it online!

Same length as Arnauld's but worse at almost all other ways

# Answer
> 0 votes
# Thunno 2 `t`, 7 bytes

```
ʠþlæ¹Ƈ}

```

Try it online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
ʠþlæ¹Ƈ}  # Implicit input
ʠ        # Powerset of the first input
 þl      # Sort it by length
   æ  }  # Remove items which:
    ¹Ƈ   #  Contain the second input
         # Implicit output of last item

```

# Answer
> 0 votes
# Pyth, 7 bytes

```
ef!}zTy

```

Try it online!

### Explanation

```
ef!}zTyQ    # implicitly add Q
            # implicitly assign Q=eval(input()); z=input()
      yQ    # powerset of Q
 f          # filter on lambda T
  !}zT      #   z not in T
e           #   last element (longest)

```

---
Tags: code-golf, string
---


title: Collatz's ice cream cone factory

text:
# Question
Title: Collatz's ice cream cone factory
# The Collatz sequence

Given a positive integer \\$a\_1\\$, the Collatz sequence with starting value \\$a\_1\\$ is defined as \begin{equation} a\_{n+1} = \begin{cases} a\_n/2 & \mathrm{if}\ a\_n\ \mathrm{is}\ \mathrm{even} \\ 3a\_n+1 & \mathrm{if}\ a\_n\ \mathrm{is}\ \mathrm{odd}. \end{cases} \end{equation} It is conjectured that, for any starting value, this sequence always reaches the number \\$1\\$. This challenge assumes that the conjecture is true.

# The challenge

Given an integer \\$a\_1 \> 2\\$, compute the Collatz sequence until \\$1\\$ is reached for the first time. Let \\$N\\$ be the number of sequence terms (including \\$a\_1\\$ and \\$a\_N = 1\\$). From the sequence of numbers \begin{equation} a\_1, a\_2, a\_3, \ldots, a\_N \end{equation} form a sequence of points in the plane by taking all pairs of consecutive terms \begin{equation} (a\_1, a\_2), (a\_2, a\_3), \ldots, (a\_{N-1}, a\_N) \end{equation} and plot these points on a 2D graph, joining consecutive points by a line segment.

# Example

For input \\$12\\$ the Collatz sequence is (\\$10\\$ terms); \begin{equation} 12, 6, 3, 10, 5, 16, 8, 4, 2, 1. \end{equation} The sequence of points is (\\$9\\$ points): \begin{equation} (12, 6), (6, 3), (3, 10), (10, 5), (5, 16), (16, 8), (8, 4), (4, 2), (2, 1). \end{equation} The plot contains \\$8\\$ line segments, as shown in the following graph. Note that some of the segments partially overlap. For clarity, the plot includes markers at the \\$9\\$ points.

# Additional rules

* Graphical output is required, with output being flexible as usual.
* Only the straight lines are required in the graph. Line width is flexible, as long as the plot can be seen reasonably well. Line color is also flexible, and may be different for each segment, as long as lines are distinguishable from the background.
* Other elements in the graph are not required, but are allowed (point markers, grid lines, axis labels, ...).
* Horizontal and vertical axis scales need not be the same. Axis limits are arbitrary, as long as the graph can be seen fully and clearly. The axes may be swapped, and each axis may be reversed.
* The code should work for any input given unlimited resources. It is acceptable if in practice it fails for large inputs due to time, memory or data-type limitations.
* If the input happens to be a counterexample for the Collatz conjecture the code can do anything, such as get stuck in an infinite loop or order a pizza.
* Programs or functions are accepted. Standard loopholes are forbidden.
* Shortest code in bytes wins.

# Test cases

| Input | Output |
| --- | --- |
| `3` |  |
| `4` |  |
| `27` |  |
| `649` |  |
| `650` |  |
| `46720` |  |
| `345435` |  |
| `63728127` |  |

# Answer
# Jelly, 35 bytes

```
r0×€:⁸
×3‘ƊHḂ?Ƭ;Ɲ_/AÞṪçƊ+ṪƲƝẎŒṬx€€3

```

Try it online!

A pair of links that takes an integer argument and returns an RGB matrix on the (0 to 1) scale. Approach is the same as PBM output below but loses some bytes from the simpler output format.

---

# Previous PBM answer Jelly, ~~49~~ 44 bytes

```
r0×€:⁸
×3‘ƊHḂ?Ƭ;Ɲ_/AÞṪçƊ+ṪƲƝẎŒṬµZL;L;FKṭ“P1

```

Try it online!

A full program that takes an integer argument and prints the contents of a PBM file.

Thanks to @cairdcoinheringaahing for some nice golfs totally 5 bytes!

## Example for 22:

---

# Original SVG-based answer: Jelly, 83 bytes

```
×3‘ƊHḂ?Ị¬$Ð¿µj”,$ƝKṭṀ,`$“¡×ȯFṗẓ"az⁺Ṭ*,ġẎlḣḂ⁷Ọ]Ẏɦ?÷hṖF.IØṣƘŻÇÄ<,Ḥ:ẆṡṂȮXȷḷ[eʂmJ]»Ỵ¤;"

```

Try it online!

A full program taking an integer argument and printing an SVG.

For example, with 45:

```
<svg width="136" height="136"><path stroke="red" fill="none" d="M45,136 136,68 68,34 34,17 17,52 52,26 26,13 13,40 40,20 20,10 10,5 5,16 16,8 8,4 4,2 2,1"/></svg>

```
> 7 votes

# Answer
# Python 3.8 with turtle, ~~156~~ 127 bytes

Thanks to Noodle9 for catching a mistake!

```
from turtle import*
def f(n,x=0):
 while~-n:goto(w:=n,n:=[n//2,3*n+1][n%2]);x<1!=clear();setworldcoordinates(0,0,x:=max(x,n),x)

```

Animation for \\$a\_1=27\\$:
> 16 votes

# Answer
# , 52 bytes

```
load 'plot'
f=:[:plot[:(}:;}.)(2&|{-:,1+*&3)^:(>&1)^:a:

```

Try it online!

Wasn't sure if loading the graphics lib counted towards byte count, so I included it.

Here's an image of calling `f 27` in the J console:
> 9 votes

# Answer
# \>= 4.1, ~~81~~ 74 bytes

```
\(x,y=x){while(x>1)y=c(y,x<-c(x/2,3*x+1)[x%%2+1]);plot(y,c(y[-1],NA),"l")}

```

Try it at RDRR.io!

Note this uses RDRR because TIO doesn’t support graphical output. It also uses `function` in place of `\` since RDRR doesn’t support R 4.1.0 yet.

Thanks to @DominicVanEssen for saving 7 bytes!
> 7 votes

# Answer
# Wolfram Language (Mathematica), 70 bytes

```
Graphics@Line@Last@Reap[#//.a_/;a>1:>Last@Sow@{a,If[2∣a,a/2,3a+1]}]&

```

-17 bytes from @att

`63728127`
> 6 votes

# Answer
# Julia using GR, 121 99 77 bytes

Even better version by @MarcMush:

```
using GR
!x=while(X=x[end])>1 plot([x;],(x=[x;X%2>0 ? 3X+1 : X/2])[2:end])end

```

Improved version thanks to the tips found here:

```
using GR
c(a)=(i=1;while a[i]>1 a=[a;%(a[i],2)>0 ? 3a[i]+1 : a[i]/2];i+=1end;plot(a[1:i-1],a[2:i]))

```

What has been done:

* single-line notation for functions -10 bytes
* replace `push!` by array concatenation -3 bytes
* use input `a` as array - 6 bytes
* replace `end` by variable `i` that stores the length -3 bytes

Original version:

```
using GR
function c(x) a=[x]
while a[end]>1 push!(a,%(a[end],2)>0 ? 3a[end]+1 : a[end]/2)end
plot(a[1:end-1],a[2:end])end

```

Calling `c(27)` gives:
> 6 votes

# Answer
# SageMath, ~~81~~ \\$\cdots\\$ ~~74~~ 71 bytes

Saved 3 bytes thanks to dingledooper!!!

```
f=lambda n,*r:n-1and f(c:=[n/2,3*n+1][n%2],*r,(n,c))or list_plot(r,1<2)

```

Try it online!

### f(63728127)
> 4 votes

# Answer
# Red, ~~230~~ 212 bytes

```
func[n][a: to[]n while[n > 1][append a n: either odd? n[3 * n + 1][n / 2]]to-pair m: last sort copy a view[base 500x500 draw append[line]collect[while[a/2][keep as-pair a/1 / m * 500(first a: next a)/ m * 500]]]]

```

Try it online!

I don't know if red has a scalable plotting mechanism, but this was what I managed to get using the draw dialect. All outputs are scaled to 500x500 and there may be some inaccuracies for larger inputs due to downscaling and pairs being integers.

In the red interpreter, you will have to redefine the function before each run because the words get messed up.

-4 after using default axes.

-18 bytes from Galen Ivanov.

## Output(n=12) (old)
> 4 votes

# Answer
# Factor \+ `ui.gadgets.charts ui.gadgets.charts.lines math.unicode`, ~~208~~ ~~204~~ 199 bytes

```
[ [ [ 3 dupn , odd? [ 3 * 1 + ] [ 2/ ] if dup 1 ≠ ] loop , ] f make chart new over supremum 1 + '[ 0 _ ] dup 2array >>axes line new COLOR: red >>color rot 2 clump >>data add-gadget "" open-window ]

```

It's quotation (anonymous function) that accepts an integer from the data stack and opens a window with the chart in it. This only works in recent-ish builds of Factor, as the `chart` gadget is fairly new; I used build `2074`. Here's what it looks like for an input of `27`:

Unfortunately, the `chart` gadget doesn't come with any constructors. It requires us to manually calculate axes, and build its subcomponents which themselves don't come with any constructors. This leads to a bit of verbosity.
> 3 votes

# Answer
# Python 3 \+ matplotlib, 127 bytes

```
def f(n,r=[]):
 k=n
 while ~-n:n=[n//2,3*n+1][n%2];r+=[n]
 p.plot(*zip(*[[k]+r,r]),'-o');p.show()
import matplotlib.pyplot as p

```

-5 bytes thanks to @ovs!!!
> 3 votes

# Answer
# HTML + JS, 166 bytes

JS: 156 bytes

HTML: 14 bytes

This is a pretty basic implementation that renders to the DOM using an HTML canvas. A good chunk of the code is spent scaling the output to fit within the canvas. Anyone got any better ideas to handle this?

The input is specified inline in the code, set the number inside `x=[...]`.

```
x=[9];c=C.getContext`2d`;c.beginPath();while((z=x[0])-1)x.unshift(z%2?3*z+1:z/2);r=Math.max(...x)/99;x.map((a,i)=>c.lineTo(a/r,99-x[i-1]/r));c.stroke()
```

```
<canvas id=C>
```
> 3 votes

# Answer
# MATLAB 1999, ~~95~~ 84 bytes

-1 from Luis Mendo

```
n=input('');i=n;while i>1;i=(i+mod(i,2)*(5*i+2))/2;n=[n;i];end;plot([0/0;n],[n;0/0])

```

Even `A(2:)` and A(2:-1)\` was unavailable at that time...
> 2 votes

# Answer
# Python + Pygame, 228 bytes

```
from pygame import*
d=display
n=int(input())
k=[]
while n>1:k+=[[n,n:=[n//2,3*n+1][n%2]]]
M=max(k)[0]
S=500
g=lambda s:[S*s[0]/M,S*s[1]/M]
s=d.set_mode([S,S])
for i,j in enumerate(k):draw.line(s,[99]*3,g(k[i-1]),g(j))
d.update()

```

No TIO link because Pygame is not supported there.

Reversed y-axis.

I could save one byte by setting `S` to 99 or something, but I chose not to for easier viewing. I could also change `[99]*3` to `[9]*3` but I chose not to for easier viewing.

Here is an example for input 63728127:
> 1 votes

---
Tags: code-golf, number, arithmetic, integer, graphical-output
---


title: Round up to a smoother number

text:
# Question
Title: Round up to a smoother number
# Input

Two positive integers `a > b`

# Output

The smallest integer `c >= a` so that `c` can be factored into two parts with one part an integer power of two (that is at least two) and the other part no larger than `b`.

# Examples

If `b = 100` and `a = 101` , then the output should be 102 as 102 is 2 times 51.

For the same `b`, if `a = 201` then the output should be 204 as that equals 4 times 51.

For the same `b`, if `a = 256` then the output should be 256.

# Answer
> 11 votes
# JavaScript (ES6), 27 bytes

Expects `(b)(a)` as either numbers or BigInts (ES11).

```
b=>g=a=>a/(a&-a)>b?g(-~a):a

```

Try it online!

### How?

We recursively increment `a` while `a / (a & -a)` is greater than `b`.

The bitwise trick `a & -a` isolates the least significant `1` in the binary representation of `a`, i.e. the largest divisor or `a` which is a power of 2.

# Answer
> 5 votes
# 05AB1E (legacy), 8 bytes

```
L/.²îoƶß

```

Try it online!

# 05AB1E, 9 bytes

```
L/.²îïoƶß

```

Try it online!

`ï` is now needed due to a bug, since `o` takes forever without it.

## Explanation

Goes over all possible values \\$d\\$ in \\$c = d 2^s\\$, by looking at the first power of \\$2\\$ which is \\$\geq \lceil \frac a d \rceil\\$.

```
L       range [1, 2, 3, ..., b]
/       [a/1, a/2, a/3, ..., a/b]
.²      [log2(a/1), log2(a/2), ..., log2(a/b)]
î       [ceil(log2(a/1)), ceil(log2(a/2)), ..., ceil(log2(a/b))]
o       [2^ceil(log2(a/1)), 2^ceil(log2(a/2)), ..., 2^ceil(log2(a/b))]
ƶ       [1*2^ceil(log2(a/1)), 2*2^ceil(log2(a/2)), ..., b*2^ceil(log2(a/b))]
ß       min([1*2^ceil(log2(a/1)), 2*2^ceil(log2(a/2)), ..., b*2^ceil(log2(a/b))])

```

# Answer
> 3 votes
# Scala, ~~38~~ 37 bytes

Saved 1 byte thanks to the comment of @xnor

Try it online!

```
(b,a)=>if((a/(-a&a))>b)f(b,a+1)else a

```

# Answer
> 3 votes
# Thunno 2 `M`, 9 bytes

```
R/Æḷ€ṃOż×

```

Try it online!

Port of Command Master's 05AB1E answer.

#### Explanation

```
R/Æḷ€ṃOż×  # Implicit input
R/         # Divide b by [1..a]
  Æḷ       # Log base 2 of each
    €ṃ     # Ceiling of each
      O    # Two power of each
       ż×  # Multiply by index
           # Take the minimum
           # Implicit output

```

# Answer
> 2 votes
# JavaScript, 46 bytes

```
o=a=>a&1n?a:o(a/2n)
f=(a,b)=>o(a)<b?a:f(++a,b)

```

takes big integers as Input

Attempt This Online!

## Explanation

`o` gets the odd part of a number (product of all odd prime factors)

`f` increments `a` until its odd part is less than `b`

# Answer
> 2 votes
# Charcoal, 21 bytes

```
Ｎθ≔±Ｘ²Ｌ↨⊕÷θ±Ｎ²ζＩ×ζ÷θζ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｎθ

```

Input `a`.

```
≔±Ｘ²Ｌ↨⊕÷θ±Ｎ²ζ

```

Calculate the smallest power of `2` not less than `a/b`.

```
Ｉ×ζ÷θζ

```

Round `a` up to that power of `2`.

# Answer
> 2 votes
# Jelly, 9 bytes

```
Họ¡2’<ð1#

```

A dyadic Link that accepts \\$a\\$ on the left and \\$b\\$ on the right and yields \\$c\\$ as a singleton list. Alternatively, a full program that prints the result.

**Try it online!**

### How?

```
Họ¡2’<ð1# - Link: integer, a; integer b
       1# - starting at k=a and incrementing find the first k for which:
      ð   -   dyadic chain - f(k, b):
  ¡       -     repeat...
 ọ 2      -     ...times: order-multiplicity 2
H         -     ...action: halve
                  -> divides k by two until we have an odd number
    ’     -     decrement
     <    -     is less than {b}? (i.e. k <= b ?)

```

---

Same method `Bt0Ḅ’<ð1#` or `BTṬḄ’<ð1#` \- remove trailing zeros from the binary representation and convert back.

# Answer
> 2 votes
# Nekomata \+ `-1`, 7 bytes

```
Ň+ᵖ{ʷ½≥

```

Attempt This Online!

```
Ň+ᵖ{ʷ½≥
Ň           Find a natural number
 +          Plus the first input
  ᵖ{        Check that:
    ʷ½        Repeatedly divide by 2 until the number is odd
      ≥       The second input is greater than or equal to the result

```

`-1` prints the first solution.

# Answer
> 1 votes
# Vyxal `g`, 57 bitsv2, 7.125 bytes

```
ɾ/2•⌈EÞż

```

Try it Online!

Ports the 05AB1E answer.

# Answer
> 1 votes
# C89, 36 bytes

*port of Arnauld's JavaScript (ES6) answer.*

```
f(a,b){return(a&-a)*b<a?f(a+1,b):a;}

```

Try it online!

---

# C (gcc), 30 bytes

*ommiting the return statement and the unchanged trailling parameter in the recursive call*

```
f(a,b){a=(a&-a)*b<a?f(a+1):a;}

```

Try it online!

# Answer
> 1 votes
# Desmos, 41 bytes

```
f(a,b)=min(2^{ceil(log_2a/L)}L)
L=[1...b]

```

Try It On Desmos!

Try It On Desmos! - Prettified

Port of 05AB1E

---
Tags: code-golf
---


title: Near miss prime multiples

text:
# Question
Title: Near miss prime multiples
*This challenge was originally posted on codidact.*

---

Given a number \\$n \geq 3\\$ as input output the smallest number \\$k\\$ such that the modular residues of \\$k\\$ by the first \\$n\\$ primes is exactly \\$\\{-1,0,1\\}\\$.

That is, there are three primes in the first \\$n\\$ primes, so that prime 1 divides \\$k\\$, prime 2 divides \\$k+1\\$ and prime 3 divides \\$k-1\\$, *and* every prime in the first \\$n\\$ primes divides one of those three values.

For example if \\$n=5\\$, the first \\$5\\$ primes are \\$2, 3, 5, 7, 11\\$ the value must be at least \\$10\\$ since with anything smaller \\$11\\$ is an issue. So we start with \\$10\\$:

$$ 10 \equiv 0 \mod 2 $$ $$ 10 \equiv 1 \mod 3 $$ $$ 10 \equiv 0 \mod 5 $$ $$ 10 \equiv 3 \mod 7 $$

Since \\$10 \mod 7 \equiv 3\\$, \\$10\\$ is not a solution so we try the next number.

* \\$11 \equiv 4\mod 7\\$ so we try the next number.
* \\$12 \equiv 2\mod 5\\$, so we try the next number.
* \\$13 \equiv 3\mod 5\\$, so we try the next number.
* \\$14 \equiv 3\mod 11\\$, so we try the next number.
* \\$15 \equiv 4\mod 11\\$, so we try the next number.
* \\$16 \equiv 2\mod 7\\$, so we try the next number.
* \\$17 \equiv 2\mod 5\\$, so we try the next number.
* \\$18 \equiv 3\mod 5\\$, so we try the next number.
* \\$19 \equiv 5\mod 7\\$, so we try the next number.
* \\$20 \equiv 9\mod 11\\$, so we try the next number.

$$ 21 \equiv 1 \mod 2 $$ $$ 21 \equiv 0 \mod 3 $$ $$ 21 \equiv 1 \mod 5 $$ $$ 21 \equiv 0 \mod 7 $$ $$ 21 \equiv -1 \mod 11 $$

21 satisfies the property so its the answer.

## Task

Take as input \\$n \geq 3\\$ and give as output the smallest number satisfying.

This is . The goal is to minimize the size of your source code as measured in bytes

## Test cases

```
3 -> 4
4 -> 6
5 -> 21
6 -> 155
7 -> 441

```

# Answer
> 4 votes
# Jelly, 11 bytes

```
%Ṁ=2ʋ1#ÆN€’

```

Try it online!

```
     1#        Find the first integer starting from n for which
 Ṁ             its greatest
%   ʋ  ÆN€     residue modulo the first n primes
  =2           is 2.
          ’    Decrement.

```

If \\$k\\$ has residues \\$ \\{-1,0,1\\} \\$, \\$k + 1\\$ has residues \\$\\{0, 1, 2\\}\\$. On reflection, I'm... not entirely sure this program is valid, since 1. it might erroneously reject a \\$k\\$ with its only \\$1\\$ residue from \\$2\\$, and 2. while every integer necessarily has \\$0\\$ and \\$1\\$ as residues from *some* primes, it's not clear that there's no \\$n\\$ for which some erroneous \\$k\\$ with a maximum minimal-positive residue of \\$2\\$ mod the first \\$n\\$ primes but not \\$0\\$ and \\$1\\$ mod *one of the first \\$n\\$* primes is less than the real least \\$k\\$. However, it does pass the test cases, and it seems plausible that it is in fact correct.

# Answer
> 4 votes
# Charcoal, 32 bytes

```
Ｎθ→Ｗ‹Ｌυθ«→¿⬤υ﹪ⅈκ⊞υⅈ»Ｗ›⌈﹪ⅈυ²Ｍ→Ｉ⊖ⅈ

```

Try it online! Link is to verbose version of code. Explanation: Port of @UnrelatedString's Jelly answer.

```
Ｎθ

```

Input `n`.

```
→Ｗ‹Ｌυθ«→¿⬤υ﹪ⅈκ⊞υⅈ»

```

Generate the first `n` primes.

```
Ｗ›⌈﹪ⅈυ²Ｍ→

```

Continue counting up while the number's greatest residue modulo those `n` primes exceeds 2.

```
Ｉ⊖ⅈ

```

Decrement to produce the final result.

# Answer
> 3 votes
# Vyxal `G`, 80 bitsv2, 10 bytes

```
?ʁǎ%G2=)2ȯ‹

```

Try it Online!

A little goofy port of Jelly.

## Explained

```
?ʁǎ%G2=)2ȯ‹
       )2ȯ   # First two integers where
    G        #   The maximum of
?ʁǎ%         #   [k % x for x in first n primes]
     2=      #   Equals 2
        2ȯ   # The first two integers is because 1 is considered to pass the test, meaning that it needs to be accounted for. This could otherwise just be a single byte if there was something that started from n
          ‹  # Decrement
# The G flag gets the biggest item (which is the number in the list that _isn't_ 1)

```

Created with the help of Luminespire.

# Answer
> 2 votes
# JavaScript (Node.js), 95 bytes

```
f=(n,k)=>(y=L=[],g=n=>(P=i=>y%i--?P(i):i)(y++)?n&&g(n):L[-~k%y]=g(n-1))(n)+',0,0'==L?k:f(n,-~k)

```

Try it online!

# Answer
> 2 votes
# Thunno 2 `t`, 12 bytes

```
2Ƙ$LÆP%G2=;⁻

```

Try it online!

Port of Unrelated String's Jelly answer.

#### Explanation

```
2Ƙ$LÆP%G2=;⁻  # Implicit input
2Ƙ        ;   # First 2 positive integers where:
  $LÆP        #   List of the first (input) primes
      %       #   The current number mod this
       G2=    #   Maximum equals 2
           ⁻  # Decrement both
              # Implicit output of last item

```

# Answer
> 1 votes
# Python 2, 115 bytes

```
f=lambda n,i=1,p=1:n*[0]and p%i*[i]+f(n-p%i,i+1,p*i*i)
x=3;q=f(input())
while max(x%y for y in q)>2:x+=1
print(x-1)

```

Try it online!

Uses Lynn's function to get the first n primes. Port of Unrelated String's Jelly answer.

# Answer
> 1 votes
# Retina, 89 bytes

```
r`\d*$
¶__
"$&"}+`\b(_+)(¶_+)*¶\1+$
$&_
$
¶$%`
+`(?>\b(_+)(¶_+)*¶\1*)(?!_?_?$)
$&_
G`$
\B

```

Try it online! Link includes test cases. Explanation:

```
r`\d*$
¶__

```

Append `2` in unary to the buffer, deleting any input number. This awkward approach is fortunately the same length as the more straightforward approach of deleting the input number before starting the loop, as that version then requires history, which prevents more than one test case from being run at once.

```
\b(_+)(¶_+)*¶\1+$
$&_

```

If the last value in the buffer is divisible by any of the previous values then increment it.

```
+`

```

Repeat until it becomes prime.

```
"$&"}`

```

Repeat until `n` primes have been generated.

```
$
¶$%`

```

Make a copy of the `n`th prime.

```
(?>\b(_+)(¶_+)*¶\1*)(?!_?_?$)
$&_

```

If there is a prime for which the copy does not have a residue of no more than `2` then increment it. The atomic group `(?>...)` ensures that the regex doesn't try to add the prime to the residue to increase it to more than `2`, or worse, divide one of the primes by one of the other primes.

```
+`

```

Repeat until no residue is greater than `2`.

```
G`$

```

Keep only the final result.

```
\B

```

Subtract `1` and convert it to decimal.

# Answer
> 1 votes
# 05AB1E, 11 bytes

```
∞+.Δ>IÅp%à<

```

Port of *@UnrelatedString*'s Jelly answer.

Try it online or verify all test cases.

**Explanation:**

```
∞            # Push an infinite positive list: [1,2,3,...]
 +           # Add the (implicit) input-integer to each: [n+1,n+2,n+3,...]
  .Δ         # Find the first integer that's truthy for:
    >        #  Increase the current value by 1: [n+2,n+3,n+4,...]
     IÅp     #  Push a list of the first input amount of primes
        %    #  Modulo the current value+1 by each of these primes
         à   #  Pop and push the maximum remainder
          <  #  Verify that it's equal to 2, by decreasing it by 1 (since only 1 is
             #  truthy in 05AB1E)
             # (after which the found result is output implicitly)

```

---
Tags: code-golf, number, primes
---


# Question
Title: Buzzing Bill's Newspaper: Four Letter Splits
"Buzzing" Bill is a well respected beaver. He is the hardest working in his home dam. He was a strong beaver and was able to lift more logs than anyone at the dam. Unfortunately Buzzing Bill's career came to an end in a tragic accident. Being such a prominent figure in his town, the Beaver newspaper wanted to write a frontpage story remembering Buzzing Bill. However Beavers have much smaller newspapers than we do and can only fit 4 letters on each line. The newspaper is assigning you to the task of writing some code to output the four letter lines.

**The objective:** We need some code written that takes in a string as an input, ex: *"Big Beaver Buzzing Bill Bite the Bullet"* and splits it into four letter segments that can fit on the Beaver newspaper, and outputs the split segments in an array/list/structure

The answer to this question will have an output to the sentence above that looks much like this: **\[Big,Bea,ver,Buz,zing,Bill,Bite,the,Bul,let\]**

The output will complete the all of these criterion for beaver readability:

1. Keeps **4 letter words or less together, and completely separate from other words**, two words cannot occupy the same line— note that the first two indexes is not \[BigB,eav\]
2. It **splits words more than four letters and an even number of letters cleanly in two** — i.e. do not have \[Beav,er\]
3. **Words with an 7 letters should split at the point between the *first* two identical adjacent consonants, where one consonant occupies the middle spot, if possible.** “y” is not a consonant — Buzzing:\[Buz,zing\] instead of \[Buzz,ing\], additionally in very rare cases where the there is a triple consonant in the center, ex: “Wallled” would become \[Wal,lled\] as the split occurs at the first middle pair
4. **Words with an odd number of letters that do not satisfy rule #3 should be split so that the front of the word contains the extra letter** — "Beavers" should be split as \[Beav, ers\] rather than \[Bea,vers\]
5. Beavers are not very good at reading, so the **newspaper will not use any words over 8 letters, and all words will be entirely lowercase letters(only the 26 used in English)**

Make the Best of it Busy Beavers!

# Answer
> 2 votes
# Jelly, ~~29~~ 26 bytes

```
Ḳµ3.ịfƒØYL×7=LạLH>2×ƊĊṬk)Ẏ

```

Try it online!

This... can probably still be better...

```
Ḳµ                      )     For each word:
      ƒ                       Reduce
  3.ị                         the third and fourth letters in the word
     f                        by intersection
       ØY                     starting with the list of all consonants.
         L                    Is the length of that result
          ×7                  times 7
            =L                equal to the length of the word?
              ạL              Decrement the length if so.
                H             Halve,
                 >2×Ɗ         zero if =< 2,
                     Ċ        ceil,
                      Ṭk      split after that index.
                         Ẏ    Flatten the splits together.

```

# Answer
> 5 votes
# JavaScript (ES10), 100 bytes

Returns an array of strings.

```
s=>s.split` `.flatMap(s=>s[4]?[s.slice(0,q=s.length+!/^..([^aeiouy])\1../.test(s)>>1),s.slice(q)]:s)

```

Try it online!

---

# JavaScript (ES6), 96 bytes

Returns a string with additional spaces.

```
s=>s.replace(/\S{5,}/g,s=>s.slice(0,q=s.length+!/^..([^aeiouy])\1../.test(s)>>1)+' '+s.slice(q))

```

Try it online!

# Answer
> 3 votes
# Scala, ~~200~~ 147 bytes

Port of @Arnauld's Javascript answer in Scala.

---

Golfed version. Attempt this online!

Saved so many bytes thanks to the comments.

```
_.split(" ").flatMap(w=>if(w.size>4){val q=w.size+1-raw"..([^aeiouy])\1..".r.findAllIn(w).size;Seq(w.slice(0,q/2),w.slice(q/2,w.size))}else Seq(w))

```

Ungolfed version. Attempt this online!

```
import scala.util.matching.Regex

object Main {
  def main(args: Array[String]): Unit = {
    val s = "big beaver buzzing bill bite the bullet"
    println(splitAndManipulate(s))
  }

  def splitAndManipulate(s: String): List[String] = {
    s.split(" ").toList.flatMap(word => {
      if (word.length >= 5) {
        val regex: Regex = """..([^aeiouy])\1..""".r
        val q = if (regex.findFirstIn(word).isEmpty) {
          (word.length + 1) >> 1
        } else {
          word.length >> 1
        }
        List(word.slice(0, q), word.slice(q, word.length))
      } else List(word)
    })
  }
}

```

# Answer
> 3 votes
# Python 3.8 (pre-release), 261,265 232 bytes

gotta love the walrus. +4 bytes to fix rule 4.

```
import re
def f(s,q=[]):
 for w in s.split():
  if len(w)<5:q+=[w]
  elif(k:=len(w))%2<1:q+=[w[:k//2],w[k//2:]]
  elif b:=re.search(r'(?=[^aeiou])([a-z])\1',w):q+=[w[:(i:=b.end()-1)],w[i:]]
  else:l=k//2+1;q+=[w[:l],w[l:]]
 return q

```

Try it online!

# Answer
> 3 votes
# Python, ~~142~~ ~~139~~ ~~134~~ ~~131~~ 130 bytes

```
import re
for w in input().split():c=re.match(r'..([^aeiouy])\1...$',w)and 3or(w>w[:4])*len(w[::2]);c>0!=print(w[:c]);print(w[c:])

```

Attempt This Online!

*-3 thanks to xnor one-lining it, with some comparison chaining on top to shave one byte off an `and`*

*-1 thanks to spooky\_simon actually knowing how `re.match` works*

Basically just a bunch of incremental golfs to spooky\_simon's solution (inspired by xnor's comment, and with fixes to rule 3), but it's barely even recognizable anymore so I figured I may as well post it for myself.

# Answer
> 2 votes
# Retina 0.8.2, 65 bytes

```
S`
(..(..(?=....)|([^aeiouy])(?=\3...)|.(.(?=...))?))(..+)
$1¶$+

```

Try it online! Link includes test case. Explanation:

```
S`

```

Split on spaces.

```
(..(..(?=....)|([^aeiouy])(?=\3...)|.(.(?=...))?))(..+)
$1¶$+

```

Split words of at least five letters in one of four ways:

* eight letter words are split after four letters
* seven letter words whose third letter is not a vowel and is doubled after three letters
* other seven letter words after four letters
* other words after three letters

`$+` just saves me counting to find the group number of the last capture group.

# Answer
> 2 votes
# Python 3, 379 bytes

I got kinda lazy at the end after banging my head against this problem for a couple hours. Since I wasn't sure if I could use built-in modules like `itertools` I decided not to test my luck and just make a function (which came out kinda bulky)

Here's my solution

```
def f(l):
    if type(l) in [list,tuple]:
        for s in l:
            yield from f(s)
    else:yield l
b=lambda s:list(f([[w[p:p+(len(w)//2)]for p in range(0,len(w),len(w)//2)]if(len(w)>4 and len(w)%2==0)else(([(w[:a],w[a:])for a in[{1:4,**{1:a for a in[i+1 for i,(a,b)in enumerate(zip(w,w[1:]))if a==b and a not in"aeiouy"]}}[1]]])if len(w)==7 else w) for w in s.split()]))

```

Was I a bit smarter and managed to remove the function I could've saved about 100 bytes, but oh well...

# Answer
> 2 votes
# Charcoal, 46 bytes

```
Ｆ⪪Ｓ ¿∧⁼Ｌι⁷›⁼§ι²§ι³№aeiouy§ι²⟦…ι³✂ι³⟧⪪ι⁻⁴⊘＆²⊕Ｌι

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｆ⪪Ｓ

```

Split the input on spaces and loop over the words.

```
¿∧⁼Ｌι⁷›⁼§ι²§ι³№aeiouy§ι²

```

Check to see whether this is a seven-letter word with third and fourth letters both the same consonant.

```
⟦…ι³✂ι³⟧

```

If so then split it after three letters.

```
⪪ι⁻⁴⊘＆²⊕Ｌι

```

Otherwise split it after a number of letters given by a formula which results in splits of `3, 3, 4, 4, 3, 3, 4, 4` for words of length `1` to `8`, which is the desired result.

# Answer
> 2 votes
# Ruby `-an`, 87 bytes

`-an` enables autosplitting on the implicit input, which is stored in `$F`.

The main strategy here is to abuse `String#slice!`, which removes the substring that matches the parameter from the original string and returns it, which means what remains can be returned as the second half. It can take as a parameter, among other things, a regex or a range, which means the 7-length case can be handled with a regex and everything else can be handled with a range.

```
puts$F.map{|f|s=f.size
s>4?[f.slice!(s==7?/..(([^aeiouy])(?=\2)|..)/:0...s/2+s%2),f]:f}

```

Attempt This Online!

# Answer
> 2 votes
# 05AB1E, 31 bytes

```
#εDg©4›i2ä®7Qi¬γθžPÃg2@iJ34S£]˜

```

Try it online.

**Explanation:**

```
#                      # Split the (implicit) input-string by spaces
 ε                     # Map over each word:
  Dg                   #  Duplicate the current word, then pop and push its length
    ©                  #  Store this length in variable `®` (without popping)
    4›i                #  If the length is larger than 4:
       2ä              #   Split the string into two 'equal-sized' parts, where the
                       #   first part is one character longer for odd-sized strings
         ®7Qi          #   If length `®` equals 7:
             ¬         #    Push the first part with four characters (without popping
                       #    the pair)
              γ        #    Group adjacent similar characters together
               θ       #    Pop and keep the last character-group
                žPÃ    #    Only keep the consonants of this group
             g2@i      #    If the length of what remains is >=2:
                 J     #     Join the pair back together to the original word
                  34S£ #     And split it into parts of sizes [3,4] (instead of the
                       #     [4,3] done by the `2ä`)
 ]                     # Close all three if-statements and the map
  ˜                    # Flatten the list
                       # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Perl 5, 99 bytes

```
$_=join$",map/(..([^aeiouy]))(\2...$)|(.{3,4})(.{3,4})|(...)(..)/i?($1||$4||$6,$3||$5||$7):$_,split

```

Try it online!

---
Tags: code-golf
---


# Question
Title: Shortest terminating program whose output size exceeds Graham's number
Write the shortest possible program (length measured in bytes) satisfying the following requirements:

* no input
* output is to stdout
* execution eventually terminates
* total number of output bytes exceeds Graham's number

Assume that programs run until "normal" termination on an *ideal* computer1 able to access unlimited resources, and that the common programming languages are modified if necessary (without changing the syntax) to allow this. Because of these assumptions, we might call this a kind of Gedankenexperiment.

To get things started, here's a 73-byte Ruby program that computes fω+1(99) in the fast-growing hierarchy:

```
f=proc{|k,n|k>0?n.times{n=f[k-1,n]}:n+=1;n};n=99;n.times{n=f[n,n]};puts n

```

1 EDIT: More precisely, suppose we're taking an existing system and modifying it only to have no upper limit on storage size (but it is always finite). The execution-times of instructions are *not* supposed to be modified, but the machine is assumed to be ideal in that it will have no upper limit on its operating lifetime.

# Answer
> 15 votes
# Binary Lambda Calculus, 78 bits = 9.75 bytes

Here is an expression in Binary Lambda Calculus that is less than 10 bytes, yet surpasses Graham's Number. This is over 5x shorter than my previous post in JavaScript. Since Binary Lambda Calculus is radically different than JavaScript, I decided to answer this in a separate post.

```
010101000001110011101000000101011000000101101101011010000110100000011100111010

```

You can find some interpreters here.

## **Explanation I made on another post**

Essentially, this binary expression encodes this lambda calculus expression:

```
(\f x.f (f x))(\f n.n (\g m.m g m) f n)(\x.x x)(\f x.f (f x))

```

The decodings can be described like this:

* `(\f x.f (f x))` at the start and at the end corresponds to the Church Numeral \\$2\\$.
* `(\f n.n (\g m.m g m) f n)` takes in a function \\$f\\$ and a number \\$n\\$, and returns \\$f\_n (n)\\$ where \\$f\_0 (n) = f(n)\\$ and \\$f\_{m+1} (n) = f\_m^n (n)\\$ using functional recursion. Let's call this function \\$S\\$.
* `(\x.x x)` corresponds to the function that raises a number to the power of itself, or \\$f(x)=x^x\\$.

Since Church Numerals naturally nest the function that they apply to, the lambda calculus string gets reduced as follows: $$2Sf2 \rightarrow S(Sf)2$$ Since each \\$S\\$ adds \\$\omega\\$ to the growth rate of the function, and the \\$f(x)=x^x\\$ has growth rate \\$f\_2\\$ in the Fast Growing Hierarchy, then \\$(Sf)\\$ has growth rate \\$f\_{\omega}\\$, and \\$S(Sf) = 2Sf\\$ has growth rate \\$f\_{\omega2}\\$.

This means the expression \\$2Sf2\\$ described above has the value of about \\$f\_{\omega2} (2)\\$ in the Fast-growing Hierarchy. This is greater than Graham's Number.

Therefore, Graham's Number can be beaten by a program that less than 10 bytes!

# Answer
> 21 votes
## Haskell, ~~59~~ ~~57~~ ~~55~~ 63

```
(f%s)1=s;(f%s)n=f.(f%s)$n-1
main=print$((flip((%3)%(3^))3)%4)66

```

How it works: `%` simply takes a function and composes it `n-1` times on top of `s`; i.e. `%3` takes a function `f` and returns a function of `n` that equals applying it `f` to 3, `n-1` times in a row. If we iterate the application of this higher-order function, we get a fast-growing sequence of functions – starting with exponentiation, it's exactly the sequence of Knuth-arrow-forest sizes:
`((%3)%(3^))1 n = (3^)n     = 3ⁿ = 3↑n`
`((%3)%(3^))2 n = ((3^)%3)n = (3↑)ⁿ⁻¹ $ 3 = 3↑↑n`
`((%3)%(3^))3 n = (((3^)%3)%3)n = (3↑↑)ⁿ⁻¹ $ 3  = 3↑↑↑n`
and so on. `((%3)%(3^))n 3` is `3 ↑ⁿ 3`, which is what appears in the calculation to Graham's number. All that's left to do is composing the function `(\n -> 3 ↑ⁿ 3) ≡ flip((%3)%(3^))3` more than 64 times, on top of 4 (the number of arrows the calculation starts with), to get a number larger than Graham's number. It's obvious that the logarithm (what a lamely slow function that is!) of `g₆₅` is still larger than `g₆₄=G`, so if we print that number the output length exceeds `G`.

# Answer
> 11 votes
## GolfScript (49 47 chars)

```
4.,{\):i\.0={.0+.({<}+??\((\+.@<i*\+}{(;}if.}do

```

See Lifetime of a worm for lots of explanation. In short, this prints a number greater than fωω(2).

# Answer
> 10 votes
# Binary Lambda Calculus, ~~7.625~~ ~~7.5~~ ~~6.75~~ 6.125 bytes, ~~61~~ ~~60~~ ~~54~~ 49 bits

```
0100011010000110011000000101101100000011100111010

```

This encodes:

```
(\x.x x) (\y.y (y (\g m.m g (\f n.f (f n)))))

```

To simplify things a bit, let `H = (\g m.m g 2)` where `2` is the Church numeral `(\f n.f (f n))`. These are the first few steps of the reduction:

```
(\x.x x) (\y.y (y H))
(\y.y (y H)) (\y.y (y H))
(\y.y (y H)) ((\y.y (y H)) H)
(\y.y (y H)) (H (H H))
H (H H) (H (H H) H)
H (H H) H (H H) 2
H (H H) 2 (H H) 2
2 (H H) 2 (H H) 2
H H (H H 2) (H H) 2
H H 2 H 2 (H H) 2
2 H 2 H 2 (H H) 2
H (H 2) H 2 (H H) 2
H (H 2) 2 2 (H H) 2
2 (H 2) 2 2 (H H) 2
H 2 (H 2 2) 2 (H H) 2
H 2 2 2 2 2 (H H) 2
2 2 2 2 2 2 (H H) 2
2^^6 (H H) 2

```

The next step is applying `H H` \\$2\uparrow\uparrow6\\$ times to `2`. After an odd number of aplications the result is not a number, but after an even number of aplications it is. Here \\$2\uparrow\uparrow6\\$ is not an aproximation, and since it is even, the final answer will be a number. We will use \\$\frac{2\uparrow\uparrow6}{2}\\$ times a function that applies `H H` twice. The function `H H (H H n)` grows as fast as the Ackermann function, to see this, let's take a look at a more general case. The function `k H 2 n` grows as fast as \\$2\uparrow^kn\\$:

```
0 H 2 n = 2 n = n^2 > 2*n = 2{0}n

k+1 H 2 n = H (k H 2) n = H (\x.k H 2 x) n >= H (\x. 2{k}x) n
    = n (\x. 2{k}x) 2 = 2{k+1}(n+1) > 2{k+1}n

```

Applying this to `H H (H H n)` we get `H H (H H n) = H H n H 2 = n H 2 H 2 = H (n-1 H 2) H 2 = H (n-1 H 2) 2 2 = 2 (n-1 H 2) 2 2 = n-1 H 2 (n-1 H 2 2) 2 >= n-1 H 2 2{n-1}2 2 >= 2{n-1}2{n-1}2 2 = 2{n}3 2 > 2{n}3`, which is about the same as \\$A(n,n)\\$. So the size of the expression `2^^6 (H H) 2` is about \\$g\_{\frac{2\uparrow\uparrow6}{2}} \> g\_{64}\\$.

# Answer
> 7 votes
# Python 3, 53 bytes

```
m=lambda x:-x if x<0 else m(x-m(x-1))/2;print(1/m(9))

```

It computes the reciprocal of the gap between the 9 and the smallest tame fusible number above it, which is shown here to be at least \\$f\_{\varepsilon\_0}(2)\\$ in the fast-growing hierarchy, thus beating Graham's number.

# Pyth, ~~24~~ 22 bytes

-2 bytes thanks to r.e.s.

```
DlHR?<HZ_H/l-Hl-H12)lT

```

Same algorithm as before. I changed the argument 9 to 10 (which due to the predefined variable `T` doesn't increase the length), thus making the output at least \\$f\_{\varepsilon\_0}(3)\\$, absolutely dominating Graham's number and every other answer so far.

# Answer
> 6 votes
# Pyth, ~~29~~ 28 bytes

```
M?*GHgtGtgGtH^ThH=ZTV99=gZTZ

```

Defines a lambda for hyper-operation and recursively calls it. Like the definition for Graham's number, but with larger values.

This:

```
M?*GHgtGtgGtH^3hH

```

Defines a lambda, roughly equal to the python

```
g = lambda G, H:
  g(G-1, g(G, H-1)-1) if G*H else 3^(H+1)

```

This gives the hyper-operation function, g(G,H) = 3↑G+1(H+1).
So, for example, g(1,2)=3↑23 = 7,625,597,484,987, which you can test here.

`V<x><y>` starts a loop that executes the body, `y`, `x` times.
`=gZT` is the body of the loop here, which is equivalent to `Z=g(Z,10)`

The code:

```
M?*GHgtGtgGtH^3hH=Z3V64=gZ2)Z

```

Should recursively call the hyperoperation above 64 times, giving Graham's Number.

In my answer, however, I've replaced the single digits with `T`, which is initialized to 10, and increased the depth of recursion to 99. Using Graham Array Notation, Graham's Number is \[3,3,4,64\], and my program outputs the larger \[10,11,11,99\]. I've also removed the `)` that closes the loop to save one byte, so it prints each successive value in the 99 iterations.

# Answer
> 4 votes
# Javascript, 50 Bytes, \\$f\_{\omega+8} (9)\\$

```
n=(y,x=9)=>y?y-9?n(y-1,x?n(y,x-1)*9:9):x:n(x);n(8)

```

Here, n is a binary function. The function is defined as followed:

* `n(9,x) = x`
* `n(y,0) = n(y-1,9)`
* `n(y,x) = n(y-1,n(y,x-1)*9)`

The `*9` ensures that `n(y,x)` is an increasing function with respect to x.

* `n(9,x)` = x
* `n(10,x)` = 9^(x+1)
* `n(11,x)` ~ 9^^x
* `n(12,x)` ~ 9^^^x
* `n(y+1,x)` recurses over `n(y,x)` with respect to x.

We also defined n(y)=n(y,9), so n(y) grows as fast as \\$f\_{\omega}\\$ in the Fast Growing Hierarchy.

Now here is the twist:

* `n(0,x)=n(x)=n(x,9)`

This starts an entirely new hierarchy starting from `y=0` all the way up to `y=8`.

* `n(0,x)` grows at \\$f\_{\omega}\\$ in the FGH
* `n(1,x)` grows at \\$f\_{\omega+1} = G\\$
* `n(2,x)` grows at \\$f\_{\omega+2}\\$
* ...
* `n(8,x)` grows at \\$f\_{\omega+8}\\$

Therefore, `n(8)` ~ \\$f\_{\omega+8} (9) \> G\_{64}\\$

# Answer
> 3 votes
## Ruby, ~~54~~ ~~52~~ 50 bytes

```
f=->b{a*=a;eval"f[b-1];"*b*a};eval"f[a];"*a=99;p a

```

---

## Ruby, ~~85~~ ~~81~~ ~~76~~ ~~71~~ ~~68~~ ~~64~~ ~~63~~ ~~59~~ 57 bytes

```
f=->a,b=-a{eval"a*=b<0?f[a,a]:b<1?a:f[a,b-1];"*a};p f[99]

```

Pretty much fast growing hierarchy with f(a+1) \> fω+1(a).

---

## Ruby, 61 bytes

```
f=->a,b=-a{a<0?9:b==0?a*a:f[f[a-1,b],b>0?b-1:f[a,b+1]]};f[99]

```

Basically an Ackermann function with a twist.

---

## Ruby, ~~63~~ 59 bytes

```
n=99;(H=->a{b,*c=a;n.times{b ?H[[b-1]*n*b+c]:n+=n}})[n];p n

```

---

## Another Ruby, ~~74~~ 71 bytes

```
def f(a,b=a)a<0?b:b<0?f(a-1):f(a-1,f(a,b-1))end;n=99;n.times{n=f n};p n

```

Basically Ackermann function to itself 99 times.

# Answer
> 2 votes
## Python (111+n), n=length(x)

Although this one is not as short as the answerer's Ruby program, I'll post it anyway, to rule this possibility out.

It uses the Ackermann function, and calls the Ackermann function with m and n being the values from another call to the Ackermann function, and recurses 1000 times.

This is **probably** bigger than Graham's number, but I'm not sure, because nobody knows the exact length of it. It can be easily extended, if it's not bigger.

```
x=999
b='A('*x+'5,5'+')'*x
def A(m,n):n+1 if m==0 else A(m-1,A(m,n-1)if n>0 else 1)
exec('print A('%s,%s')'%(b,b))

```

# Answer
> 2 votes
# GolfScript, ~~24~~ ~~20~~ 18 bytes

```
"`'1$,*~'+"{.~~})*

```

Try it online!

```
"`'1$,*~'+"         # Push this string
           {.~~})*  # Becomes {.~}126* and this duplicates and executes the string 126 times

```

When executed, this string modifies the string at the top of the stack:

```
 `          # Parse it to a string inside the string  'foo'  -> '"foo"'
  '1$,*~'+  # Add '1$,*~' at the end                  '"foo"' -> '"foo"1$,*~'

```

When we execute this new string it does whatever `foo` used to do, but many times.

```
     1$,     # Get the number of bytes of the string at the top of the stack
"foo"   *    # Make that many copies of foo
         ~   # Execute all of them

```

We will be dealing with only one string, that will modify itself 126 times. Let `L` be the number of loops and `B` the number of bytes the string has. These values can be calculated with \\$B=2^{L+1}+3L+7\\$, but for simplicity's sake we will round `B` down to `L`. The number of bytes grows exponentially because every time a loop is added, every `"` becomes `\"` and every `\` becomes `\\`. Now the loops execute `L` times instead of `B`. When the string has no loops it just adds `"` `"1$,*~` around itself, in other words `L = L + 1`. With `a` loops it executes `L` times the version with `a-1` loops. This is exactly the same definition of `f` in the fast growing hierarchy for when `a` is a successor:

$$f\_0(L)=L+1$$ $$f\_a(L)=f\_{a-1}^L(L)$$

Before each execution `a` and `L` are the same number, so every time we execute the string, `L` becomes \\$f\_\omega(L)\\$.

We execute it 126 times starting with `L = 0`, so the number of bytes in the output will be:

$$f\_\omega^{126}(0)=f\_\omega^{122}(f\_8(8))\>f\_\omega^{122}(122)=f\_{\omega+1}(122)$$

# Answer
> 2 votes
# Functoid, 14 bytes

```
B"W(BiCA])9.Ef

```

Try it online!

The pointer wraps around whenever it moves out of the source code, this happens once here, making the code equivalent to `B"W(BiCA])9.EfB"W(BiCA])9.Ef`. The string `"W(BiCA])9.EfB"` gets converted to base 10 and becomes `"91772447243986"`. Now we can rewrite the code as `BkW(BiCA])9.Ef`, where `k` represents that big number.

```
BkW(BiCA])9         # set the current function to B k W (B i C A ]) 9
           .        # evaluate and print the current function as a number
            Ef      # terminate the program

```

Let `f_a` be a lambda function equivalent to \\$f\_a\\$ in the fast growing hierarchy. To increase the index by 1, the function needs to be applied to itself `n` times \\$f\_a^n(n) = f\_{a+1}(n)\\$. In code this would be `f_(a+1) n = n f_a n = C A f_a n`. To get any finite index we just need to apply `C A` a lot of times to `f_0 = ]`:

```
f_0 = ]
f_1 = C A ]
f_2 = C A (C A ])
f_3 = C A (C A (C A ]))
...

```

\\$f\_\omega(n) = f\_n(n)\\$ = `n (C A) ] n = W (i (C A) ]) n`

The expression `B k W (B i C A ]) 9` can be reduced to `k (W (i (C A) ])) 9 = k f_ω 9` and this returns \\$f\_\omega^{91772447243986}(9)\\$.

# Answer
> 2 votes
# Python 3, 79 bytes

```
f=lambda x,y:f(x-1,f(x,y-1))if x*y else x+y+1
z=9;exec("z=f(z,z);"*99);print(z)

```

f(x,y) is a modified version of ackermann for golfing purposes
f(x,y) = f(x-1,f(x,y-1)) if both x and y are greater than 0
f(x,0) and f(0,y) each add one to the nonzero entry (if both are zero, it is 1)

Then the program does recursion on f(x,x) 99 times.

# Answer
> 1 votes
# JavaScript, 68 bytes, however uncompeting for using ES6

```
a=(x,y)=>y?x?a(a(x-1,y)*9,y-1):a(9,y-1):x;b=x=>x?a(9,b(x-1)):9;b(99)

```

`a` function is similar to up-arrow notation with base 9.

```
       /a(a(x-1,y)*9,y-1)  x>0, y>0
a(x,y)=|a(9,y-1)           x=0, y>0
       \x                  y=0

```

`b` function is: b(x)=bx(9).

`b(99)` is ~fω+1(99), compared to Graham's number\<fω+1(64).

# Answer
> 1 votes
# Python 3, ~~174~~ ~~171~~ ~~168~~ ~~148~~ ~~125~~ ~~117~~ ~~116~~ ~~112~~ 101 bytes

3^^^...^3 with Graham's number arrows i.e. G(65) (boring, I know)

```
a=lambda b,c:3if b<2else(a(a(b-1,c),c-1)if c else 3*b)
G=lambda k:a(3,G(k-1))if k else 4
print(G(65))

```

Pretty human-readable. a implements arrow notation, G is Graham's sequence.

## Improvements

* Replaced G(64)+1 with G(65), saving two bytes
* Replaced `if c==1:return a**b` with `if c==0:return a*b`, saving one byte
* Renamed ar function to a and renamed variable a to k, saving three bytes
* Turned G function from a proper function into a lambda, saving twenty bytes, believe it or not!
* Turned a function from a proper function also into a lambda, saving twenty-three bytes!
* Removed k from a function since we will only be using it with base 3, saving eight bytes.
* Removed an unnecessary space
* Removed some more unnecessary spaces, saving four bytes
* Shortened definitions of a and G, saving eleven bytes

# Answer
> 1 votes
# , 17.5 bytes

```
00000000: 505e 91e7 a3a4 63c8 edda 476d ea0b d556  P^....c...Gm...V
00000010: d7e                                      ..

```

Written in octal:

```
24057221717216443074435566443555724057252555375

```

Try it online!

`721gge644355` is a function that, given a function `f_a()`, returns `f_(a+1)()`:

```
|f_a() 721gge644355
|c7{f_a()}ggerr          # Where {f_a()} represents the pacified version of f_a()

# Applying the result to some number n, to see that it worked:
|n c7{f_a()}ggerr
|n|f_a() nr
   f_a() n               # Make n copies of f_a(), resulting in f^n_a()
 n        r              # Apply it to n, resulting in f^n_a(n) = f_(a+1)(n)

```

From that, a function `f_w()` can be written:

```
|n cc71721644307443556ggerrr
|n|n|721gge644355 nrr
   n                              # A function (\x -> x^n), representing f_0()
     721gge644355 nr              # Add 1 n times to the index of f_0(), resulting in f_n()
 n                  r             # Apply the result to n, resulting in f_n(n) = f_w(n)

```

The full program computes `f^256_w(2)`, which is greater than Graham's number:

```
|| 24057221717216443074435566443555724057252555375
||cg6r|cc71721644307443556ggerrr|cg6r|crcrrre|r
||cg6r|cc71721644307443556ggerrr|cg6r|crcrrre|r r
||cg6r|cc71721644307443556ggerrr|cg6r|crcrrre r
||cg6r|cc71721644307443556ggerrr|cg6r crcrrre
                                 cg6r              # The number 2
                                      cr           # Raise 2, to itself returning 4
                                        cr         # Raise 4, to itself returning 256
       cc71721644307443556ggerrr          r        # Make 256 copies of f_w(), resulting in f^256_w()
  cg6r                                     r       # Apply this function to 2, resulting in f^256_w(2)
                                            e      # Print the result in the same encoding as the source code

```

We can see the code working by reducing it to just `f_w(2)`. This outputs `2^2^18`, which is represented by `2^18` copies of `2405` in the same encoding as the source.

```
2405722171721644307443556644355575375

```

Try it online!

# Answer
> 0 votes
**Python: 85**

```
f=lambda a,a:a*a
exec'f=lambda a,b,f=f:reduce(f,[a]*b,1)'*99
exec'f('*64+'3'+',3)'*64

```

Which maybe could be shortened to *74 + `length(X)`*:

```
f=lambda a,a:a*a
exec'f=lambda a,b,f=f:reduce(f,[a]*b,1)'*int('9'*X)
f(3,3)

```

Where `X` is an appropriate big number such that the resultant hyperoperation on `3, 3` is bigger than Grahams number(if this number is less than `99999999999` then some byte is saved).

---

Note: I assume the python code is executed on the interactive interpreter hence the result is printed to stdout, otherwise add `9` bytes to each solution for the call to `print`.

# Answer
> 0 votes
# Javascript, 83 bytes

Another Ackermann function solution.

```
(function a(m,n,x){return x?a(a(m,n,x-1),n,0):(m?a(m-1,n?a(m,n-1):1):n+1)})(9,9,99)

```

# Answer
> 0 votes
# Ruby, 60 bytes

```
f=->n{n.times{eval("n.times{"*n+"n+=1"+"}"*n)};n};f.call(64)

```

This is \\$f\_{\omega+1}(64)\\$, exactly, which is slightly bigger than Graham's number :) I copied this from Simply Beautiful Art on their Bignum Bakeoff post.

---
Tags: code-golf, math, busy-beaver
---