# Question
Title: Generate a Pronounceable Nonsense Word \$n\$ syllables long
Your task is to generate a nonsense word that is reasonably pronounceable with the specified number of 'syllables'. Each time the program is run possibly results in a different nonsense word.

# Pronounceability

A pronounceable word is made up of syllables, which are in turn made up of a vowel group that is possibly sandwiched between two consonant groups. Not all sounds are pronounceable in all positions, and since this depends on the language, we'll use patterns understandable to English speakers

Starting consonant groups:

b c d f g h j k l m n p r s t v w y z bl br ch cl cr dr fl fr gh gl gn gr kn ph pl pr qu sc sh sk sl sm sn sp st th tr wh wr sch scr shm shr squ str thr

Vowel Groups:

a e i o u ae ai ao au ea ee ei eu ia ie io oa oe oi oo ou ue ui

Ending Consonant groups:

b c d f g l m n p r s t x z bt ch ck ct ft gh gn lb ld lf lk ll lm ln lp lt mb mn mp nk ng nt ph pt rb rc rd rf rg rk rl rm rn rp rt rv rz sh sk sp ss st zz lch lsh lth rch rsh rst rth sch tch

## Combining Syllables

Both starting and ending consonant groups are optional in general, however you cannot place a syllable ending with a vowel immediately before one starting with a vowel.

### Disclaimer

In the interest of simplicity, certain English words can't actually be generated this way, such as vacuum, xylophone, mnemonic, pterodactyl, beautiful, blah, they, wow, and most plurals.

## Overview

Possible syllable patterns using this key:

(SC) = starting consonant; (V) = vowel group; (EC) = ending consonant

For one syllable:

* (SC)(V)(EC)
* (V)(EC)
* (SC)(V)
* (V)

With two syllables:

* (SC)(V)(EC)(SC)(V)(EC)
* (SC)(V)(EC)(SC)(V)
* (SC)(V)(EC)(V)(EC)
* (SC)(V)(EC)(V)
* (SC)(V)(SC)(V)(EC)
* (SC)(V)(SC)(V)
* (V)(EC)(SC)(V)(EC)
* (V)(EC)(SC)(V)
* (V)(EC)(V)(EC)
* (V)(EC)(V)
* (V)(SC)(V)(EC)
* (V)(SC)(V)

... and so on

# Examples

### 1 syllable

* charst
* tigh
* shriegn
* eess
* shue
* oo
* cheezz

### 2 syllables

* jazzcrap
* whylprog
* eating
* umba
* ola
* have
* ingsoc
* greespheurz
* bleuspoo

### 3 syllables

* brokiompic
* squirdshlicker
* capital
* opengtrass
* doublethink
* bigbrother
* phoebliaptmoo
* skolfblauquent

### 4 syllables

* strawishoepick
* patchworkzombie
* prearneajoomie
* slephotoschou
* doubleplusgood

# Coding

Input: an integer for the number of syllables to generate

Output: a (probably) nonsense word that many syllables long

# Rules

* Some form of (psuedo)randomness is required. All combinations of syllables should be (theoretically) possible to generate, though the distribution does not have to be uniform.
    + You may assume that your generator is aperiodic, so it doesn't have to be mathematically possible to generate every possible word (It might not have a long enough period in reality) and you don't need to provide any sort of proof that your generator can, in fact, produce every possible word.
    + Your generator must actually be able to produce at least 255 distinct values, so you can't just return 4 every time the generator is called.
    + What's ultimately important is that you somehow include all the above letter groups in your code, that each letter group has a nonzero probability of being picked, and each syllable pattern has a nonzero probability of occurring (if provided with true randomness).
* You must support up to 16 syllable words
* In addition to the rules on combining syllables, the output word must not have:
    + 3 consecutive vowels (`a` `e` `i` `o` `u`; this can happen for `qu` words)
    + 3 consecutive matching consonants

Good luck!

---

Note that this is distinct from Generate a pronounceable word for a few reasons:

* Variable number of syllables specified by input rather than a strict 10-letter requirement.
* This challenge adds non-exhaustive letter groups that must be (cleverly) encoded and allows for more variants of syllables, so code can't just be copied from the other challenge
* Squirdshlicker. Need I say more?

*I also forgot to dupe check, but it turns out this brings enough new to the table that it doesn't matter. After all, there are hundreds of quine variant challenges.*

# Answer
# JavaScript (ES6),  ~~407~~  403 bytes

```
f=n=>/[aeiou]{3}|(.)\1\1/.test(s=(h=k=>k?(g=s=>p=s.match(/.[a-z]*/g)[Math.random()*99|0]||(s>x&&p?'':g(s)))(x+'lBrClCrDrFlFrGlGrHJKKnPlPrQuScScrShmShrSlSmSnSquStrThThrTrVWWhWrY')+g('AAeAiAoAuEEaEeEiEuIIaIeIoOOaOeOiOoOuUUeUi')+g(x+'tCkCtFtLbLchLdLfLkLlLmLnLpLshLtLthMbMnMpNgNkNtPtRbRcRchRdRfRgRkRlRmRnRpRshRstRtRthRvRzSsTchXZz')+h(k-1):'')(n,p=x='BCChDFGGhGnLMNPPhRSSchShSkSpStTZB').toLowerCase())?f(n):s

```

Try it online!
> 4 votes

# Answer
# 05AB1E, ~~237~~ ~~234~~ ~~230~~ 228 bytes

```
.•O0¦"ÐD›ô:ΓF9—∊‘àÕGÌ•3LŽZв₂в×S£V[1U.µ\µTΩiY.•1θ₆Ω–¸‡ÊΔιÃмº³ô»ÝAïG3_@|å“₄bÒs₃l¬t©ïÙK:≠•3LŽII₂в×S£«Ω1U}XižM•·Áy&ŒGηΩ¼αŸKq•6вèJ•Λ1"•bS>£Ω¼0U}TΩiY.•E–æƵHl¨åñyBY±(ú,ā]JùË‚aEuŒ—[K³|C~ôÙŸ„#¼ÑûĀdš+¢zsÄΘä¹ÊÌ₅ôθ•3LŽAE₆в×S£«Ω1U}J}Dγ€g3‹P#

```

-2 byte thanks to *@MagicOctopusUrn*.

Try it online or get a few more outputs.

**Explanation:**

```
.•O0¦"ÐD›ô:ΓF9—∊‘àÕGÌ•
                  "# Push compressed string "bcdfglmnprstzchghgnphshskspstsch"
  3L               # Push list [1,2,3]
    ŽA;            # Push compressed integer 8997
       ₂в          # Converted to Base-26 as list: [13,8,1]
         ×         # Repeat the digits [1,2,3] that many times: ["1111111111111","22222222","3"]
          S        # Convert it to a list of flattened digits
           £       # Split the string into parts of that size
            V      # Pop and store this string-list in variable `Y`
[                  # Start an infinite loop:
 1U                #  Reset variable `X` to 1
 .µ                #  Reset the counter_variable to 0
 \                 #  Discard the top of the stack (if any)
 µ                 #  Loop while the counter_variable is not equal to the (implicit) input:
  TΩi              #   If a random boolean is truthy:
     Y             #    Push the string-list we stored in variable `Y`
     .•1θ₆Ω–¸‡ÊΔιÃмº³ô»ÝAïG3_@|å“₄bÒs₃l¬t©ïÙK:≠•
                   #    Push compressed string "hjkvwyblbrclcrdrflfrglgrknplprquscslsmsnthtrwhwrscrshmshrsqustrthr"
       3L          #    Push list [1,2,3]
         ŽII       #    Push compressed integer 4608
            ₂в     #    Converted to Base-26 as list: [6,21,6]
              ×    #    Repeat the digits [1,2,3] that many times: ["111111","222222222222222222222","333333"]
               S   #    Convert it to a list of flattened digits
                £  #    Split the string into parts of that size
     «             #    Merge it with list `Y`
      Ω            #    Pop and push a random starting consonant group from this list
     1U            #    And set variable `X` to 1
    }              #   Close the if-statement
  Xi               #   If variable `X` is 1:
    žM             #    Push builtin string "aeiou"
      •·Áy&ŒGηΩ¼αŸKq•
                   #    Push compressed integer 13814931869773709280202935082102
        6в         #    Converted to Base-6 as list: [1,0,1,1,1,2,1,4,0,1,0,2,0,3,0,4,2,0,2,1,2,3,3,0,3,1,3,2,3,3,3,4,4,1,4,2,0,1,2,3,4]
          èJ       #    Index each into the string "aeiou", and join together: "aeaiaoaueaeeeieuiaieiooaoeoiooouueuiaeiou"
      •Λ1"•       "#    Push compressed integer 8388576
           b       #    Converted to binary: "11111111111111111100000"
            S>     #    Split into a list of digits, and each increased by 1
              £    #    Split the string into parts of that size
               Ω   #    Pop and push a random vowel group from this list
    ¼              #    Increase the counter_variable by 1
    0U             #    And then set variable `X` to 0
   }               #   Close the if-statement
  TΩi              #   If a random boolean is truthy:
     Y             #    Push the string-list we stored in variable `Y`
     .•E–æƵHl¨åñyBY±(ú,ā]JùË‚aEuŒ—[K³|C~ôÙŸ„#¼ÑûĀdš+¢zsÄΘä¹ÊÌ₅ôθ•
                   #    Push compressed string "xbtckctftlbldlflklllmlnlpltmbmnmpnkngntptrbrcrdrfrgrkrlrmrnrprtrvrzsszzlchlshlthrchrshrstrthtch"
       3L          #    Push list [1,2,3]
         ŽAE       #    Push compressed integer 2564
            ₆в     #    Converted to Base-36 as list: [1,35,8]
              ×    #    Repeat the digits [1,2,3] that many times: ["1","222...222","33333333"]
               S   #    Convert it to a list of flattened digits
                £  #    Split the string into parts of that size
     «             #    Merge it with list `Y`
      Ω            #    Pop and push a random ending consonant group from this list
     1U            #    And set variable `X` to 1
    }              #   Close the if-statement
  J                #   Join all strings on the stack together
 }D                #  After the while-loop: duplicate the resulting string
   γ               #  Split the copy into chunks, with adjacent characters that are
                   #  the same grouped together
    €g             #  Get the length of each chunk
      3‹           #  Check for each length if it's smaller than 3
        P          #  Check if all are truthy by taking the product, and if it is:
         #         #   Stop the infinite loop
                   # (after which the string at the top of the stack is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*) to understand how the compression parts works.
> 3 votes

# Answer
# Jelly, 231 bytes

```
e€ØẹŒrḢƇ,ŒɠF>2Ẹ
“yŒʠT¬ḅɼṬɦṀUżGv¶æɲCĊQ>ṙȦẇɼṄ0IḤhDẋDċṀĊṪɗĖƇẊ;1JƒṾỊżỵhṖ8>Ȯ⁶]¦Qṭ|Ṛṇẹm⁵ØKƈBNɦÇȯ¢ṣḟPṇMʠ¬YėĊÇẒỊĿXJÑḷÞeȮȮɼ$ỴœeṂṠɲẓḊ⁺ċŻ⁽⁶Ẓ⁹<>#nẇṬ⁴\¤ÐṡḞF5ƙẇwḶȤYḍ¡¢~ṚⱮ-ṃƲ⁻Ṙ6ɱṬ?İẆḌỊþEØ»Ḳµe€ØẹIkḣ3)Z;€“squ“qu”$1¦
“Ø¦µ£‘ḃ3$Xµ³Ð¡ḊFµ⁺wØ2$¿ịÇX€Fß¹Ñ?

```

Try it online!

A full program that takes a single argument, the number of syllables required.

### Explanation

The core of this is a 66-word compressed dictionary string. If the words are split into groups of consonants and vowels and the first 3 groups taken for each word, they generate the desired starting, vowel and end groups from the question. The exceptions are `qu` and `squ` because they have a vowel in, so these are added manually. The word list was built algorithmically from the Jelly dictionary using a Python script. Note some letter groups are repeated, but the question allows the outputs to not uniformly represent each possible combination. If this were preferred, it would be straightforward to make each group unique at the cost of two bytes (`Q€`).

Helper link 1: check whether more than 3 vowels in a row or more than 3 of the same letter in a row
```
                | Sample input: branggag
e€Øẹ            | For each letter, is it a vowel? [0, 0, 1, 0, 0, 0, 1, 0]
    Œr          | Run-length encode [[0, 2], [1, 1], [0, 3], [1, 1], [0, 1]]
      ḢƇ        | Filter only those with true first value, popping first value [[1], [1]]
        ,       | Pair with
         Œɠ     | Run lengths of input [[[1], [1]], [1, 1, 1, 1, 2, 1, 1]
           F    | Flatten [1, 1, 1, 1, 1, 1, 2, 1, 1]
            >2  | Greater than 2 [0, 0, 0, 0, 0, 0, 0, 0, 0]
              Ẹ | Any 0

```
Helper link 2: The three groups of strings
```
“yŒʠ...þEØ»                          | Compressed string: shmooze gaolbird hailshot shriech waeful furze ghaut cruelness stealthier gneiss shoeshine wheelchair wring build priorship knosp spoilfive karst through coalpit teschenite schoolkid theurgic zabtieh skiamachies yirth snazzier slimnastics scripted smirch droskies strift blepharism chaulmoogra glegness scarf fratch clerk brank jarvey flourless vorpal grex nard plumb larn philter sorbo tractabilities parcel mart damp rearm back bast bag bant baba boll bad bap becap basal ban bail bare
           Ḳ                         | Split at spaces
            µ        )               | For each word: e.g. hailshot
             e€Øẹ                    |   Check whether each character is a vowel [0, 1, 1, 0, 0, 0, 1, 0]
                 I                   | Increments of this [1, 0, -1, 0, 0, 1, -1]
                  k                  |   Split word at truthy values of this [h, ai, lsh, o, t]
                   ḣ3                |   Take the first three [h, ai, lsh]
                      Z              | Transpose (so now have three lists, start consonants, vowels, end consonants)
                        €        $1¦ | For the first group
                       ; “squ“qu”    | Append squ and qu

```
Main link
```
          µ³Ð¡                     | Repeat the following the input number of times, collecting results:
“Ø¦µ£‘                             |   18, 5, 9, 2
      ḃ3$                          |   bijective base 3: [1,2,3],[1,2],[2,3],[2]
         X                         |   Take one at random
              Ḋ                    | Remove first item (which will be the input to the link because if the way Ð¡ works
               F                   | Flatten; we now have e.g. [1,2,3,2,3,1,2,3,2]. This corresponds to SC V EC V EC AC V EC V
                µ⁺    ¿            | Do everything so far once and then repeat while:
                  wØ2$             |   The output contains two twos (i.e. vowel-vowel)
                       ịÇ          | Look these up in the previous link, so we now have a group of letter groups for each position
                         X€F       | Pick a random letter group for each position
                            ß¹Ñ?   | If helper link 1 is true, retry the whole of this link again. Otherwise implicitly output

```
> 1 votes

# Answer
# Python 2, ~~522~~ 510 bytes

```
from random import*
import re
c=choice
S,V,E=[map(str.lower,re.findall('[A-Z][a-z]*',x))for x in'BCDFGHJKLMNPRSTVWYZBlBrChClCrDrFlFrGhGlGnGrKnPhPlPrQuScShSkSlSmSnSpStThTrWhWrSchScrShmShrSquStrThr','AeAiAoAuEaEeEiEuIaIeIoOaOeOiOoOuUeUiAEIOU','BCDFGLMNPRSTXZBtChCkCtFtGhGnLbLdLfLkLlLmLnLpLtMbMnMpNkNgNtPhPtRbRcRdRfRgRkRlRmRnRpRtRvRzShSkSpSsStZzLchLshLthRchRshRstRthSchTch']
def f(n):w=c(['',c(S)]);exec"e=c(E);w+=c(V)[-(w[-1:]in V):]+c([c(S),e,e+c([x for x in S if x[0]*2!=e])])*(n>1);n-=1;"*n;return w+c(['',e])

```

Try it online!
> 0 votes

# Answer
# Pyth, ~~346~~ 335 bytes

```
McG.u+NYr9,VHSlH1smjOgs@L"eaiou"jC" ¤EÌ½]¢¨¦l#"5,4 17*Vd,Og"bcdfghjklmnprstvwyzblbrchclcrdrflfrghglgngrknphplprquscshskslsmsnspstthtrwhwrschscrshmshrsqustrthr"[18 29 6)Og"bcdfglmnprstxzbtchckctftghgnlbldlflklllmlnlpltmbmnmpnkngntphptrbrcrdrfrgrkrlrmrnrprtrvrzshskspssstzzlchlshlthrchrshrstrthschtch"[13 43 8)tuaGO<W!eeG^,1Z2 2Q]1

```

Try it online here.
> 0 votes

# Answer
# Ruby, ~~381~~ ~~379~~ 375 bytes

Uses messy regex matches to get the consonant groups. Could probably be optimized.

```
->n,w=?a..s='zzz',a=[1]{s=(1..n).map{a=[w.grep(/^([^aeiouq]|[bcfgp][lr]|s?ch|dr|gn|kn|ph|s?qu|s[ct]r?|sh[mr]?|th?r?|s[klmnp]|wh|wr|gh)$/)+(a[-1]?[p]:[]),w.grep(/^[aeiou]{,2}$/),w.grep(/^([^aeiouqhjkvwy]|[bcflnprs]t|ck|gh|gn|l[bdfk-np]|m[bnp]|nk|ng|ph|r[bcdfgk-npvz]|[lr]?[stc]h|s[kps]|zz|rst|[st]ch)$/)<<p].map(&:sample)}*''while s=~/[aeiou]{3}|(.)\1\1|aa|eo|ii|iu|u[aou]/;s}

```

Try it online!
> 0 votes

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


title: Chaos is an ASCII ladder

text:
# Question
Title: Chaos is an ASCII ladder
~~*You know nothing*~~ ~~*The things I do for*~~ "*Chaos is a ladder*" is a memorable line from the television series *Game of Thrones*.

The purpose of this challenge is to build a ladder from chaos, in ASCII art.

# The challenge

### Input

* Ladder width, `W >= 3` (integer)
* Step height, `H >= 2` (integer)
* Number of rungs, `N >= 2` (integer).

### Output

A ladder with *horizontal rungs* and *vertical rails*, all 1 character wide. Ladder width (`W`) includes the two rails, and step height (`H`) includes the corresponding rung.

All rungs, including the uppermost and the lowermost, will have a piece of vertical rail of length `H-1` directly above and below. The example will make this clearer.

The ladder will be made of *printable, non-whitespace ASCII characters*, that is, the inclusive range from `!` (code point `33`) to `~` (code point `126`).The actual characters will be chosen *randomly*. Given the inputs, each of the random choices of characters must have nonzero probability. Other than that, the probability distribution is arbitrary.

*Leading or trailing whitespace*, either horizontal or vertical, is allowed.

### Example

Given `W=5, H=3, N=2`, one possible output is as follows.

```
x   :
g   h
q$UO{
t   T
6   <
bUZXP
8   T
5   g

```

Note that total height is `H*(N+1)-1`, as there are `N` rungs and `N+1` vertical sections.

# Aditional rules

* Input means and format are flexible as usual. For example, you can input the three numbers in any order, or an array containing them.
* Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines, a 2D character array or an array of strings.
* A program or a function can be provided.
* Standard loopholes are forbidden.
* Shortest code in bytes wins.

# Test cases

For each `W, H, N` a possible output is shown.

```
W=5, H=3, N=2:

\   ~
:   K
ke:[E
5   u
0   _
8Fr.D
#   r
7   X

W=3, H=2, N=2:

$ X
Mb)
0 ]
(T}
j 9

W=12, H=4, N=5:

d          Y
P          `
5          3
p$t$Ow7~kcNX
D          x
`          O
*          H
LB|QX1'.[:[F
p          p
x          (
2          ^
ic%KL^z:KI"^
C          p
(          7
7          h
TSj^E!tI&TN8
|          [
<          >
=          Q
ffl`^,tBHk?~
O          +
p          e
n          j

W=20, H=5, N=3:

G                  %
o                  y
%                  3
-                  7
U'F?Vml&rVch7{).fLDF
o                  }
U                  I
h                  y
a                  g
;W.58bl'.iHm\8v?bIn&
,                  U
N                  S
4                  c
5                  r
F3(R|<BP}C'$=}xK$F]^
'                  h
h                  u
x                  $
6                  5

```

# Answer
> 6 votes
# Jelly,  ~~24 23~~  22 bytes

```
«þỊoU$ẋ⁵‘¤Ḋ×94X€€+32ỌY

```

A full program taking the three arguments `W`, `H`, `N` and printing the result.

**Try it online!**

### How?

Builds a 2d array mask of a single rung and its vertical sections below, repeats it `N+1`times and removes the top rung then places random characters or spaces depending upon the mask value.

```
«þỊoU$ẋ⁵‘¤Ḋ×94X€€+32ỌY - Main link: W, H (N is third input / 5th command line argument)
 þ                     - outer product (build a table using):
«                      -  minimum
                       -  ...note: þ implicitly builds ranges of W and H prior
  Ị                    - insignificant? (abs(z)<=1) - yields a W by H 2-d array,
                       -   all zeros except the left and top edges which are 1s
     $                 - last two links as a monad:
    U                  -   upend (reverse each row)
   o                   -   or (vectorises) - giving us our |‾| shape of 1s
         ¤             - nilad followed by link(s) as a nilad:
       ⁵               -   5th command line argument, N
        ‘              -   increment -> N+1
      ẋ                - repeat list - giving us our ladder-mask plus a top rung)
          Ḋ            - dequeue - remove the top rung
            94         - literal ninety-four
           ×           - multiply (vectorises) - replace the 1s with 94s
              X€€      - random for €ach for €ach - 0 -> 0; 94 -> random integer in [1,94]
                  32   - literal thirty-two
                 +     - add (vectorises) - 0 -> 32; random integers now from [33,126]
                    Ọ  - character from ordinal (vectorises)
                     Y - join with newlines
                       - implicit print

```

# Answer
> 34 votes
# Operation Flashpoint scripting language, ~~643~~ 624 bytes

```
f={l=["""","!","#","$","%","&","'","(",")","*","+",",","-",".","/","0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","[","\","]","^","_","`","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","{","|","}","~"];t=_this;w=t select 0;r={l select random 92};v="";s=v;i=2;while{i<w}do{i=i+1;v=v+" "};p={i=1;while{i<t select 1}do{i=i+1;s=s+call r+v+call r+"\n"}};k=0;call p;while{k<t select 2}do{k=k+1;i=0;while{i<w}do{i=i+1;s=s+call r};s=s+"\n";call p};s}

```

Ridiculously long because there is no way to create the characters from the character codes.

**Call with:**

```
hint ([5, 3, 2] call f)

```

**Output:**

*The ladder is extra chaotic because the font is not monospaced.*

**Unrolled:**

```
f =
{
    l = ["""","!","#","$","%","&","'","(",")","*","+",",","-",".","/","0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","[","\","]","^","_","`","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","{","|","}","~"];

    t = _this;
    w = t select 0;

    r =
    {
        l select random 92
    };

    v = "";
    s = v;

    i = 2;
    while {i < w} do
    {
        i = i + 1;
        v = v + " "
    };

    p =
    {
        i = 1;
        while {i < t select 1} do
        {
            i = i + 1;
            s = s + call r + v + call r + "\n"
        }
    };

    k = 0;
    call p;
    while {k < t select 2} do
    {
        k = k + 1;

        i = 0;
        while {i < w} do
        {
            i = i + 1;
            s = s + call r
        };
        s = s + "\n";

        call p
    };

    s
}

```

# Answer
> 14 votes
# 05AB1E, 29 bytes

Input taken in the order `N, H, W`

```
>*GNUžQ¦©.RIÍFð®.R«X²Öè}®.RJ,

```

Try it online!

**Explanation**

```
>*G                              # for N in [1 ... (N+1)*H)-1] do:
   NU                            # store N in variable X
     žQ                          # push a string of printable ascii
       ¦©                        # remove the first (space) and save a copy in register
         .R                      # pick a random character
           IÍF                   # W-2 times do:
              ð                  # push a space
               ®.R               # push a random ascii character
                  «              # concatenate
                   X²Ö           # push X % H == 0
                      è          # index into the string of <space><random_char> with this
                       }         # end inner loop
                        ®.R      # push a random ascii character
                           J,    # join everything to a string and print

```

# Answer
> 13 votes
# C, 95 bytes

```
f(w,h,n,i){++w;for(i=0;i++<w*~(h*~n);)putchar(i%w?~-i%w%(w-2)*((i/w+1)%h)?32:33+rand()%94:10);}

```

# Answer
> 8 votes
# , ~~138~~ ~~129~~ ~~111~~ ~~98~~ 93 bytes

*-13 bytes thanks to Neal Fultz!*

*-1 byte thanks to Robin Ryder*

```
function(W,H,N){m=matrix(intToUtf8(32+sample(94,W*(h=H*N+H-1),T),T),h)
m[-H*1:N,3:W-1]=" "
m}

```

Try it online!

Anonymous function; returns the result as a matrix.

Thanks to that Word Grids question, I've been thinking about matrices a lot more than usual. I observed that the rungs are in those matrix rows that are a multiple of the step height `H` (R is 1-indexed), and that the rails are the first and last columns, `1` and `W`. So I create a matrix of random ASCII characters, and replace those letters that didn't match those criteria with spaces, and return the matrix. TIO link prints it out nicely.

Neal Fultz suggested a different indexing for the space characters, `[-H*(1:N),3:W-1]`, which replaces all characters except for those in rows of multiples of `H`: `-H*(1:N)` and not on the edge, `3:W-1` \<==\> `2:(W-1)`.

# , 121 bytes

```
function(W,H,N)for(i in 1:(H*N+H-1)){for(j in 1:W)cat("if"(!(i%%H&j-1&j-W),sample(intToUtf8(33:126,T),1)," "))
cat("\n")}

```

Try it online!

An improvement over the original matrix-based approach I started with; it's the same algorithm but `for` loops are shorter than constructing and printing a matrix (but not if I don't print it!)

# Answer
> 6 votes
## Perl 5, 81 bytes

**80 bytes code + 1 for `-p`.**

```
/ \d+ /;$_=(($}=(_.$"x($`-2)._.$/)x($&-1))._ x$`.$/)x$'.$};s/_/chr 33+rand 94/ge

```

Try it online!

# Answer
> 6 votes
# C (gcc), ~~141~~ ~~131~~ ~~114~~ ~~109~~ 107 bytes

Should be able to golf this down quite a bit...

```
i,j,c;f(w,h,n){for(i=1;i<h*n+h;i+=j==w)printf(i%h?i++,j=0,"%c%*c\n":"%c",++j^w?c^8:10,w-2,c=33+rand()%94);}

```

Try it online!

# Answer
> 6 votes
# Charcoal, ~~34~~ 32 bytes

```
Ｅ…¹×⁺¹ＮＮ⪫ＥＩζ⎇∧﹪ιＩη﹪λ⁻Ｉζ¹ §⮌γ‽⁹⁴ω

```

Try it online! Takes input in the order N, H, W. Verbose approximation (`Plus(InputNumber(), 1)` is currently broken on TIO). Explanation:

```
Ｅ…¹×⁺¹ＮＮ

```

Map over the range `1..H*(N+1)`. This means that the rungs appear when `i` is a multiple of `H`.

Join the result of:

```
ＥＩζ

```

mapping over the implicit range `0..W`:

```
⎇∧﹪ιＩη﹪λ⁻Ｉζ¹

```

if the column is not `0` or `W-1` and the row is not a multiple of `H` then output a space;

```
§⮌γ‽⁹⁴

```

otherwise, take the predefined ASCII character variable, reverse it (putting the space in 94th place), and print a random character from what is now the first 94. (Because `Slice` sucks.)

```
ω

```

Join using the empty string. Final result is implicitly printed.

# Answer
> 6 votes
# Perl 6, ~~76~~ 73 bytes

```
->\h,\n,\w{map {chrs (roll(w,1..94)Z*1,|($_%%h xx w-2),1)X+32},1..^h*n+h}

```

Try it online!

Takes (h, n, w) as arguments. Returns a list of strings.

Explanation:

```
-> \h, \n, \w {  # Block taking arguments h, n, w
    map {
        # String from codepoints
        chrs
             # Generate w random numbers between 1 and 94
             (roll(w, 1..94)
              # Set inner numbers on non-rungs to zero
              Z* 1, |($_%%h xx w-2), 1)
             # Add 32 to numbers
             X+ 32
    }
    # Map h*n+h-1 row numbers (1-indexed)
    1..^h*n+h
}

```

# Answer
> 5 votes
# Python 2, 142 bytes

```
lambda w,h,n,e=lambda:chr(randint(33,126)):[e()+[eval(("e()+"*(w-2))[:-1])," "*(w-2)][-~i%h>0]+e()for i in range(h*-~n-1)]
from random import*

```

Try it online!

Saved bytes thanks to ovs!

# Answer
> 5 votes
# PowerShell, ~~132~~ 124 bytes

```
param($w,$h,$n)-join([char[]]((($a=('#'+' '*($w-2)+"#`n")*--$h)+'#'*$w+"`n")*$n+$a)|%{($_,[char](33..126|Random))[$_-eq35]})

```

Try it online!

We construct a ladder composed of only `#` first (example), then loop `|%{...}` through each character and `if` it's `-eq`ual to `35`, we pull out a new `Random` character from the appropriate range. Otherwise we output (i.e., either a space or newline).

# Answer
> 5 votes
# JavaScript (ES6), ~~117~~ 115 bytes

A recursive function building the output character by character.

*"Look Ma, no literal line-feed!"*

```
(w,h,n)=>(g=x=>y<h*n+h-1?String.fromCharCode(x++<w?x%w>1&&-~y%h?32:Math.random()*94+33|0:10)+g(x>w?!++y:x):'')(y=0)

```

### Demo

```
let f =

(w,h,n)=>(g=x=>y<h*n+h-1?String.fromCharCode(x++<w?x%w>1&&-~y%h?32:Math.random()*94+33|0:10)+g(x>w?!++y:x):'')(y=0)

O.innerText = f(5,3,4)
```

```
<pre id=O></pre>
```

# Answer
> 4 votes
# Pyth, 33 bytes

```
VhEjtW!Nmsm?&d}kr1tQ\ Or\!C127Qvz

```

Try it online: Demonstration

# Answer
> 3 votes
# Java 8, ~~203~~ ~~188~~ ~~168~~ ~~133~~ ~~132~~ ~~130~~ ~~128~~ 126 bytes

```
W->H->N->{for(double i=0,j,q;++i<H*N+H;)for(j=W,q=10;j-->=0;q=i%H*j<1|j>W-2?33+Math.random()*94:32)System.out.print((char)q);}

```

Try it online!

# Answer
> 3 votes
# SOGL V0.12, ~~32~~ 31 bytes

```
 ~ΔkψR
I{e{R}¶bH{Re⁾⌡@R¶}}¹∑e⌡k

```

Try it Here!

Input in the order N, W, H.

Explanation:

```
 ~ΔkψR

     R  a function named "R", pushes a random character:
 ~       push "~"
  Δ      get the charasters from " " to "~"
   k     remove the 1st character
    ψ    choose a random character from that

I{e{R}¶bH{Re⁾⌡@R¶}}¹∑e⌡k  main program

I                         increase the 1st input - N
 {                }       N times do
  e                         push the variable e, which is here initialised to the next input - W
   { }                      E times do
    R                         execute R
      ¶                     push a newline
       bH                   push b-1, where b is initialised to the next input - H
         {       }          B-1 times do
          R                   execute R
           e⁾                 push e-2 aka width-2
             ⌡@               push that many spaces
               R              execute R
                ¶             push a newline
                   ¹∑     join the stack together
                     e⌡k  remove the first width characters

```

18 bytes without the random characters :/

# Answer
> 3 votes
# Python 2, 114 bytes

```
lambda w,h,n:[[chr(32+randint(1,94)*(x%~-w*(y%h)<1))for x in range(w)]for y in range(1,h*-~n)]
from random import*

```

Try it online!

# Answer
> 3 votes
# Haskell, ~~226~~ ~~220~~ ~~211~~ 190 bytes

```
import System.Random
a=mapM id
b=(putStr.unlines=<<).a
c=randomRIO('!','~')
r w=a$c<$[1..w]
s w=a$c:(return ' '<$[3..w])++[c]
(w#h)0=b$s w<$[2..h]
(w#h)n=do{b$(s w<$[2..h])++[r w];(w#h)$n-1}

```

Try it online!

*Saved 9 bytes thanks to Laikoni*

*Saved 21 bytes thanks to wchargin*

Should be golfable (`b$(s w)<$[2..h]` and `b$((s w)<$[2..h])++[r w]`). I don't feel comfortable with IO and golfing.

# Answer
> 2 votes
# Japt `-R`, ~~42~~ ~~41~~ ~~40~~ ~~37~~ ~~34~~ ~~28~~ 25 bytes

Takes input in the order `H,W,N`.

```
;*°WÉ ÆJ²ùVXgJùU¹r,@EÅöÃé

```

Try it

# Answer
> 2 votes
# JavaScript (ES6), 144 bytes

```
(w,h,n)=>Array(n+1).fill(("#".padEnd(w-1)+`#
`).repeat(h-1)).join("#".repeat(w)+`
`).replace(/#/g,_=>String.fromCharCode(33+Math.random()*94|0))

```

Creates the ladder out of `#` characters then replaces each one with a random ASCII char.

## Test Snippet

```
let f=
(w,h,n)=>Array(n+1).fill(("#".padEnd(w-1)+`#
`).repeat(h-1)).join("#".repeat(w)+`
`).replace(/#/g,_=>String.fromCharCode(33+Math.random()*94|0))

;(W.oninput=H.oninput=N.oninput=B.onclick=_=>{let vals=[W.value,H.value,N.value].map(eval);D.innerText=vals.join`, `;O.innerText=f(...vals);})()
```

```
W: <input id=W type=range min=3 max=25 value=12><br>
H: <input id=H type=range min=2 max=25 value=5><br>
N: <input id=N type=range min=2 max=10 value=2><br>
<button id=B>Rerun</button> <code id=D></code>
<pre id=O></pre>
```

# Answer
> 2 votes
# JavaScript (ES6), ~~129~~ 117 bytes

Unfortunately, while I was in the process of golfing this down, Arnauld beat me to a similar but shorter solution. By combining our 2 solutions, this can be 113 bytes

Includes a trailing newline.

```
(w,h,n)=>(g=c=>l?(c++<w?c%w>1&&l%h?` `:String.fromCharCode(94*Math.random()+33|0):`
`)+g(c>w?!--l:c):``)(0,l=h*++n-1)

```

---

## Try it

```
o.innerText=(f=
(w,h,n)=>(g=c=>l?(c++<w?c%w>1&&l%h?` `:String.fromCharCode(94*Math.random()+33|0):`
`)+g(c>w?!--l:c):``)(0,l=h*++n-1)
)(i.value=5,j.value=3,k.value=2);oninput=_=>o.innerText=f(+i.value,+j.value,+k.value)
```

```
label,input{font-family:sans-serif;font-size:14px;height:20px;line-height:20px;vertical-align:middle}input{margin:0 5px 0 0;padding:0 0 0 5px;width:100px;}
```

```
<label for=i>W: </label><input id=i min=3 type=number><label for=j>H: </label><input id=j min=2 type=number><label for=k>N: </label><input id=k min=2 type=number><pre id=o>
```

# Answer
> 1 votes
# QBIC, 76 bytes

```
[:*:+b-1|G=chr$(_r33,126|)~a%b\[:-2|G=G+@ `]][e|G=G+chr$(_r33,126|)]?_sG,1,e

```

## Explanation

```
[                       FOR a = 1 TO
 :                         input 1 (Height, now in var b)
  *                        times
   :                       input 2 (# of rungs, now in var c)
    +b-1|                  plus one bottom rung without crossbar
G=chr$(_r33,126|)       Assign to G a random char (_r is the RAND() function, chr$() is BASIC's num-to-char)
~a%b|                   IF we are not at a crossbar (the modulo returns anything but 0),
  [:-2|G=G+@ `            add to G x spaces, where x is width (input 3, now 'e') - 2
                        Note that G is now either 'X' or 'X   '  (for rnd char X and W=5)
]]                      Close the spacing FOR, close the IF
[e|                     FOR f = 1 to width
  G=G+chr$(_r33,126|)]     Append to G a rnd char
                        G is now either 'XXXXXX'  or 'X   XXXXX' (for rnd char X and W=5)
?_sG,1,e                PRINT the first w characters of G, and on to the next line

```

## Sample run

```
Command line: 3 2 5
N   F
M   `
Bj#=y
!   (
S   N
q(.Ho
%   7
g   ,

```

# Answer
> 1 votes
# MATL, ~~63~~ 50 bytes

*-13 bytes thanks to Luis Mendo*

```
Q*qXJ*6Y2HY)wT3$ZrJ3G3$eJ3G&Ol5LZ(J:HG\~3GTX"!+g*c

```

Try it online!

I'm still new to golfing in MATL (and I'm not super good at MATLAB for that matter), so I know this probably isn't close to optimal. Tips are welcome. Takes input in order `N,H,W`.

Here we go:

```
Q*qXJ                     # compute H*(N+1)-1, store as J
     *                    # multiply by W
      6Y2HY)              # push printable ASCII
            wT3$Zr        # sample uniformly with replacement
                  J3G3$e  # reshape to make a matrix of the appropriate shape.

```

We now have a matrix of random char.

```
J3G                       # push J,W
   &O                     # zero matrix, J x W
     l5LZ(                # assign 1 to first and last columns

```

Now there's also a logical matrix for the rails.

```
J:                        # push J, range, so 1...J
  HG                      # take second input (H)
    \~                    # mod and bool negate (so it's 1 for rows of multiples of H)
      3GTX"!              # repmat and transpose so we have 1's for rungs

```

Now we have 3 matrices on the stack:

* Top: 0 for non-rung, 1 otherwise
* Middle: 0 for non-rail, 1 otherwise
* Bottom: random characters, -20

So we do the following:

```
+                         # add the top two matrices.
 g                        # convert to logical so 0->0, nonzero->1
   *                      # elementwise multiply
    c                     # convert to char, implicit output (0 -> space).

```

# Answer
> 1 votes
# Powershell, 102 bytes

```
param($w,$h,$n)1..(++$n*$h-1)|%{$l=$_%$h
-join(1..$w|%{[char](32,(33..126|Random))[!$l-or$_-in1,$w]})}

```

Less golfed test script:

```
$f = {

param($w,$h,$n)
1..(++$n*$h-1)|%{       # for each lines of the ladder
    $l=$_%$h            # line number in a step
    -join(1..$w|%{      # make a line
        [char](32,(33..126|Random))[!$l-or$_-in1,$w]
    })                  # a random character if the line number in a step is a rung line or char position is 1 or width
                        # otherwise a space
}

}

&$f 5 3 2
&$f 3 2 2
&$f 12 4 5
&$f 20 5 3

```

Output:

```
0   {
H   S
']UxR
G   ]
3   t
q^R8O
q   y
t   J
U h
YQZ
_ i
3#D
I #
=          m
&          <
]          6
8nmuyw2'Y7%+
o          l
;          !
D          M
Fn[zGfT";RYt
@          B
$          e
z          @
@J[1|:-IS~y<
(          L
:          [
|          q
zBow0T0FnY8)
/          *
e          B
R          p
9{d2(RacBdRj
u          ~
`          l
J          h
v                  t
T                  -
v                  H
'                  Y
IS7{bx2&k@u7]o}>[Vq?
F                  U
?                  U
|                  Q
}                  T
:wv1wEfc6cS;430sigF|
<                  L
:                  }
*                  `
H                  =
L8k5Q/DQ=0XIUujK|c6|
j                  =
!                  p
V                  :
#                  w

```

# Answer
> 1 votes
# Ruby, 71 bytes

EDIT: Oops I thought this was a new challenge because of the recent edit to fix a typo lol. I'm still leaving this up though because there's no Ruby answer for it yet.

```
->w,h,n{(1..h*-~n-1).map{|i|[*?!..?~].sample(x=i%h>0?2:w)*(' '*(w-x))}}

```

Try it online!

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


title: Gambler's Fallacy Dice

text:
# Question
Title: Gambler's Fallacy Dice
The gambler's fallacy is a cognitive bias where we mistakenly expect things that have occurred often to be less likely to occur in the future and things that have not occurred in a while to be more likely to happen soon. Your task is to implement a specific version of this.

## Challenge Explanation

Write a function that returns a random integer between 1 and 6, inclusive. The catch: the first time the function is run, the outcome should be uniform (within 1%), however, each subsequent call will be skewed in favor of values that have been rolled fewer times previously. The specific details are as follows:

* The die remembers counts of numbers generated so far.
* Each outcome is weighted with the following formula: \\$count\_{max} - count\_{die} + 1\\$
    + For instance, if the roll counts so far are \\$\[1, 0, 3, 2, 1, 0\]\\$, the weights will be \\$\[3, 4, 1, 2, 3, 4\]\\$, that is to say that you will be 4 times more likely to roll a \\$2\\$ than a \\$3\\$.
    + Note that the formula means that a roll outcome of \\$\[a, b, c, d, e, f\]\\$ is weighted the same as \\$\[a + n, b + n, c + n, d + n, e + n, f + n\]\\$

## Rules and Assumptions

* Standard I/O rules and banned loopholes apply
* Die rolls should not be deterministic. (i.e. use a PRNG seeded from a volatile source, as is typically available as a builtin.)
* Your random source must have a period of at least 65535 or be true randomness.
* Distributions must be within 1% for weights up to 255
    + 16-bit RNGs are good enough to meet both the above requirements. Most built-in RNGs are sufficient.
* You may pass in the current distribution as long as that distribution is either mutated by the call or the post-roll distribution is returned alongside the die roll. Updating the distribution/counts *is a part of this challenge*.
* You may use weights instead of counts. When doing so, whenever a weight drops to 0, all weights should increase by 1 to achieve the same effect as storing counts.
    + You may use these weights as repetitions of elements in an array.

Good luck. May the bytes be ever in your favor.

# Answer
> 12 votes
# , 59 bytes

```
function(){T[o]<<-T[o<-sample(6,1,,max(T)-T+1)]+1
o}
T=!1:6

```

Try it online!

Keeps the counts in `T`, which is then transformed to be used as the `weights` argument to `sample` (which then most likely normalizes them to sum to `1`).

The `[<<-` operator is used to assign a value to `T` in one of the parent environments (in this case, the only parent environment is `.GlobalEnv`).

# Answer
> 6 votes
# Python 3, ~~112~~ 99 bytes

```
from random import*
def f(C=[0]*6):c=choices(range(6),[1-a+max(C)for a in C])[0];C[c]+=1;print(c+1)

```

Try it online!

**Explanation**

```
# we only need the "choice" function
from random import*

      # C, the array that holds previous choices, is created once when the function is defined
      # and is persisted afterwards unless the function is called with a replacement (i.e. f(C=[0,1,2,3,4,5]) instead of f() )
      C=[0]*6
# named function
def f(.......):
                  # generate weights
                  [1-a+max(C)for a in C]
# take the first item generated using built-in method
c=choices(range(6),......................)[0]
    # increment the counter for this choice
    C[c]+=1
    # since the array is 0-indexed, increase the number by 1 for printing
    print(c+1)

```

Edit: Saved 13 bytes. Thanks, attinat!

# Answer
> 5 votes
# 05AB1E, 13 bytes

```
Z>αāDrÅΓΩ=Q+=

```

Try it online!

Takes the list of counts as input. Outputs the roll and the new counts.

Explanation:

```
Z                 # maximum
 >                # plus 1
  α               # absolute difference (vectorizes)
                  # the stack now has the list of weights
ā                 # range(1, length(top of stack)), in this case [1..6]
 D                # duplicate
  r               # reverse the entire stack
   ÅΓ             # run-length decode, using the weights as the run lengths
     Ω            # pick a random element
                  # the stack is now: counts, [1..6], random roll
=                 # output the roll without popping
 Q                # test for equality, vectorizing
  +               # add to the counts
   =              # output the new counts

```

# Answer
> 4 votes
# APL (Dyalog Unicode), 32 bytesSBCS

-4 bytes using replicate instead of interval index.

```
{1∘+@(⎕←(?∘≢⌷⊢)(1+⍵-⍨⌈/⍵)/⍳6)⊢⍵}

```

Try it online!

Defined as a function that takes the current distribution as an argument, prints the resulting die roll, and returns the updated distribution. First run on TIO is 100 invocations starting with `[0,0,0,0,0,0]`, second run is heavily biased towards 1 with `[0,100,100,100,100,100]`, and the last run is heavily biased towards 6 in the same manner.

# Answer
> 3 votes
# JavaScript (ES8), 111 bytes

```
_=>++C[C.map((v,i)=>s+=''.padEnd(Math.max(...C)-v+1,i),s=''),n=s[Math.random()*s.length|0]]&&++n;[,...C]=1e6+''

```

Try it online!

### How?

This is a rather naive and most probably suboptimal implementation that performs the simulation as described.

We keep track of the counts in \\$C\\$. At each roll, we build a string \\$s\\$ consisting of each die \\$i\\$ repeated \\$max(C)-C\_i+1\\$ times and pick a random entry in there with a uniform distribution.

# Answer
> 3 votes
# Perl 6, 31 bytes

```
{--.{$/=.pick}||++«.{1..6};$/}

```

Try it online!

Accepts the current weight distribution as a BagHash, starting with one where all weights are 1. The distribution is mutated in-place.

The BagHash `pick` method selects a key at random using the associated weights; the weight of that key is then decremented by one. If that weight is thereby made zero, `++«.{1..6}` increments the weights of all numbers 1-6.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 91 bytes

```
w=1~Table~6
F:=Module[{g},g=RandomChoice[w->Range@6];w[[g]]++;w=Array[Max@w-w[[#]]+1&,6];g]

```

Try it online!

# Answer
> 2 votes
## Javascript (ES6+), 97 bytes

```
d=[1,2,3,4,5,6]
w=[...d]
r=x=>(i=~~(Math.random()*w.length),k=w[i],w.concat(d.filter(x=>x!=k)),k)

```

### Explanation

```
d=[1,2,3,4,5,6]                   // basic die
w=[...d]                          // weighted die
r=x=>(                            // x is meaningless, just saves 1 byte vs ()
  i=~~(Math.random()*w.length),   // pick a random face of w
  k=w[i],                         // get the value of that face
  w.concat(d.filter(x=>x!=k)),    // add the faces of the basic die that aren't the value
                                  // we just picked to the weighted die
  k                               // return the value we picked
)

```

Note this will eventually blow up if `w` exceeds a length of 232-1, which is the max array length in js, but you'll probably hit a memory limit before then, considering a 32-bit int array 232-1 long is 16GiB, and some (most?) browsers won't let you use more than 4GiB.

# Answer
> 2 votes
# Perl 6, 49 bytes

```
{($!=roll (1..6 X=>1+max 0,|.{*})∖$_:),$_⊎$!}

```

Try it online!

Takes the previous rolls as a Bag (multiset). Returns the new roll and the new distribution.

### Explanation

```
{                                            }  # Anon block taking
                                                # distribution in $_
                     max 0,|.{*}  # Maximum count
                   1+             # plus one
           1..6 X=>  # Pair with numbers 1-6
          (                     )∖$_  # Baggy subtract previous counts
     roll                            :  # Pick random element from Bag
 ($!=                                 )  # Store in $! and return
                                       ,$_⊎$!  # Return dist with new roll

```

# Answer
> 1 votes
# Pyth, ~~22~~ 20 bytes

```
Xt
hOs.e*]kh-eSQbQQ1

```

Try it online!

Input is the previous frequencies as a list, outputs the next roll and the updated frequencies separated by a newline.

```
Xt¶hOs.e*]kh-eSQbQQ1   Implicit: Q=eval(input())
                       Newline replaced with ¶
      .e         Q     Map elements of Q, as b with index k, using:
             eSQ         Max element of Q (end of sorted Q)
            -   b        Subtract b from the above
           h             Increment
        *]k              Repeat k the above number of times
                       Result of the above is nested weighted list
                       e.g. [1,0,3,2,1,0] -> [[0, 0, 0], [1, 1, 1, 1], [2], [3, 3], [4, 4, 4], [5, 5, 5, 5]]
     s                 Flatten
    O                  Choose random element
   h                   Increment
  ¶                    Output with newline
 t                     Decrement
X                 Q1   In Q, add 1 to the element with the above index
                       Implicit print

```

# Answer
> 1 votes
# Jelly, 12 bytes

```
’ạṀJx$X,Ṭ+¥¥

```

Try it online!

A monadic link which takes a single argument, the current count list, and returns a list of the number chosen and the updated count list.

# Jelly, 18 bytes

```
0x6+ɼṀ_®‘Jx$XṬ+ɼṛƊ

```

Try it online!

As an alternative, here’s a niladic link which returns the number chosen and keeps track of the count list in the register.

---
Tags: code-golf, random
---


# Question
Title: Search text for a prefix and list all its suffixes in the text
I use "suffix" loosely here to mean "any sub-string that follows the prefix".

"Prefix" here means the START of a word, where a word's start is defined as either after a space or from the first character of the input text (for the first word). A "prefix" in the middle of a word is ignored.

E.g. if your input prefix is "arm" and the input text is "Dumbledore's army was fully armed for the impending armageddon" then the output list contains (y, ed, ageddon).

## Test Cases

Assume case-sensitive, strings end after spaces. Input will not start with a space.

Removing duplicates is optional.

---

```
Input prefix: "1"

Input text:

"He1in aosl 1ll j21j 1lj2j 1lj2 1ll l1j2i"

Output: (ll, lj2j, lj2) - in any permutation

```

---

```
Input prefix: "frac"

Input text:

"fracking fractals fracted fractional currency fractionally fractioned into fractious fractostratic fractures causing quite a fracas"

Output: (king, tals, ted, tional, tionally, tioned, tious, tostratic, tures, as)

```

---

```
Input prefix: "href="https://www.astrotheme.com/astrology/"

Input text:

"(div style="padding: 0; background: url('https://www.astrotheme.com/images/site/arrondi_450_hd.png') no-repeat; text-align: left; font-weight: bold; width: 450px; height: 36px")
  (div class="titreFiche" style="padding: 5px 0 0 6px")(a href="https://www.astrotheme.com/astrology/Nolwenn_Leroy" title="Nolwenn Leroy: Astrology, birth chart, horoscope and astrological portrait")Nolwenn Leroy(br /)
(/div)
  (div style="text-align: right; border-left: 1px solid #b2c1e2; border-right: 1px solid #b2c1e2; width: 446px; padding: 1px 1px 0; background: #eff8ff")
    (table style="width: 100%")(tr)(td style="width: 220px")
(div style="padding: 0; background: url('https://www.astrotheme.com/images/site/arrondi_450_hd.png') no-repeat; text-align: left; font-weight: bold; width: 450px; height: 36px")
  (div class="titreFiche" style="padding: 5px 0 0 6px")(a href="https://www.astrotheme.com/astrology/Kim_Kardashian" title="Kim Kardashian: Astrology, birth chart, horoscope and astrological portrait")Kim Kardashian(br /)(span style="font-weight: normal; font-size: 11px")Display her detailed horoscope and birth chart(/span)(/a)(/div)
(/div)
(div style="padding: 0; background: url('https://www.astrotheme.com/images/site/arrondi_450_hd.png') no-repeat; text-align: left; font-weight: bold; width: 450px; height: 36px")
  (div class="titreFiche" style="padding: 5px 0 0 6px")(a href="https://www.astrotheme.com/astrology/Julia_Roberts" title="Julia Roberts: Astrology, birth chart, horoscope and astrological portrait")Julia Roberts(br /)(span style="font-weight: normal; font-size: 11px")Display her detailed horoscope and birth chart(/span)(/a)(/div)
    (td id="cfcXkw9aycuj35h" style="text-align: right")
  (/div)"

Output: (Nolwenn_Leroy", Kim_Kardashian", Julia_Roberts")

```

## The Winner

This is , so the fewest bytes wins. :)

Can accept the inputs in any way that works, as long as your code can solve arbitrary problems like the test cases.

# Answer
# , 63 bytes

```
function(s,p,z=el(strsplit(s,' ')))sub(p,'',z[startsWith(z,p)])

```

Try it online!

The positive-lookbehind implementation is unfortunately 5 bytes longer due to the huge `regmatches/gregexpr` combination :

```
function(s,p)regmatches(s,gregexpr(paste0('(?<=',p,')[^ ]*'),s,,T))

```
> 5 votes

# Answer
# Jelly, 12 bytes

```
Ḳfṛ"€¥Ḋ€ṫ€L}

```

Try it online!
> 4 votes

# Answer
# C (gcc), ~~113~~ ~~109~~ ~~106~~ 105 bytes

*-4 bytes thanks to @LambdaBeta!*
*-3 bytes thanks to @WindmillCookies!*

```
i;f(char*s,char*t){for(i=strlen(s);*t;t++)if(!strncmp(t,s,i))for(t+=i,puts("");*t^32&&*t;)putchar(*t++);}

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~57~~ 56 bytes

```
lambda i,j:[w[len(i):]for w in j.split()if w.find(i)==0]

```

Try it online!

-1 with thanks to @mypetlion
> 4 votes

# Answer
# Japt, 9 bytes

8 bytes if we can take input as an array of words.

```
¸kbV msVl
¸         // Shorthand for `qS`, split into words.
 kbV      // Filter the words, selecting only those that start with the prefix.
     msVl // For each remaining word, remove prefix length chars from the start.

```

Try it online!
> 4 votes

# Answer
# Retina, 31 bytes

```
L`(?<=^\2¶(.|¶)*([^ ¶]+))[^ ¶]+

```

Try it online! First line should be the desired prefix, the rest is the input text. Does not remove duplicates. Would be 25 bytes if any white space was a valid seprator. Explanation: We want to list the suffixes of valid prefixes. The `[^ ¶]+` matches the suffix itself. The prefix of the regexp is a lookbehind that ensures that the prefix of the suffix is the input prefix. As a lookbehind is evaluated right-to-left, this starts by matching the prefix (using the same pattern but inside `()`s to capture it), then any characters, before finally matching the prefix on its own line at the beginning of the input.
> 3 votes

# Answer
# Japt, ~~16~~ 12 bytes

*Port of Arnauld Answer*

*-4 bytes from @Shaggy*

```
iS qS+V Å®¸g

iS                  Insert S value (S = " ") at beginning of first input (Implicit)
   q                split using
    S+V             S + Second input
        Å           slice 1
         ®          map
          ¸         split using S
           g        get first position

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 11 bytes

```
#ʒηså}εsgF¦

```

Try it online! (here is a demo for multiline strings)

### How does it work?

```
#ʒηså}εsgF¦    Full program.
#              Split the first input by spaces.
 ʒ   }         Filter the words by ...
  ηså          ... "Does the second input occur in the prefixed of the word?"
      ε        And for each valid word
       sg      Retrieve the length of the of the second input.
         F¦    And drop the first character of the word that number of times.

```
> 3 votes

# Answer
# Stax, 8 bytes

```
·B¬╤²*6&

```

Run and debug it

Explanation:

```
j{x:[fmx|- Full program, implicit input: On stack in order, 1st input in X register
j          Split string on spaces
 {   f     Filter:
  x:[        Is X a prefix?
      m    Map passing elements:
       x|-   Remove all characters in X the first time they occur in the element
             Implicit output

```

I could also use `x%t` (length of X, trim from left), which is equally long but packs to 9 bytes.
> 3 votes

# Answer
# Brachylog, ~~24~~ 21 bytes

```
tṇ₁W&h;Wz{tR&h;.cR∧}ˢ

```

Try it online!

Could have been a few bytes shorter if there was variable sharing with inline predicates.

Input is an array with the prefix as the first element and the text as the second element.

```
tṇ₁W                    % Split the text at spaces, call that W
    &h;Wz               % Zip the prefix with each word, to give a list of pairs
         {         }ˢ   % Select the outputs where this predicate succeeds:
          tR            % Call the current word R
            &h;.c       % The prefix and the output concatenated
                 R      % should be R
                  ∧     % (No more constraints on output)

```
> 3 votes

# Answer
# IBM/Lotus Notes Formula, 54 bytes

```
c:=@Explode(b);@Trim(@If(@Begins(c;a);@Right(c;a);""))

```

Takes it's input from two fields named `a` and `b`. Works because Formula will recursively apply a function to a list without the need for a `@For` loop.

No TIO available so here's a screenshot:
> 2 votes

# Answer
# APL (Dyalog Unicode), 23 bytesSBCS

Full program. Prompts for text and prefix from stdin. Prints list to stdout.

```
(5⌽'(\w+)\b',⎕)⎕S'\1'⊢⎕

```

Try it online!

prompt (for text)

yield that (separates `'\1'` from )

`(``)⎕S'\1'` PCRE Search and return list of capture group 1 from the following regex:

prompt (for prefix)

`'(\w+)\b',` prepend this string (group of word characters followed by a word boundary)

`5⌽` rotate the first 5 characters to the end; `'\bPREFIX(\w+)'`
> 2 votes

# Answer
# MATL, 17 bytes

```
Yb94ih'(.*)'h6&XX

```

Try it on MATL Online

### How?

`Yb` \- Split the input at spaces, place the results in a cell array

`94` \- ASCII code for `^` character

`ih` \- Get the input (say "frac"), concatenate '^' and the input

`'(.*)'h` \- Push the string `'(.*)'` into the stack, concatenate '^frac' and '(.\*)'. So now we have `'^frac(.*)`, a regex that matches "frac" at the beginning of the string and captures whatever comes after.

`6&XX` \- Run regexp matching, with `6&` specifying 'Tokens' mode i.e., the matched capture groups are returned instead of the entire match.

Implicitly output the results.
> 2 votes

# Answer
# C (clang), 107 bytes

```
i;f(s,t,_)char*s,*t,*_;{i=strlen(s);_=strtok(t," ");while((strncmp(_,s,i)||puts(_+i))&&(_=strtok(0," ")));}

```

Try it online!

Description:

```
i;f(s,t,_)char*s,*t,*_;{   // F takes s and t and uses i (int) and s,t,u (char*)
    i=strlen(s);           // save strlen(s) in i
    _=strtok(t," ");       // set _ to the first word of t
    while(                 // while loop
        (strncmp(_,s,i)||  // short-circuited if (if _ doesn't match s to i places)
         puts(_+i))        // print _ starting at the i'th character
        &&                 // the previous expression always returns true
        (_=strtok(0," "))) // set _ to the next word of t
    ;                      // do nothing in the actual loop
}

```

Has to be clang because gcc segfaults without `#include <string.h>` due to strtok problems.
> 2 votes

# Answer
# PowerShell 3.0, ~~60~~ ~~62~~ 59 bytes

```
param($p,$s)-split$s|%{if($_-cmatch"^$p(.*)"){$Matches[1]}}

```

Lost some bytes suppressing the cmatch output. Had a janky solution that gained some by purposely causing duplicates. But it also threw redlines if it didn't match on the first but that is not fine now that I think about it. +2 bytes to fix it though.
> 2 votes

# Answer
# Bash \+ grep, 20 bytes

```
grep -Po "\b$1\K\S*"

```

Prefix is given as a command-line parameter, and input text is piped in via stdin.

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), ~~64~~ 59 bytes

*-5 bytes from @Shaggy*

```
a=>b=>b.match(eval(`/\\b${a}\\w*/g`)).map(x=>x.split(a)[1])

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 57 bytes

Takes input in currying syntax `(text)(prefix)`. Does not remove duplicates.

```
s=>p=>(' '+s).split(' '+p).slice(1).map(s=>s.split` `[0])

```

Try it online!
> 1 votes

# Answer
# Perl 6, 30 bytes

```
{$^t.comb: /[^|' ']$^p <(\S+/}

```

Test it

## Expanded:

```
{  # bare block lambda with placeholder params $p, $t

  $^t.comb:    # find all the substrings that match the following
  /
    [ ^ | ' ' ] # beginning of string or space
    $^p        # match the prefix
    <(         # don't include anything before this
    \S+        # one or more non-space characters (suffix)
  /
}

```
> 1 votes

# Answer
# Perl 5 with -asE, ~~23~~ ~~22~~ 21 bytes (?)

```
say/^$b(.*)/ for@F

```

Try it online!

Can be run as a commandline one-liner as `perl -asE 'say/^$b(.*)/ for@F' -- -b=frac -`, or with a filename in place of the last `-`.
Or from a script file, say `perl -as -M5.010 script.pl -b=frac -` (thanks to @Brad Gilbert b2gills for the TIO link demonstrating this).

The code itself is 18 bytes, I added 3 bytes for the `-b=` option which assigns its value (the prefix input) to a variable named `$b` in the code. That felt like an exception to the usual "flags aren't counted" consensus.

`-a` splits each input line at spaces and places the result in the array `@F`. `-s` is a shortcut way of assigning a command-line argument as a variable, by giving a name on the command-line. Here the argument is `-b=frac`, which places the prefix "frac" in a variable `$b`.

`/^$b(.*)/` \- Matches the value of `$b` at the beginning of the string. `.*` is whatever comes after that, until the end of the word, and the surrounding parantheses capture this value. The captured values are automatically returned, to be printed by `say`. Iterating through space-separated words with `for @F` means we don't have to check for initial or final spaces.
> 1 votes

# Answer
# Jelly,  ~~11~~  9 bytes

```
Ḳœṣ€ḢÐḟj€

```

A dyadic link accepting the text (a list of characters) on the left and the prefix (a list of characters) on the right which yields a list of lists of characters (the resulting suffixes).

**Try it online!** (footer joins with spaces to avoid full-program's implicit smashing)
Note: I added three edge cases to the string in the OP - unfrackled and nofracfracheremate to the beginning, which should not output and fracfracit to the end which should output fracit.

### How?

```
Ḳœṣ€ḢÐḟj€ - Link: text, prefix                        e.g. "fracfracit unfracked", "frac"
Ḳ         - split (text) at spaces -> list of words        ["fracfracit", "unfracked"]
   €      - for each (word):
 œṣ       -   split around sublists equal to (prefix)       ["","","it"]  ["un","ked"]
     Ðḟ   - filter discard items for which this is truthy:
    Ḣ     -   head
          -   -- Crucially this modifies the list:             ["","it"]       ["ked"]
          -   -- and yields the popped item:                 ""            "un"
          -   -- and only non-empty lists are truthy:       kept          discarded
          -            ...so we end up with the list:      [["","it"]]
        € - for each (remaining list of lists of characters):
       j  -   join with the prefix                          "fracit"
          -                                                ["fracit"]

```

---

**previous 11 byter:**

```
Ḳs€L}Ḣ⁼¥ƇẎ€

```

Also a dyadic link as above.

Try it online!
> 1 votes

# Answer
# Haskell, 51 bytes

```
p#x=[length p`drop`y|y<-words x,and$zipWith(==)p y]

```

Try it online!
> 1 votes

# Answer
# Husk, 11 bytes

Pretty much just a port of the Haskell answer:

```
m↓L⁰foΠz=⁰w

```

Try it online!

## Explanation

```
m↓L⁰f(Πz=⁰)w  -- prefix is explicit argument ⁰, the other one implicit. eg: ⁰ = "ab" and implicit "abc def"
           w  -- words: ["abc","def"]
    f(    )   -- filter by (example w/ "abc"
       z=⁰    -- | zip ⁰ and element with equality: [1,1]
      Π       -- | product: 1
              -- : ["abc"]
m             -- map the following
 ↓            -- | drop n elements
  L⁰          -- | n being the length of ⁰ (2)
              -- : ["c"]

```
> 1 votes

# Answer
# Java 10, 94 bytes

```
p->s->{for(var w:s.split(" "))if(w.startsWith(p))System.out.println(w.substring(p.length()));}

```

Try it online here.

Ungolfed:

```
p -> s -> { // lambda taking prefix and text as Strings in currying syntax
    for(var w:s.split(" ")) // split the String into words (delimited by a space); for each word ...
        if(w.startsWith(p)) //  ... test whether p is a prefix ...
            System.out.println(w.substring(p.length())); // ... if it is, output the suffix
}

```
> 1 votes

# Answer
# Small Basic, 242 bytes

A Script that takes no input and outputs to the `TextWindow` Object

```
c=TextWindow.Read()
s=TextWindow.Read()
i=1
While i>0
i=Text.GetIndexOf(s," ")
w=Text.GetSubText(s,1,i)
If Text.StartsWith(w,c)Then
TextWindow.WriteLine(Text.GetSubTextToEnd(w,Text.GetLength(c)+1))
EndIf
s=Text.GetSubTextToEnd(s,i+1)
EndWhile

```

Try it at SmallBasic.com! *Requires IE/Silverlight*
> 1 votes

# Answer
# Python 2, 53 bytes

```
lambda i,j:[w.split()[0]for w in j.split(i)if len(w)]

```

Try it online!
> 1 votes

# Answer
# Brachylog, 12 bytes

```
hṇ₁∋R&t;.cR∧

```

Try it online!

Takes input as `[text, prefix]` through the input variable, and generates each word through the output variable. This was originally sundar's answer, which I started trying to golf after reading that it "could have been a few bytes shorter if there was variable sharing with inline predicates", which is possible now. Turns out that generator output saves even more bytes.

```
    R           R
   ∋            is an element of
h               the first element of
                the input
 ṇ₁             split on spaces,
     &          and the input
      t         's last element
         c      concatenated
       ;        with
        .       the output variable
          R     is R
           ∧    (which is not necessarily equal to the output).

```

My first two attempts at golfing it down, using fairly new features of the language:

With the global variables that had been hoped for: `hA⁰&tṇ₁{∧A⁰;.c?∧}ˢ` (18 bytes)

With the apply-to-head metapredicate: `ṇ₁ᵗz{tR&h;.cR∧}ˢ` (16 bytes)

And my original solution:

# Brachylog, 15 bytes

```
ṇ₁ʰlᵗ↙X⟨∋a₀⟩b↙X

```

Try it online!

Same I/O. This is essentially a generator for words with the prefix, `ṇ₁ʰ⟨∋a₀⟩`, modified to remove the prefix.

```
                   The input variable
  ʰ                with its first element replaced with itself
ṇ₁                 split on spaces
    ᵗ              has a last element
   l               the length of which
     ↙X            is X,
       ⟨   ⟩       and the output from the sandwich
       ⟨∋  ⟩       is an element of the first element of the modified input
       ⟨ a₀⟩       and has the last element of the input as a prefix.
                   The output variable
       ⟨   ⟩       is the output from the sandwich
            b      with a number of characters removed from the beginning
             ↙X    equal to X.

```

A very different predicate with the same byte count:

# Brachylog, 15 bytes

```
hṇ₁∋~c₂Xh~t?∧Xt

```

Try it online!

Same I/O.

```
   ∋               An element of
h                  the first element of
                   the input variable
 ṇ₁                split on spaces
    ~c             can be un-concatenated
      ₂            into a list of two strings
       X           which we'll call X.
        h          Its first element
         ~t        is the last element of
           ?       the input variable,
            ∧      and
             Xt    its last element is
                   the output variable.

```
> 1 votes

# Answer
# Red, 62 bytes

```
func[p s][parse s[collect[any[p keep to[" "| end]| thru" "]]]]

```

Try it online!
> 0 votes

# Answer
# Pyth, ~~21~~ ~~20~~ ~~18~~ ~~17~~ 16 bytes

```
AQVcH)IqxNG0:NG"

```

Try it online!

-1 by using `V` instead of `FN` because `V` implicitly sets `N`

-2 after some further reading about string slicing options

-1 using `x` to check for the presence of the substring at index 0

-1 using replace with "" for getting the end of the string

I'm sure this could use some serious golfing but as a Pyth beginner, just getting it to work was a bonus.

**How does it work?**

```
assign('Q',eval_input())
assign('[G,H]',Q)
for N in num_to_range(chop(H)):
    if equal(index(N,G),0):
        imp_print(at_slice(N,G,""))

```
> 0 votes

# Answer
# Excel VBA, 86 bytes

Takes input as prefix in `[A1]` and values in `[B1]` and outputs to the console.

```
For each w in Split([B1]):?IIf(Left(w,[Len(A1)])=[A1],Mid(w,[Len(A1)+1])+" ","");:Next

```
> 0 votes

# Answer
# C (gcc), 99 bytes

This uses `strsep` instead of `strtok`, saving a few bytes. Oddly, I had to include the function prototype for `strsep` (and `strtok`) to avoid segment faults when not including `string.h`.

```
char*strsep();w;f(s,t,u)char*s,*t,*u;{for(w=strlen(t);u=strsep(&s," ");)strncmp(u,t,w)||puts(u+w);}

```

Try it online!
> 0 votes

---
Tags: code-golf, string, data-structures, search
---


title: Which really big number is bigger?

text:
# Question
Title: Which really big number is bigger?
This question is tricky (and in particular harder than Which big number is bigger?), for those who like more challenging puzzles.

**Input**

Integers a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 each in the range 1 to 10.

**Output**

```
True if a1^(a2^(a3^(a4^a5))) > b1^(b2^(b3^(b4^b5))) and False otherwise.

```

^ is exponentiation in this question.

**Rules**

This is code-golf. Your code must terminate correctly within 10 seconds for any valid input on TIO. If your language is not on TIO, the code should finish under 10 seconds on your machine.

You can output anything Truthy for True and anything Falsey for False.

**Test cases**

Recall that by the rules of exponentiaon, a1^(a2^(a3^(a4^a5))) == a1^a2^a3^a4^a5.

```
10^10^10^10^10 > 10^10^10^10^9
1^2^3^4^5 < 5^4^3^2^1
2^2^2^2^3 > 10^4^3^2^2
6^7^8^9^10 is not bigger than 6^7^8^9^10
10^6^4^2^2 < 10^6^2^4^2
2^2^2^2^10 > 2^2^2^10^2
10^9^8^7^6 < 6^7^8^9^10
3^1^10^10^10 > 2^1^10^10^10
9^10^10^10^10 < 10^9^10^10^10

```

**New test cases from Kevin Cruijssen**

```
[10,10,10,10,10, 10,10,10,10,9] #true
[2,2,2,2,3,      10,4,3,2,2]    #true
[2,2,2,2,10,     2,2,2,10,2]    #true
[10,10,10,10,10, 9,10,10,10,10] #true
[3,2,2,1,1,      2,5,1,1,1]     #true
[2,2,3,10,1,     2,7,3,9,1]     #true
[7,9,10,10,10,   6,9,10,10,10]  #true
[3,2,2,2,2,      2,2,2,2,2]     #true
[8,3,1,2,1,      2,2,3,1,1]     #true
[2,4,2,1,1,      3,3,2,1,1]     #true
[5,4,3,2,1,      1,2,3,4,5]     #true

[1,2,3,4,5,      5,4,3,2,1]     #false
[6,7,8,9,10,     6,7,8,9,10]    #false
[10,6,4,2,2,     10,6,2,4,2]    #false
[10,9,8,7,6,     6,7,8,9,10]    #false
[1,10,10,10,10,  1,10,10,10,9]  #false
[2,4,1,1,1,      2,2,2,1,1]     #false
[2,2,2,1,1,      2,4,1,1,1]     #false
[2,5,1,1,1,      3,2,2,1,1]     #false
[4,2,1,1,1,      2,4,1,1,1]     #false
[2,4,1,1,1,      4,2,1,1,1]     #false
[2,3,10,1,1,     8,3,9,1,1]     #false
[8,3,9,1,1,      2,3,10,1,1]    #false
[2,4,1,1,1,      3,3,1,1,1]     #false
[2,2,1,9,9,      2,2,1,10,10]   #false
[2,2,1,10,10,    2,2,1,9,9]     #false
[1,1,1,1,1,      1,2,1,1,1]     #false

```

# Answer
> 8 votes
# Ruby, 150 bytes

See revisions for previous byte counts.

```
->a,b,c,d,e,f,g,h,i,j{l=->s,t=c{Math.log(s,t)};y,z=l[l[g,b]]-d**e+l[h]*i**=j,l[l[a,f]*b**c,g];a>1?f<2?1:b<2||g<2?z>h:c<2||d<2?l[z,h]>i:y==0?a>f:y<0:p}

```

-10 bytes thanks to *@ValueInk*

+16 bytes thanks to *@RosLuP* for bugs.

Try it online.

Compare different base powers-towers (of 'height' five)?

### Ungolfed code:

```
-> a, b, c, d, e, f, g, h, i, j {
    l =-> s, t = c {Math.log(s, t)}
    i **= j
    y = l[l[g, b]] - d ** e + l[h] * i
    z = l[l[a, f] * b ** c, g]
    if a == 1
        return p
    elsif f == 1
        return 1
    elsif b == 1 || g == 1
        return z > h
    elsif d == 1 || c == 1
        return l[z, h] > i
    elsif y == 0
        return a > f
    else
        return y < 0
    end
}

```

### Code breakdown:

```
l =-> s, t = c {Math.log(s, t)}

```

This is the base `t` logarithm, which will be used to reduce the size of the numbers we are comparing. It defaults to base `c` when only one argument is given.

```
i **= j
y = l[l[g, b]] - d ** e + l[h] * i
z = l[l[a, f] * b ** c, g]

```

This updates `i = i ** j` since `i` never gets used on it's own, and `y` is the result of logging `b^c^d^e == g^h^i(^j)` twice and moving everything to one side. We then let `z = l[a, f] * b ** c` as the log base `g` of the log base `f` of `a ** b ** c`.

```
if a == 1
    return p
elsif f == 1
    return 1

```

`1^b^c^d^e = 1` is never greater than `f^g^h^i^j`, and likewise, `a^b^c^d^e` is always greater than `1^g^h^i^j = 1` if `a != 1`. Note that `return p` returns `nil`, which is falsey, and `return 1` returns `1`, which is truthy.

```
elsif b == 1
    return z > h

```

If `b == 1` or `g == 1`, then this reduces to comparing `a ** b ** c` to `f ** g ** h`, which is done with two logs to both sides.

```
elsif d == 1 || c == 1
    return l[z, h] > i

```

This compares `a ** b ** c` with `f ** g ** h ** i` by rearranging it as `log[log[b ** c * log[a, f], g], h]` compared to `i`. (Recall that `i **= j` in the beginning and `z = log[b ** c * log[a, f], g]`.)

```
elsif y == 0
    return a > f
else
    return y < 0
end

```

This compares the 4 highest powers after logging both sides twice. If they are equal, it compares the base.

# Answer
> 5 votes
# Python 2, ~~671~~ ~~612~~ ~~495~~ ~~490~~ ~~611~~ 597 bytes

```
lambda a,b:P(S(a,b))>P(S(b,a))if P(a)==P(b)else P(a)>P(b)
def S(a,b):
  if a and a[-1]==b[-1]:
    a.pop()
    b.pop()
    return S(a,b)
from math import*
L=log
E=exp
N=lambda m,n,x:N(m,n+1,L(x))if x>=1else N(m,n-1,E(x))if x<0else(m+n,x)
A=lambda a,n,x:(0,1)if a==1else(1,R(x,n)*L(a))if a<1else N(2,*C(L(L(a)),x,n-1))if n else(1,x*L(a))
def C(c,x,n):
 if c*n==0:return(0if c else n,x+c)
 z=R(x,n-1)
 if z<=L(abs(c)):return(0,E(z)+c)
 return N(1,*C(L(1-E(L(-c)-z)if c<0else 1+E(L(c)-z)),x,n-1))
def R(x,n):
 try:exec'x=E(x)'*n
 except:x=float('inf')
 return x
P=lambda b:b and N(0,*A(b[0],*P(b[1:])))or(0,1)

```

-59 bytes thanks to *@EmbodimentOfIgnorance*
-117 bytes thanks to *@Neil*
+121 bytes for about five bug-fixes, all found by *@ngn*

Takes the inputs as two lists. ~~NOTE: Also works with larger lists or those of unequal length.~~ EDIT: No longer true; it still works if `P(a)` and `P(b)` result in different tuples, but if they are the same this updated code above only works with lists with a fixed size of 5 now.

Try it online.

**Explanation:**

Golfed version of this answer on math.stackexchange.com, so all credit goes to *@ThomasAhle*.

To quote his answer:

> The idea is to represent power towers as a single floating point number with \\$n\\$ exponentiations: \\$(x\mid n) := exp^n(x)\\$. Normalizing \\$x\in\[0,1)\\$, this format allows easy comparison between numbers.
>
> What remains is a way to calculate \\$a^{(x\mid n)}\\$ for any real, positive \\$a\\$. My Python code below is an attempt to do so, while being as numerically stable as possibly, e.g. by using the log-sum trick. My code runs in time proportional to the height of the tower (number of `apow` calls) and the iterated-log of it's value (number of recursive calls).
>
> I haven't been able to find two towers with values close enough to case my method to fail. At least for integer exponents. With fractional exponents it is possible to create very towers too close for my representation to handle. E.g. \\$2^{2^{2^{2^0}}}\<2^{2^{2^{2^{(1/2)^{2^{2^{2^2}}}}}}}\\$
>
> I would be interested in suggestions to other types of counter examples, especially integer ones.
>
> It seems to me that for the problem to be in P, we need to non-numerical methods. It doesn't seem unlikely at all, that certain analytical cases are harder than P.
>
> **Examples:**
>
> ```
> powtow([2,2,2,2,2,2,2,2,2,2,2,2,2,2,4,2,2,2]) = (0.1184590219613409, 18)
> powtow([9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]) = (0.10111176550354063, 18)
>
> powtow([2,2,5,2,7,4,9,3,7,6,9,9,9,9,3,2]) = (0.10111176550354042, 17)
> powtow([3,3,6,3,9,4,2,3,2,2,2,2,2,3,3,3]) = (0.19648862015624008, 17)
>
> ```
>
> **Counter examples:**
>
> ```
> powtow([2,2,2,2,2,2,2]) = (0.8639310719129168, 6)
> powtow([3,2,2,2,2,2,2]) = (0.8639310719129168, 6)
>
> ```

Regarding the counter examples, he mentions the following in the comment-section:

> I believe if we bound the exponents so \\$1\<a\<100\\$ (or maybe a much larger upper bound) we can use my method for comparing the height 3 or 4 head of the tower. It should be strong enough to tell us if they are equal or one is larger. Plan B is to choose the highest tower. Plan C is the interesting one: At this point the values of the rest of the tower only matter if the heads are equal, so we can walk down the towers in parallel, stopping as soon as we see a differing value.
>
> Hence the main thing to be proven is that once the head of a tower exceeds a certain point, and the rest of the exponents are bounded (and equally numerous), we can simply look at the top differing value. It's a bit counter intuitive, but it seems very likely from the simple inequalities you get.

Since plan A and B are irrelevant in this challenge, since the height is 5 for both power-towers we input, plan C it is. So I've changed `P(a)>P(b)` to `P(S(a,b))>P(S(b,a))if P(a)==P(b)else P(a)>P(b)` with the recursive function `S(a,b)`. If `P(a)` and `P(b)` result in the same tuple, the `P(S(a,b))>P(S(b,a))` will first remove trailing values which are equal at the same indices, before doing to same `P(A)>P(B)` check on these now shorter lists.

# Answer
> 4 votes
# 05AB1E, ~~96~~ 104 bytes

```
3èI4èmU8.$`m©I7èI2è.n*I6èI1è.nI2è.n+Vнi0ë5èi1ë2ô1èßi¦2£`mIнI5è.n*I6è.nDI7èDi\1›·<žm*ë.n}®›ëXYQiнI5è›ëXY›

```

Port of *@SimplyBeautifulArt*'s Ruby answer, so make sure to upvote him!

+8 bytes as work-around, because \\$\log\_1(x)\\$ should result in `POSITIVE_INFINITY` for \\$x\gt1\\$ and `NEGATIVE_INFINITY` for \\$x\lt1\\$, but results in `0.0` for both cases instead in 05AB1E (i.e. test cases `[3,2,2,1,1,2,5,1,1,1]` (`POSITIVE_INFINITE` case) and `[2,4,1,1,1,3,3,1,1,1]` (`NEGATIVE_INFINITY` case).

Input as a list of ten integers: `[a,b,c,d,e,f,g,h,i,j]`.

Try it online or verify all test cases.

**Explanation:**

```
3èI4èm         # Calculate d**e
      U        # And pop and store it in variable `X`
8.$`m          # Calculate i**j
     ©         # Store it in variable `®` (without popping)
I7èI2è.n       # Calculate c_log(h)
 *             # Multiply it with i**j that was still on the stack: i**j * c_log(h)
I6èI1è.nI2è.n  # Calculate c_log(b_log(g))
 +             # And sum them together: i**j * c_log(h) + c_log(b_log(g))
  V            # Pop and store the result in variable `Y`

нi             # If `a` is 1:
 0             #  Push 0 (falsey)
ë5èi           # Else-if `f` is 1:
 1             #  Push 1 (truthy)
ë2ô1èßi        # Else-if the lowest value of [c,d] is 1:
 ¦2£`m         #  Calculate b**c
 IнI5è.n       #  Calculate f_log(a)
  *            #  Multiply them together: b**c * f_log(a)
   I6è.n       #  Calculate g_log(^): g_log(b**c * f_log(a))
 D             #  Duplicate it
  I7è          #  Push h
     Di        #  Duplicate it as well, and if h is exactly 1:
       \       #   Discard the duplicated h
       1›      #   Check if the calculated g_log(b**c * f_log(a)) is larger than 1
               #   (which results in 0 for falsey and 1 for truthy)
         ·<    #   Double it, and decrease it by 1 (it becomes -1 for falsey; 1 for truthy)
           žm* #   Multiply that by 9876543210 (to mimic POSITIVE/NEGATIVE INFINITY)
      ë        #  Else:
       .n      #   Calculate h_log(g_log(b**c * f_log(a))) instead
      }        #  After the if-else:
       ®›      #  Check whether the top of the stack is larger than variable `®`
ëXYQi          # Else-if variables `X` and `Y` are equal:
     нI5è›     #  Check whether `a` is larger than `f`
ë              # Else:
 XY›           #  Check whether `X` is larger than `Y`
               # (after which the top of the stack is output implicitly as result)

```

If anyone wants to try and golf it further, here is a helper program I've used to get the correct variables from the input-list.

# Answer
> 3 votes
## C, ~~168~~ 180 bytes

C port from Kevin Cruijssen's answer.

```
#define l(a,b)log(a)/log(b)
z(a,b,c,d,e,f,g,h,i,j){float t=pow(i,j),y=l(l(g,b),c)-pow(d,e)+l(h,c)*t,z=l(l(a,f)*pow(b,c),g);return~-a&&f<2|(b<2|g<2?z>h:c<2|d<2?l(z,h)>t:y?y<0:a>f);}

```

Try it online

# Answer
> 2 votes
# APL(NARS), chars 118, bytes 236

```
{p←{(a b c d)←⍵⋄a=1:¯1⋄b=1:⍟⍟a⋄(⍟⍟a)+(c*d)×⍟b}⋄(=/(a b)←{p 1↓⍵}¨⍺⍵)∧k←(∞ ∞)≡(m n)←{p(3↑⍵),*/3↓⍵}¨⍺⍵:(↑⍺)>↑⍵⋄k:a>b⋄m>n}

```

The function above call z, in "a z w" would return 1 if the number in a is greater than the number in w, otherwise it would return 0.

If I have

```
f(a,b,c,d,e)=a^b^c^d^e

```

It will be f(aa)\>f(bb) with both aa and bb array of 5 positive numbers if and only if (if the a\>1 of aa and bb) log(log(f(aa)))\>log(log(f(bb))) one has to use the log() laws:

```
log(A*B)=log(A)+log(B)
log(A^B)=B*log(A)

```

for build v(aa)=log(log(aa))=v(a,b,c,d,e)=log(log(a))+log(b)*(c^(d^e))={p(3↑⍵),*/3↓⍵} function and so the exercise is find when v(aa)\>v(bb).

But there is a case where v(aa) and v(bb) are both infinite (APL has end the float space) in that case i would use the unsecure function

```
s(a,b,c,d,e)=log(log(b))+log(c)*(d^e)={p 1↓⍵}

```

that i not fully understand if it is ok and it not take in count a parameter too... test:

```
  z←{p←{(a b c d)←⍵⋄a=1:¯1⋄b=1:⍟⍟a⋄(⍟⍟a)+(c*d)×⍟b}⋄(=/(a b)←{p 1↓⍵}¨⍺⍵)∧k←(∞ ∞)≡(m n)←{p(3↑⍵),*/3↓⍵}¨⍺⍵:(↑⍺)>↑⍵⋄k:a>b⋄m>n}
  10 10 10 10 10 z 10 10 10 10 9
1
  1 2 3 4 5 z 5 4 3 2 1
0
  2 2 2 2 3 z 10 4 3 2 2
1
  10 6 4 2 2 z 10 6 2 4 2
0
  2 2 2 2 10 z 2 2 2 10 2
1
  10 9 8 7 6 z 6 7 8 9 10
0
  10 10 10 10 10 z 10 10 10 10 9
1
  2 2 2 2 3   z    10 4 3 2 2
1
  2 2 2 2 10   z   2 2 2 10 2
1
  10 10 10 10 10 z 9 10 10 10 10
1
  3 2 2 1 1   z    2 5 1 1 1
1
  2 2 3 10 1  z    2 7 3 9 1
1
  7 9 10 10 10 z   6 9 10 10 10
1
  3 2 2 2 2    z   2 2 2 2 2
1
  3 10 10 10 10 z  2 10 10 10 10
1
  8 3 1 2 1    z   2 2 3 1 1
1
  2 4 2 1 1    z   3 3 2 1 1
1
  5 4 3 2 1    z   1 2 3 4 5
1
  1 2 3 4 5    z   5 4 3 2 1
0
  6 7 8 9 10    z  6 7 8 9 10
0
  10 6 4 2 2 z     10 6 2 4 2
0
  10 9 8 7 6  z   6 7 8 9 10
0
  1 10 10 10 10 z 1 10 10 10 9
0
  2 4 1 1 1 z     2 2 2 1 1
0
  2 2 2 1 1    z  2 4 1 1 1
0
  2 5 1 1 1   z   3 2 2 1 1
0
  4 2 1 1 1   z   2 4 1 1 1
0
  2 4 1 1 1   z   4 2 1 1 1
0
  2 3 10 1 1  z   8 3 9 1 1
0
  8 3 9 1 1   z   2 3 10 1 1
0
  2 4 1 1 1   z   3 3 1 1 1
0
  2 2 1 9 9   z   2 2 1 10 10
0
  2 2 1 10 10 z   2 2 1 9 9
0
  1 1 1 1 1   z   1 2 1 1 1
0
  1 1 1 1 2   z   1 1 1 1 1
0
  1 1 1 1 1   z   1 1 1 1 1
0
  9 10 10 10 10 z  10 9 10 10 10
1
  9 10 10 10 10 z  10 10 10 10 10
0
  10 10 10 10 10 z  10 10 10 10 10
0
  11 10 10 10 10 z  10 10 10 10 10
1

```

# Answer
> 1 votes
# Java 8, ~~299~~ ~~288~~ ~~286~~ ~~252~~ ~~210~~ ~~208~~ 224 bytes

```
Math M;(a,b,c,d,e,f,g,h,i,j)->{double t=M.pow(i,j),y=l(l(g,b),c)-M.pow(d,e)+l(h,c)*t,z=l(l(a,f)*M.pow(b,c),g);return a>1&&f<2|(b<2|g<2?z>h:c<2|d<2?l(z,h)>t:y==0?a>f:y<0);}double l(double...A){return M.log(A[0])/M.log(A[1]);}

```

Port of *@SimplyBeautifulArt*'s Ruby answer, so make sure to upvote him!
-14 bytes thanks to *@SimplyBeautifulArt*.
+17 bytes for the same bug-fixes as the Ruby answer.

Try it online.

**Explanation:**

```
Math M;                      // Math M=null on class-level to save bytes

(a,b,c,d,e,f,g,h,i,j)->{     // Method with ten integer parameters and boolean return-type
  double t=M.pow(i,j),       //  Temp `t` = `i` to the power `j`
    y=l(l(g,b),c)            //  Temp `y` = `c`_log(`b`_log(`g`))
      -M.pow(d,e)            //  - `d` to the power `e`
      +l(h,c)*t,             //  + `c`_log(`h`) * `t`
    z=l(l(a,f)*M.pow(b,c),g);//  Temp `z` = `g`_log(`f`_log(`a`) * `b` to the power `c`)
  return a>1&&               //  If `a` is 1:
                             //   Return false
   f<2|(                     //  Else-if `f` is 1:
                             //   Return true
    b<2|g<2?                 //  Else-if either `b` or `g` is 1:
     z>h                     //   Return whether `z` is larger than `h`
    :c<2|d<2?                //  Else-if either `c` or `d` is 1:
     l(z,h)>t                //    Return whether `h`_log(`z`) is larger than `t`
    :y==0?                   //   Else-if `y` is 0:
      a>f                    //    Return whether `a` is larger than `f`
    :                        //   Else:
     y<0);}                  //    Return whether `y` is negative

// Separated method to calculate `B`_log(`A`) for inputs `A,B`
double l(double...A){return M.log(A[0])/M.log(A[1]);}

```

---
Tags: code-golf, math, restricted-time
---