# Question
Title: Convert Numbers to Letters, and vice-versa in a string
Based on a list of numbers and their equivalent letters, take a string input, replace the characters of that string with the equivalent number/letter and output the result.

### List

> * 1 = a
> * 2 = b
> * 3 = c
> * 4 = d
> * 5 = e
> * 6 = f
> * 7 = g
> * 8 = h
> * 9 = i
> * 0 = j

### Input

> thisisastring1124

### Output

> t89s9s1str9n7aabd

### Rules

* Numbers are equivalent to lowercase letters only.
* Any character outside the list will be left as is.
* Input string must not contain spaces.
* Either full program or function is permitted.
* Since it's code-golf, fewest bytes wins.

# Answer
## bash, 18 bytes

```
tr 1-90a-j a-j1-90

```

Try it online!
> 14 votes

# Answer
# Python 3, ~~76~~ 68 bytes

```
lambda w:w.translate(dict(zip(s,s[::-1])))
s=b'1234567890jihgfedcba'

```

Try it online!
> 10 votes

# Answer
# Perl 6, ~~45~~ 23 bytes

```
tr/1..90a..j/a..j1..90/

```

Try it online!

Just a plain transliteration regex.
> 7 votes

# Answer
## Perl 5, 17 bytes

```
y;a-j1-90;1-90a-j

```

Try it online!
> 7 votes

# Answer
# 05AB1E, ~~13~~ 9 bytes

```
žmÁAT£JÂ‡

```

Try it online!

**Explanation**

```
žmÁ         # push 0987654321
   AT£      # push abcdefghij
      J     # join strings
       Â    # bifurcate
        ‡   # transliterate

```
> 6 votes

# Answer
# Retina 0.8.2, 12 bytes

```
T`a-j09-1`Ro

```

Try it online! Explanation:

```
T``

```

Perform a transliteration.

```
a-j09-1

```

The source list is the letters `a-j`, then `0`, then the digits `9-1`.

```
Ro

```

The destination list is the source list reversed, i.e. the digits `1-9`, then `0`, then the letters `j-a`.
> 5 votes

# Answer
# , 38 bytes

```
rplc[:(;~"0|.)'9876543210jabcdefghi'"1

```

Try it online!
> 5 votes

# Answer
# Python 2, ~~82~~ 78 bytes

```
lambda i,l='1234567890jihgfedcba':''.join((x,l[~l.find(x)])[x in l]for x in i)

```

Try it online!

-4 with thanks to @ovs
> 3 votes

# Answer
# JavaScript (ES6), 66 bytes

```
s=>s.replace(e=/[1a2b3c4d5e6f7g8h9i0j]/g,c=>e[e.search(c)^1],e+=e)

```

Try it online!
> 3 votes

# Answer
# , 40 bytes

```
function(s)chartr("0-9ja-i","ja-i0-9",s)

```

Try it online!

Surprisingly, R is decent at this kind of challenge, because it has a `tr`-like function as in the Bash answer. No idea why it exists, but I'm grateful for it!
> 3 votes

# Answer
# MS-SQL, 71 bytes

```
SELECT TRANSLATE(v,'1234567890abcdefghij','abcdefghij1234567890')FROM t

```

The new SQL 2017 function `TRANSLATE` performs individual character replacement, so is ideally suited for this purpose. See my similar answer in a prior challenge.

Input is via a pre-existing table **t** with varchar column **v**, per our IO rules. To replace only lowercase letters, the table must be created using a *case-sensitive collation*:

```
CREATE TABLE t(v varchar(max) COLLATE Latin1_General_CS_AS)

```
> 3 votes

# Answer
# Haskell, ~~80~~ 66 bytes

```
map(!"1a2b3c4d5e6f7g8h9i0j")
e!(a:b:y)|e==a=b|e==b=a|1<2=e!y
e!_=e

```

Try it online!
> 2 votes

# Answer
# Jelly, 16 bytes

```
⁵Øaḣ,ØDṙ1¤ċÞ⁸Ṛy)

```

Try it online!
> 2 votes

# Answer
# Pyth, 13 bytes

```
Xz+jk+0_S9<GT

```

Try it here!

### Explanation

```
Xz+jk+0_S9<GT – Full program.
       _S9    – Yield [9, 8, 7, ..., 1]
     +0       – Prepend a 0.
   jk         – Join to a single string.
  +       <GT – And append the first 10 letters of the alphabet to it.
                Yields 0987654321abcdefghij.
Xz            – Transliterates the input from the above to the above reversed.

```
> 2 votes

# Answer
# C (gcc), 81 72 bytes

Thanks to Giacomo Garabello for the suggestions.

```
f(char*s){for(;*s++=*s-97U<11?(*s-6)%10+48:*s-48U<11?(*s-9)%10+97:*s;);}

```

Try it online!
> 1 votes

# Answer
## REXX, 57 bytes

```
#=1234567890
a='abcdefghij'
say translate(arg(1),a #,# a)

```
> 1 votes

# Answer
# Powershell, 94 bytes

```
-join($args|% t*y|%{if(1+($p=($s='1a2b3c4d5e6f7g8h9i0j').IndexOf($_))){$s[$p-bxor1]}else{$_}})

```

Test script:

```
$f = {
-join($args|% t*y|%{if(1+($p=($s='1a2b3c4d5e6f7g8h9i0j').IndexOf($_))){$s[$p-bxor1]}else{$_}})
}

&$f "thisisastring1124"

```

## Explanation

* `$args` \- argument strings
* `$args|% t*y` \- expands to `|ForEach-Object -Method ToCharArray` equivalent of `"$args".ToCharArray()`
* `($s='1a2b3c4d5e6f7g8h9i0j').IndexOf($_)` \- find a char in the string, returns a position or -1 if not found. Let $s stores the string which contains a paired char on neighbor positions that differ by the last bit: 0+1, 2+3, 4+5....
* `if(1+($p=...))` \- if position was found
* `$p-bxor1` \- position bit xor 1
> 1 votes

# Answer
# , 107 bytes

```
function(s){a=utf8ToInt(s);l=a>96&a<107;n=a>47&a<58;a[n]=(a[n]-9)%%10+97;a[l]=(a[l]+4)%%10+48;intToUtf8(a)}

```

Try it online!

First attempt, definitely improvable...
> 0 votes

# Answer
# Rust, 96 bytes

```
|x|x.bytes().map(|x|match
x{49..=57=>x+48,97..=105=>x-48,48=>106,106=>48,x=>x}as
char).collect()

```

Try it online!

Not Unicode-safe, if it was it would be even longer.
> 0 votes

# Answer
# K4, 38 bytes

**Solution:**

```
{(,/|x,a)(,/a:0 1_'10 11#'.Q`a`n)?x}@'

```

**Explanation:**

Lookup each character in the list `"abcdefghij1234567890"` and then index into the list `"1234567890abcdefghijX"` where `X` is the original character.

Need to find a shorter way to build the strings...

```
{(,/|x,a)(,/a:0 1_'10 11#'.Q`a`n)?x}@'
{                                  }@' / apply (@) lambda {} to each (')
                                 ?x    / lookup x in
         (                      )      / do this together
                          .Q`a`n       / index into .Q with a (gives a-z) and n (gives 0-9)
                   10 11#'             / take 10 from first list and 11 from second list
              0 1_'                    / drop 0 from first list and 1 from second list
            a:                         / save as a
          ,/                           / flatten
 (      )                              / do this together
     x,a                               / prepend x to a
    |                                  / reverse it
  ,/                                   / flatten

```

**Bonus:**

Another solution for **38 bytes**:

```
{(a,b,x)?[(b:1_11#.Q.n),a:10#.Q.a]x}@'

```
> 0 votes

# Answer
# Yabasic, 135 bytes

Takes input from the console and outputs to the console.

```
Input""s$
For i=1To Len(s$)
c$=Mid$(s$,i,1)
n=asc(c$)-96
If-38>n Then?chr$(143+n+11^(n=-48));ElsIf n<11Then?n*(10>n),"";Else?c$;Fi
Next

```

Try it online!
> 0 votes

# Answer
# Japt, ~~44~~ 42 bytes

```
V=1oA q +0+"jihgfedcba"Um@W=VaX)¦É?Vw gW:X

```

Try it online!
> 0 votes

# Answer
# sed, 44 bytes

```
y/1234567890abcdefghij/abcdefghij1234567890/

```

A bit boring, I admit.

Testing:

```
$ echo 'thisisastring1124' | sed 'y/1234567890abcdefghij/abcdefghij1234567890/'
t89s9s1str9n7aabd

```
> 0 votes

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


title: Fabulous glamour shot

text:
# Question
Title: Fabulous glamour shot
Found this picture on the web today. Being a lazy programmer, I don't want to actually open google and type a couple of characters. Way too much work! This is such an important task that it should be automated.

# Challenge

Everyone knows that the first image in a google search result is always the best. Hence it should be presented to the user.

You are to write a program or function which takes a string as parameter and displays the first image it finds on google when you search for that name + the words `glamour shot` behind it.

# Google search queries

To search for images on google, the url should contain the query parameter `tbm=isch` and `q=query`, with `query` being the name you want to search for.
A valid query string for my name `Bas` would be `www.google.com/search?tbm=isch&q=Bas`

# Input

Your program or function takes a single parameter of input, which is the name you want to search for on google. This string will consist of the characters `[a-z]`, `[A-Z]`, `[0-9]` and  (space). This string can be space seperated, to search for a space seperated string on google, one should replace the spaces with `+`. For example, this is a valid query:
www.google.com/search?tbm=isch&q=Bassdrop+Cumberwubwubwub+glamour+shot

# Output

The image can either be drawn to the screen, or saved to a file (in any format).
If the first search result on google is a gif file, you can either show the gif or show any frame of that gif.

# Test cases

Run this snippet to see the expected results

```
<pre>f('Bas') // www.google.com/search?tbm=isch&q=Bas+glamour+shot

<img src="https://i.stack.imgur.com/IViaM.jpg" style="width:40%;height:40%"/>

<pre>f('Bassdrop Cumberwubwubwub') // www.google.com/search?tbm=isch&q=Bassdrop+Cumberwubwubwub+glamour+shot

<img src="https://i.stack.imgur.com/tdhvW.png" style="width:40%;height:40%"/>
```

This is , shortest code in bytes wins!

# Answer
## PowerShell v4+, 160 bytes

```
param($a)iwr (((iwr "google.com/search?tbm=isch&q=$($a-replace' ','+')+glamour+shot").links|?{$_.innerhtml-like"*$a*"})[0].innerhtml-split'"')[3] -outf "$a.jpg"

```

Takes input `$a` as a string. Does an `Invoke-WebRequest` (`iwr`) to the appropriate Google location, using inner-string script block to `-replace` spaces with `+` in the input string. We take the `.links` of that, where the `.innerhtml` is `-like` our input string. That yields the links with the proper thumbnail description. Take the first `[0]` one of those, take *its* `.innerhtml` and `-split` it on quotations. The fourth `[3]` element is the text inside the `img src="` portion, so we do another `iwr` on that, specifying `-outf`ile to be `$a.jpg` in the local folder. Since these are just the Google generated thumbnails, they're guaranteed to be jpg.
> 8 votes

# Answer
# Excel VBA ***+***, ~~465~~ 332 Bytes

> ***NOTE:*** Uses References to
>
> * Microsoft HTML Object Library
> * Microsoft Internet Controls
> * Microsoft Scripting Runtime

**Golfed:**

Full `Sub` routine that takes input `n` (short for name) of expected type `Variant/String` and outputs the first google image search result for the query of that name and `glamour shot` to an internet explorer window.

```
Sub g(n)
Set i=New InternetExplorer
l="google.nl/search?tbm=isch&q="&Replace(n," ","+")&"+glamour+shot"
For y=0To 2
i.navigate l
While i.readyState<4
DoEvents
Wend
j=0
Do Until InStr(1,l,IIf(y,"yp","res"))
j=j+1
Set x=i.document.getElementsByTagName(IIf(y,"img","a"))(j)
If y Then l=x.src Else l=x.href
Loop
Next
i.visible=1
End Sub

```

-2 bytes for removing white space in `If InStr(1, a.href, "imgres") Then`

-2 bytes for changing `.navigate (a.href)` to `.navigate a.href`

-27 bytes for reducing `for each a in ... if (...) then ... end if .. next` loop to `do until ... loop`

-10 bytes for condensing `imgres` to `res` and `encrypted` to `yp`

-8 bytes for removing initalizers for `j`, `k` and assuming clean module

-1 byte for changing `google.com` to `google.nl`

-3 bytes for replacing `Dim i as New ...` with `Set i=New ...`

-8 bytes for removing `SHDocVw.` class reference

-12 bytes for removing `with i` block

-7 bytes for removing `i.quit` \- this causes some memory leakage by leaving internet explorer open in the background, as such it is recommended that either the full ungolfed version is used instead or that the internet explorer task is terminated through task manager after use

-6 bytes for moving `i.navigate` into helper subroutine `h`

-13 bytes for moving `Do Until ... Loop` into helper subroutine

-2 bytes by moving `j=0` into helper and removing `,j`, `,0` (x2)

-11 bytes for converting to an anonymous immediate window function

-8 bytes for reducing helper function calls into `for .. next` loop

-16 bytes for changing output from `Sheets(1)` picture object to displaying via the `InternetExplorer` object

**Ungolfed, 1304 Bytes**

```
Option Private Module
Option Compare Text
Option Explicit
Option Base 0

Sub GlamourShot(ByVal name As String)

    Dim ie As New SHDocVw.InternetExplorer, _
        doc As MSHTML.HTMLDocument, _
        link As String, _
        j As Integer, _
        k As Integer

    With ie
        On Error GoTo CloseIE #'prevents memory leak

        Let .visible = True
        Call .navigate("www.google.com/search?tbm=isch&q=" & _
                    Replace(name, " ", "+") & _
                    "+glamour+shot")
        While .readyState <> READYSTATE_COMPLETE Or .Busy
            VBA.DoEvents
        Wend

        Set doc = .document

        Let j = 1
        Do Until InStr(1, link, "imgres") > 0
            Let link = doc.getElementsByTagName("a")(j).href
            Let j = j + 1
        Loop

        Call .navigate(link)
        While .readyState <> READYSTATE_COMPLETE Or .Busy
            VBA.DoEvents
        Wend

        Let k = 1
        Do Until InStr(1, link, "encrypted") > 0
            Let link = doc.getElementsByTagName("img")(k).src
            Let k = k + 1
        Loop

        With ThisWorkbook.ActiveSheet
            Call .Range("A1").Select
            Call .Pictures.Insert(link)
            Call .Activate
        End With
CloseIE:
        Call .Quit
    End With
End Sub

```

**Usage gif**
> 4 votes

# Answer
# Vimperator, 30 keystrokes

```
pgi<End> glamour shot<CR>fi222jf<CR>fim2

```

Alternatively 27 keystrokes if you don't need the highest resolution image:

```
pgi<End> glamour shot<CR>fi222j;I<CR>

```

Video: https://youtu.be/t8824UjlYt8

Fortunately the standard search engine in Firefox is google, and Vimperator let you type hints by default. This is longer than it has to be to make sure that it always works regardless of what you search for.

Takes input through the clipboard.

### Explanation:

```
p             Google the contents of the clipboard
gi            Select the search box
<End>         Move the cursor to the end of the text
 glamour shot Type " glamour shot"
<CR>          Press enter to search
fi2           Click the second link that begins with the letter "i" (images)
22j           Go 22 scroll steps down on the page.
              This makes it so that the first row of images are at
              the very top of the screen.

f<CR>         Click the first clickable element, which is the
              first image because we scrolled down

fim2          Click the second link containing "im" (view image)

```

Thanks to @TaylorScott for finding an edge case.
> 3 votes

# Answer
# Python 3.6, ~~247~~ ~~242~~ 232 maybe 224 bytes

This is a cute attempt to solve this one. It will save a the file as `p.png` in the current directory.

```
import sys; import requests as r; from bs4 import BeautifulSoup as s;
n = sys.argv[1]; open('p.png', 'wb').write(r.get(s(r.get(f'https://www.google.com.br/search?tbm=isch&q={n}+glamour+shot').content,'lxml').find_all('img')[1].get('src')).content)

```

To run it with ease from the command line, just place the above content in a file, such as `glamour.py` and run:

```
$ python glamour.py NAME_YOU_WANT

```

### Update 1: Better version with new google url

```
import sys; import requests as r; from bs4 import BeautifulSoup as s;
n = sys.argv[1]; open('p.png', 'wb').write(r.get(s(r.get(f'http://www.google.nl/search?tbm=isch&q={n}+glamour+shot').content,'lxml').find_all('img')[1].get('src')).content)

```

### Update 2:

I saved a few bytes:

* By only importing the get function from the requests module
* taking advantage of the new python 3.6 string interpolation `f` flag without allocating the `sys.argv` to a variable
* eliminating some white spaces
* turning it into a one-liner
* removing the parser specification from the `BeautifulSoup` call

The last one is controversial, since it results in a std.output message telling the programmer to specify the parser for cross platform compatibility, so it might be considered unwanted output.

Here is the 224 bytes version:

```
import sys;from requests import get;from bs4 import BeautifulSoup as s;open('p.png','wb').write(get(s(get(f'http://www.google.nl/search?tbm=isch&q={sys.argv[1]}+glamour+shot').content).find_all('img')[1].get('src')).content)

```

Here is the 232 bytes version:

```
import sys;from requests import get;from bs4 import BeautifulSoup as s;open('p.png','wb').write(get(s(get(f'http://www.google.nl/search?tbm=isch&q={sys.argv[1]}+glamour+shot').content, 'lxml').find_all('img')[1].get('src')).content)

```

But the shorter version could be used if std.out is redirected to `/dev/null` or something :D
> 3 votes

# Answer
# Racket, 284 byes

```
(require net/url html-parsing sxml racket/draw)(define(g n)(let([g(compose get-pure-port string->url string-append)])(make-object bitmap%(g(car((sxpath"//*[@id='ires']//@src/text()")(html->xexp(g"http://www.google.com/search?tbm=isch&q="(string-replace n" ""+")"+glamour+shot"))))))))

```

Screenshot:
> 1 votes

---
Tags: code-golf, graphical-output, internet
---


# Question
Title: Generate TeX to typeset Sierpinski Triangle Fractal
# Challenge

Write code that outputs TeX (LaTeX) math-equation code (given below) that will typeset Sierpinski Triangle Fractal of 5 levels. **Shortest code wins**.

# Details

TeX (and friends like LaTeX, etc.) is a sophisticated typesetting system. It can render arbitrary nested complex expressions for mathematical formulas. Coincidentally this "nested complex" is also descriptive of fractals. The following is rendered with MathJaX

$${{{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}^{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}\_{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}}^{{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}^{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}\_{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}}\_{{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}^{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}\_{{{x^x\_x}^{x^x\_x}\_{x^x\_x}}^{{x^x\_x}^{x^x\_x}\_{x^x\_x}}\_{{x^x\_x}^{x^x\_x}\_{x^x\_x}}}}}$$

by the following plain-text math-equation code consisting of nested super- and sub-scripts:

```
{{{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}^{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}_{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}}^{{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}^{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}_{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}}_{{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}^{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}_{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}}}

```

Note this is just a 5-level nesting. You do not need to generate `$...$` or `$$...$$` or other markup required to start/end a math equation in TeX & Co. You can preview generated TeX in many online editors, for instance: http://www.hostmath.com but you can find many others too. This question was inspired by a discussion with friends.

# Update

There is a similar question but it much more general and will produce different solutions. I wanted to see really kolmogorov-complexity for a very fixed simple code that in one system (TeX) is completely explicit while in another compressed. This also address the `n` instead of 5 levels comment.

# Answer
# SOGL V0.12, ~~16~~ 12 bytes

```
 x5{"{^_}”;∑

```

Try it Here!

Port of Erik The Outgolfer's Python 2 answer
> 8 votes

# Answer
# Python 2, 32 bytes

```
exec"print'x'"+".join('{^_}')"*5

```

Try it online!
> 21 votes

# Answer
# plain TeX, 29 bytes

```
\def~#1x{{#1x_#1x^#1x}}~~~~~x

```

That outputs what others have output. But if we need the code to be compilable it would be 6 bytes more

```
\def~#1x{{#1x_#1x^#1x}}$~~~~~x$\bye

```

**Explanation**

`~` is an active character in TeX, so we can give it a (new) definition.

`\def~#1x{{#1x_#1x^#1x}}` defines `~` as a macro, so that when TeX sees `~`, it does the following:

* Read everything up to the next `x`, and call that `#1` (pattern-matching).
* Replace the whole thing with `{#1x_#1x^#1x}`

For example, `~ABCx` would get replaced with `{ABCx_ABCx^ABCx}`.

When `~~~~~x` is used, `#1` is `~~~~`, so the whole thing gets replaced with `{~~~~x_~~~~x^~~~~x}`. And so on.

Once we have the long string, we can print it out to terminal with `\message` (and ending with a `\bye` so TeX stops), so `\message{~~~~~x}\bye`. Or typeset the resulting expression (as a mathematical formula), by surrounding it in `$`s : so `$~~~~~x$\bye`.
> 15 votes

# Answer
# PowerShell,  ~~44~~  35 bytes

```
"'x'"+"-replace'x','{x^x_x}'"*5|iex

```

Try it online!

Uses string multiplication to repeatedly `-replace` `x`es with the sub- and super-scripts, then output.

*Saved 9 bytes thanks to Joey.*
> 4 votes

# Answer
# 05AB1E, 17 bytes

```
'x5F'x¡"{x^x_x}"ý

```

Try it online!

**Explanation**

```
'x                  # push "x"
  5F                # 5 times do
    'x¡             # split on "x"
       "{x^x_x}"ý   # join on "{x^x_x}"

```

**Other programs at the same byte-count include**

```
"{x^x_x}"©4F'x¡®ý
'x5F'x"{x^x_x}".:

```
> 4 votes

# Answer
## JavaScript (ES6), ~~45~~ ~~42~~ 37 bytes

```
f=n=>n>4?'x':[...'{^_}'].join(f(-~n))

```

Edit: Saved ~~3~~ 2 bytes thanks to @Arnauld. Specifying 5 still costs me 2 bytes; this ~~41~~ ~~40~~ 35-byte version takes a parameter instead:

```
f=n=>n?[...'{^_}'].join(f(n-1)):'x'

```
> 2 votes

# Answer
# Japt, ~~21~~ ~~20~~ 18 bytes

```
5Æ="\{^_}"¬qUª'xÃÌ

```

Test it

---

## Explanation

```
5Æ             Ã

```

Generate an array of length 5 and map over it.

```
"\{^_}"¬

```

Split a string to an array of characters

```
qUª'x

```

Rejoin (`q`) to a string using the current value of `U` or (`ª`) `"x"`.

```
=

```

Assign the result of that to `U`.

```
Ì

```

Get the last element in the array.

---

## Alternatives, 18 bytes

Same as above but reducing the array after it's been created.

```
5o r@"\{^_}"¬qX}'x

```

Test it

The recursive option.

```
>4©'xª"\{^_}"¬qßUÄ

```

Test it
> 2 votes

# Answer
# MATL, ~~21~~ 20 bytes

```
'x'XJ5:"J'{x^x_x}'Zt

```

-1 byte thanks to *Giuseppe*

Try it online!
> 2 votes

# Answer
# 05AB1E, 13 bytes

```
'x5F"{^_}"Ssý

```

Try it online!

Port of my Python 2 answer.
> 2 votes

# Answer
# Jelly, 12 bytes

```
”x“{^_}”j$5¡

```

Try it online!

Port of my Python 2 answer.
> 2 votes

# Answer
# Java (OpenJDK 8), ~~179~~ 167 bytes

@Neil port

```
interface Y{static void main(String[]a){System.out.println(t.apply(1));}java.util.function.Function<Integer,String>t=N->N>0?Y.t.apply(N-1).replace("x","{x^x_x}"):"x";}

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (*Mathematica*) - 40 characters

Summarizing 3 best answers here:

### 40 bytes:

```
Nest["{"<>#<>"_"<>#<>"^"<>#<>"}"&,"x",5]

```

### 41 bytes:

```
Nest[StringReplace["x"->"{x^x_x}"],"x",5]

```

### 44 bytes:

```
Last@SubstitutionSystem["x"->"{x^x_x}","x",5]

```
> 0 votes

# Answer
# Pyth, ~~17~~ ~~16~~ 13 bytes

```
jF+\x*5]"{^_}

```

Try it online!

Python 3 translation:
```
from functools import*;print(reduce(lambda x,y:x.join(y),["x"]+5*["{^_}"]))

```
> 0 votes

# Answer
# C (gcc), 82 bytes

```
O(o){o--?_(125,O(o,_(95,O(o,_(94,O(o,_(123))))))):_(120);}main(){O(5);}

```

Try it online!
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, code-generation, fractal
---


title: Bridge Deal Scoring

text:
# Question
Title: Bridge Deal Scoring
# Goal

Given a deal result from Duplicate Contract Bridge, calculate the deal score.

Basically the same as iBug's question, which was deleted. I figured out this scoring system while trying to answer that question.

### Input

Input is a deal result, and whether or not the declaring side is vulnerable.

The **deal result** is a string in the following format:

```
[contract] [result]

```

The contract is defined as follows:

```
[tricks][suit][doubling]

```
* The `tricks` is a number `1-7` (both inclusive),
* The `suit`is one of `C`, `H`, `S`, `D`, or `NT` (Clubs, Hearts, Spades, Diamonds, and notrump)
    + Suits are grouped as follows: `notrump: NT`, `Major suits: H, S` and `Minor suits: C, D`.
* `doubling` can be *blank* , `X` or `XX` (Undoubled, Doubled, Redoubled)

`result` is the resulting number of 'tricks' in relation to the contract. The value can be in the range `[-13; +6]`, depending on the `value` (sign included).

The sum of `contract number` and `result` must be in the range`[-6; 7]`, which means:

* For `tricks= 1`, `result` must be `[-7; +6]`
* For `tricks= 2`, `result` must be `[-8; +5]`
* ..
* For `tricks= 7`, `result` must be `[-13; 0]`

**Examples of valid deal results:**

`1S 0`, `4NT -3`, `7NTXX -13`, `3HX +3`

---

**Vulnerability** can be input as a boolean or any *truthy/falsy* value.

### Output

Output is the scoring of the deal result.

The score is based on the number of tricks in a deal, and whether it reached the contract.

---

# Scoring

The score is a measure of the result compared to the contract.

If the contract is made, the score for each such deal consists of:

* Contract points, assigned to each trick bid and made
* Overtrick points, assigned for each trick taken over the contracted number of tricks
* A slam bonus for a small slam or grand slam contract
* A doubling bonus
* A game bonus

If the contract is defeated, the defenders receive

* Penalty points, assigned for every undertrick (negative value of `result`)

---

### Contract points:

Contract points are awarded for the tricks of the contract.

```
                                   Points per trick
Suit                      undoubled    doubled     redoubled
------------------------------------------------------------
 Notrump
  -first trick               40          80           160
  -subsequent tricks         30          60           120
 Major suits                 30          60           120
 Minor suits                 20          40           80

```

### Overtrick points:

Overtrick points are awarded for the tricks made, more than the contract (`result` \> `0`)

```
                                Points per trick
Suit                      vulnerable    not vulnerable
 If undoubled:
  Notrump                     30             30
  Major suits                 30             30
  Minor suits                 20             20
 Doubled (per trick)          200            100
 Redoubled (per trick)        400            200

```

### Slam bonus

If a large contract is made, it earns a slam bonus:

* `tricks = 6` earns a bonus of `500` if not vulnerable, and `750` if vulnerable
* `tricks = 7` earns a bonus of `1000` if not vulnerable, and `1500` if vulnerable

### Doubled or redoubled bonus

If a doubled or redoubled contract is made, a bonus is earned:

* `50` points for a doubled contract
* `100` points for a redoubled contract

### Game bonus

A game bonus is awarded based on the contract points.

* Contract points below `100` earns a bonus of `50`points.
* Contract points `>= 100` earns a bonus of `300` if not vulnerable, and `500` if vulnerable

---

### Penalty

Each undertrick (negative `result`) gives a penalty point. No points are ganied for the contract, as it was failed.

```
                                      Points per undertrick
                           vulnerable                        not vulnerable
                   undoubled  doubled   redoubled     undoubled  doubled   redoubled
1st undertrick        100       200        400           100       100        200
2nd and 3rd, each     100       300        600           100       200        400
4th and subsequent    100       300        600           100       300        600

```

---

## Examples:

Deal result: `4DX +1`, Vulnerable=`true`:

* Contract points = `4*40 = 160`
* Overtrick points = `1*200 = 200`
* Slam bonus = no bonus
* (re)doubled bonus = `50`
* Game bonus = `500` (`140>=100`and vulnerable)

**Result =** `160+200+50+500 =` **`910`**

---

Deal result: `6NTXX 0`, Vulnerable=`false`:

* Contract points = `4*40 = 160`
* Overtrick points = `1*200 = 200`
* Slam bonus = no bonus
* (re)doubled bonus = `50`
* Game bonus = `500` (`140>=100`and vulnerable)

**Result =** `160+200+50+500 =` **`910`**

---

Deal result: `4SX -3`, Vulnerable=`false`:

* Penalty = `1*100 + 2*200 = 500`

**Result = `-500`**

---

Deal result: `7SNTXX -13`, Vulnerable=`true`:

* Penalty = `1*400 + 2*600 + 10*600 = 7600`

**Result = `-7600`**

---

# Example Input/Output:

Input is guaranteed to be valid.

```
1S 0 (non-vul)    # => 80
3NT +1 (non-vul)  # => 430
3NT +1 (vul)      # => 630
6CX +1 (vul)      # => 1740
4D -1 (vul)       # => -100
7NTXX -13 (vul)   # => -7600

```

---

Results can be checked against these tables.

I've also included a TIO with all results hardcoded in python, to check against.

# Answer
> 2 votes
# JavaScript (Node.js), ~~211~~ ~~204~~ ~~195~~ 192 bytes

```
(r,v,[,c,s,d,t]=r.match(/(.)(.T?)(X*)(.*)/),l=d.length,m=s>'D',g=(c*(m+=2)+!!s[1])<<l)=>10*(t<0?10*(l*(v?3*t+1:-"13"[~t]||3*t+4)||t):g+(10*l*-~v||m)*t+5*l+25*(c>5&&(5-c)*~-~v)+5*(g>9?4*v+6:1))

```

Try it online! Link includes test cases. Edit: Saved 6 bytes by multiplying by 10 at the end. Saved 9 bytes thanks to @Arnauld. Explanation:

```
(r,v

```

Input the result as a string and the vulnerability as a boolean (or 1/0).

```
,[,c,s,d,t]=r.match(/(.)(.T?)(X*)(.*)/)

```

Split the string up into contract, suit, doubles and (over/under)tricks.

```
,l=d.length

```

Count the number of doubles.

```
,m=s>'D'

```

Track whether this is a major or minor suit.

```
g=(c*(m+=2)+!!s[1])<<l

```

Calculate the contract score. This is 3 per major suit or 2 per minor suit trick, plus 1 extra for no trump, and then doubled or redoubled as appropriate.

```
)=>10*

```

The score is always a multiple of 10. Subsequent comments take this multiplication into account.

```
(t<0

```

Do we have undertricks?

```
?10*

```

Undertricks are multiples of 100.

```
(l*(v?3*t+1:-"13"[~t]||3*t+4)

```

If they're doubled, then the potentially redoubled score depending on the vulnerability or number of undertricks.

```
||t)

```

But if they're not doubled, then just the number of undertricks.

```
:g

```

If the contract is made, then we start with the contract score.

```
+(10*l*-~v||m)*t

```

Add on overtricks; per trick, if doubled then 100 potentially redoubled and doubled again if vulnerable, otherwise 30 for major or 20 for minor suits.

```
+5*l

```

Add on the potentially redoubled doubled game bonus.

```
+25*(c>5&&(5-c)*~-~v)

```

Add on the slam bonus if applicable.

```
+5*(g>9?4*v+6:1))

```

Add on the game bonus.

# Answer
> 1 votes
# Python 2, ~~230~~ ~~225~~ ~~221~~ 220 bytes

I've posted this answer, as I found out the rules while creating this answer to the other question.

```
def f(D,V):v,s=D[:2];d=D.count('X');m=int(D.split()[1]);v=int(v);C=3-(s<'E');P=(v*C+(s=='N'))*2**d;W=-~V;return[-~W*25*max(0,v-5)+P+m*[C,10*W,20*W][d]+5*d+[5,30+20*V][P>9],((m-W)*3+7+~-V*max(0,m+3))*d*10or+W*m*5][m<0]*10

```

Try it online!

---

Saved:

* -4 bytes, thanks to Mr. Xcoder
* -1 byte, thanks to Jonathan Frech

---
Tags: code-golf, card-games
---


title: Mixed Fraction Equality

text:
# Question
Title: Mixed Fraction Equality
In elementary school, children learn about proper fractions, where the numerator is less than the denominator, and thus the value of the fraction is less than one. Later, they are taught about fractions where the value of the fraction is greater than one, and two different ways to express these fractions: mixed fractions and improper fractions.

Given a mixed fraction, determine if it is equivalent to the improper fraction where the integer value and the numerator are concatenated together. For example, for input `1 3/4`, the improper fraction is `13/4`.

## Test Cases

```
1 3/4        -> falsey
1 3/10       -> truthy
6 6/7        -> falsey
55 55/100    -> truthy
4 9/100      -> falsey
40 9/100     -> falsey
7 49/1000    -> falsey
9 1/2        -> falsey
999 999/1000 -> truthy
1 21/200     -> falsey
1 21/101     -> falsey

```

For input, you may take the integer part and the fraction part as separate inputs, but you may not take the fraction as input in two pieces, and you may not take it as a decimal value. You may drop the integer part (not take it as input) if you do not need to use it.

# Answer
> 8 votes
# MATL, 7 bytes

```
UsGXzU=

```

Input is a string. Output is `1` for truthy, `0` for falsey.

Try it online! Or verify all test cases.

### Explanation

```
U     % Implicit input. Convert to number(s): gives a vector of two numbers
s     % Sum of that vector
G     % Push input again
Xz    % Remove spaces
U     % Convert to number
=     % Equal? Implicit display

```

# Answer
> 8 votes
# Perl 6, ~~16~~ 12 bytes

```
{1+$_==1~$_}

```

Try it online!

Takes input as a string representing the fraction. Turns out Perl 6's dynamic typing can handle strings to rational fractions, who knew? So the string `"1/10"` when coerced to a number, returns `0.1`

The anonymous code block simply checks if the fraction plus one equals one concatenated with the fraction. Thanks to xnor's Python answer for showing me that the integer part doesn't matter.

### Old solution, ~~27~~ 26 bytes

```
{.nude[0]==.Int~[%] .nude}

```

Try it online!

Takes input as a rational mixed fraction, and returns true or false. Returns false for the fourth test case because it can be simplified.

### Explanation:

`.nude` returns a list of `[numerator, denominator]`.

```
{                        } # Anonymous code block
 .nude[0]    # Check if the numerator of the mixed fraction
         ==  # Is equal to
           .Int  # The integer part of the fraction
               ~ # Concatenated to
                [%] .nude  # The numerator modulo the denominator
                           # And return implicitly

```

# Answer
> 6 votes
# Retina 0.8.2, ~~17~~ 16 bytes

```
(.)+/1(?<-1>0)*$

```

Try it online! Requires just the fraction part, so the linked test suite removes the integer from the test cases. Explanation: The improper concatenation is equal to the mixed number only if the denominator is a power of 10 and the numerator has one digit for every zero in the denominator. .NET's balancing groups are used to verify that sufficient digits exist. Edit: Saved 1 byte thanks to @sundar.

# Answer
> 6 votes
# Husk, 8 bytes

```
§·=r¤+r+

```

Try it online!

### Explanation

```
§(·=r)(¤+r)(+)  -- example arguments: "1" "3/10"
§               -- fork both arguments
      (¤ r)     -- | read both: 1 3/10
      ( + )     -- | and add them: 13/10
           (+)  -- | concatenate: "13/10"
                -- and do
 (· r)          -- | read the second argument: 13/10
 ( = )          -- | and compare: 13/10 == 13/10
                -- : 1

```

# Answer
> 5 votes
# , ~~78~~ 65 bytes

```
function(n,e=function(a)eval(parse(t=sub(" ",a,n))))e("")==e("+")

```

Try it online!

-13 bytes thanks to both Giuseppe and JayCe!

# Answer
> 5 votes
# Python 2, 43 bytes

```
lambda k:k.split('/')[1]==`10**k.find('/')`

```

Try it online!

# Answer
> 4 votes
# Stax, 5 bytes

```
╡ÄLσ`

```

Run and debug it

Explanation:

```
+yj$e= Full program, implicit input
+      Add integer and fraction part
 y     Push unparsed input
  j$   Split on spaces and flatten, i.e. Remove spaces
    e  Evaluate
     = Check for equality

```

# Answer
> 4 votes
# Brachylog, 15 bytes

```
ḍ{lᵛ&ht¬ị&t↔ị1}

```

Try it online!

Takes the fractional part alone as a string input.

Indirectly uses the same idea as my Julia answer - "the denominator is 10^{length of numerator}" can be said as "the denominator is a power of ten, and the length of the denominator is equal to the length of the numerator + the length of "/" (i.e. 1).

```
ḍ                   % split the input in half
 {            }     % and verify that
  lᵛ                % each half has the same length (i.e. the string had even length)
    &ht¬ị           % and the last character of the first half is
                    %  not a number (it should be "/")
         &t↔ị1      % and the second half when reversed is the number 1
                    %  i.e. the denominator should be a power of 10

```

---

Older answer:

### ~~15~~ 20 bytes

```
a₀ᶠịˢtl;10↺^.&a₁ᶠịˢh

```

Try it online!

*(-1 byte thanks to @Fatalize, but unfortunately +6 bytes since I discovered bugs in the older method.)*

Same idea as my Julia answer.

# Answer
> 4 votes
# Python 3, 26 bytes

```
lambda k:eval(k+'+1==1'+k)

```

Try it online!

For example, input `3/4` gives `3/4+1==13/4`. Instead of taking the whole part of the fraction, we just set it to `1` to test the mixed fraction equality. Test cases from Chas Brown.

# Answer
> 3 votes
# Clean, 57 bytes

```
import StdEnv,Text
$b#[u,v:_]=split"/"b
=v==""<+10^size u

```

Try it online!

This one is a little shorter but breaks for large numerator/denominators.

# Clean, ~~77~~ ~~61~~ ~~60~~ 58 bytes

*-1 thanks to OMᗺ's tip on my other answer*

```
import StdEnv,Text
$b#[u,v:_]=split"/"b
=1<+[48\\_<-:u]==v

```

Try it online!

This uses Neil's method, it's a bit shorter than doing it directly.
There's some trickery with conversion overloading, where `1<+[48\\_<-:u]` converts `[Int]` to `[Char]` and then to `{#Char} (:== String)`, but `Int` directly to `String`.

# Clean, ~~91~~ 89 bytes

```
import StdEnv,Text
t=toInt
$a b#[b,c:_]=map t(split"/"b)
#d=t(a<+b)
=d/c==t a&&d-d/c*c==b

```

Try it online!

Defines a function `$ :: String String -> Bool` which extracts the numerator and denominator, string-concatenates the integer part and the numerator, and checks equivalence.

# Answer
> 3 votes
# JavaScript, 26 bytes

Takes input in currying syntax (`f(x)(y)`) where `x` is the integer and `y` is the fraction as a string.

```
x=>y=>x==eval(x+y)-eval(y)

```

Try it online

# Answer
> 3 votes
# Julia 0.6, 29 bytes

```
r->10^ndigits(num(r))==den(r)

```

Try it online!

Based on the idea that the output should be true only when the denominator is a power of ten with as many zeros as there are digits in the numerator. Takes input as a `Rational` type, checks that the denominator is equal to 10 raised to the number of digits in the numerator.

# Answer
> 3 votes
# Java 10, ~~107~~ ~~70~~ ~~67~~ 57 bytes

```
f->new Long(f.split("/")[1])==Math.pow(10,f.indexOf("/"))

```

Welcome to the world without `eval`..

-40 bytes by creating a port of *@ChasBrown*'s Python 2 answer.
-10 bytes thanks to *@Shaggy* (I should have read *@ChasBrown*'s answer better and his use of `find` (`indexOf`)..)

Try it online.

**Explanation:**

```
f->                         // Method with String parameter and boolean return-type
  new Long(f.split("/")[1]) //  Take the denominator as integer
  ==Math.pow(10,            //  And check whether it is equal to 10 to the power of:
                f.indexOf("/"))
                            //   the length of the numerator-String

```

# Answer
> 3 votes
# 05AB1E, 7 bytes

```
'/¡ćg°Q

```

Only takes the fractions as input.

Try it online or verify all test cases.

**Explanation:**

```
'/¡        # Split the input by '/'
           #  i.e. '3/10' → ['3', '10']
   ć       # Head extracted:
           #  i.e. ['3', '10'] → 10 and 3
    g      # Take the length of the numerator
           #  i.e. '3' → 1
     °     # Take 10 to the power of this length
           #  1 → 10**1 → 10
      Q    # Check if that value equals the denominator
           #  10 and 10 → 1 (truthy)

```

**Or a more general explanation:**

We have to validate two things:

* Is the denominator a factor 10 (`1, 10, 100, 1000`, etc.)?
* Does the length of the numerator + 1 equal the length of the denominator?
    + This second part is done by checking if the denominator as is, is equal to 10 to the power of the length of the numerator, which saves 2 bytes

PS: If we could take the numerator and denominator as separated inputs, just 3 bytes would have been enough: `g°Q`.

# Answer
> 2 votes
# Haskell, ~~47~~ 40 bytes

*-7 thanks to OMᗺ*

```
f b|(u,v)<-span('/'<)b="/1"++('0'<$u)==v

```

Try it online!

A port of my Clean answer using Neil's method.

# Answer
> 2 votes
# Perl 5 -p, 23 bytes

```
$_=eval=~s/..//r eq$_+0

```

Try it online!

Takes the fractional part alone as input (as allowed by OP), outputs 1 for true and nothing for false.

```
$_=       # assign to be printed by -p
eval      # evaluate fraction to get 0.something, for eg. 0.54
=~s/..//r # remove the 0. part, giving 54
 eq       # string equality check
$_+0      # after first coercing input to number to remove / and denominator

```

The decimal part taken by itself would be exactly equal to the numerator only when the denominator is the immediate next power of ten greater than the numerator, which is the condition we need to check for.

# Answer
> 2 votes
# Noether, 17 bytes

```
I#I"/"^WL1-%WL_=P

```

**Try it online!**

## Explanation

So how does this work? Well, if you look at the test cases, the only true cases are when the denominator is a power of ten, \\$10^a\\$, where \\$a\\$ is the length of the numerator plus one (\\$a = \lfloor \log\_{10} n \rfloor + 1\\$, where \\$n\\$ is the numerator and \\$\lfloor x \rfloor\\$ represents the flooring function).

```
I#                - Push the first input then pop it off the stack
  I"/"^           - Push the second input and split the string at "/"
       W          - Convert the top (the denominator) of the stack from a string to a number
        L1-       - Take the log 10 of the top of the stack and subtract 1 (a)
           %      - Rotate the stack
            WL_   - Convert the top of the stack (the numerator) to a number, take the log10 and floor the result (b)
               =  - Check if a and b are equal
                P - Print the top of the stack

```

# Answer
> 2 votes
# C (gcc), ~~67~~ ~~56~~ 55 bytes

```
m;x(char*_){for(m=1;*_++;m*=10)*_*=*_^47;m=m==atoi(_);}

```

Try it online!

# Answer
> 2 votes
# TeaScript, 25 bytes

First input is the fraction, second is the integer.

*I just started in TeaScript so it might be golfed down a lot*

```
s"/")▒⌐ep(xs"/")░.n

```

Try it online!

# Answer
> 2 votes
# , 53 bytes

```
function(n,x=el(strsplit(n,"/")))x[2]==10^nchar(x[1])

```

Try it online!

Takes only the fractional part as input. As mentioned by xnor in a comment:

> This seems to be equivalent to "given an input that doesn't matter and two numbers as a string separated by a slash, determine whether the second number equals 10 to the power of the length of the first number".

Robert S.'s answer is less golfy but much more interesting than mine.

# Answer
> 1 votes
# Excel, 52 bytes

```
=10^FIND("/",B1)/10-MID(B1,FIND("/",B1)+1,LEN(B1))=0

```

Ignores the Integer input. Basically: `IS Denominator = 10^LEN(Numerator)`

---

For denominators limited to `<10^9`: 48 bytes:

```
=10^FIND("/",B1)/10-MID(B1,FIND("/",B1)+1,1E9)=0

```

---

Bulk of logic is splitting on `/`. If input could be taken separately, 16 bytes:

```
=10^LEN(B1)-C1=0

```

# Answer
> 1 votes
# Elixir, 81 bytes

```
fn b->[n,d]=String.split b,"/";String.to_integer(d)==:math.pow 10,byte_size n end

```

Try it online!

Might be able to get somewhere with `{n,"/"<>d}=Integer.parse b`, but not sure how.

# Answer
> 1 votes
# C (gcc/clang), ~~59~~ ~~49~~ 47 bytes

```
f(a,b){a=atoi(b=strchr(a,47)+1)==pow(10,b+~a);}

```

Port of Chas Brown's Python 2 answer. Try it online here.

Ignores the integer part of the input. Thanks to Jonathan Frech for golfing 2 bytes.

Ungolfed:

```
f(a, b) { // function returning an int and taking a string as input; also declaring another string variable
          // this abuses the parameters as much as possible, omitting the type int and implicitly converting it to char *
    a =                             // return a truthy or falsey value based on
        atoi(b = strchr(a, 47) + 1) // the denominator (as integer; 47 is the ASCII code for '/')
        == pow(10, b + ~a);         // is equal to 10 to the power of the length of the numerator-string
}

```

# Answer
> 1 votes
# 2DFuck, 86 bytes

```
..!x..!...,,,,[>,,,,,,,,],,,,,,,,,[v!],[v!],[v!],![v!],,,[,,[v!],[v!],[v!],[v!]<,,,]r.

```

Try it online!

Takes input without integer part.

# Answer
> 1 votes
# ForceLang, ~~86~~ 78 bytes

```
set a io.readnum()
set b io.readnum()
set d number.parse a+b+""
io.write d=a+b

```

---
Tags: code-golf, number, decision-problem, rational-numbers
---


title: Make the super number hyper-pyramid

text:
# Question
Title: Make the super number hyper-pyramid
# Challenge

Given a positive integer \\$n\\$, output the \\$n\\$-dimensional pyramidal list.

# Example

---

\\$n = 1\\$:

Objects arranged in a 1D pyramid (line) with side length 1 is just by itself.

So, the output is `{1}`.

---

\\$n = 2\\$:

Objects arranged in a 2D pyramid (a triangle) with side length 2 would have one on the first row (cyan), and two on the second row (magenta).

Note, the first row is a 1D pyramid with side length 1 (`{1}`), and the second row is a 1D pyramid with side length 2 (`{1, 1}`).

So, the output is `{{1}, {1, 1}}`.

---

\\$n = 3\\$:

Objects arranged in a 3D pyramid with side length 3 would have 3 layers:

* The first layer (cyan) is a 2D pyramid with side length 1. It has one row, which has one object. (`{{1}}`)
* The second layer (magenta) is a 2D pyramid with side length 2; It has two rows: the first row with one object and the second row with two objects. (`{{1}, {1, 1}}`)
* The third layer (yellow) is a 2D pyramid with side length 3; it has three rows: the first row with one object, second with two, and third with three. (`{{1}, {1, 1}, {1, 1, 1}}`)

So, the output is `{{{1}}, {{1}, {1, 1}}, {{1}, {1, 1}, {1, 1, 1}}}`.

---

\\$n = k\\$

This is a \\$k\\$ dimensional pyramid with side length \\$k\\$. Each "layer" would be a \\$k-1\\$ dimensional pyramid, whose side length is its index (1-indexed).

---

## Sample Outputs

```
n  output

1  {1}

2  {{1},
    {1, 1}}

3  {{{1}},
    {{1}, {1, 1}},
    {{1}, {1, 1}, {1, 1, 1}}}

4  {{{{1}}},
    {{{1}}, {{1}, {1, 1}}},
    {{{1}}, {{1}, {1, 1}}, {{1}, {1, 1}, {1, 1, 1}}},
    {{{1}}, {{1}, {1, 1}}, {{1}, {1, 1}, {1, 1, 1}},
     {{1}, {1, 1}, {1, 1, 1}, {1, 1, 1, 1}}}}

```

## Rules

* No standard loopholes as always.
* The innermost values of your list may be anything (does not need to be consistent for all elements), as long as they are not lists.

This is , so shortest submissions in *each* language win!

---

Note: Graphics generated using Mathematica

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

Ha! Of course it is biased towards Mathematica!

```
Nest[Range,#,#]&

```

Try it online!

---
Tags: code-golf, array
---


title: Roman Army Shields

text:
# Question
Title: Roman Army Shields
*Sandbox post (deleted)*

The old roman army formations are very famous around the world. In these formations roman legionaries grouped in a geometric shape (usually a rectangle) protecting the flanks and the superior part of it using their shields. The legionaries at interior positions covered the superior part placing their shield above their heads, the legionaries at the flanks carried 2 or more shields: one for protecting the superior part, and one or more shields for protecting the flanks (if someone was in the corner he had 3 shields, if someone was alone in a formation he had 5 shields *Yes, I know it is impossible for a human to carry 5 shields, but somehow they did it*). Using this formation all roman legionaries protected themselves and were the hardest opponent at the time.

The history tells there was a roman general who stated that the best formation shape was the square (same number of legionaries in rows and columns). The problem was figuring out how many formations (and the size) he should split his army in order to:

* Do not left any legionary out of a formation (although he admitted single legionary formation)
* Reduce the amount of required shields

The general, after doing some math and calculations, he figured out that the best way to accomplish this 2 conditions is to **start with the biggest square possible, and then repeat until no legionaries left**.

---

**Example:**

If 35 legionaries in his army, the formation consisted in

* A 5x5 legionaries square (This is the biggest square possible).

With the remaining legionaries (10)

* A 3x3 square

With the remaining legionaries (1)

* A 1x1 square.

At the end it will look something like this:

```
   5x5
* * * * *        3x3
* * * * *       * * *      1x1
* * * * *       * * *       *
* * * * *       * * *
* * * * *

```

*The legionaries at interior positions covered the superior part placing their shield above their heads*. They only needed 1 shield.

```
* * * * *
* 1 1 1 *       * * *
* 1 1 1 *       * 1 *       *
* 1 1 1 *       * * *
* * * * *

```

*The legionaries at the flanks carried 2*

```
* 2 2 2 *
2 1 1 1 2       * 2 *
2 1 1 1 2       2 1 2       *
2 1 1 1 2       * 2 *
* 2 2 2 *

```

*If someone was in the corner he had 3 shields*

```
3 2 2 2 3
2 1 1 1 2       3 2 3
2 1 1 1 2       2 1 2       *
2 1 1 1 2       3 2 3
3 2 2 2 3

```

*If someone was alone in a formation he had 5 shields*

```
3 2 2 2 3
2 1 1 1 2       3 2 3
2 1 1 1 2       2 1 2       5
2 1 1 1 2       3 2 3
3 2 2 2 3

```

This formation required a total of 71 shields.

---

**Challenge**

* Calculate the amount of shields that are needed for a X amount of legionaries

**Input**

* Amount of legionaries in the army

**Output**

* Amount of shields needed.

**Test Cases**

```
35 => 71
20 => 44
10 => 26
32 => 72

```

---

# Answer
# Python 2, ~~60~~ ~~50~~ 48 bytes

```
def f(s):n=s**.5//1;return s and(n+4)*n+f(s-n*n)

```

Try it online!

New to code golf, but giving it my best swing!

**Method:**

Sum `n^2 + 4n` where `n` is each of the largest square numbers that sum to the input.

**Edit 1**

Reduced to 50 bytes thanks to @Jonathan Frech!

**Edit 2**

Switched `int(s**.5)` to `s**.5//1` to save 2 bytes thanks to @ovs
> 14 votes

# Answer
# , ~~51~~ 50 bytes

```
f=function(x,y=x^.5%/%1)"if"(x,y^2+4*y+f(x-y^2),0)

```

Try it online!

A square of side length \\$y\\$ must have exactly \\$y^2+4y\\$ shields. We reduce by the largest square less than or equal to \\$x\\$ until \\$x\\$ is zero, accumulating the number of shields as we go.

Proof:

Given a perfect square of side length \\$y\\$, we need precisely 1 shield for each member of the square. Next, for each member on the edge, we need an additional shield. There are \\$(y-2)^2\\$ members *not* on the edges, so there are \\$y^2-(y-2)^2\\$ members on the edges. Finally, for each corner, we need an additional shield. Apart from the case where \\$y=1\\$, we can thus add 4. This simplifies to \\$y^2+4y\\$ which fortunately also yields the correct value of \\$5\\$ when \\$y=1\\$, allowing us to use it for all \\$y\\$.
> 10 votes

# Answer
# JavaScript (ES7), 34 bytes

```
f=n=>n&&(w=n**.5|0)*w+w*4+f(n-w*w)

```

Try it online!

### How?

At each iteration, we compute the width \\$w = \lfloor\sqrt{n}\rfloor\\$ of the largest possible square. The number of shields \\$s\_w\\$ for this square is given by:

$$s\_w = w^2+4w$$

For instance, for \\$w=3\\$:

$$\begin{align}&\pmatrix{3 & 2 & 3\\2 & 1 & 2\\3 & 2 & 3}=&(s\_3=21)\\\&\pmatrix{1 & 1 & 1\\1 & 1 & 1\\1 & 1 & 1}+&(3^²=9)\\\&\pmatrix{1 & 1 & 1\\0 & 0 & 0\\0 & 0 & 0}+\pmatrix{0 & 0 & 1\\0 & 0 & 1\\0 & 0 & 1}+\pmatrix{0 & 0 & 0\\0 & 0 & 0\\1 & 1 & 1}+\pmatrix{1 & 0 & 0\\1 & 0 & 0\\1 & 0 & 0}&(4\times3=12)\end{align}$$

The formula holds for \\$w=1\\$, as \\$s\_1=5\\$.
> 10 votes

# Answer
# Jelly, 13 bytes

```
Æ½²ạƊƬ_Ɲ½ẋ4S+

```

Try it online!

-1 thanks to Jonathan Allan.
> 5 votes

# Answer
# Julia 0.6, 36 bytes

```
!n=(s=isqrt(n))*s+4s+(n>0&&!(n-s*s))

```

Try it online!

Uses the same \\$ n^2 + 4n \\$ method as @Giuseppe's R answer, though my method to arrive there involved less meaningful thinking and more just visual inspection: the inner square of 1s has dimensions \\$ (n - 2) \\$ by \\$ (n - 2) \\$, so that has \\$ (n - 2)^2 \\$ shields. Surrounding that, there are 4 walls of \\$ n - 2 \\$ soldiers each, each with 2 shields - so that adds \\$ 4\*(n - 2)\*2 \\$ shields. Finally, there are four 3s in the four corners, so that adds 12 shields.

$$ (n-2)^2 + 4\*(n-2)\*2 + 4\*3 = n^2 + 4 - 4n + 8n - 16 + 12 = n^2 + 4n $$

### Ungolfed:

```
!n = begin       # Assign to ! operator to save bytes on function parantheses
  s = isqrt(n)   # Integer square root: the largest integer m such that m*m <= n
  s * s +
    4 * s +
      (n > 0 &&  # evaluates to false = 0 when n = 0, otherwise recurses
        !(n - s * s))
end

```

(This can also be done it in 35 bytes with `n>0?(s=isqrt(n))*s+4s+f(n-s*s):0`, but I wrote this for Julia 0.7 wanted to avoid the new deprecation warnings (requiring spaces are `?` and `:`).)
> 4 votes

# Answer
# Stax, 15 bytes

```
ëñ|^○╖?║<l╛P╝z√

```

Run and debug it
> 4 votes

# Answer
# Brachylog, 26 bytes

```
0|⟧^₂ᵐ∋N&;N-ℕ↰R∧N√ȧ×₄;N,R+

```

Try it online!

```
0           % The output is 0 if input is 0
|           % Otherwise,
⟧           % Form decreasing range from input I to 0
^₂ᵐ         % Get the squares of each of those numbers
∋N          % There is a number N in that list
&;N-ℕ       % With I - N being a natural number >= 0 i.e. N <= I
            % Since we formed a decreasing range, this will find the largest such number
↰           % Call this predicate recursively with that difference I - N as the input
R           % Let the result of that be R
∧N√ȧ        % Get the positive square root of N
×₄          % Multiply by 4
;N,R+       % Add N and R to that
            % The result is the (implicit) output

```
> 3 votes

# Answer
# Retina 0.8.2, 28 bytes

```
.+
$*
(\G1|11\1)+
$&11$1$1
.

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to decimal.

```
(\G1|11\1)+

```

Match odd numbers. The first pass through the group, `\1` doesn't exist yet, so only `\G1` can match, which matches 1. Subsequent matches can't match `\G1` since `\G` only matches at the beginning of the match, so instead we have to match the `11\1` which is 2 more than the previous match. We match as many odd numbers as we can, and the total match is therefore a square number, while the last capture is one less than twice its side.

```
$&11$1$1

```

Add the side shields to each match. `$&` is \\$n^2\\$ and `$1` is \\$2n-1\\$ while we need \\$n^2+4n=n^2+2+2(2n-1)\\$.

```
.

```

Sum and convert to decimal.
> 2 votes

# Answer
# 05AB1E, 17 bytes

```
[Ð_#tïÐns4*+Šn-}O

```

Try it online or verify all test cases.

Work-around because `ΔDtïÐns4*+Šn-}O` (**15 bytes**) doesn't seem to work.. Try it online in debug-mode to see what I mean. I would expect it to go from `[45,'35',25]` to `[45,10]` after the `-` and next iteration of `Δ`, but apparently it clears the stack except for the last value and becomes `[10]`, resulting in 0 at the very end.. Not sure if this is intended behavior or a bug.. (EDIT: It's intended, see bottom.)

**Explanation:**

Also uses \\$w^2+4w\\$ where \\$w\\$ is the width in a loop like most other answers.

```
[        }     # Start an infinite loop:
 Ð             #  Triplicate the value at the top of the stack
  _#           #  If the top is 0: break the infinite loop
 t             #  Take the square-root of the value
               #   i.e. 35 → 5.916...
  ï            #  Remove any digits by casting it to an integer, so we have our width
               #   i.e. 5.916... → 5
   Ð           #  Triplicate that width
    n          #  Take the square of it
               #   i.e. 5 → 25
     s         #  Swap so the width is at the top again
      4*       #  Multiply the width by 4
               #   i.e. 5 → 20
        +      #  And sum them together
               #   i.e. 25 + 20 → 45
 Š             #  Triple-swap so the calculated value for the current width
               #  is now at the back of the stack
               #   i.e. [35,5,45] → [45,35,5]
  n            #  Take the square of the width again
               #   5 → 25
   -           #  Subtract the square of the width from the value for the next iteration
               #   i.e. 35 - 25 → 10
          O    # Take the sum of the stack
               #   i.e. [45,21,5,0,0] → 71

```

---

EDIT: Apparently the behavior I described above for `Δ` is intended. Here two 17-bytes alternatives provided by *@Mr.Xcoder* that do use `Δ` by putting values in the global\_array (with `^`) and retrieving them again afterwards (with `¯`):

```
ΔÐˆtïnα}¯¥ÄDt··+O

```

Try it online or verify all test cases.

```
ΔÐˆtïnα}¯¥ÄtD4+*O

```

Try it online or verify all test cases.
> 2 votes

# Answer
# dc, 25 bytes

```
d[dvddSa*-d0<MLa+]dsMx4*+

```

Try it online!

Calculates the shields as `sum(n^2)` (the original number) plus `4*sum(n)` by pushing a copy of each square side length into stack register `a` as it goes, then adding all the values from register `a` as the recursion "unrolls".
> 2 votes

# Answer
# Husk, 17 bytes

```
ṁS+o*4√Ẋ≠U¡S≠(□⌊√

```

Try it online!

### Alternative

```
ṁS*+4m√Ẋ≠U¡S≠(□⌊√

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), ~~31~~ 30 bytes

```
{⍵<2:⍵×5⋄(S×S+4)+∇⍵-×⍨S←⌊⍵*.5}

```

Try it online!

-1 byte thanks to @jslip
> 2 votes

# Answer
# Ruby, 45 bytes

```
->n{n+(1..n).sum{n-=(z=(n**0.5).to_i)*z;z*4}}

```

Try it online!
> 1 votes

# Answer
# Pyth, 19 bytes

A recursive function, which should be called using `y` (see the link).

```
L&b+*Ks@b2+4Ky-b^K2

```

Try it here!

# Pyth, 21 bytes

The revision history is quite funny, but make sure to visit it if you want a much faster version :)

```
sm*d+4deeDsI#I#@RL2./

```

Try it here!

### Explanation

```
sm*d+4deeDsI#I#@RL2./     Full program, let's call the input Q.
                   ./     Integer partitions of Q. Yields all combinations of positive
                          integers that add up to Q.
               @RL2       Take the square root of all integers of each partition.
             I#           Keep only those partitions that are invariant under:
          sI#             Discarding all non-integers. This basically only keeps the
                          partitions that are formed fully of perfect squares, but
                          instead of having the squares themselves, we have their roots.
       eeD                Get the partition (say P) with the highest maximum.
 m                        For each d in P ...
  *d+4d                   ... Yield d*(d+4)=d^2+4d, the formula used in all answers.
s                         Sum the results of this mapping and implicitly output.

```
> 1 votes

# Answer
# PHP, 67 bytes

```
<?for($n=$argv[1];$w=(int)sqrt($n);$n-=$w**2)$a+=$w**2+$w*4;echo$a;

```

To run it:

```
php -n <filename> <n>

```

Example:

```
php -n roman_army_shields.php 35

```

Or Try it online!

---

Using `-R` option, this version is **60 bytes**:

```
for(;$w=(int)sqrt($argn);$argn-=$w**2)$a+=$w**2+$w*4;echo$a;

```

Example:

```
echo 35 | php -nR "for(;$w=(int)sqrt($argn);$argn-=$w**2)$a+=$w**2+$w*4;echo$a;"

```

*(on Linux, replace `"` with `'`)*

---

**Note:** This is using Arnauld's answer great formula, I was not able to find anything shorter than that.
> 1 votes

# Answer
# Swift 4, ~~111 99 84~~ 78 bytes

```
func f(_ x:Int)->Int{var y=x;while y*y>x{y-=1};return x>0 ?(y+4)*y+f(x-y*y):0}

```

Try it online!

That feel when implementing integer square root manually is *far* shorter than the built-in...

## Ungolfed and Explained

```
// Define a function f that takes an integer, x, and returns another integer
// "_" is used here to make the parameter anonymous (f(x:...) -> f(...))
func f(_ x: Int) -> Int {

    // Assign a variable y to the value of x

    var y = x

    // While y squared is higher than x, decrement y.

    while y * y > x {
        y -= 1
    }

    // If x > 0, return (y + 4) * y + f(x - y * y), else 0.

    return x > 0 ? (y + 4) * y + f(x - y * y) : 0
}

```
> 1 votes

---
Tags: code-golf, matrix
---


# Question
Title: L€€CH€$! D€AṬH ỊṢ ṢOOṄ! (Length Mapping)
 The title is valid Jelly Code which has the same output as `L€€` except printed twice.

### Background

You can skip this section without losing ability to complete the challenge

Some operations in Jelly try to convert its argument to a list first before applying the operation. One example is , the mapping quick. This sometimes leads to unintended output.

For the program `L€` and input 5, the Jelly interpreter tries to find the length of every element of the list 5. Since 5 is not a list, Jelly converts it to the list \[1,2,3,4,5\]. Then the length of every element is output: `[1,1,1,1,1]`. Note that every integer has length `1`. If e.g. `10` was present, it would become `1`, not `2` (the length in digits).

For the program `L€€` and input 5, the Jelly interpreter tries to find the length of every element of every element of the list 5. Since 5 is not a list, Jelly converts it to the list `[1,2,3,4,5]`. Now the interpreter tries to find the length of every element of every element of the list `[1,2,3,4,5]`. Every element is not a list, so Jelly converts them to lists in the same manner: `[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]`. The length of every sub-element is output as `[[1],[1,1],[1,1,1],[1,1,1,1],[1,1,1,1,1]]`

### Task

Your task is to find the output of the Jelly program `L` followed by  repeated `a` times, with input `b`, where `a` and `b` are positive integers equal to your program/function's inputs.

A way to do this is:

Starting with the input `b`, do the following `a` times:

* For every integer that the program sees, replace it with the range of the integer (where `range(x) := [1,2,3,...,x-1,x]`)

Finally, replace every integer with 1.

### Test Cases

```
a
b
output
- - - - -
1
1
[1]
- - - - -
1
2
[1, 1]
- - - - -
1
3
[1, 1, 1]
- - - - -
1
4
[1, 1, 1, 1]
- - - - -
1
5
[1, 1, 1, 1, 1]
- - - - -
1
6
[1, 1, 1, 1, 1, 1]
- - - - -
2
1
[[1]]
- - - - -
2
2
[[1], [1, 1]]
- - - - -
2
3
[[1], [1, 1], [1, 1, 1]]
- - - - -
2
4
[[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]
- - - - -
2
5
[[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]
- - - - -
2
6
[[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]
- - - - -
3
1
[[[1]]]
- - - - -
3
2
[[[1]], [[1], [1, 1]]]
- - - - -
3
3
[[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]
- - - - -
3
4
[[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]
- - - - -
3
5
[[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]
- - - - -
3
6
[[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]]
- - - - -
4
1
[[[[1]]]]
- - - - -
4
2
[[[[1]]], [[[1]], [[1], [1, 1]]]]
- - - - -
4
3
[[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]]
- - - - -
4
4
[[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]]
- - - - -
4
5
[[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]]
- - - - -
4
6
[[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]]]
- - - - -
5
1
[[[[[1]]]]]
- - - - -
5
2
[[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]]]
- - - - -
5
3
[[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]]]
- - - - -
5
4
[[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]]]
- - - - -
5
5
[[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]]]
- - - - -
5
6
[[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]]]]
- - - - -
6
1
[[[[[[1]]]]]]
- - - - -
6
2
[[[[[[1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]]]]
- - - - -
6
3
[[[[[[1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]]]]
- - - - -
6
4
[[[[[[1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]]]]
- - - - -
6
5
[[[[[[1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]]]]
- - - - -
6
6
[[[[[[1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]]]]]

```

### Rules

* `a` and `b` are restricted to positive integers
* Your program or function may take `a` and `b` in any order and in any standard input format
* The output should be a depth-a list or string representation of such a list
* The output should be returned through any standard output format.
* This is , so shortest code **in each language** wins!

# Answer
# Jelly, 3 bytes

```
R¡Ṡ

```

Try it online!

Takes input in reverse order.
-2 bytes thanks to fireflame.
-1 byte thanks to Dennis

# Explanation

```
R¡Ṡ  Main link
 ¡   Repeat <first argument> times
R    Range (generates range, and vectorizes on lists)
  Ṡ  Sign (converts all numbers to 1 because they are all positive)

```
> 13 votes

# Answer
# Python 2, 49 bytes

-1 thanks to Jonathan Allan

```
f=lambda a,b:1>>a or[0]*b and f(a,b-1)+[f(a-1,b)]

```

Try it online!

This problem seemed like it could be written in the form of a doubly recursive function, subtracting one from each parameter. The key idea is that the sequence can be related as follows:

```
f(0,b) = 1
f(a,0) = []
f(a,b) = f(a,b-1) + [f(a-1,b)]

```

However writing a recursive function like this is pretty tricky, since `1` is a truthy value and `[]` is a falsy value, so we need two short-circuiting keywords (`and` and `or`).

A less golfed version might look like:

```
lambda a,b:int(a<1)or[1,[]][b<1]and f(a,b-1)+[f(a-1,b)]

```

However we can use the trick that `1>>a` gives `1` if a is zero, and `0` otherwise, and that we can return a truthy value if `b>0` and an empty list otherwise by doing `[0]*b`.
> 11 votes

# Answer
# Mathematica, 17 bytes

```
1^Range~Nest~##&

```

Takes `b` then `a`.

Try it on Wolfram Sandbox

### How?

```
1^Range~Nest~##&

  Range             (* Range function; generates {1..<input>} *)
       ~Nest~##     (* Apply it on <input 1> <input 2> times *)
                    (* Mathematica automatically maps Range onto integers *)
1^                  (* Raise those to the exponent of 1; make everything 1 *)

```

### Usage

```
1^Range~Nest~##&[4, 2]

```

> `{{1}, {1, 1}, {1, 1, 1}, {1, 1, 1, 1}}`
> 9 votes

# Answer
# Gaia, 7 bytes

```
ẏ¦”@)⊃e

```

Try it online!

`ẏ¦` does just about the same thing here as `L€` in Jelly.  is "is positive?" and `¦` is map, which also implicitly casts an integer to the range 1 .. n before mapping. And since we're dealing with only integers \>= 1,  will result in `1` for each.

```
ẏ¦”      Push the string "ẏ¦"
   @)    Push the first input+1
     ⊃   Repeat the last character of the string until it's input+1 characters long.
      e  Eval it.

```
> 4 votes

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

-1 byte thanks to Jakob
-1 byte thanks to notjagan

```
f=lambda a,b:[1]*b*(a<2)or[f(a-1,i+1)for i in range(b)]

```

Try it online!
> 3 votes

# Answer
# PHP, 134 bytes

```
for($r=[$argv[2]];$argv[1]--;)($w=array_walk_recursive)($r,function(&$n){$n=range(1,$n);});$w($r,function(&$n){$n=1;});print_r($r[0]);

```

There may be a shorter approach than the literal one ... but it´s working at least.

Run with `-nr` and provide `a` and `b` as arguments or try it online.

---

For output as in the examples, use `echo strtr(preg_replace('#"\d":#','',json_encode($r[0],JSON_NUMERIC_CHECK)),"{}","[]");` (as I do in the TiO) instead of `print_r($r[0]);`.
> 3 votes

# Answer
## JavaScript (ES6), 95 bytes

```
f=(a,b,r=/\d+/g)=>a--?f(a,b.replace(r,s=>`[${[...Array(+s)].map((_,i)=>++i)}]`)):b.replace(r,1)
```

```
<div oninput=o.textContent=f(a.value,b.value)><input type=number min=0 value=0 id=a><input type=number min=0 value=0 id=b><pre wrap id=o>1
```

I/O is with strings. The best I could do nonrecursively was 100 bytes:

```
(a,b)=>[...Array(-~a)].reduce(r=>r.replace(/\d+/g,a--?s=>`[${[...Array(+s)].map((_,i)=>++i)}]`:1),b)

```
> 3 votes

# Answer
# Brachylog, 21 bytes

```
,1{t+₁I&⟦₁ᵐ⁾;I}ⁱ⁽ṡᵐ⁾c

```

Try it online!

Conceptually simple, but keeping track of the right level to map the 'range'  predicate at, takes up almost half the bytes. :(

```
                 % Implicit input, list [a, b]
,1               % Append iteration index 1 to the list
{           }ⁱ⁽  % Do this iteratively a times, with [b, i] as the initial input
 t+₁I            % Increment iteration index, let this be I
     &⟦₁ᵐ⁾       % Map the "range from 1 to input" predicate on the first part of input
                 %   (b in the first iteration), at depth given by (old) iteration index
          ;I     % Append the incremented index to this, this is the input to next iteration
ṡᵐ⁾              % Take the sign of each element, mapped at depth given by final I
c                % "Concatenate" to remove extra surrounding array

```

And a recursive solution, just for the heck of it:

### 24 bytes

```
{t0&hṡᵐ|t-₁L&h⟦₁ᵐ;Lz↰ᵐ}c

```

Try it online!
> 3 votes

# Answer
# Jelly, 12 bytes

```
⁴Ṿ;”L;”€ẋ³¤V

```

Try it online!

Just to get things started. I'm pretty sure it would be shorter if I actually did it the way I'm supposed to, so I'm working on that (inb4 ninja'd by someone)

# Explanation

```
⁴Ṿ;”L;”€ẋ³¤V  Main link
 Ṿ            Generate Jelly code that will evaluate to
⁴             The second input
  ;           Concatenate with
   ”L         "L"
     ;        Concatenate with
      ”€ẋ³¤   Niladic Expression
      ”€      "€"
        ẋ     Repeated                times
         ³             <first input>
           V  Jelly-eval it

```
> 1 votes

---
Tags: code-golf, array, jelly
---