title: DNA to RNA Transcription

text:
# Question
Title: DNA to RNA Transcription
# Guidelines

### Task

Given a DNA strand, return its RNA complement (per RNA transcription).

Both DNA and RNA strands are a sequence of nucleotides.

The four nucleotides found in DNA are adenine (**A**), cytosine (**C**), guanine (**G**) and thymine (**T**).

The four nucleotides found in RNA are adenine (**A**), cytosine (**C**), guanine (**G**) and uracil (**U**).

Given a DNA strand, its transcribed RNA strand is formed by replacing each nucleotide with its complement:

* `G` -\> `C`
* `C` -\> `G`
* `T` -\> `A`
* `A` -\> `U`

---

### Rules

* The input will always be either a string or an array/list of characters
* The output should always be either a string or an array/list of characters
* In the case of invalid input, you should output `'Invalid Input'` as a string or an array/list of characters
* You can assume that you will only be given printable ASCII characters.
* This is code golf so the person with the least amount of bytes winsx

---

### Examples

`'C' -> 'G'`

`'A' -> 'U'`

`'ACGTGGTCTTAA' -> 'UGCACCAGAAUU'`

`'XXX' -> 'Invalid Input'`

`'ACGTXXXCTTAA' -> 'Invalid Input'`

---

### Other info

This task was taken from Exercism, which was founded by Katrina Owen and is licensed under the MIT License.

# Answer
> 1 votes
# 05AB1E, 23 bytes

```
„—ÄGu©ÃQi®"GUAC"‡ë”Í¼î®

```

Try it online!

**Explanation**

```
„—ÄGu©                    # push "CATG" and store a copy in register
      Ã                   # keep only those letters of input
       Qi                 # if the result equals the input
         ®"GUAC"‡         # translate "CATG" to "GUAC"
                 ë”Í¼î®   # else, push "Invalid Input"

```

# Answer
> 1 votes
## Retina, ~~36~~ 31 bytes

```
T`GCTAp`CGAUx
K'x`Invalid input

```

Try it online!

### Explanation

```
T`GCTAp`CGAUx

```

Perform the required character substitutions as a transliteration, while also replacing all invalid characters with `x`.

```
K'x`Invalid input

```

If the result contains `x` (i.e. the input contained an invalid character), replace it with the constant string `Invalid input`.

# Answer
> 1 votes
# K (oK) / K4, 38 bytes

**Solution:**

```
(x;"Invalid Input")@|/^x:"CGAU""GCTA"?

```

Try it online!

**Examples:**

```
q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"C"
"G"
q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"C"
"G"
q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"G"
"C"
q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"ACGTGGTCTTAA"
"UGCACCAGAAUU"
q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"XXX"
"Invalid Input"
q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"ACGTXXXCTTAA"
"Invalid Input"

```

**Explanation:**

The mapping is trivial. 25 bytes for the "Invalid Input" portion.

```
(x;"Invalid Input")@|/^x:"CGAU""GCTA"? / the solution
                               "GCTA"? / return index in left list
                         "CGAU"        / index into this list
                       x:              / save as x
                      ^                / null, any nulls in x?
                    |/                 / take max
                   @                   / index into
( ;               )                    / two item list
   "Invalid Input"                     / result if null found
 x                                     / result if no nulls found

```

# Answer
> 1 votes
# Python, ~~103~~ ~~95~~ 86 bytes

```
def f(b):
 try:return["CGAU"["GCTA".index(i)]for i in b]
 except:return"Invalid Input"

```

Or, if lowercase inputs count:

```
def f(b):
 try:return["cgau"["gcta".index(i.lower())]for i in b]
 except:return"Invalid Input"

```

# Answer
> 1 votes
# Python 3, ~~82~~ ~~79~~ 67 bytes

thanks to Laikoni for -3 bytes!
-12 bytes by looking at this 3 years later.

```
lambda s:{*s}-{*'ACGT'}and'Invalid Input'or s.translate('UCG A'*17)

```

Try it online!

`str.translate` takes any kind of collection of characters or codepoints that can be indexed into with an integer, in this case we use a string.

| `c` | `ord(c)` | `ord(c)%5` | `('UCG A'*20)[ord(c)]` |
| --- | --- | --- | --- |
| `'A'` | `65` | `0` | `'U'` |
| `'C'` | `67` | `2` | `'G'` |
| `'G'` | `71` | `1` | `'C'` |
| `'T'` | `84` | `4` | `'A'` |

# Answer
> 1 votes
# Red,118 114 bytes

```
func[s][t: copy{}foreach c s[append t switch/default to-word c[G[{C}]C[{G}]T[{A}]A[{U}]][return"Invalid Input"]]t]

```

Try it online!

Ungolfed:

```
f: func [s] [
    t: copy {}                              ; initialize t to an empty string
    foreach c s [                           ; for each character c of the input
        append t switch/default to-word c [ ; append to t the following if c is one of GCTA
            G [{C}]
            C [{G}]
            T [{A}]
            A [{U}]
        ]
        [ return "Invalid Input" ]          ; otherwise return "Invalid Input"
    ]
    t                                       ; return t
]

```

# Answer
> 1 votes
# GNU sed, ~~70~~ 43 bytes

```
s/^.*[^ATCG].*$/Invalid Input/
y/ATCG/UAGC/

```

Try it online!

# Answer
> 1 votes
# C (clang) or MinGW, 110 bytes

```
f(s){for(char*t="GCTA",*o=s=strdup(s),*q;*o;o++)(q=strchr(t,*o))?*o="CGAU"[q-t]:(s="Invalid input!");puts(s);}

```

Try it online!

# Answer
> 1 votes
# Coconut, ~~75~~ 70 bytes

```
s->set(s)-set('ACGT')and'Invalid Input'or["UCG A"[ord(c)%5]for c in s]

```

Try it online! A mix of ovs' Python answer and my Haskell answer.

*Edit: -5 bytes thanks to ovs!*

# Answer
> 1 votes
# CJam, 43 bytes

```
l{"GCTA"#"CGAU "=}%_S#){];"Invalid input"}&

```

Online interpreter: http://cjam.aditsu.net/

# Answer
> 0 votes
## Perl 5 with `-p`, 39 bytes

```
y/GCTA/CGAU/<y///c?$_="Invalid Input":0

```

Saved 1 byte thanks to wastl!

Try it online!

# Answer
> 0 votes
## Batch, 192 bytes

```
@echo off
set/ps=
set t=%s:A=%
set t=%t:C=%
set t=%t:G=%
set t=%t:T=%
if not "%t%"=="" echo Invalid Input&exit/b
set s=%s:A=U%
set s=%s:C=A%
set s=%s:G=C%
set s=%s:A=G%
echo %s:T=A%

```

Takes input on STDIN.

# Answer
> 0 votes
# JavaScript (ES6), 78 bytes

```
f=([c,...r],s='',k='GCTA'.indexOf(c))=>c?~k?f(r,s+'CGAU'[k]):'Invalid input':s

```

### Test cases

```
f=([c,...r],s='',k='GCTA'.indexOf(c))=>c?~k?f(r,s+'CGAU'[k]):'Invalid input':s

console.log(f('C'           )) // 'G'
console.log(f('A'           )) // 'U'
console.log(f('ACGTGGTCTTAA')) // 'UGCACCAGAAUU'
console.log(f('XXX'         )) // 'Invalid Input'
console.log(f('ACGTXXXCTTAA')) // 'Invalid Input'
```

---

### Without input validation (non-competing)

47 bytes using `search()`:

```
f=([c,...r])=>c?'CGAU'['GCTA'.search(c)]+f(r):r

```

48 bytes using a hash:

```
f=([c,...r])=>c?'UCG_A'[parseInt(c,36)%5]+f(r):r

```

# Answer
> 0 votes
# Haskell, 75 bytes

```
f s|all(`elem`"GCTA")s=["UCG A"!!mod(fromEnum c)5|c<-s]
f _="Invalid Input"

```

Try it online! The mapping is done by taking the character values mod 5 and indexing into the string `"UCG A"`.

# Answer
> 0 votes
# Jelly,  ~~24~~  23 bytes

```
“ɠ{>dʠ»ɓ,Ṛ;⁾TUyðḟ?“TGCA

```

A full program printing the result (a monadic link is  ~~25~~  24 with a closing  appended)

**Try it online!**

### How?

```
“ɠ{>dʠ»ɓ,Ṛ;⁾TUyðḟ?“TGCA - Main Link: list of characters
                  “TGCA - literal list of characters = ['T','G','C','A']
                 ?      - if...
                ḟ       - ...condition: filter discard (empty is falsey)
“ɠ{>dʠ»                 - ...then: compressed string = "Invalid Input"
       ɓ       ð        - ...else: dyadic chain with swapped arguments:
         Ṛ              - reverse = ['A','C','G','T']
        ,               - pair = [['T','G','C','A'],['A','C','G','T']]
           ⁾TU          - literal list of characters = ['T','U']
          ;             - concatenate = [['T','G','C','A'],['A','C','G','T'],'T','U']
              y         -   translate...
                        -   ... 1: {'T'->'A';'G'->'C';'C'->'G';'A'->'T'}
                        -   ... 2: {'T'->'U'}

```

# Answer
> 0 votes
# C, 128 bytes

```
k,l;f(S){char*s=S,b[l=strlen(s)],*t=b;for(;*t++=(k=*s++)-65?k-67?k-71?k-84?0:65:67:71:85;);puts(strlen(b)-l?"Invalid Input":b);}

```

Try it online!

**Unrolled:**

```
k, l;
f(S)
{
    char *s=S, b[l=strlen(s)], *t=b;
    for(; *t++ = (k=*s++)-65 ? k-67 ? k-71 ? k-84 ? 0 : 65 : 67 : 71 : 85;);
    puts(strlen(b)-l ? "Invalid Input" : b);
}

```

# Answer
> 0 votes
# APL+WIN, 66 bytes

Prompts for screen input of original string

```
('CGAU',⊂'Invalid Input')[(((⍴n)×~m)↑n),(m←0<+/(n←,'GTCA'⍳⎕)=5)↑5]

```

# Answer
> 0 votes
# , 75 bytes

```
function(s)"if"(grepl("[^ACGT]",s),"Invalid Input",chartr("ACGT","UGCA",s))

```

Try it online!

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


# Question
Title: Find number of ones to get a number using + and *
# Introduction

Your goal is to find the least number of ones you need to add or multiply together to get the input value, this is A005245.

## Input

One positive integer ***N***.

## Output

The smallest number of ones that must be added/multiplied to get ***N***.

### Sample Input

> 7

### Sample Output

> 6

### Explanation

> (`1` \+ `1` \+ `1`) * (`1` \+ `1`) + `1` = 7
>
> Because this requires `6` ones, the output is `6`

### Test cases

```
 1  1
 2  2
 3  3
 5  5
10  7
20  9
50 12

```

As this is a challenge, lowest number of bytes wins.

# Answer
# Python 2, ~~74~~ 70 bytes

```
f=lambda n:min([n]+[f(j)+min(n%j*n+f(n/j),f(n-j))for j in range(2,n)])

```

Try it online!

### Alternate version, 59 bytes (unverified)

```
f=lambda n:min([n]+[f(j)+f(n/j)+f(n%j)for j in range(2,n)])

```

This works at least up to **n = 1,000,000**, but I have yet to prove that it works for all positive **n**.

Try it online!
> 17 votes

# Answer
# Jelly, ~~16~~ 14 bytes

Thanks Dennis for saving 2 bytes!

```
ÆḌḊ,Ṗß€€+U$FṂo

```

Try it online!

---

## Logic explanation

Given a number **n**:

* If it's `1`, the answer is `1`. Otherwise:

The representation is either `a + b` or `a × b`, where `a` and `b` are expressions.

Consider all possible values of `a` and `b`:

* If the representation is `a + b`, then `a` and `b` are in range `[1 .. n-1]`.
* If the representation is `a × b`, `a` and `b` are proper divisors of `n` larger than `1`.

In both cases, the list `[[<proper divisors of n larger than 1>], [1, 2, ..., n-1]]` is computed (`ÆḌḊ,Ṗ`), map the current link over each number `ß€€`, add the correct pairs together (`+U$`) and get the minimum value (`FṂo`).

## Code explanation

```
ÆḌḊ,Ṗß€€+U$FṂo   Main link. Assume ***n*** = 10.
ÆḌ       Proper **d**ivisors. *[1,2,5]*equeue, remove the first element. *[2,5]*
   ,Ṗ    Pair with op. Auto convert ***n*** = 10 to range
         *[1,2,3,4,5,6,7,8,9,10]* and remove the last element
         *10*, get *[1,2,3,4,5,6,7,8,9]*.

ß€€      Apply this link over each element.
   +U$   Add with the **U**pend of itself.

FṂ       **F**latten and get the inimum element.
  o      Logical **o**r with ***n***.
         If the list is empty, minimum returns *0* (falsy), so logical or
         convert it to ***n***.

```
> 10 votes

# Answer
# Pari/GP, 66 bytes

A port of Dennis's Python answer:

```
f(n)=vecmin(concat(n,[f(j)+min(n%j*j+f(n\j),f(n-j))|j<-[2..n-1]]))

```

Try it online!

---

# Pari/GP, 72 bytes

Longer, but more efficient:

```
f(n)=if(n<6,n,vecmin([if(d>1,f(d)+f(n/d),1+f(n-1))|d<-divisors(n),d<n]))

```

Try it online!
> 5 votes

# Answer
## JavaScript (ES6), ~~108~~ 96 bytes

```
f=n=>n<6?n:Math.min(...[...Array(n-2)].map((_,i)=>Math.min(f(++i)+f(n-i),n%++i/0||f(i)+f(n/i))))

```

Very inefficient; `Array(n>>1)` speeds it up slightly at a cost of a byte. Explanation: `n%++i` is non-zero if `i` is not a factor, so `n%++i/0` is `Infinity` (and therefore truthy, and also definitely not minimal) if `i` is not a factor, but `NaN` (and therefore falsy) if `i` is a factor. Edit: Saved 12 bytes with inspiration from @edc65.
> 5 votes

# Answer
# Pari/GP, 213 bytes

**Edit:** I've been severely beaten.

```
f(n)={d;n<6&return(n);if(n<=#a,a[n]&return(a[n]),a=vector(n));for(i=1,n-1,a[i]||a[i]=f(i));a[n]=min(vecmin(vector(n\2,k,a[k]+a[n-k])),if(isprime(n),n,vecmin(vector((-1+#d=divisors(n))\2,i,a[d[i+1]]+a[d[#d-i]]))))}

```

Try it online!
> 4 votes

# Answer
# Python 2, 181 bytes

```
def F(N,n,s="",r=""):
 try:
	if n<1:return(eval(s)==N)*0**(`11`in s or"**"in s)*s
	for c in"()+*1":r=F(N,~-n,s+c)or r
 except:r
 return r
f=lambda N,n=1:F(N,n).count(`1`)or f(N,-~n)

```

Try it online!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 59 bytes

Saved 3 bytes thanks to Martin Ender. Using CP-1252 encoding, where `±` is one byte.

```
±1=1;±n_:=Min[1+±(n-1),±#+±(n/#)&/@Divisors[n][[2;;-2]]]

```

Try it online!
> 2 votes

# Answer
# Perl 5, -p 78 bytes

79 bytes in old style counting (`+1` for `-p`)

The fact that perl must use an extra `$` for all scalar access really hurts the length of golfs that do a lot of arithmetic...

This method is mostly like the others already posted (try multiplication and addition to build a target number, take the cheapest). It however doesn't repeatedly recurse down so it can be used for relatively large inputs.

It also doesn't try to minimize the cost of building a number by addition or multip\[lication because perl 5 has no builtin `min` and numeric sort is looooooong (as seen from the sort still in the code). Instead I just assume if a number is a factor of the target that I will use multiplication. That is safe since if e.g. `3` is a factor of `12` (so it sums the cost of `3` and `12/3`) later in the loop it will consider `9=12-3` which will not be a factor, so `9+3` with the same cost as `3+9` will get tried anyways. However that may fail for targets `<= 4` (it only does for `1` and `2`). Adding `$_` to the list to minimize fixes that. Which is unfortunate since I don't actually need that for the base cases because I already initialize `@;` with the proper starting values so it costs 3 bytes.

```
#!/usr/bin/perl -p
($_)=sort{$a-$b}$_,map{$;[$_]+$;[$'%$_?$'-$_:$'/$_]}//..$_ for@;=0..$_;$_=pop@

```

Try it online!
> 1 votes

---
Tags: code-golf, sequence, arithmetic, integer, expression-building
---


title: Make a base64 Quine!

text:
# Question
Title: Make a base64 Quine!
Your challenge is to output a Base64-encoded version of your source code, and optionally a line break. You must output the correct padding, if any. Standard quine rules apply, shortest answer wins.

It must be a valid RFC 4648 encoded base64 string, with no linebreaks (except optionally a trailing newline).

# Test cases:

```
h -> aA==
PPCG! -> UFBDRyE=
Programming Puzzles and Code Golf -> UHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZSBHb2xm

```

#Base64 table

```
0   A   16  Q   32  g   48  w
1   B   17  R   33  h   49  x
2   C   18  S   34  i   50  y
3   D   19  T   35  j   51  z
4   E   20  U   36  k   52  0
5   F   21  V   37  l   53  1
6   G   22  W   38  m   54  2
7   H   23  X   39  n   55  3
8   I   24  Y   40  o   56  4
9   J   25  Z   41  p   57  5
10  K   26  a   42  q   58  6
11  L   27  b   43  r   59  7
12  M   28  c   44  s   60  8
13  N   29  d   45  t   61  9
14  O   30  e   46  u   62  +
15  P   31  f   47  v   63  /

```

If you want to test your submission, try base64encode.org.

# Answer
# Bash, 27 bytes

```
trap -- 'trap|base64' EXIT

```

Based on this Bash quine. Note the trailing linefeed.

Try it online!
> 10 votes

# Answer
# Javascript (ES6), 17 bytes

```
f=_=>btoa(`f=`+f)

```

I thought this solution would be obvious...

```
f=_=>btoa(`f=`+f)
console.log(f())
console.log(atob(f()))
```
> 5 votes

# Answer
# Python, ~~133~~ 112 bytes

```
from base64 import*;s=b'from base64 import*;s=%r;print(b64encode(s%%s).decode())';print(b64encode(s%s).decode())

```

Base64 representation:

```
ZnJvbSBiYXNlNjQgaW1wb3J0KjtzPWInZnJvbSBiYXNlNjQgaW1wb3J0KjtzPSVyO3ByaW50KGI2NGVuY29kZShzJSVzKS5kZWNvZGUoKSknO3ByaW50KGI2NGVuY29kZShzJXMpLmRlY29kZSgpKQ==

```

Try it online!
> 3 votes

# Answer
# C (gcc), 342 bytes

```
f(a){putchar(a>61?43+a%2*4:a>51?a-4:a+65+a/26*6);}main(a){char*s="f(a){putchar(a>61?43+a%2*4:a>51?a-4:a+65+a/26*6);}main(a){char*s=%c%s%c,*t=malloc(342);for(sprintf(t,s,34,s,34);*t;f(*t%4*16+*++t/16),f(*t%16*4+*++t/64),f(*t++%64))f(*t/4);}",*t=malloc(342);for(sprintf(t,s,34,s,34);*t;f(*t%4*16+*++t/16),f(*t%16*4+*++t/64),f(*t++%64))f(*t/4);}

```

Try it online!
> 2 votes

# Answer
# Alice, ~~72~~ 69 bytes

*-3 bytes thanks to Martin Ender.*

```
".w6+55*&w.q+!]k;9&wq4-!]kq&[d.t&w;q,ww].4%~4:k;28d3:&wq&[&]?ow4*+k@;

```

Base 64 representation:

```
Ii53Nis1NSomdy5xKyFdazs5JndxNC0hXWtxJltkLnQmdztxLHd3XS40JX40Oms7MjhkMzomd3EmWyZdP293NCora0A7

```

If anything, the base 64 representation looks less inscrutable than the original program.

Try it online!

### Explanation

Since Alice has no base64 built-in, the vast majority of this program is a reduced implementation of base64. The quine framework prevents me from using `'` to define constants in two bytes, but it also has some advantages. As luck would have it, the length of the source code is divisible by 3, and the characters `>`, `?`, and `~` do not appear at the end of a 3-character block.

The first step is to create (most of) the base64 alphabet. The characters `+` and `/` do not appear in the base64 representation of the source code, so we do not need to handle them. This saves 9 bytes.

```
"      wrap the entire source code in a string and push each byte

.      copy ; from top of stack (i.e., push 59)
w      push return address (i.e., do the following twice)
6+     add 6 to the constant on the stack
       this gives us 65 in the first iteration, and 71 in the second
55*w   do the following 26 times:
.q+    add tape position to constant
!      store at tape position
]      move tape right
k      return to pushed return address (end both loops)
;      remove constant from the stack, since it's no longer needed
9&w    do 10 times:
q4-    tape position minus 4
!      store at tape position
]      move tape right
k      repeat
q&[    return to position 0

```

Positions 0-61 on the tape are now filled with their base64 character equivalents. We now convert the source code to base 4.

```
d.     push stack depth (length of code excluding "), and put a useless copy below it
t&w    do that many times:
;      remove top of stack (copy of length on first iteration, 0 otherwise)
q,     move next byte to top of stack (using tape position as a register)
ww     do 4 times:
]      move tape forward (increase counter)
.      duplicate current byte or part thereof
4%     mod 4
~      swap: work with other copy
4:     divide by 4
k      repeat (end both loops)
;28    remove the excess 0 and push the base 4 representation of ",
       except that the first three base 4 digits are already in base 64

```

Finally, we convert from base 4 to base64 and output.

```
d3:&w  push return address once for each output character
q&[    move tape to position 0
&]     move tape to position corresponding to base 64 digit
?      get character from tape
o      output
w4*+   convert next base 64 digit (equivalent to 4*+4*+)
k      repeat until stack is empty
@      terminate

```
> 2 votes

# Answer
# Mathematica, 108 bytes

```
Print[StringDelete[ExportString[StringJoin["Print[", ToString[#0, InputForm], "[]]"], "Base64"], "\n"] & []]

```

Full program. The spaces are necessary as part of the `InputForm` formatting. Output, note the trailing linefeed character:

```
UHJpbnRbU3RyaW5nRGVsZXRlW0V4cG9ydFN0cmluZ1tTdHJpbmdKb2luWyJQcmludFsiLCBUb1N0cmluZ1sjMCwgSW5wdXRGb3JtXSwgIltdXSJdLCAiQmFzZTY0Il0sICJcbiJdICYgW11d

```
> 1 votes

# Answer
# Java 8, 202 bytes

```
v->{String s="v->{String s=%c%s%1$c;return java.util.Base64.getEncoder().encodeToString(s.format(s,34,s).getBytes());}";return java.util.Base64.getEncoder().encodeToString(s.format(s,34,s).getBytes());}

```

**Explanation:**

Try it online.

* The `String s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* `s.format(s,34,s)` puts it all together.

And then `java.util.Base64.getEncoder().encodeToString(....getBytes())` is used to encode the entire source code to a Base64-String.

Try it here with the Base64-encoding part removed to prove it's a quine.
> 1 votes

---
Tags: code-golf, quine
---


title: Are circular tapes exciting?

text:
# Question
Title: Are circular tapes exciting?
## A Brainfuck derivative

Let's define a simple Brainfuck-like programming language. It has a two-directional tape of cells, and each cell holds one bit. All bits are initially 0. There is a moving head on the tape, initially at position 0. A program is a string over the characters `<>01!`, executed from left to right, with the following semantics:

* `<` moves the head one step to the left.
* `>` moves the head one step to the right.
* `0` puts 0 in the current cell.
* `1` puts 1 in the current cell.
* `!` flips the current cell.

There are no loops, so a program of **n** characters terminates after exactly **n** steps. A program is *boring* if all cells contain 0 at the end of execution, and *exciting* if there is at least one 1. Note that the size of the tape is not specified, so depending on the implementation, it may be two-way infinite or circular.

## An example program

Consider the program `1>>>!<<<<0>!>>>!`. On an infinite tape, execution proceeds as follows:

```
     v
00000000000000  Put 1
     v
00000100000000  Move by >>>
        v
00000100000000  Flip
        v
00000100100000  Move by <<<<
    v
00000100100000  Put 0
    v
00000100100000  Move by >
     v
00000100100000  Flip
     v
00000000100000  Move by >>>
        v
00000000100000  Flip
        v
00000000000000

```

At the end, all cells are 0, so this program is boring. Now, let's run the same program on a circular tape of length 4.

```
v
0000  Put 1
v
1000  Move by >>>
   v
1000  Flip
   v
1001  Move by <<<< (wrapping around at the edge)
   v
1001  Put 0
   v
1000  Move by > (wrapping back)
v
1000  Flip
v
0000  Move by >>>
   v
0000  Flip
   v
0001

```

This time, there is a cell with value 1, so the program is exciting! We see that whether a program is boring or exciting depends on the size of the tape.

## The task

Your input is a non-empty string over `<>01!` that represents a program in the above programming language. An array of characters is also an acceptable input format. The program is guaranteed to be boring when run on an infinite tape. Your output shall be the list of tape lengths on which the program is exciting. Note that you only need to test the program on tapes that are shorter than the program length.

The solution with the lowest byte count in each language is the winner. Standard rules apply.

## Test cases

```
> : []
110 : []
1>0<! : [1]
0>>1>0<<>! : [1]
1>>>!<<<<0>!>>>! : [2, 4]
!<!<><<0>!>!<><1!>>0 : [2]
>>!>><>001>0<1!<<!>< : [1, 2, 3]
1!><<!<<<!!100><>>>! : [1, 3]
!!1>!>11!1>>0<1!0<!<1><!0<!<0> : [3, 4]
<><<>>!<!!<<<!0!!!><<>0>>>>!>> : [1, 2, 4]
0>>><!<1><<<0>!>>!<<!!00>!<>!0 : [3]
0000!!!!><1<><>>0<1><<><<>>!<< : []
!>!>!>!>!>1>!>0<!<!<!<0<!<0<!<!<!<1>!>0<<! : [1, 2, 5, 7]
<!!>!!><<1<>>>!0>>>0!<!>1!<1!!><<>><0<<!>><<!<<!>< : [1, 2, 4, 5]
!>1<<11<1>!>!1!>>>0!!>!><!!00<><<<0<<>0<<!<<<>>!!> : [1, 2, 3, 5, 6]

```

# Answer
## Haskell, 119 bytes

```
t#'<'=last t:init t
(h:t)#c|c<'#'=1-h:t|c>'='=t++[h]|1<2=read[c]:t
f p=[n|n<-[1..length p],sum(foldl(#)(0<$[1..n])p)>0]

```

Try it online!

Function `#` is the interpreter for a single command `c`. The whole program `p` is run by `fold`ing `#` with the starting tape into `p`. `f` executes `p` for every tape and keeps those where the sum of the cells is at least 1.
> 6 votes

# Answer
# Stax, ~~56~~ ~~54~~ ~~43~~ ~~38~~ 35 bytesCP437

```
è¥%►BΣ░ÜY⌂y(â&.═ªê►V½▲y▌)▀♫♂╣ª?√»!#

```

42 bytes when unpacked,

```
%fz(y{{|(}{|)}{B!s+}{0_]e&}4ls"><! "I@!F|a

```

Run and debug online!

-2 bytes per comment by @recursive

## Explanation

I will use the version with a prefix `i`(i.e. `i%fz(y{{|(}{|)}{B!s+}{0_]e&}4ls"><! "I@!F|a`) to explain and I will explain why the `i` can be removed

```
i               Suppress implicit eval
                    This prevents the test case "110" from being interpreted as a number
                    However, this can be removed because a program containing only numbers cannot be exciting and the output will be empty anyway.
                    This is based on the fact that the program is boring on non-circular tapes
 %f             Filter range [1..n] with the rest of this program
                    Where n is the length of the input
                    Implicit output the array after filtering, one element per line
   z(           Initialize the tape
     y{  F      Run the program
          |a    Any cell is non-zero

```

Code for running the program:

```
{|(}                                 Block to rotate left by one element
    {|)}                             Block to rotate right by one element
        {B!s+}                       Block to perform logical not on the element at index 0
              {0_]e&}                Block to obtain current instruction,
                                         Convert it to a number
                                         And assign to element at index 0

                     4l              Pack the 4 blocks in an array
                       s"<>! "I      Find the index of current instruction in string, if not found, the index will be -1
                                         And when indexed with -1, it wraps around to the 4th element.

                               @!    And execute the corresponding block.

```
> 4 votes

# Answer
# CJam, ~~57~~ ~~56~~ ~~49~~ 46 bytes

-7 thanks to @MartinEnder

```
{:T,({)0a*T{i23%")!+(+ W0tW1t)\+"3/=~}/:+},:)}

```

Try it online!
> 3 votes

# Answer
# Perl 5, ~~83~~ ~~82~~ ~~79~~ 77 bytes

Includes `+3` for `-F`

Give instructions as one line on STDIN

```
#!/usr/bin/perl -F
1~~@$m&&say$m until++$m>map{*r=\$$m[($n+=/>/-/</)%$m];$r=/\d/?$&:$r^/!/}@F

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), ~~126~~ 118 bytes

*Saved 3 bytes thanks to @user71546*

Takes input as an array of 1-character strings.

```
f=(s,l=0,p=0,t=[])=>s[l++]?s.map(c=>1/c?t[p%l]=+c:c>'='?p++:c>';'?p+=l-1:t[p%l]^=1)&&+t.join``?[l,...f(s,l)]:f(s,l):[]

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~139~~ ~~135~~ ~~133~~ ~~132~~ 131 bytes

-3 bytes thanks to Mr. Xcoder

```
def f(p):i=0;exec"i+=1;s=[0]*i\nfor c in p:c=ord(c)-61;s=c>-2and s[c:]+s[:c]or[[s.pop(0)^1,0,1][c%7]]+s\nif 1in s:print i\n"*len(p)

```

Try it online!
> 2 votes

# Answer
# Perl 5 (`-F`), 101 bytes

```
map{$,=@a=(0)x$_;map{$,+=/>/-/</;$a[$,%@a]=$&if/0|1/;$a[$,%@a]=!$a[$,%@a]if/!/}@F;say if@a~~/1/}1..@F

```

Try it online!
> 2 votes

# Answer
# Red, 243 bytes

```
func[p][repeat n length? p[b: copy[]insert/dup b 0 n i: 1
parse p[any["<"(i: i - 1 if i < 1[i: n])|">"(i: i + 1 if i > n[i: 1])|"0"(b/(i): 0)|"1"(b/(i): 1)|"!"(b/(i): either b/(i) = 0[1][0])|
skip]]s: 0 foreach c b[s: s + c]if s > 0[print n]]]

```

Try it online!

Prety verbose and straightforward implementation. Red's 1-indexing doesn't allow me to reduce the byte count by using modular arithmetic for looping through the circular tapes.

Ungolfed

```
f: func[p][
    repeat n length? p[
        b: []
        insert/dup b 0 n
        i: 1
        parse p[
            some [
                 "<" (i: i - 1 if i < 1[i: n])
               | ">" (i: i + 1 if i > n[i: 1])
               | "0" (b/(i): 0)
               | "1" (b/(i): 1)
               | "!" (b/(i): either b/(i) = 0 [1][0])
               | skip
            ]
        ]
        s: 0
        foreach c b[s: s + c]
        if s > 0 [print n]
    ]
]

```
> 2 votes

# Answer
# APL (Dyalog Unicode), ~~79~~ ~~64~~ 54 bytes (Adám's SBCS)

```
⍸⊂{∨/⍎⍕(↓',',⍨5 3⍴'0@11@1~@1 1⌽¯1⌽')['01!<'⍳⌽⍺]⍵}¨0=,\

```

Try it online!

-15 thanks to Adám (forgot about monadic ).
-10 thanks to ngn.
> 2 votes

# Answer
# Retina, 121 bytes

```
.+
$.&*0¶$&
\G0
0$`¶
{ms`^.(?=.*¶¶(0|1))
$1
"¶¶!"&mT`d`10`^.
"¶¶>"&`(.)(.*)¶
$2$1¶
"¶¶<"&`(.*)(.)¶
$2$1¶
)`¶¶.
¶¶
G`1
%`.

```

Try it online! Explanation:

```
.+
$.&*0¶$&
\G0
0$`¶

```

Create an array of tapes of each length up to the length of the input program.

```
{

```

Loop until the program is consumed.

```
ms`^.(?=.*¶¶(0|1))
$1

```

If the next character in the program is a 0 or 1, change the first character on each line to that character.

```
"¶¶!"&mT`d`10`^.

```

If it is a `!` then toggle the first character on each line.

```
"¶¶>"&`(.)(.*)¶
$2$1¶
"¶¶<"&`(.*)(.)¶
$2$1¶

```

If it is a `>` or `<` then rotate the line. (Easier than moving the head.)

```
)`¶¶.
¶¶

```

Delete the instruction and end the loop.

```
G`1

```

Keep only the exciting lines.

```
%`.

```

Count the length of each line.
> 2 votes

# Answer
# MATL, ~~46~~ 39 bytes

```
f"@:~G"@59>?@61-YS}@33=?t1)~}@U]1(]]a?@

```

Try it online! Or verify all test cases.

### How it works

```
f             % Push indices of nonzero chars of (implicit) input string: gives
              % [1 2 ... n] where n is input length
"             % For each k in [1 2 ... n]. These are the possible tape lengths
  @:~         %   Push array of k zeros. This is the tape, in its initial state
  G           %   Push input string
  "           %   For each char in the input string
    @59>?     %     If code point of current char exceeds 59 (so it is '<' or '>')
      @61-    %       Push code point minus 61: gives -1 for '<', or 1 for '>'
      YS      %       Circularly shift the tape by that amount. Instead of moving
              %       the head, we shift the tape and keep the head at entry 1
    }         %     Else
      @33=?   %       If code point of current char is 33 (so it is '!')
        t1)   %         Duplicate the array representing the tape, and get its
              %         first entry
        ~     %         Logical negate
      }       %       Else
        @U    %         Push current char (it is '0' or '1') converted to number
      ]       %       End
      1(      %       Write (either 0, 1 or old value negated) at entry 1
    ]         %     End
  ]           %   End
  a?          %   If the tape contains at least a nonzero value
    @         %     Push tape length, k
              %   End (implicit)
              % End (implicit)
              % Display (implicit)

```
> 1 votes

# Answer
# APL (Dyalog Unicode), ~~192~~ 78 bytes

```
⊂{t/⍵⊣⍵{t[m]←('01!'⍳⍵)⊃0 1,e,⍨~e←t[m←⍺|i⊣i+←¯1 1 0⊃⍨'<>'⍳⍵]}¨⍺⊣i←⊃t←⍬⍳⍺}¨1+⍳∘≢

```

Try it online! (non-flattened result)

Try it online! (flattened)

~~After some time spent banging my head against the wall, I decided to make a Tradfn instead of a Dfn. This is the result. Smarter people than me may be able to golf the heck out of this.~~

Surprise, surprise, someone smarter than me *did* golf the heck out of this. Thank you Adám for 114 bytes.

He said:

> Notice that it is your exact program, except using indexing instead of the inner :Ifs and collapsing :For-loops to {\_}¨ while giving a left argument to replace the global.

The function assumes `⎕IO←0`.

---

### How?

(This explanation uses an "ungolfed" version to facilitate reading)

```
⊂{                                  ⍝ Enclose
      i←⊃t←⍬⍳⍺                      ⍝ Assign a vector of 0s to t (the tape), then assign the first 0 to i.
      t/⍵⊣⍵{                        ⍝ Use ⍵ as left argument for the nested function, then compress the result into t. If there is a 1 anywhere in t, the result will be a vector of the result. If not, the result is an empty vector.
          i+←¯1 1 0⊃⍨'<>'⍳⍵         ⍝ Map the string '<>' to the argument (which is the BF program). That yields 0 for <, 1 for >, and 2 for anything else.
                                    ⍝ The resulting vector will then be used as the argument for ⊃ to add -1 (index 0), 1 (index 1) or 0 (index 2) to the variable i.
          e←t[m←⍺|i]                ⍝ Assign i mod ⍺ (left arg) to m, and use it to index t. Then, assign the value to e.
          t[m]←('01!'⍳⍵)⊃0 1,e,⍨~e  ⍝ Map the string '01!' to ⍵. As before, this yields 0 for 0, 1 for 1, 2 for ! and 3 for anything else.
                                    ⍝ Then, concatenate (not e) with e, then concatenate that with the vector 0 1. This is used as argument to be picked from, and it is assigned to t[m].
      }¨⍺                           ⍝ Do that for each argument
  }¨1+⍳∘≢                           ⍝ And do that for each possible tape length from 1 to the length of the input.

```
> 1 votes

# Answer
# Jelly, 41 bytes

```
JR0ṁð3“1⁺¦01¦¬1¦ṙ1 ṙ- ”s“10!<>”,yẎvÐ€⁸Ẹ€T

```

Try it online!
> 0 votes

# Answer
# C (clang), 171 bytes

```
l,i;f(S){for(char*p,t[l=strlen(S)];l;memchr(t,1,l)&&printf("%d ",l),l--)for(memset(t,i=0,l),p=S;*p;p++)*p==60?i=i?i-1:l-1:*p==62?i=i^l-1?i+1:0:*p^33?t[i]=*p-48:(t[i]^=1);}

```

Try it online!

Had to use clang, since using `char*p,t[l=strlen(S)]` as the initialisation expression for some reason makes GCC think I want to declare `strlen` instead of calling it.

Pretty straight-forward: Runs the program on circular tapes of decreasing length, outputting any length that resulted in a 1 somewhere on the tape.

Tried shortening the tangle of the ternary operators, but ended up needing more parenthesis than was healthy.
> 0 votes

---
Tags: code-golf, brainfuck
---


title: Want to see a Magic Card Trick?

text:
# Question
Title: Want to see a Magic Card Trick?
The first magic card trick I ever learned as a child was the following:

* Have 1 deck of cards where the pattern on the back is not vertically symmetric.
* Organize all cards to be facing one direction.
* Ask an individual to, "pick a card, any card, memorize it and give it back to you".
* Proceed to put it into the deck (in the wrong direction).
* Shuffle vigorously, giving the illusion that you won't know where their card is.
* Produce their card to their amazement.

---

This trick is obviously a little bit lack-luster in nature now-a-days, however it makes for a good challenge. Write a program, that when given no input, outputs a randomly shuffled deck of cards with one of the cards, chosen at random, reversed. However, when the input is a deck of cards with one card reversed, you must output the reversed card (in the correct order).

---

***The Deck of Cards***

A deck of cards is defined to be:

```
[2S,3S,4S,5S,6S,7S,8S,9S,TS,JS,QS,KS,AS,
 2D,3D,4D,5D,6D,7D,8D,9D,TD,JD,QD,KD,AD,
 2H,3H,4H,5H,6H,7H,8H,9H,TH,JH,QH,KH,AH,
 2C,3C,4C,5C,6C,7C,8C,9C,TC,JC,QC,KC,AC]

```

A card is defined as it's number, then the first letter of its suit. The reverse of a card is the exact opposite, the first letter of its suit followed by a number.

***The Drawn Card***

Example, if the card we randomly chose to reverse was the `4 of Clubs (4C)`, we'd end up with (without shuffling, obviously):

```
[2S,3S,4S,5S,6S,7S,8S,9S,TS,JS,QS,KS,AS,
 2D,3D,4D,5D,6D,7D,8D,9D,TD,JD,QD,KD,AD,
 2H,3H,4H,5H,6H,7H,8H,9H,TH,JH,QH,KH,AH,
 2C,3C,C4,5C,6C,7C,8C,9C,TC,JC,QC,KC,AC]

```

***The Shuffling***

Then, after shuffling:

```
[2H,2C,6S,4D,QH,6C,TD,8C,7H,5H,C4,3D,7S,7C,KC,QD,QC,JS,7D,6D,2S,5C,KD,3C,3S,2D,8H,KH,6H,AH,8S,JH,TS,AD,5D,9H,4H,JD,QS,4S,JC,3H,8D,TC,AS,TH,KS,AC,9C,9S,5S,9D]

```

This is a valid output given empty input.

***The Deck Input***

However, conversely, when our program receives the above output as input, it should output `4C`. That is to say, for an input of:

```
[2H,2C,6S,4D,QH,6C,TD,8C,7H,5H,C4,3D,7S,7C,KC,QD,QC,JS,7D,6D,2S,5C,KD,3C,3S,2D,8H,KH,6H,AH,8S,JH,TS,AD,5D,9H,4H,JD,QS,4S,JC,3H,8D,TC,AS,TH,KS,AC,9C,9S,5S,9D]

```

You iterate through until you find the reversed card, and return it, reversed back to the normal state. So here we'd find `C4`, know that C isn't a number, and return it as `4C`, which is correct.

---

# Rules

* You may not load the deck from any external sources.
* An empty input should result in a randomly shuffled deck with 1 random card reversed.
* A deck of cards with 1 card reversed as input should result in the reversed card.
* Any other inputs can result in explosive llamas riding segways through a futuristic tube.
    + Or anything else, for that matter.
* Both the chosen card and the shuffling order must be uniformly random.
    + I.E. all cards have equal chance of being selected to be reversed.
    + I.E. all combinations of cards have an equal chance of appearing.
* You may use `SHCD` or `shcd` for the suits, but be consistent:
    + If you choose uppercase suits (`SHCD`) you must also use `TJQKA`.
    + If you choose lowercase suits (`shcd`) you must also use `tjqka`.
* This is , winner is lowest bytes.

# Answer
> 7 votes
# Retina, ~~61~~ ~~60~~ 59 bytes

```
G`[HCDS].
^$
23456789TJQK
/^2/&L$`.
$&H¶$&D¶$&C¶$&S
@V`
O?`

```

Try it online! Edit: Saved ~~1~~ 2 bytes thanks to @MartinEnder. Explanation:

```
G`[HCDS].

```

Delete all unreversed cards. This should leave one reversed card or no cards.

```
^$
23456789TJQK
/^2/&L$`.
$&H¶$&D¶$&C¶$&S

```

If the input is (now) empty, create a pack of cards.

```
@V`

```

Randomly select one card and reverse it (unreverses the single reversed card).

```
O?`

```

Shuffle the card(s).

# Answer
> 4 votes
# 05AB1E, 29 bytes

```
Y9ŸJ.•§®т•«.•öB•âsKDgiëDΩÂ:.r

```

Try it online!

# Answer
> 3 votes
# PowerShell v2 or later, 175 bytes

```
%{$s=[char[]]'SDHC';if($_){$_|?{$s-contains$_[0]}|%{$_[1]+$_[0]}}else{$d=$s|%{$e=$_;[char[]]'23456789TJQKA'|%{$_+$e}}|random -c 52;$r=random 52;$d[$r]=$d[$r][1]+$d[$r][0];$d}}

```

Long version:

```
ForEach-Object {
    $s = [char[]]'SDHC'                         # Create a character array with the suits
    if ($_) {                                   # If there's pipeline input ...
        $_ |                                    # ... write it to the output pipeline ...
            Where-Object {$s -contains $_[0]} | # ... but let only those input elements pass where the first letter appears in the suits ...
            ForEach-Object {$_[1] + $_[0]}      # ... and swap the two elements
    } else {
        $d = $s | ForEach-Object {              # Assign $d to the output of the suits, processing each element first.
                $e = $_                         # Store the current suit element for use in the inner loop
                [char[]]'23456789TJQKA' | ForEach-Object {$_ + $e}  # Process each of the numbers, joining it with the current suit, ...
            } | Get-Random -Count 52            # ... and the resulting 2-char-strings goes back into the output to be shuffled
        $r = Get-Random -Maximum 52
        $d[$r] = $d[$r][1] + $d[$r][0]          # Swap the two chars of a random array element in $d
        $d                                      # Write $d to the output pipeline
    }
}

```

## Usage:

Create a shuffled deck and store it in a variable:

```
$Deck = %{$s=[char[]]'SDHC';if($_){$_|?{$s-contains$_[0]}|%{$_[1]+$_[0]}}else{$d=$s|%{$e=$_;[char[]]'23456789TJQKA'|%{$_+$e}}|random -c 52;$r=random 52;$d[$r]=$d[$r][1]+$d[$r][0];$d}}

```

Inspect the variable at will, for example

```
$Deck -join ','

```

Pipe the deck back into the script:

```
$Deck | %{$s=[char[]]'SDHC';if($_){$_|?{$s-contains$_[0]}|%{$_[1]+$_[0]}}else{$d=$s|%{$e=$_;[char[]]'23456789TJQKA'|%{$_+$e}}|random -c 52;$r=random 52;$d[$r]=$d[$r][1]+$d[$r][0];$d}}

```

# Answer
> 2 votes
# Python 2, 175 bytes

```
from random import*
s='SHCD';c='23456789TJQKA'
d=input()
if d:print[b+a for a,b in d if a in s];q
k=sample
r=k(c,1)+k(s,1)
print k([(a+b,b+a)[r==a+b]for a in c for b in s],52)

```

Try it online! empty input is denoted as `[]`

# Answer
> 2 votes
# Jelly, 26 bytes

```
9ḊṾ€;“AJKQT”p“CDHS”ḟ⁸ẊU-¦Ẋ

```

A monadic link accepting a list of lists of characters (a stub of 0 cards or a full-deck of 52 cards with one card reversed) and returning a list of lists of characters (a stub of the 1 reversed card but forward or a full-deck with one random card reversed).

**Try it online!** (footer to make input and output representations match - as a full program Jelly code Python-evals the argument and smashes the characters together for the output)

### How?

```
9ḊṾ€;“AJKQT”p“CDHS”ḟ⁸ẊU-¦Ẋ - Link: list of lists of characters, Z
9Ḋ                         - nine dequeued = [2,3,4,5,6,7,8,9]
  Ṿ€                       - unevaluate €ach = ['2','3','4','5','6','7','8','9']
     “AJKQT”               - literal list of characters = ['A','J','K','Q','T']
    ;                      - concatenate = ['2','3','4','5','6','7','8','9','A','J','K','Q','T']
             “CDHS”        - literal list of characters = ['C','D','H','S']
            p              - Cartesian product = [['2','C'],['2','D'],...,['T','S']]
                           -   a full deck of forward cards
                    ⁸      - chain's left argument, Z
                   ḟ       - filter discard
                           -   leaving either that deck or the 1 reversed card in the input
                     Ẋ     - shuffle
                        ¦  - sparse application...
                       -   - ...to index: -1 (which doesn't exist when the length is only 1)
                      U    - ...do: upend (reverses the penultimate card of the deck)
                         Ẋ - shuffle

```

# Answer
> 2 votes
# \>\<\>, ~~215~~ 193 bytes

```
i:0)?\~"CHSD":"2"$:"3"$:"4"$:"5"$:"6"$:"7"$:"8"$:"9"$:"T"$:"J"$:"Q"$:"K"$:"A"$&105&"S"=?.~~~{c0.
=+i$?\i$:::"B")$"I"(*$"S"
_oo$~/;
x0
x0
x0
x0
x0
x0
x0
x0
x0
x0
\l&>?!<
>&"3"%:?\~$>o<
\  }}&-1/

```

Try it online!

Takes input as not separated cards, and output as the same (e.g. `KCAC5C6S...`)

To make it easier to test, here's a version that takes input as comma separated and outputs as newline separated.

All the `x0`s are just an attempt to make a semi-uniform random number generator. More of them increases the range of possible values, and the opposite for less. 10 of them is where I judged it to be random enough.

Note that it follows the rules in that:

* All cards have an equal chance of being selected to be reversed.
* All cards have an equal chance of appearing anywhere in the shuffled deck.

*But not all* shuffled combinations are possible outputs (and in fact, the vast majority aren't).

# Answer
> 1 votes
# , ~~177~~ 171 bytes

```
function(l=1,F="(.)(.)",R="\\2\\1",S=sample)if(l>1)sub(F,R,grep("^[SDHC]",l,v=T))else{m=S(outer(c(2:9,"T","J","Q","K"),c("S","D","H","C"),paste0))
m[1]=sub(F,R,m[1])
S(m)}

```

Try it online!

Given empty input, (call `f` with no input), we default to `l=1` and thus create a random permutation `m` of the deck. Assuming `sample` is truly random, there is an equal probability of any card being the first in this list. So we modify the first one, and then shuffle again, returning the list.

Reversing it, we look for a card starting with one of `SDHC` and reverse it.

# Answer
> 1 votes
# Ruby, 95 (or 100) bytes

```
->n{s=(0..51).map{|i|"A23456789TJQK"[i/4]+"HCDS"[i%4]}
n[0]?s-n:s[rand 52].reverse!&&s.shuffle}

```

Given an empty array as input, returns the deck as an array of strings. Given a nonempty array as input, returns the flipped card as an array containing a single string. If the flipped card is required as a string rather than a single-element array containing a string, the following adds 5 bytes: change `s-n` to `(s-n)[0]`

Try it online!

The first line generates a standard deck. The second line breaks down as follows

```
 n[0]?                  #If the input array is not empty (contains a truthy first element)
  s-n:                  #Find the contents of s with the contents of n removed. The only card remaining from the standard deck corresponds to the flipped card in the input.
                        #ELSE
  s[rand 52].reverse!&& #Flip one card in place in the array s. As the result is truthy, whatever is next will be returned.
 s.shuffle              #shuffle the deck and return the shuffled deck with one element flipped
}

```

# Answer
> 1 votes
# Java 8, ~~275~~ ~~274~~ 259 bytes

```
import java.util.*;s->{if(s==null){List l=new Stack();char i=52,r=i,x,y;for(r*=Math.random();i-->0;y="23456789TJQKA".charAt(i%13),l.add(i==r?x+""+y:y+""+x))x="HSDC".charAt(i&3);Collections.shuffle(l);return l;}return s.replaceAll(".*,(.)([^HSDC]).*","$2$1");}

```

Input is a String, output is either a String or a `java.util.List` depending on the input.

**Explanation:**

Try it online.

```
import java.util.*;          // Required import for List, Stack and Collections
s->{                         // Method with String parameter and Object return-type
  if(s==null){               //  If the input is `null`:
    char i=52,               //   Index-integer
         r=i,                //   Random-integer
         x,y;                //   Temp characters
    List l=new Stack();      //   Create a List
    for(r*=Math.random();    //   Determine the random integer in the range (0;52]
        i-->0                //   Loop `i` 52 times:
        ;                    //     After every iteration:
         y="23456789TJQKA".charAt(i%13)
                             //      Set `y` to one of 23456789TJQKA based on `i` modulo-13
         ,l.add(i==r?        //      If the random integer equals the current `i`
                 x+""+y      //       Add the current card reversed
                :            //      Else:
                 y+""+x))    //       Add the current card as is
      x="HSDC".charAt(i&3);  //    Set `x` to one of HSDC based on `i` bitwise-AND 3
    Collections.shuffle(l);  //   Shuffle the generated Deck
    return l;}               //   And return this Deck as result
                             //  If the input was a Deck instead:
  return s.replaceAll(".*,(.)([^HSDC]).*",
                             //   Get the reversed card from the Deck,
            "$2$1");}        //   and output it non-reversed

```

# Answer
> 1 votes
# Pyth, 45 bytes

```
J"CDHS"KO52=NsM.S*+c"AKQJT"1S9J|f}hTJQXNK_@NK

```

Takes the empty list for empty input.
Try it online

### Explanation

```
J"CDHS"KO52=NsM.S*+c"AKQJT"1S9J|f}hTJQXNK_@NK
J"CDHS"                                        Save the suits as J.
       KO52                                    Save a random index as K.
           =NsM.S*+c"AKQJT"1S9J                Save a shuffled deck as N.
                                f}hTJQ         Find all cards with suit first.
                               |      XNK_@NK  If there aren't any, flip a card.

```

# Answer
> 1 votes
# Python 2, 135 bytes

```
from random import*
s=shuffle
d=zip('A23456789TJQK'*4,'SCDH'*13)
s(d)
D=input()
if D:d=list(set(D)-set(d))
d[0]=d[0][::-1]
s(d)
print d

```

Try it online!

Cards are tuples of `(value,suit)`

Empty input is `[]`

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


title: The weight of a Zero

text:
# Question
Title: The weight of a Zero
Given an ordered list of numbers (possibly with leading zeros), arrange the numbers vertically, then let all zeros drop all the way to the bottom and all overhangs drop to the bottom-most open slot. Output the resulting integers, removing leading zeros.

### Worked Example

Say we were given the following as input:

```
['0000312941295', '239124000124581598', '32852353800451258', '10235923505185190', '1491359102149']

```

First we arrange it vertically:

```
0000312941295
239124000124581598
32852353800451258
10235923505185190
1491359102149

```

Then, column by column, drop the zeros "through" the other numbers so they rest on the bottom and "push" the other numbers up. This would result in the first couple steps being as follows:

```
2000312941295
339124000124581598
12852353800451258
10235923505185190
0491359102149
^

2300312941295
329124000124581598
14852353800451258
10235923505185190
0091359102149
 ^

2390312941295
328124000124581598
14252353800451258
10935923505185190
0001359102149
  ^

...

2391312941295
328524538124581598
14232323525451258
10915991001185190
0000350000049
                ^

```

Next, drop all overhangs as if gravity is pulling them down like sand.

```
2391312941295
3285245381245 1598
14232323525458258
10915991001181190
00003500000495
             ^

2391312941295
3285245381245  598
14232323525458158
10915991001181290
000035000004951
              ^

...

2391312941295
3285245381245
14232323525458159
10915991001181258
000035000004951908
                 ^

```

Finally, output these numbers, removing leading zeros. For our worked example, output:

```
[2391312941295, 3285245381245, 14232323525458159, 10915991001181258, 35000004951908]

```

For another example, suppose input of `[1234000,12345678,1234,12340608,12341234]`.

```
1234000
12345678
1234
12340608
12341234

```

Drop the zeros:

```
1234
12345678
1234163
12340208
12340004

```

Drop the remaining overhanging digits:

```
1234
1234567
12341638
12340208
12340004

```

Output is `[1234, 1234567, 12341638, 12340208, 12340004]`.

### Rules

* The input *may* contain leading zeros. The output *must not* contain leading zeros.
* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# Jelly, 8 bytes

```
Z¬Þ€UZṚḌ

```

Try it online!

### How it works

```
Z¬Þ€UZṚḌ  Main link. Argument: M (2D array / matrix)

Z         Zip; transpose M by reading columns as rows.
 ¬Þ€      Sort each row of the transpose by logical NOT, pushing 0's to the end.
    U     Upend; reverse all sorted rows of the transpose.
     Z    Zip again, restoring rows from columns. Overhangs rise to the top.
      Ṛ   Reverse the order of the rows.
       Ḍ  Decimal; convert the rows from base 10 to integer.

```
> 10 votes

# Answer
# 05AB1E, 11 bytes

```
ζεð†R0†R}øï

```

Try it online!
> 5 votes

# Answer
# Python 2, 118 bytes

```
lambda l:[int(''.join(z))for z in zip(*map(lambda*a:['']*a.count(None)+[e for e in a if'0'<e]+['0']*a.count('0'),*l))]

```

Try it online!

### Ungolfed version

```
def f(list_):
 max_len = max(len(x) for x in list_)
 transposed_list = zip(*[list(row)+(max_len-len(row))*[None] for row in list_])
 weighted_list = [['']*column.count(None)+[cell for cell in column if cell != '0' and cell != None]+['0']*column.count('0') for column in transposed_list]
 return [int(''.join(row)) for row in zip(*weighted_list)]

```

The first two lines are equivalent to `map(lambda*a...)`, the default behaviour if for `map` to fill with `None`s if one list is shorter than the other.
`e>'0'` is equivalent to `cell != '0' and cell != None`, because if it is any digit (1~9) it will have a higher codepoint, and (any) string is higher than `None`.
> 4 votes

# Answer
# Husk, 12 bytes

```
md↔TmoÖ±miT↔

```

Try it online!

### Explanation

```
md↔Tm(Ö±mi)T↔  -- input as list of strings, example: ["103","32","258"]
            ↔  -- reverse: ["258","32","103"]
           T   -- transpose: ["231","520","83"]
    m(    )    -- with each line do (example with "520")
        mi     -- | convert each char to digit: [5,2,0]
      Ö±       -- | sort by signum (stable): [0,5,2]
               -- : [[2,3,1],[0,5,2],[8,3]]
   T           -- transpose: [[2,0,8],[3,5,3],[1,2]]
  ↔            -- reverse: [[1,2],[3,5,3],[2,0,8]]%
md             -- convert each to integer: [12,353,208]

```
> 4 votes

# Answer
# Ruby, 104 bytes

```
->a{a.map{|x|x.ljust(99).chars}.transpose.map{|x|x.sort_by{|x|x<?1?x:?!}}.transpose.map{|x|x.join.to_i}}

```

Try it online!

## Explanation

```
->a{
  a.map{|x|x.ljust(99).chars}  # Fill spaces to make this rectangular
    .transpose.map{|x|
       x.sort_by{|x|x<?1?x:?!} # Treat all chars but " 1" as ! (see ascii table)
    }.transpose.map{|x|x.join.to_i} # Convert back to numbers
                       # note: if no leading 0s, eval x*'' , doesn't work here
}

```
> 3 votes

# Answer
# Pyth, 11 bytes

```
iRT_C_M!DMC

```

Try it online!
> 2 votes

# Answer
# Retina 0.8.2, ~~95~~ 92 bytes

```
m(+`^((.)*)(.+)(¶(?<-2>.)*)(?(2)_)$
$1$4$3
+`^((.)*)0(.*¶(?>(?<-2>.)*))([^0])
$1$4${3}0
^0+

```

Try it online! Explanation: The first stage drops the overhanging digits as this makes it easier (edit: even easier for a 3-byte saving) for the second stage to drop the zeros. The third stage then removes leading zeros.
> 2 votes

# Answer
# Perl 5, -p0 77 bytes

Old style counting: 79 bytes (`+2` for `p0`)

Give input as lines on STDIN without final newline (otherwise everything is seen as overhang and the final newline rises to the top as the input string crashes down). E.g.:

```
0000312941295
239124000124581598
32852353800451258
10235923505185190
1491359102149

```

It was a bit tricky to get the overhang dropping and the `0` dropping into one regex

```
#!/usr/bin/perl -p0
s/^.{@{+}}\K((0)|.+$)(.*
.{@{+}})((?(2)[1-9]|$))/$4$3$1/m while/|/g;s/^0+//mg

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), 26 bytesSBCS

Anonymous tacit prefix function taking a character matrix as argument and returning a list of numbers.

```
⍎⍤1∘⍉' 0'(∩∘⊃,~,∩∘⊃∘⌽)⍤1⍨⍉

```

Try it online!

transpose the input (as we need to work on the columns)

`' 0'(``)⍤1⍨` apply the following tacit function to each row (sub-array of tensor rank 1) with `' 0'` as *right* argument ( swaps the arguments) :

intersection of the row and
and
the first of `' 0'`
(i.e. `row∩' '`; all the spaces from each row)

`,` followed by…

`~` the set difference
(i.e. `row~' 0'`; the row but without spaces and zeros)

`,` followed by…

intersection of the row and
and
the first
of
the reversed `' 0'`
(i.e. `row∩'0'`; all the zeros from each row)

`⍎⍤1` evaluate each row (sub-array of tensor rank 1)
of
the transpose of that (i.e. each column; the now modified input rows)
> 1 votes

# Answer
# Ruby, 203 bytes

```
->a{t=->b{b[0].zip(*b[1..-1])}
m=a.map{|s|s.size}.max
a.map!{|s|(s+" "*m)[0...m].chars}
a=t[a].map{|c|c.size.times{|i|" 0"[c[i]]&&(c.slice!(i)==?0?c.push(?0):c.unshift(" "))}
c}
t[a].map{|r|r.join.to_i}}

```

Try it online!

A lambda accepting an array of strings and returning an array of ints. I feel like I'm missing something; this feels enormous :/

```
->a{
  t = -> b { b[0].zip(*b[1..-1]) }     # t is a lambda that transposes 2D arrays
  m = a.map{ |s| s.size }.max          # m is the maximum input string length
  a.map!{ |s| (s+" "*m)[0...m].chars } # Right-pad every string to the same length
  a = t[a].map{ |c|                    # Transpose a, and for every row (column)
    c.size.times{ |i|                  # For every character in the column
      " 0"[c[i]] && (                  # If the character is 0 or space
        c.slice!(i) == ?0 ?            # Remove it from the column, and if it was 0,
          c.push(?0) :                 # Push a 0 to the end (bottom) of the column, else
          c.unshift(" ")               # Add a space to the top of the column
      )
    }
    c
  }
  t[a].map{ |r| r.join.to_i }          # Transpose a back, and parse each row to int
}

```
> 0 votes

# Answer
# APL (Dyalog Classic), ~~24~~ ~~23~~ 22 bytes

```
⍎⍤1⍉{⍵[⍒⌈9÷⍨⎕d⍳⍵]}⍤1⍉⎕

```

Try it online!

based on Adam's solution
> 0 votes

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


title: Create a solar system

text:
# Question
Title: Create a solar system
**Intro**

This is based on an actual problem I recently faced while making a computer game and I thought it would make for a nice round of .

There are seven main spectral classes of star which put out varying amounts of heat. The geology of planets around a star are greatly influenced by the amount of heat received from the star, which is a factor of spectral class and distance from the star. Hence Mercury is practically molten, Neptune frozen.

The galaxy in my game is procedurally generated and randomly selecting planet types for given stars turned out to be a real 'if statement hell'!

**The challenge**

Your method should select one planet from a list of planet types appropriate for the class of star, based on a minimum heat threshold, a maximum heat threshold and a random number. For simplicity this challenge will only use a class G star, just like our sun.

**Inputs**

An integer `heat` in the range 4 to 11 representing the amount of heat received by the planet from the star.

**Variables**

This table shows the possible planets based on `heat`. Your method should first narrow the available choices based on the heat min and heat max, `heat` should fall on or between the two. E.g. with a heat of 10 passed in the only choices would be Desert, Iron and Lava.

```
Planet type    Heat min   Heat max   Random Chance
Gas Giant         4          9            15
Ice               4          6            10
Ice Giant         4          6            10
Gaia class        5          7            10
Dense Atmosphere  7          9            10
Desert            7          10           25
Iron              7          10           14
Lava             10          11           6

```

Next, the probability of a planet (in the remaining choices) being chosen is its random chances divided by the sum of the random chances of all the choices.

In the above example, the probability of Iron being chosen is `14/(25+14+6)`.

**Output**

Return the planet type as a string.

Do the best you can to avoid logic arrowheads. Shortest code wins, points all round for creativity. Happy golfing!

# Answer
> 12 votes
# Jelly,  ~~78~~  75 bytes

```
“'ĖøÆḳƙ’ḃ7ṣ6Ä+3r/ċ€×“½½½½©ÐÇı‘
“ŀỊẋ8ƒ³ẈRɼƈñqẋẏȧɱḌ<ṄỴḳ⁾ÆʋeẒĊ'@ƬØƓƝ}ḟ¬»Ỵx'ÇX

```

A monadic link accepting an integer (in **\[4,11\]**) which returns a list of characters.

**Try it online!**

### How?

Creates the heat ranges of the planets as a list of lists and counts the occurrences of the input heat in those lists to get a list of zeros and ones representing which planet types are possible, then multiplies by the likelihood numbers of the eight planet types to get the distribution. The distribution is used to repeat the planet type names, and finally, a uniform random choice is made.

```
“'ĖøÆḳƙ’ḃ7ṣ6+\+3r/ċ€×“½½½½©ÐÇı‘ - Link 1, getDistribution: integer
“'ĖøÆḳƙ’                        - base 250 integer = 39824688429662
        ḃ7                      - to bijective-base 7 = [1,1,2,4,7,1,4,4,6,2,2,2,2,1,5,3,3]
          ṣ6                    - split at sixes = [[1,1,2,4,7,1,4,4],[2,2,2,2,1,5,3,3]]
            +\                  - reduce by addition = [[1,1,2,4,7,1,4,4],[3,3,4,6,8,6,7,7]]
              +3                - add three = [[4,4,5,7,10,4,7,7],[6,6,7,9,11,9,10,10]]
                r/              - reduce by inclusive range = [[4,5,6],[4,5,6],[5,6,7],[7,8,9],[10,11],[4,5,6,7,8,9],[7,8,9,10],[7,8,9,10]]
                  ċ€            - count (input) in €ach e.g. for 5: [1, 1, 1, 0,0, 1, 0, 0]
                     “½½½½©ÐÇı‘ - list of code-page indices        [10,10,10,10,6,15,14,25]
                    ×           - multiply                         [10,10,10, 0,0,15, 0, 0]

“ ... »Ỵx'ÇX - Main link: integer
“ ... »      - compressed string = "Ice\nIce Giant\nGaia class\nDense Atmosphere\nLava\nGas Giant\nIron\nDesert"
       Ỵ     - split at new lines = ["Ice","Ice Giant","Gaia class","Dense Atmosphere","Lava","Gas Giant","Iron","Desert"]
          Ç  - call last link (1) as a monad e.g. for 5: [10,10,10,0,0,15,0,0]
         '   - spawn:
        x    -   times e.g. for 5: ["Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant"]
           X - a random choice from that list

```

# Answer
> 7 votes
# , ~~225~~ ~~223~~ 183 bytes

Thanks to Giuseppe for clever refactoring to take it down to 188 bytes; the remaining five were shaved off by using less redundant number representations.

```
i=scan()-4
sample(c("Gas Giant","Ice","Ice Giant","Gaia class","Dense Atmosphere","Desert","Iron","Lava")[l<-c(0,0,0,1,3,3,3,6)<=i&c(5,2,2,3,5,6,6,7)>=i],1,,c(3,2,2,2,2,5,2.8,1.2)[l])

```

Try it online!

# Answer
> 4 votes
# JavaScript 212

**Edit** 6 bytes save thx Jonathan Allan

```
h=>[963,640,640,649,667,1628,924,437].map((z,i)=>(z/8&7)+4>h|z%8+6<h?0:t=r.push(...Array(z>>6).fill(i)),r=[])&&"Gas Giant,Ice,Ice Giant,Gaia class,Dense Atmosphere,Desert,Iron,Lava".split`,`[r[t*Math.random()|0]]

```

*less golfed*

```
h=>(
   r = [],
   // heat min,max and chance encoded in base 8 with offsets
   // min range 4 to 10, with offset 4, 0 to 6
   // max range 6 to 11, with offset 6, 0 to 5
   [(4-4)*8 + 9-6 + 15*64,
    (4-4)*8 + 6-6 + 10*64,
    (4-4)*8 + 6-6 + 10*64,
    (5-4)*8 + 7-6 + 10*64,
    (7-4)*8 + 9-6 + 10*64,
    (7-4)*8 + 10-6+ 25*64,
    (7-4)*8 + 10-6+ 14*64,
    (10-4)*8+ 11-6+  6*64]
   .forEach( (z,i) => (
      min = (z / 8 & 7) + 4,
      max = z % 8 + 6,
      chance = z >> 6,
      min > h || max < h
      ? 0 // out of range
      // add current position i repeated 'chance' times
      // array size in t
      : t = r.push(...Array(chance).fill(i))
   ),
   pos = r[t * Math.random() | 0],
   ["Gas Giant", "Ice", "Ice Giant", "Gaia class", "Dense Atmosphere", "Desert", "Iron", "Lava"][pos]
)

```

*Test*

```
var F=
h=>[963,640,640,649,667,1628,924,437].map((z,i)=>(z/8&7)+4>h|z%8+6<h?0:t=r.push(...Array(z>>6).fill(i)),r=[])&&"Gas Giant,Ice,Ice Giant,Gaia class,Dense Atmosphere,Desert,Iron,Lava".split`,`[r[t*Math.random()|0]]

function test()
{
   var heat=+H.value
   var i,result,hashtable={},rep=1e5
   for (i=0;i<rep;i++)
     result = F(heat),
     hashtable[result] = -~hashtable[result]

   console.log('Input',heat)
   for (i in hashtable)
   {
     console.log(i,(hashtable[i]/rep*100).toFixed(2),'%')
   }
}
```

```
<input id=H type=number min=1 max =15 value=10>
<button onclick='test()'>Test</button>
```

# Answer
> 4 votes
# Charcoal, ~~115~~ 111 bytes

```
≔Ｉ⁻Ｎ³θＦ⁸«≔§⪪”↷＆∧⬤.YLφκ¦(⁼；σ≕]✂↙ζＣ” ιη¿›θη¿‹θ§η¹ＦＩ✂η²⊞υι»§⪪”↓(″1↨▷]Ｕ,&ζ^iＩ″ＲＳＹ≡´⍘'#﹪υＶw5Ｖu>D<U5r6⁰Ｑ▷Ｚ◨⌕⁸ΣεCＺ”¶‽υ

```

Try it online! Link is to verbose version of code. Edit: Saved 4 bytes thanks to @ASCII-only. Explanation:

```
≔Ｉ⁻Ｎ³θ

```

Subtract 3 from the input so that it can be compared against single digits.

```
Ｆ⁸«≔§⪪”↷＆∧⬤.YLφκ¦(⁼；σ≕]✂↙ζＣ” ιη

```

Split the string `0715 0410 0410 1510 3710 3825 3814 696` on spaces (spaces seem to compress better than commas but I didn't try any other characters) and loop over each portion.

```
¿›θη¿‹θ§η¹ＦＩ✂η²⊞υι»

```

Compare the input against the first and second digits and if it's between then push the loop index the given number of times to the predefined empty list, thus populating it.

```
§⪪”↓(″1↨▷]Ｕ,&ζ^iＩ″ＲＳＹ≡´⍘'#﹪υＶw5Ｖu>D<U5r6⁰Ｑ▷Ｚ◨⌕⁸ΣεCＺ”¶‽υ

```

Split the list of planets on newlines (again, better than commas for some reason) and select the element corresponding to a index chosen randomly from the list.

# Answer
> 4 votes
# Coconut, ~~214~~ 195 bytes

```
t->choice..sum([[n]*g(p)*(g(a)<t<g(b))for*n,a,b,p in'Gas Giant3AF_Ice37A_Ice Giant37A_Gaia class48A_Dense Atmosphere6AA_Desert6BP_Iron6BE_Lava9C6'.split('_')],[])
from random import*
g=int$(?,36)

```

Try it online!

A Python port would be ~~203~~ 200 bytes long:

```
lambda t:choice(sum([[n]*int(p,36)*(int(a)<t<int(b,36))for*n,a,b,p in'Gas Giant3AF_Ice37A_Ice Giant37A_Gaia class48A_Dense Atmosphere6AA_Desert6BP_Iron6BE_Lava9C6'.split('_')],[]))
from random import*

```

Try it online!

# Answer
> 3 votes
# , ~~196~~ ~~193~~ ~~190~~ ~~175~~ 171 bytes

```
sample(readLines(,8),1,,c(3,2,2,2,2,5,2.8,1.2)*((x=scan()-3)>c(0,0,0,1,3,3,3,6)&x<c(7,4,4,5,7,8,8,9)))
Gas Giant
Ice
Ice Giant
Gaia class
Dense Atmosphere
Desert
Iron
Lava

```

Try it online!

Initially inspired by this solution by @rturnbull, however as both submissions have significantly evolved, this is now essentially a mix of ideas of the original author, @Giuseppe who has been very helpful in comments, and mine. Here is a summary of key points that helped to bring the byte count down:

* ~~Encoding planet data as CSV~~ Collecting names with `readLines` to avoid the large number of quotation characters around strings.
* Tweaking the heat params so that we could use `<` and `>` signs instead of `<=` and `>=`.
* ~~Changing the heat data format from `Heat min, Heat max` to `Heat min,
Heat Delta` to get rid of double digit numbers.~~
Replaced by shifting all numbers by -3
* Dividing all planet probabilities by 5 which also results in a few less digits.
* Multiplying the vector of planet probabilities with the vector of Booleans (indicating whether our input satisfies the heat requirements) to nullify the probabilities of unsuitable planets.

~~Probably, a few more bytes could be gained by applying some sort of data compression.~~
I think, not anymore.

# Answer
> 2 votes
# Python, ~~282 Bytes~~, 261 Bytes:

```
from random import*
i,p,l=input(),[('Gas Giant',3,11,15),("Ice",3,7,10),("Ice Giant",3,7,10),("Gaia Class",4,8,10),("Dense Atmosphere",6,10,10),("Desert",6,11,25),("Iron",6,11,14),("Lava",9,12,6)],[]
for x in p:exec"l+=x[0],;"*(x[1]<i<x[2])*x[3]
print choice(l)

```

Pretty simple - fairly sure it could be golfed more - Still looking for a better way to represent the planet range and probability data. If i is in range of the planet type, appends it to the list according to the probability, then randomly prints one.

EDIT: With credit to Jonathan Frech - redid the for loop to knock a few bytes off. Better way of appending items to the list

# Answer
> 2 votes
# Octave with Statistics Package, ~~178~~ ~~176~~ ~~174~~ 158 bytes

```
@(h)randsample(strsplit('Gas Giant,Ice,Ice Giant,Gaia class,Dense Atmosphere,Desert,Iron,Lava',','),1,1,('UPPPP_TL'-70).*(h>'IIIJLLLO'-70&h<'PMMNPQQR'-70)){1}

```

The code defines an anonymous function that inputs a number and outputs a string.

**Try it online!**

### Explanation

The code

```
@(h)

```

defines an anonymous function with input `h`.

The string

```
'Gas Giant,Ice,Ice Giant,Gaia class,Dense Atmosphere,Desert,Iron,Lava'

```

is split at commas using

```
strsplit(...,',')

```

The result is a cell array of strings, where each string is a planet class.

The code

```
'IIIJLLLO'-70

```

defines the shown string and subtracts `70` from the code points of its chars. This gives the array of minimum heat values *minus 1*, that is, `[3 3 3 4 6 6 6 9]`.

Similarly,

```
'PMMNPQQR'-70

```

produces the array of maximum heat values *plus 1*, that is, `[10 7 7 8 10 11 11 12]`.

The comparisons

```
h>...&h<...

```

give an array containing `true` or `false` indicating which planet classes are possible.

On the other hand,

```
'UPPPP_TL'-70

```

defines the array of random chance values, `[15 10 10 10 10 25 14 6]`.

The operation

```
(...).*(...)

```

is the element-wise multiplication of the latter two arrays (`true` and `false` behave like `0` and `1` respectively). This gives an array where each planet class has either its random chance, or `0` if that class is not possible based on the input. This array will be used as weights in the random sampling

The function call

```
randsample(...,1,1,...)

```

selects one of the cells from the cell array of strings (first input argument), using the computed array of weights (fourth input argument). Specifically, the function `randsample` automatically normalizes the weights to probabilities, and then does the random selection with those probabilities. The result is a cell array containing a string. The code

```
{1}

```

is used to extract that string, which constitutes the function output.

# Answer
> 2 votes
# Python 3, 263 bytes

```
from random import*
P=lambda h:"Gas Giant|Ice|Ice Giant|Gaia class|Dense Atmosphere|Desert|Iron|Lava".split("|")[choices(*list(zip(*filter(lambda x:h in range(*x[2:]),zip(*[[int(x,32)for x in"0f4a1a472a473a584a7a5p7b6e7b76ac"][a::4]for a in(0,1,2,3)]))))[:2])[0]]

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~199~~ 194 bytes

```
from random import*
lambda n:choices("Ice|Ice Giant|Gas Giant|Gaia class|Dense Atmosphere|Desert|Iron|Lava".split('|'),[(0x33b2a53d4a>>5*i&31)*(0xc07878380e3f0707>>8*i+n-4&1)for i in range(8)])

```

Splitting `h` into separate bit masks and random chance values (see explanation) saves a few bytes by eliminating an assignment to `h` and simplifying the `range()` in the list comprehension.

### Previous solution

```
from random import*
h=0xc033c39e3270a0e51fbc1d40ea
lambda n:choices("Ice|Ice Giant|Gas Giant|Gaia class|Dense Atmosphere|Desert|Iron|Lava".split('|'),[(h>>i&31)*(h>>i+n+1&1)for i in range(0,104,13)])

```

Defines an anonymous function that takes an int and returns the planet type.

For each planet type, a 13-bit value was calculated. The top 8 bits define a bit mask of valid heat values for that planet type. The bottom 5 bits are the random chance for that planet type. For example, "Gaia class" is a valid type for heat values 4 to 7, so it has a mask of `0b00001111`. It has a random chance of 10, or `0b01010`. Combining them results it the 13-bit value `0b0000111101010` for the "Gaia class" type. The 13-bit values for each planet type are concatenated to get the value for `h` (the lowest 13 bits are for the "Ice" planet type). (The newer answer doesn't combine these values).

The list comprehension iterates over the 13-bit values to create a list of weights, where the weight is the random chance if the planet type is a valid choice for the given heat value, and zero otherwise. For each planet type, `(h>>i&31)` extracts the random chance for that planet type. `(h>>i+n+1&1)` evaluates to 1 if the planet type is a valid choice for the heat value `n` and evaluates to 0 otherwise.

The library function `random.choices(choices, weights)` selects an item from the list of choices based on the list of weights.

# Answer
> 1 votes
# Ruby, ~~214 193~~ 189 bytes

```
->h{'Gas Giant,Desert,Iron,Lava,Ice,Ice Giant,Gaia class,Dense Atmosphere'.split(?,).zip(31006330.digits,75449887.digits,[15,25,14,6]).flat_map{|n,m,x,r|m<h-3&&x>h-3?[n]*(r||10):[]}.sample}

```

Try it online!

# Answer
> 1 votes
# Perl 5 (`-p`), 230 bytes

```
@a=(['Gas Giant',4,9,15],[Ice,4,6,10],['Ice Giant',4,6,10],['Gaia class',5,7,10],['Dense Atmosphere',7,9,10],[Desert,7,10,25],[Iron,7,10,14],[Lava,10,11,6]);//;map{push@b,($$_[0])x($$_[3]*($$_[1]<=$'&&$'<=$$_[2]))}@a;$_=$b[rand@b]

```

Try it online!

# Answer
> 1 votes
# Nim, ~~~~314~~ 298~~ 294 bytes

```
import random,sequtils
proc c(h:int)=
 var a= @[""]
 a.del 0
 for n in[("Gas Giant",4,9,15),("Ice",4,6,10),("Ice Giant",4,6,10),("Gaia Class",5,7,10),("Dense Atmosphere",7,9,10),("Desert",7,10,25),("Iron",7,10,14),("Lava",10,11,6)]:(if h>=n[1]and h<=n[2]:a.add repeat(n[0],n[3]))
 echo random a

```

For loop now in one line, no return, less bytes to implicit type

4 spaces removed (thanks Kevin)

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~78~~ 76 bytes

```
”Œï²°™Ä²° Gaia classêÎ·•™Äµ‰Ÿ± Lava”#8äðýā<•ŒEŽuS,•2ô×•9èÁnÇ∞Λ•SÌ2ôεŸIå}ÏSΩè

```

Try it online!

**Explanation**

`”Œï²°™Ä²° Gaia classêÎ·•™Äµ‰Ÿ± Lava”`
pushes the string `Gas Giant Ice Giant Gaia class Dense Atmosphere Ice Desert Iron Lava`

```
#                                          # split on spaces
 8ä                                        # divide into 8 parts
   ðý                                      # join each by spaces
     ā<                                    # push the range [0 ... 7]
       •ŒEŽuS,•                            # push 151010101025146
               2ô                          # split into pieces of 2
                                           # results in [15, 10, 10, 10, 10, 25, 14, 6]
                 ×                         # repeat each number in the range by these amounts
                                           # results in ['000000000000000', '1111111111', '2222222222', '3333333333', '4444444444', '5555555555555555555555555', '66666666666666', '777777']
                  •9èÁnÇ∞Λ•                # push 2724355724585889
                           S               # split to list of digits
                            Ì              # decrement each twice
                                           # results in [4,9,4,6,5,7,7,9,4,6,7,10,7,10,10,11]
                             2ô            # split into pieces of 2
                                           # results in [[4, 9], [4, 6], [5, 7], [7, 9], [4, 6], [7, 10], [7, 10], [10, 11]]
                               εŸIå}       # apply to each pair
                                Ÿ          # range [a ... b]
                                 Iå        # check if input is contained in the range
                                           # ex, for input 10: [0, 0, 0, 0, 0, 1, 1, 1]
                                    Ï      # keep only the indices which are true
                                           # ex, for input 10: ['5555555555555555555555555', '66666666666666', '777777']
                                     S     # split to list of digits
                                      Ω    # pick one at random
                                       è   # index into the list of strings with this

```

# Answer
> 1 votes
# Haskell, ~~377~~ ~~364~~ ~~358~~ ~~318~~ ~~312~~ ~~270~~ ~~265~~ ~~262~~ ~~256~~ 251 bytes

```
import System.Random
f h|x<-[n|(n,(a,b,c))<-zip(lines"Gas Giant\nIce\nIce Giant\nGaia class\nDense Atmosphere\n
Desert\nIron\nLava")$zip3[4,4,4,5,7,7,7,10][9,6,6,7,9,10,10,11][15,10,10,10,10,25,14,6],h<=
b,h>=a,_<-[1..c]]=(x!!)<$>randomRIO(0,length x-1)

```

(I've added linebreaks for nicer printout). The task says "return", not "print", so `f` is a function which returns the randomly selected planet name into the `IO` monad, `f :: Int -> IO String`.

The `main` is `main = do {f 10 >>= print}` (Haskell golfing tips says it doesn't count). Prints

> ```
> "Iron"     -- or "Desert", or "Lava"
>
> ```

(edits: removed `&`'s base case; moved `main` out; changed to quadruples and `unzip`, and switched to pattern guards and `>>=` following suggestions from Laikoni, thanks!; implemented the approach from the Jelly solution instead, repeating the names; explicit type is no longer needed; another advice by Laikoni saves 3 more bytes; made it an `IO` function; implemented advice from the chat room).

Try it online!

# Answer
> 0 votes
# Min, ~~280~~ 277 bytes

```
:a ' =b (("Gas Giant" 4 9 15) ("Ice" 4 6 10) ("Ice Giant" 4 6 10) ("Gaia Class" 5 7 10) ("Dense Atmosphere" 7 9 10) ("Desert" 7 10 25) ("Iron" 7 10 14) ("Lava" 10 11 6)) (=n (a n 1 get >= a n 2 get <= and) ((n 0 get b append #b) n 3 get times) when) foreach b b size random get

```

Starts with heat on the stack, leaves a string on the stack. Same general process as Python 2 answer.

### Explanation

Note that min is concatenative

```
:a ' =b                               ;Set the value on the stack (heat) to a, set empty quot to b
(("Gas Giant" 4 9 15) ("Ice" 4 6 10) ("Ice Giant" 4 6 10) ("Gaia Class" 5 7 10) ("Dense Atmosphere" 7 9 10) ("Desert" 7 10 25) ("Iron" 7 10 14) ("Lava" 10 11 6)) ;Data to be iterated over
(=n                                   ;  set n to current item
 (a n 1 get >= a n 2 get <= and)      ;    check if n is between the min (2nd elment of n) and max (3rd element of n) heat
 (
  (n 0 get b append #b) n 3 get times ;      insert the name(1st element of n) into the quot of names (b) a number of times corresponding to the 4th element of n
 ) when                               ;    when the previous check is true
) foreach                             ;  for every quot in previous data
b b size random get                   ;choose a random element from the list of names

```

# Answer
> 0 votes
# Java 8, ~~398~~ 384 bytes

```
n->{String r="",a[];for(String x:"456789~Gas Giant~15;456~Ice~10;456~Ice Giant~10;567~Gaia class~10;789~Dense Atmosphere~10;78910~Desert~25;78910~Iron~14;1011~Lava~6".split(";"))if(x.split("~")[0].contains(n))r+=x+";";long t=0,u=0;for(String x:(a=r.split(";")))t+=new Long(x.split("~")[2]);t*=Math.random();for(String x:a)if((u+=new Long((a=x.split("~"))[2]))>t)return a[1];return"";}

```

It can definitely be golfed some more, but the probability in combination with the Strings isn't very easy in Java.

**Explanation:**

Try it online.

```
n->{                // Method with String as both parameter and return-type
  String r="",      //  Temp-String, starting empty
         a[];       //  Temp String-array
  for(String x:"456789~Gas Giant~15;456~Ice~10;456~Ice Giant~10;567~Gaia class~10;789~Dense Atmosphere~10;78910~Desert~25;78910~Iron~14;1011~Lava~6".split(";"))
                    //  Loop over the String-parts in the format "heats~type~probability"
    if(x.split("~")[0].contains(n))
                    //   If the heats contains the input
      r+=x+";";     //    Append this entire String-part to the temp-String `r`
  long t=0,u=0;     //  Temp numbers, both starting empty
  for(String x:(a=r.split(";")))
                    //  Loop over the temp-String parts:
    t+=new Long(x.split("~")[2]);
                    //   Sum their probabilities
  t*=Math.random(); //  Get a random number in the range [0,sum_of_probabilities)
  for(String x:a)   //  Loop over the temp-String parts again
    if((u+=new Long((a=x.split("~"))[2]))>t)
                    //   The moment the current probability-sum is > the random number
      return a[1];  //    Return the Type of planet
  return"";}        //  Mandatory return we won't encounter (which returns nothing)

```

# Answer
> 0 votes
# PowerShell, 56 + 135 (CSV file) + 1 (file name) = 192 bytes

```
param($z)ipcsv a|?{$z-in$_.m..$_.x}|%{,$_.p*$_.r}|Random

```

Try it online! <sub>(this is a slightly modified version that creates the temporary CSV file described below)</sub>

Imports a CSV file using `ipcsv` (short for `Import-CSV`) named `a` in the local directory that contains the following:

```
P,m,x,r
Gas Giant,4,9,15
Ice,4,6,10
Ice Giant,4,6,10
Gaia class,5,7,10
Dense Atmosphere,7,9,10
Desert,7,10,25
Iron,7,10,14
Lava,10,11,6

```

That automatically creates an iterable hashtable of things like the following:

```
@{P=Gas Giant; m=4; x=9; r=15}
@{P=Ice; m=4; x=6; r=10}
...

```

We then use `Where-Object` (`?`) to pull out those entries where our input integer `$z` is `-in` the range `$_.m` to `$_.x` (i.e., it's in the heat range). We then pump those into a `Foreach-Object` loop (`%`) that creates an array of strings of names based on the random chance of those names. For example, this will create an array of `15` `"Gas Giant"` strings if that heat matches. We then put those into `Get-Random` which will pull out the appropriate string with the appropriate weighting.

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


title: Little Boxes on the Hillside

text:
# Question
Title: Little Boxes on the Hillside
There's a satirical song called *Little Boxes*, originally by Malvina Reynolds, about suburban sprawl that has lyrics as follows:

> Little boxes on the hillside,
> Little boxes made of ticky-tacky,
> Little boxes on the hillside,
> Little boxes all the same.
> There's a green one and a pink one
> And a blue one and a yellow one,
> And they're all made out of ticky-tacky
> And they all look just the same.

Your job here is, given an integer input `n>1` that represents the size of the house, output the four "little boxes" using the following colors (in 0xRRGGBB notation):

```
Green -- 0x00FF00
Pink --- 0xFF00FF (technically magenta)
Blue --- 0x0000FF
Yellow - 0xFFFF00

```

*If your particular console doesn't have these exact colors, you may use the closest available (e.g., ANSI escape codes).*

The houses are constructed with `n` `_` representing the floor and roofline. They are surrounded by `n/2` (round-up) `|` characters representing the walls. The roofs are always `2` high and are two `/` on the left edge, two `\` on the right edge, and `n-2` `-` representing the roof peak. As the houses get larger, the comparative size of the roof gets smaller; this is intended.

Here's a house of size `2`:

```
 /\
/__\
|__|

```

Here's size `3`:

```
 /-\
/___\
|   |
|___|

```

Here's size `7`:

```
 /-----\
/_______\
|       |
|       |
|       |
|_______|

```

Thus given an input of `7`, output four houses of size `7` as described above, with the first one in green, the second in pink (magenta), the third in blue, and the fourth in yellow. *Output of the colors in that order is important.*

Example picture of size `3`:

### Rules

* The houses can be horizontal or vertical so long as there is a clear separation between them.
* Leading/trailing newlines or other whitespace are optional, provided that the houses line up appropriately.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, saved as an image, etc.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 5 votes
# Python 2, ~~123~~ ~~121~~ ~~119~~ ~~111~~ ~~109~~ 108 bytes

* Saved two bytes thanks to caird coinheringaahing; using the actual unprintable ASCII character instead of escaping it (`\33`)
* Could (and did) save a byte by writing an entire program using `input()` instead of defining a function
* Saved seven bytes thanks to ElPedro; using the fact that `str(90+n)` with `0<=n<=9` is `"9%s"%n`
* Saved ~~two~~ three bytes by using string formatting rather than string concatenation

```
N=input()
for(n)in"2543":Z="_"*N;print"[9%sm /"%n+~-~-N*"-"+"\ \n/%s\\\n"%Z+~-N/2*("|%s|\n"%" "*N)+"|%s|"%Z

```

Try it online!

Uses ANSI escape codes for coloring the houses.

# Answer
> 5 votes
# JavaScript (ES6), Chrome / Firefox, ~~156~~ ~~148~~ ~~151~~ 150 bytes

*Saved 8 bytes thanks to @Shaggy*
*Saved 1 byte thanks to @Neil*

```
n=>['0f0','f0f','00f','ff0'].map(c=>console.log(`%c /${'-'[r='repeat'](n-2)}\\
/${s='_'[r](n)}\\
${(`|${' '[r](n)}|
`)[r](~-n/2)}|${s}|`,'color:#'+c))

```

### Demo

Make sure to open the console of your browser to get the colored output.

```
let f =

n=>['0f0','f0f','00f','ff0'].map(c=>console.log(`%c /${'-'[r='repeat'](n-2)}\\
/${s='_'[r](n)}\\
${(`|${' '[r](n)}|
`)[r](~-n/2)}|${s}|`,'color:#'+c))

f(3)
```

# Answer
> 3 votes
# Japt, ~~79~~ ~~76~~ ~~74~~ ~~73~~ 72 bytes

```
3#²¤r1'f ò3 w £Ol"%c /{ç- ¤}\\
/{ç'_}\\
{/2-½ ç"|{ç}|
"}|{ç'_}|"Xi`¬l:#

```

Try it (Open your browser's console before hitting "Run").

Thanks to ETH for helping me to test this last night while I was working it up on my phone.

---

## Explanation

Implicit input of integer `U`

```
3#²¤r1'f ò3 w

```

First we build an array of 3-digit hex colours to map over. The charcode of `²` is 178 so `3#²` gives us 3178. We convert that to a base-2 string with `¤` and then replace all occurrences of `1` with `f`. `ò3` splits the string into an array of strings of length 3 and `w` reverses that array.
(I need to figure out a way to shorten that, somehow.)

```
£Ol

```

We map over the array using `£` \- with `X` being the current element - and `Ol` logs to console. We'll be passing 2 strings to that, one containing the house and one containing the CSS.

```
Xi`¬l:#

```

The second string is constructed using `i` to prepend `X` with the compressed string `color:#`.

```
"%c /{ç- ¤}\\

```

The `%c` tells the console to use the second string as CSS. The top line of the house is built by repeating (`ç`) the `-` character `U` times and then slicing that from the second element (0-indexed) with `¤`. The braces act as a shortcut, of sorts, for string concatenation.

```
/{ç'_}\\

```

The second line is built in a similar way, this time repeating the `_` character `U` times.

```
{/2-½ çRi|²iUç 1}

```

The body of the house is built by first repeating the `|` character twice with `²` and then inserting a space repeated `U` times into that string at index 1. The resulting string is then prepended to a newline (`R`) and that string is repeated `U/2-0.5` times.

```
|{ç'_}|"

```

Finally, the last line is built in the same way as the second.

# Answer
> 3 votes
# Excel VBA, 243 Bytes

Anonymous VBE immediate window function that takes input from `A1` and outputs to the range `A2:A5`

```
[C1]=vbLf:For i=1To 4:Cells(i+1,1)=[" /"&Rept("-",A1-2)&"\"&C1&"/"&Rept("_",A1)&"\"&C1&Rept("|"&Rept(" ",A1)&"|"&C1,A1/2)&"|"&Rept("_",A1)&"|"]:Cells(i+1,1).Font.Color=Array(32768,&HFF00FF,rgbBlue,65535)(i-1):Next:Cells.Font.Name="Courier New"

```

### Output

# Answer
> 1 votes
# Python 2, 120 bytes

```
n=input()
for i in'2543':s='_'*n;print'[1;3'+i+('m /'+'-'*(n-2)+'\ \n/%s\\\n'%s+(-~n/2-1)*('|'+' '*n+'|\n')+'|%s|\n'%s)

```

Try it online! (shows escape chars instead of actual colors, tested on local terminal)

# Answer
> 1 votes
# Yabasic, 220 bytes

An anonymous function that takes input as an integer, `n` and outputs 4 colored homes to the terminal.

The lack of a dedicated string repeating or replacement function in yabsic really hurts this response.

```
Clear Screen
Input""n
b$="__"
c$="|  "
For i=1To n-2
a$=a$+"-"
b$=b$+"_"
c$=c$+" "
Next
c$=c$+"|\n"
For i=1To n-4
d$=d$+c$
Next
For i=0To 3
?Color(Mid$("gremagbluyel",1+3*i,3))" /"+a$+"\\\n/"+b$+"\\\n"+d$+"|"+b$+"|"
Next

```

This version requires graphics mode and thus does not work on TIO.

### Output

The input value for the below is `n=7`.

# Answer
> 1 votes
# SmileBASIC, 115 bytes

```
INPUT N
H.H 6H 4H 2DEF H C
COLOR C+5?" /";"-"*(N-2);"\
?"/";"_"*N;"\
FOR I=3TO N?"|";" "*N;"|
NEXT?"|";"_"*N;"|
END

```

Another one which is also 115 bytes:

```
INPUT N
FOR J=0TO 3COLOR!!J*8-J*2+5?" /";"-"*(N-2);"\
?"/";"_"*N;"\
FOR I=3TO N?"|";" "*N;"|
NEXT?"|";"_"*N;"|
END

```

The colors codes I need (in 4-bit RGBI) are 5, 11, 9, 7. This is generated using `!!J*8-J*2+5` If J is not 0, this is `13-J*2` (giving 11,9,7), and if it is, the result is just 5.

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