title: Inverted ragged list

text:
# Question
Title: Inverted ragged list
Given a ragged list of positive integers, where the maximum depth is \\$d\_\text{max}\\$, return the same list, except for every element \\$e\\$, its depth is \\$d\_\text{max}+1-d\_e\\$ (where \\$d\_e\\$ is the depth of that element).

Your output should contain the minimal number of brackets, and you can assume the same from your input. Or in other words, "\],\[" doesn't appear in the input, and shouldn't appear in the output. You can assume that nonempty inputs contain at least one element with depth 1.

# Test cases

```
[] <-> []
[[1,2],3,4] <-> [1,2,[3,4]]
[1,[2],1,[3],1] <-> [[1],2,[1],3,[1]]
[3,[2,[1],2],3] <-> [[[3],2],1,[2,[3]]]
[1,2,3,4] <-> [1,2,3,4]
[[[1]],10] <-> [1,[[10]]

```

# Answer
# Retina 0.8.2, 83 bytes

```
+`],
,]
T`[]`][
+`,]
],
{`^(?!\[((\[)|(?<-2>])|\d|,)*(?(2)^)]$).*
[$&]
\[([][])]
$1

```

Try it online! Link include test cases. Explanation:

```
+`],
,]
T`[]`][
+`,]
],

```

Exchange `],` with `,[`, and also flip the leading `[`s and trailing `]`s.

```
{`

```

Repeat until the string has been rebalanced.

```
^(?!\[((\[)|(?<-2>])|\d|,)*(?(2)^)]$).*
[$&]

```

If it's unbalanced then wrap it in `[]`s.

```
\[([][])]
$1

```

Collapse unnecessary `[]` pairs.
> 4 votes

# Answer
# Jelly, ~~31~~ ~~30~~ 27 bytes

```
ŒJẈạṀ$‘Ø0jIr0Ṣ€Ṡị“[],”żFFḊṖ

```

I'm pretty rusty in Jelly, ~~so can probably be golfed a bit further~~. It indeed can:
-3 bytes thanks to *@JonathanAllan*.

Input as a list; output as a string.

Port of my 05AB1E answer. The `Ø0jIr0Ṣ€Ṡị“[],”żFFḊṖ` is a slight modification from *@xigoi*'s Jelly answer for the *Build a list from a depth map* challenge.

Try it online or verify all test cases.

**Explanation:**

```
                 # Main link, taking the input-list as argument:
ŒJẈ              #  Determine the depth of each integer:
ŒJ               #   Get the multidimensional arguments
  Ẉ              #   Get the length of each inner list
   ạṀ$‘          #  Invert this depth-list:
     $           #   Apply the previous two links as monad:
    Ṁ            #    Get the maximum of this list of depths
   ạ             #    Calculate the absolute difference
      ‘          #   Increase each 0-based depth by 1
Ø0jIr0Ṣ€Ṡị“[],”  #  Create a string to zip with:
Ø0j              #   Surround the list with leading/trailing 0
   I             #   Forward-differences
    r0           #   Map each integer `n` to a list in the range [n,0]
      Ṣ€         #   Sort each range
        Ṡ        #   Signum (-1 if <0; 0 if 0; 1 if >0)
         ị“[],”  #   Index into "[]," ("[" if 1; "," if 0; "]" if -1)
ż                #  Zip/transpose, using the list above
 F               #  and the flattened input as arguments
  F              #  Then flatten the result
   ḊṖ            #  And remove the leading/trailing ","
                 #  (after which the result is output implicitly)

```
> 3 votes

# Answer
# , 172 bytes

Or **\>=4.1, 151 bytes** by replacing three `function` occurrences with `\`s.

```
function(l,`?`=unlist,g=function(l)"if"(is.list(l),1+?Map(g,l),0),h=function(v)"if"(any(v),{y[]=cumsum(c(T,y<-v<2)|y);Map(h,split(v-1,y))},v))relist(?l,h(max(g(l))-g(l)+1))

```

Try it online!

### Explanation outline

1. Compute the depths of elements using recursive function `g`.
2. Compute the target depths.
3. Compute the target structure of the list using a recursive function `h` just like here: Build a list from a depth map.
4. Use an obscure  function `relist` to assign original values to the new structure (as suggested by @Giuseppe).
> 3 votes

# Answer
# Python3, 274 bytes:

```
from itertools import*
f=lambda x,c=0:[i for j in x for i in([(j,c)]if int==type(j)else f(j,c+1))]
g=lambda x,m:[j for a,b in groupby(x,key=lambda x:x[1]==m)for j in(lambda b:[u for u,_ in b]if a else[[*g(b,m-1)]])([*b])]
r=lambda x:g(l:=f(x),max(b for _,b in l))if x else x

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~75~~ 72 bytes

```
If[v@#,#/.l->List,#0[##&@@@SequenceReplace[#,{a__}?v:>!l@a]]]&
v=VectorQ

```

Try it online!

-9 bytes if lower levels can have non-`List` heads: Try it online!

```
                           SequenceReplace[#,{a__}        ]     group consecutive
                                                  ?v              non-List elements
                                                    :> l@a        by wrapping with l
                     ##&@@@                           !         flatten out Lists
                  #0[                                      ]    recurse
If[v@#,          ,                                          ]     until no Lists left
       #/.l->List                                               turn l into List

```

---

### Wolfram Language (Mathematica), ~~76~~ 74 bytes

```
#/.{{__d}:>#0/@d/@SplitBy[D@@@#,Head],{__}:>#0[d/@#]}&
d@{a__}=d@a:{__d}=a

```

Try it online!

```
main function:
#/.                                   {__}:>#0[d/@#]    get depths
#/. {__d}:>                                             construct by:
               d/@SplitBy[D@@@#,Head]                     group this layer
           #0/@                                           recurse
                                                          (atoms are unchanged)

depth helper:
        d@a:{__d}=a     don't change lists that only have d[...]s
d@{a__}=          a     splat other lists
                        (stay unevaluated on atoms)

```

The first step of the main function wraps each value in a number of `d`s equal to their final depth. Then the final structure is constructed recursively in a manner similar to this answer.
> 2 votes

# Answer
# Python 3.8 (pre-release), 191 bytes

```
f=lambda a:(a*0==0)*[(0,a)]or[(d+1,x)for y in a for d,x in f(y)]
def g(a):
 s=",".join("["*(z:=max(f(a))[0]+1-n)+f"{x}"+z*"]"for n,x in f(a))
 for _ in s:s=s.replace("],[",",")
 return s or[]

```

Try it online!
> 2 votes

# Answer
# Python, 165 bytes

```
lambda x,i=0:x and[*eval(",".join((j-i)*"["+(i-(i:=j))*"],"+str(k)for j,k in d(x,-min(d(x))[0]))+i*"]")]
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```

Attempt This Online!

#### Old Python, 169 bytes

```
lambda x,i=0:x and[*eval(",".join(((n:=j-min(d(x))[0])-i)*"["+(i-(i:=n))*"],"+str(k)for j,k in d(x))+i*"]")]
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```

Attempt This Online!

#### Old Python, 174 bytes

```
lambda x,i=0:x and[*eval(",".join(((n:=j-min(sum(d(x),())))-i)*"["+(i-(i:=n))*"],"+str(k)for j,k in d(x))+i*"]")]
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```

Attempt This Online!

#### Old Python, 178 bytes

```
lambda x,i=0:x and eval("["+",".join(((n:=j-min(sum(d(x),())))-i)*"["+(i-(i:=n))*"],"+str(k)for j,k in d(x))+-~i*"]")
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```

Attempt This Online!

Based on this answer to a related challenge.
> 2 votes

# Answer
# 05AB1E, 44 bytes

```
_"Ddië®δ.V>"©.V˜ZαU˜εXNèF…[ÿ]]',ý…[ÿ]…],[',:

```

I knew this approach would be pretty long, but not sure what a good alternative would be..

Input as a list; output as a string.

Try it online or verify all test cases.

**Explanation:**

In pseudo-code I do the following steps:

1. Determine the (0-based) depth of each integer in the nested input-list (`_"Ddië®δ.V>"©.V˜Zα` \- try it online).
2. Flatten the input-list (`˜`).
3. Use a minor modification of my 05AB1E answer for the *Build a list from a depth map* challenge with the list of step 1 to mold the flattened input-list (as string..) (`εXNèF…[ÿ]}}',ý…[ÿ]…],[',:`).

As for the actual code:

```
_           # Transform each integer in the (implicit) input to 0
 "..."      # Push the recursive string explained below
      ©     # Store it in variable `®` (without popping)
       .V   # Evaluate and execute it as 05AB1E code
  D         # Duplicate the current list
   dië      # If it's not an integer (so it's a list):
       δ    #  Map over each item:
      ® .V  #   Do a recursive call
      >     #  Then increase each integer in this list by 1
˜           # Flatten the result
 Z          # Push the maximum depth (without popping the list)
  α         # Pop and push the absolute difference
   U        # Pop and store this list in variable `X`
˜           # Flatten the (implicit) input-list
 ε          # Map over each integer:
  XNè       #  Get the depth from `X` at the same index
     F      #  Loop that many times:
      …[ÿ]  #   Wrap it in square blocks
 ]          # Close both the inner loop and outer map
  ',ý      '# Join everything by "," delimiter
     …[ÿ]   # Wrap the entire string in square blocks as well
  …],[',:  '# Replace all "],[" with ","
            # (after which the string is output implicitly as result)

```
> 1 votes

# Answer
# JavaScript (ES6), 156 bytes

```
f=(a,i=d=+(m=b=[]))=>a.map?a.map(v=>f(v,i+1))|i||eval('b='+[...b,[f,'b']].map(g=a=>d^([v,x]=a,v+=~m)?d-->v?"["+g(a):"],"+g(a,d+=2):x)):b.push([i<m?i:m=i,a])

```

Try it online!
> 1 votes

# Answer
# Jelly, 27 bytes

Is there something shorter than the `¬ȦƇẈƊ` this uses?

```
ŒṖṚ¬ȦƇẈƊÞṪḢ’$Ȧ¡€
ŒJẈÇŒṪ¿ṁ@F

```

A monadic Link accepting a ragged list that yields a ragged list.

**Try it online!** Or see the test-suite.

### How?

Firstly, get the depths of the items.

While there are any non-zero integers at any depth group together as many zeros, and lists that are only zeros at all depths, as possible and decrease all the other integers by one.

Lastly, mould a flattened version of the input like that ragged list.

```
ŒJẈÇŒṪ¿ṁ@F - Main Link: ragged list, A
ŒJ         - multidimensional indices of A
  Ẉ        - length of each -> flat list of depths
      ¿    - while...
    ŒṪ     - ...condition: truthy multidimensional indices
   Ç       - ...do: call the helper link
         F - flatten A
        @  - with swapped arguments:
       ṁ   -   mould like

ŒṖṚ¬ȦƇẈƊÞṪḢ’$Ȧ¡€ - Helper link: ragged list, Current State
ŒṖ               - all partitions of the Current State
  Ṛ              - reverse (to have longest last rather than first)
        Þ        - sort by:
       Ɗ         -   last three links as a monad:
   ¬             -     logical NOT (vectorises)
     Ƈ           -     filter keep those for which:
    Ȧ            -       any and all?
      Ẉ          -     length of each
         Ṫ       - tail
               € - for each:
              ¡  -   repeat...
             Ȧ   -   ...times: any and all?
            $    -   ...action: last two links as a monad:
          Ḣ      -     head
           ’     -     decrement

```

---

Alternative helper, same byte count:

```
ŒṖṚŒṪƇẈ$ÞḢḢ’$Ȧ¡€

```
> 1 votes

# Answer
# JavaScript (Node.js), 137 bytes

```
x=>(y=JSON.stringify(x).replace(/,\[|],/g,t=>t>'['?(b+=']]',',['):(a+='[[','],'),a=b=''),g=t=>t?t.map?t[1]?t:g(t[0]):[t]:[])(eval(a+y+b))

```

Try it online!

First with lots of outer brackets then clean some
> 0 votes

# Answer
# Charcoal, ~~122~~ 120 bytes

```
≔＆θ⁰η≔⟦η⟧ζＦζＦιＦ⁼κ⁺⟦⟧κ«ＵＭκ⊖μ⊞ζκ»⊞υθ⊞υηＦυＦιＦ⁼κ⁺⟦⟧κ⊞υκＦ⮌υ«≔⟦⟧ζＷι⊞ζ⊟ιＦ⮌ζ¿⁺⟦⟧κＦκ⊞ιλ⊞ικ»≔⮌θθ≔⁰ζＦ⁻η⊖⌊η«Ｆ⁻ζι]→Ｆ⁻ιζ[Ｉ⊟θ≔ιζ»Ｆζ]ＵＢ,

```

Try it online! Link is to verbose version of code. Explanation: Not an easy problem to solve without access to recursion.

```
≔＆θ⁰η

```

Make a deep clone of the input and set all of the integers in that clone to zero. (`BitwiseAnd` fully vectorises, unlike, say, `Times`.)

```
≔⟦η⟧ζＦζＦιＦ⁼κ⁺⟦⟧κ«ＵＭκ⊖μ⊞ζκ»

```

Perform a breadth-first search over the clone and decrement each sublist. (Again, it is fortunate that `Decremented` fully vectorises, although I still have to `MapCommand` it because I need to modify each sublist in-place.) The resulting list ends up with values appropriate to their depth.

```
⊞υθ⊞υηＦυＦιＦ⁼κ⁺⟦⟧κ⊞υκＦ⮌υ«≔⟦⟧ζＷι⊞ζ⊟ιＦ⮌ζ¿⁺⟦⟧κＦκ⊞ιλ⊞ικ»

```

Flatten both the input and the depth clone in-place.

```
≔⮌θθ≔⁰ζＦ⁻η⊖⌊η«Ｆ⁻ζι]→Ｆ⁻ιζ[Ｉ⊟θ≔ιζ»Ｆζ]ＵＢ,

```

Adjust the depth list so that the minimum depth is 1, and use that to build the desired output list from the depth list and the flattened input list. (See my answer to Build a list from a depth map for more detail.)
> 0 votes

---
Tags: code-golf, ragged-list
---


title: Generate four type-4 GUIDs for me

text:
# Question
Title: Generate four type-4 GUIDs for me
The type 4 GUID is described by Wikipedia, quoth:

> Version 4 UUIDs use a scheme relying only on random numbers. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479).

Write a program that loads 488 bits (61 bytes) of cryptographic quality randomness and output them as 4 GUIDs using the format quoted above.

* Do not waste randomness.
    + All random bits must appear in the encoded output.
    + All encoded bits must be traceable to either a single random bit or one of the six fixed bits that must appear in each GUID.
* Use the cryptographic quality random number generator supplied by your language's standard library.
* Do not use a library or external resource that generates GUIDs.
* The hyphens must appear in their correct positions.
* The fixed bits of this form of GUID must appear in their correct positions.
* You may use a standard library function designed to output a GUID from 128 bits.
* Normal code-golf rules apply.

For example...

```
> gentype4
6FA53B63-E7EA-4461-81BE-9CD106A1AFF8
856970E9-377A-458E-96A7-43F587724573
E4F859AC-0004-4AA1-A3D2-AECB527D1D24
766811C5-0C44-4CC8-8C30-E3D6C7C6D00B

```

Update:
I asked for *four* GUIDs in order to allow a whole number of random bytes to be gathered without leaving any remainder. I also specified that none of the bits should be wasted in order to avoid the easy answer of getting 16 random bytes and dropping the 4 in. (No, shift the other bits along first.)

Update 2:
If your language's standard library doesn't have a cryptographic quality random byte generator, you may instead assume that there is a 61 byte file present with enough random bytes for you to use when the program starts. The file should be called "/dev/urandom" or another filename with 12 characters.

# Answer
> 1 votes
# PHP, 338 bytes

```
<?php $r=openssl_random_pseudo_bytes(61);$b="";$s="substr";for($i=0;$i<61;)$b.=str_pad(decbin(ord($r[$i++])),8,0,0);function p($B,$L){return str_pad(dechex(bindec($B)),$L,0,0);}for($i=0;$i<4;$i++)echo p($s($b,$p=122*$i,32),8)."-".p($s($b,$p+32,16),4)."-4".p($s($b,$p+48,12),3)."-".p("10".$s($b,$p+60,14),4)."-".p($s($b,$p+74,48),12)."\n";

```

## Some output

```
> php 32309.min.php
635fa088-4a66-47fc-9e50-2ccb2445b643
6e5c23c7-ba16-427e-960b-5316980ce4e3
fdb570ca-2e5e-4594-ab2e-db8446599b8f
203f2538-b5f4-47f0-89ac-012ca14b2f99
> php 32309.min.php
a6981255-0ab2-4d82-aab4-d1c64d2bb7eb
c348e728-f817-45d2-9bbf-b40426baa461
9b2baed2-e58b-41ef-a6fb-57e96db74a68
63e464e7-ab55-4e2a-a2a0-abdc535481dc
> php 32309.min.php
af7e68d3-b3ed-4e19-85b2-280270f746c6
0a86c610-8d0c-4c0a-bafe-44a6886d71f8
98c742b8-6a3b-47ff-97c7-ccab70d79a3c
59a93afc-ff81-4c97-a57b-72f0de384acb
> php 32309.min.php
72b352fc-0174-4051-969e-cacc0adbf941
50e4f859-76fe-45f6-baf5-d5fcceb41f72
5a18408e-6e7e-43a6-bd71-09d22a0fbf14
ae5a1391-5367-467e-8ecc-785ca72cbf95

```

## Ungolfed

```
<?php
$r = openssl_random_pseudo_bytes(61);
$b = "";
$s = "substr";
for($i=0 ; $i<61 ;) $b .= str_pad(decbin(ord($r[$i++])), 8, 0, 0);

function p($B, $L) {
    return str_pad(dechex(bindec($B)), $L, 0, 0);
}

for($i=0 ; $i<4 ; $i++) {
    echo p($s($b, 122*$i, 32), 8)."-";
    echo p($s($b, 122*$i+32, 16), 4)."-4";
    echo p($s($b, 122*$i+48, 12), 3)."-";
    echo p("10".$s($b, 122*$i+60, 14), 4)."-";
    echo p($s($b, 122*$i+74, 48), 12)."\n";
}

```

# Answer
> 1 votes
## J - 114 bytes

I took the simplest approach available. The function takes amount of GUID's required (you could replace the `]` near the end with `4:` to make it return 4 always) and outputs that many of them, separated by newlines.

Edit: I missed that no generated bits must go to waste... This answer doesn't comply and I don't know how to make it to.

```
f=:[:}.(,LF,(x@8:,'-',x@4:,'-4',x,'-',('89AB'{~?@4:),x,'-',(x=:'0123456789ABCDEF'{~?@$&16)@(12"_))@3:)^:(]`(''"_))

```

If an extra newline is allowed after the output, this could be written in **111 bytes**.

```
f=:(,LF,~(x@8:,'-',x@4:,'-4',x,'-',('89AB'{~?@4:),x,'-',(x=:'0123456789ABCDEF'{~?@$&16)@(12"_))@3:)^:(]`(''"_))

```

Example:

```
   f 4
B23B10E3-6593-40F7-A5B0-D25A2763D781
3901709C-654E-4AF0-B23E-7252E859D35B
91E8D566-8E84-48CD-9B9D-EFC4E3F62C4E
F4578389-097C-4C38-A3C0-31EABFDCD630
   f 5
AF234012-8A9F-47A3-9BF5-4B28AF580E9C
A3FE1785-8B40-44E9-8D69-CFF1BE06AC06
84A2CEB9-744F-4B86-B37F-747D0FD3F3FC
0FD8B7A6-9642-42C3-89ED-DB4A35D83CF8
4F860D9B-6E20-4AF8-B6BF-0F8CB307B9B0

```

# Answer
> 1 votes
# Golfscript, 75

Fixed now!

```
{{'0123456789ABCDEF'{.,rand>1<}:|~}:&8*'-':^&&&&^4&&&^'89AB'|&&&^{&}12*n}4*

```

### Output example:

```
>ruby golfscript.rb p.gs
140BC879-EAC4-4170-B349-A616523458DB
E26B34A4-8E86-4508-9EE5-3C76BF7456B6
89F9B995-CC9E-4EF0-AA25-70703B80AF82
5F6A513C-9E97-45A4-A9D1-E9D3DF71EF99

>ruby golfscript.rb p.gs
38D7A76B-BEEB-4C98-A148-D1EA8C31E85F
807373E4-5CFE-4953-9D5E-671205EE1E8F
8BD88B76-5890-4543-9787-2753AB15D24B
CD7DF25F-632B-4902-A46C-A1E10BE83EC5

```

You can test it yourself here.

# Answer
> 1 votes
# Python, 287 bytes

```
from random import choice
s="0123456789abcdef"
def gen4():
  for i in range(4):
    m,n="",""
    l = []
    d = choice(s[8:12])
    for k in range(30):
      l.append(choice(s))
    m="".join(l)
    n=m[:12]+"4"+m[12:15]+d+m[15:]
    print(n[:8]+"-"+n[8:12]+"-"+n[12:16]+"-"+n[16:20]+"-"+n[20:])

```

There's already a Python answer, but that just used .uuid, so here's one without it. Wish i could get it shorter though.

Still beat PHP :P

# Answer
> 0 votes
## Python (85)

```
import os,uuid
for i in [1]*4:print uuid.UUID(os.urandom(16).encode('hex'),version=4)

```

os.urandom(n): Return a string of n random bytes suitable for cryptographic use.

I assume generating more than 488 bits is ok?

# Answer
> 0 votes
# Python 2 - 188 / 182

This should obey the requirements faithfully:

```
import os
a=(ord(x)>>i&3for i in(0,2,4,6)for x in os.urandom(61))
h=lambda n:eval('"%X"%(a.next()*4+a.next())+'*n+'"-"')
exec'print h(8)+h(4)+"4"+h(3)+"%X"%(8+a.next())+h(3)+h(12)[:-1];'*4

```

If python's UUID is acceptable for outputting a nicely-formatted uuid from a 32-digit hex string, then this version has 182 bytes:

```
import os,uuid
a=(ord(x)>>i&3for i in(0,2,4,6)for x in os.urandom(61))
exec('s='+'"%X"%(a.next()*4+a.next())+'*30+'"";print uuid.UUID(s[3:15]+"4"+s[:3]+"%X"%(8+a.next())+s[15:]);')*4

```

`a` is a generator comprehension that gives 2 bits at a time from an initial source of 61 random bytes.

Thanks TheRare for tips

# Answer
> 0 votes
## Javascript (ES6) - ~~177~~ ~~163~~ 158

Removed `.toUpperCase()`, replaced `substring` with `substr` and `substr(0,3)` to `substr(1)`

```
function f(){g=()=>(((1+Math.random())*0x10000)|0).toString(16).substr(1);for(i=0;i<4;i++)alert((g()+g()+"-"+g()+"-4"+g().substr(1)+"-"+g()+"-"+g()+g()+g()))}

```

EcmaScript 5 version of the above script:

```
function f(){function g(){return (((1+Math.random())*0x10000)|0).toString(16).substr(1)}for(i=0;i<4;i++)alert((g()+g()+"-"+g()+"-4"+g().substr(1)+"-"+g()+"-"+g()+g()+g()))}

```

# Answer
> 0 votes
# Common Lisp

## SBCL, 223

```
(define-alien-routine("arc4random_uniform"a)int(u
int))(labels((g(n)(a(expt 2 n)))(h()(g 16)))(dotimes(i 4)(format
t"~4,'0X~4,'0X-~4,'0X-~4,'0X-~4,'0X-~4,'0X~4,'0X~4,'0X~%"(h)(h)(h)(+
16384(g 12))(+ 32768(g 14))(h)(h)(h))))

```

## CLISP, 299

```
(use-package :ffi)(def-call-out
a(:name"arc4random_uniform")(:arguments(u int))(:return-type
int)(:language :c)(:library :default))(labels((g(n)(a(expt 2
n)))(h()(g 16)))(dotimes(i 4)(format
t"~4,'0X~4,'0X-~4,'0X-~4,'0X-~4,'0X-~4,'0X~4,'0X~4,'0X~%"(h)(h)(h)(+
16384(g 12))(+ 32768(g 14))(h)(h)(h))))

```

## About arc4random\_uniform(3)

Both of these call the C function arc4random\_uniform(3) in BSD libc. Some systems do not have this function.

Beware that my declaration of arc4random\_uniform(3) is **wrong**. The correct declaration is

```
u_int32_t arc4random_uniform(u_int32_t);

```

where `u_int32_t` is an old BSDism for an unsigned 32-bit integer. (The standard type in C99 is `uint32_t` without the first underscore.) My **wrong** declaration is

```
int arc4random_uniform(int);

```

where `int` is a signed 32-bit integer. (I know systems where `int` only has 16 bits, but I would not run Lisp there.) I am wrong to use signed for unsigned, but my program works because I only pass small non-negative integers. In code golf, `int` is shorter than `unsigned-int` in SBCL or `uint` in CLISP.

To use arc4random\_uniform(3) in Lisp, I define a Lisp function `a`. Here it is in SBCL:

```
; (use-package :sb-alien)  ; SBCL does this by default!
(define-alien-routine ("arc4random_uniform" a)
  int       ; return type
  (u int))  ; argument named u

```

And in CLISP:

```
(use-package :ffi)
(def-call-out a
  (:name "arc4random_uniform")
  (:arguments (u int))
  (:return-type int)
  (:language :c)
  (:library :default))

```

CLISP has two languages, `:c` for traditional K&R C and `:stdc` for C89, but I find no difference, so I use the shorter name.

Now `(a u)` returns a random integer at least 0 and less than *u*. If *u* is 2*n*, then I get exactly *n* bits. For example, `(a (expt 2 14)` provides 14 bits. Because of my wrong declaration, *u* must be less than 231. If I want 32 bits, I may call `(a 16)` twice.

## Rest of program

```
; after defining A
(labels ((g (n) (a (expt 2 n)))
         (h () (g 16)))
  (dotimes (i 4)
    (format t
            "~4,'0X~4,'0X-~4,'0X-~4,'0X-~4,'0X-~4,'0X~4,'0X~4,'0X~%"
            (h) (h) (h) (+ 16384 (g 12)) (+ 32768 (g 14)) (h) (h) (h))))

```

I define two local functions. `(g n)` generates *n* random bits. `(expt 2 n)` is much shorter than a left shift: `1<<n` in C would become `(let((v 0))(setf(ldb(byte 1 n)v)1)v)` in Common Lisp!

`(h)` is an alias for `(g 16)`. This alias costs 13 characters: 11 in `(h()(g 16))`, plus 2 to upgrade `flet` to `labels`, because *h* needs *g* in scope. Each call to `(h)` saves 3 characters, and I have 6 calls, so I save 18 after I spend 13.

When formatting each GUID, `(+ 16384(g 12))` is shorter than `(logior #x4000 (g 12)` and `(+ 32768(g 14))` is shorter than `(logior #x8000 (g 14))`.

One can generate the long format string `"~4,'0X~4,'0X-~4,'0X-~4,'0X-~4,'0X-~4,'0X~4,'0X~4,'0X~%"` (56 characters) with the expression `(format()"~{~A~}~~%"(mapcar(lambda(e)(if e(format()"~~4,'0X")'-))'(t t()t()t()t()t t t)))` (89 characters), but the literal string is shorter.

# Answer
> 0 votes
# 05AB1E, 41 bytes

```
4F30F15ÝΩh}J•2,ÈĆ•13в£'-4и4DL7+hΩ‚.ιÁ.ιJ,

```

Try it online.

**Explanation:**

```
4F                  # Loop 4 times:
  30F               #  Inner loop 30 times:
     15Ý            #   Push the list [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
        Ω           #   Pop and push a random integer from this list
         h          #   Convert the integer to hexadecimal
          }J        #  After the inner loop: join the characters on the stack together
•2,ÈĆ•              #  Push compressed integer 40106286
      13в           #  Convert it to base-13 as list: [8,4,0,3,0,3,12]
         £          #  Split the string into parts of that size
                    #   i.e. "FBA4C1C6FE22479659019DA439B7D6"
                    #    → ["FBA4C1C6","FE22","","479","","659","019DA439B7D6"]
'-4и               '#  Push a list of 4 "-"s: ["-","-","-","-"]
    4               #  Push a 4
     DL             #  Duplicate it to create the list [1,2,3,4]
       7+           #  Add 7 to each: [8,9,10,11]
         h          #  Convert each to hexadecimal: [8,9,"A","B"]
          Ω         #  Pop and push a random value from this list
                    #   i.e. "B"
           ‚        #  Pair it together with the 4
            .ι      #  Interleave it with the list of "-": ["-",4,"-","B","-","-"]
              Á     #  Rotate it once towards the right: ["-","-",4,"-","B","-"]
               .ι   #  Interleave it with the earlier created list
                    #   → ["FBA4C1C6","-","FE22","-","",4,"479","-","","B","659","-","019DA439B7D6"]
                 J  #  Join this list together to a string
                    #   → "FBA4C1C6-FE22-4479-B659-019DA439B7D6"
                  , #  And output it with trailing newline

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•2,ÈĆ•` is `40106286` and `•2,ÈĆ•13в` is `[8,4,0,3,0,3,12]`.

Without the requirement that no random bits must go to waste, this could have been **36 bytes**, by utilizing the builtin `ǝ` (based on my answer here):

```
4FŽΣÌvy4*F15ÝΩh}'-}J¨4DL7+hΩ‚Ž5Ā2äǝ,

```

Try it online.

# Answer
> 0 votes
# Coconut 1.4.1, 114 bytes

```
from random import*
for C in[->f'{randrange(16**_):0{_}x}']*4:print(C 8,C 4,'4'+C 3,choice'89ab'+C 3,C 12,sep='-')

```

Try it online!

This works on the old version on TIO, for newer versions you might need parentheses around `'89ab'`.

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


title: A BlackJack KOTH contest

text:
# Question
Title: A BlackJack KOTH contest
# BlackJack

> As I had a blast working on the original KOTH challenge, I wanted to come up with another one. For me, the fun of these AI challenges is in refining a comparatively simple bot which plays a very simple game subtly. Due to the probabilistic nature of card games, I think that blackjack could be an interesting KOTH game just like TPD.

**All the rules are derived from this website's description of BlackJack with shoes**

# Rules Regarding Cards & the Deck

* Bots play at tables of four (4) competitors and one (1) dealer
* One (1) shoe (a shuffled deck) is shared by all players **and the dealer** until it is exhausted, at which point a new randomly shuffled deck will be added and play will continue. The bots ARE NOT (at present) NOTIFIED of the addition of this new deck. Such notification may be added if lack of this feature causes sufficient distress/trouble.
* There is a buy-in of 10 per round, and cards are free
* Perfect/ideal hand has a score of 21
* All face cards have a value of 10
* All numeric cards are worth their number
* Aces are worth 11 or 1. this will be dealt with automatically by the framework, not the bots.
* As per the rules, all players' cards are dealt face-up and are visible. One of the dealer's cards is face-down and the other is face-up.

# Scoring

* Scores in excess of 21 which use an ace as 11 force the ace to reduce in value to 1
* scores in excess of 21 which cannot be coerced below the threshold of 21 "bust" the bot

# The Dealer

* The dealer draws until he busts, or excedes a score of 17 **at which point he is forced to stand**

# Betting and Chips

* At the start of each round, a buy-in of 10 is charged, so there is a minimum **stake** of 10, and a minimum **bet** of 1. **NOTE** \- the bet is the absolute value of the bet argument, so don't bother trying negative bets.
* Bots which cannot afford the buy-in are removed from the contest
* When making bets, bots cannot bet more than the chips they have
* If the bet is possible, the chips bet are emmidiately removed from the bot and added to the stake
* Winning a bet gives the bot 2x chips bet. However because the bet is subtracted from the bot's chips, the bot breaks even and then wins 1x the bet.
* **Bots win bets only if their score is greater than that of the dealer**

# Gameplay Breakdown

**One Hand**

1. When the game starts, each player is iteratively dealt one card, and has the $10 buy-in fee/minimum bet subtracted from their chips.
2. The dealer draws
3. A second pass is made, and another card is dealt to all players.
4. The dealer draws
5. Then (in the same order as they were dealt to) each bot is executed as described in the "Programmer's Interface" section and **must** make a move or stand. Betting is considered a move. ***NOTE THAT BETTING DOES NOT AFFECT BOTS' ABILITY TO MAKE FURTHER MOVES.*** It is very possible to bet and then draw a card, and it is possible to draw multiple cards and them bet before standing.
6. When all the bots have busted or stood, the dealer plays to its threshold of 17
7. The scores of the bots are then compared to that of the dealer, bets are won and lost

**One Round**

Is considered to constitute five (5) hands. In-between hands, the list of contestants is sorted to remove players and then further processed to ensure that all the bots play the same number of hands (a provision for the fact that the number of entries will not devide evenly among four-bot tables).

# Programmer's Interface and Legal Moves

As documented in the CardShark file:

```
#   DOCUMENTATION
#       INPUT SPECIFICATION
#          $ ./foo.bar <hand-score> <hand> <visible cards> <stake> <chips>
#          <hand-score>     is the present integer value of the player's hand.
#          <hand>           is a space-free string of the characters [1-9],A,J,Q,K
#          <visible cards>  every dealt card on the table. when new shoes are brought
#                           into play, cards drawn therefrom are simply added to this list
#                           NOTE: the first TWO (2) cards in this list belong to the dealer.
#                             one however will be "hidden" by a "#". the other is visible.
#                           !!! THE LIST IS CLEARED AT THE END OF HANDS, NOT SHOES !!!
#          <stake>          the  number of chips which the bot has bet this hand
#          <chips>          the number of chips which the bot has
#       SAMPLE INPUT
#          $ ./foo.bar 21 KJA KQKJA3592A 25 145
#
#       OUTPUT SPECIFICATION
#          "H"|"S"|"D"|"B"  (no quotes in output)
#          "H"              HIT - deal a card
#          "S"              STAND - the dealer's turn
#          "D"              DOUBLEDOWN - double the bet, take one card. FIRST MOVE ONLY
#          "B 15"           BET - raises the bot's stakes by $15.

```

As (now) documented in the Cards file:

```
#       class CARD
#           card is a container for representing paper playing cards in
#           otherwise fairly functional programming.
#           letter()
#               gets the letter used to identify the card in a string
#               LETTER MAPPINGS
#                   Ace     :   'A'
#                   Two     :   '2'
#                   Three   :   '3'
#                   Four    :   '4'
#                   Five    :   '5'
#                   Six     :   '6'
#                   Seven   :   '7'
#                   Eight   :   '8'
#                   Nine    :   '9'
#                   Ten     :   'T'
#                   Jack    :   'J'
#                   Queen   :   'Q'
#                   King    :   'K'
#                   "Hidden":   '#'

```

**The source code for the scoring system is HERE**

# **Sample Bots**

**Lim 17**

```
#!/usr/bin/env python
import sys
s = sys.argv
if int(s[1]) < 17:
    print "H"
else:
    print "S"

```

# Entry Languages

At present, Java, c/c++, Python and Lisp are supported. A reasonable effort will be made to include submissions in other languages, but remember that the final contest will be run on a Linux box.

# Winner Selection

The winner would be the author of the bot which consistently accrued the most chips over a yet-to-be determined number of tables and rounds. ~~The winner will be announced on June 3rd, but the announcement may be delayed if there are still submissions coming in.~~ Contest extended indefinitely.

# Answer
> 3 votes
## BlackJackDavey

Boring, old fashioned c. Should compiler under ANSI or c99.

```
/* BlackJackDavey
 *
 * A entry for
 * http://codegolf.stackexchange.com/questions/2698/a-blackjack-koth-contest
 * copyright 2011
 *
 * Currently expects a slightly extended version of the spec. Two
 * expected changes:
 * - Tens will be represented as 'T'
 * - The visible card string will include '#' for those cards whose
 *     *backs* we can see (slight improvement in card counting technique)
 *
 * No disaster if neither feature is present, just sligtly degraded
 * performance.
 */
#include <stdio.h>
#include <string.h>

/* A full deck has a total value of 4*( (11*5) + (3*10) + ace ) where
 * ace is 11 or according to our need.
 **/
int fullWeight(const int current){
  int ace = (current>10) ? 1 : 11;
  return 4 * ( 11*5 + 3*10 + ace);
}
/* Return the value of a particular card in the context of our
 * current score
 */
int cardWeight(const char c, const int current){
 switch (c) {
 case '1': case '2': case '3': case '4': case '5':
 case '6': case '7': case '8': case '9':
   return (c - '0');
 case 'T': case 'J': case 'Q': case 'K':
   return 10;
 case 'A':
   return current>10 ? 1 : 11;
 }
 return 0;
}
/* returns the mean card *value* to be expected from the deck
 *
 * Works by computing the currently unknown value and diviing by the
 * number of remaining cards
 */
float weight(const char*known, const int current){
  int weight = fullWeight(current);
  int count=52;
  int uCount=0;
  const char*p=known;
  while (*p != '\0') {
    if (*p == '#') { /* Here '#' is a stand in for the back of a card */
      uCount++;
    } else {
      weight -= cardWeight(*p,current);
    }
    count--;
    p++;
    if ( count==0 && *p != '\0') {
      count += 52;
      weight += fullWeight(current);
    }
  }
  return (1.0 * weight)/(count+uCount);
}

int main(int argc, char*argv[]){
  int score=atoi(argv[1]);
  const char*hand=argv[2];
  const char*visible=argv[3];
  int stake=atoi(argv[4]);
  int chips=atoi(argv[5]);

  /* If current stake is less than 10, bet all the rest because a loss
     does not leave us enough to continue */
  if (chips < 10 && chips > 0) {
    printf("B %d\n",chips);
    return 0;
  }
  /* First round stategy differs from the rest of the game */
  if (strlen(hand)==2 && stake==10) {
    switch(score){
    case 10:
    case 11: /* Double down on particularly strong hands */
      if (chips >= 10) {
    printf("D\n");
    return 0;
      }
      break;
    default:
      break;
    };
  }
  /* In future rounds or when first round spcialls don't apply it is
     all about maximizing chance of getting a high score */
  if ((score + weight(visible,score)) <= 21) {
    /* if the oods are good for getting away with it, hit */
    printf("H\n");
    return 0;
  }
  /* Here odd are we bust if we hit, but if we are too low, the dealer
     probably makes it.*/
  printf("%c\n", score>14 ? 'S' : 'H');
  return 0;
}

```

The strategy here is documented in the comments, but is very straight ahead. Additional bets are made in only two cases (not enough stake for the next round, or double down), and this may need to change.

The game differs some from the guides offered for casino gamblers in that there is no specific information about the dealer's showing card (or can we could on that being the last entry in `visible`?), so some of the magic numbers are guesses.

May need some modest diddling depending on the answer to two questions in the comments.

Name from the game, my first name, and the old folk ballad.

# Answer
> 3 votes
# Linear Bet

```
#!/usr/bin/env python
from __future__ import division
import sys
s = sys.argv

c=150    # chip modifier
f=15     # stand score

if int(s[1]) < f:
    print "H"
else:
    if int(s[4]) == 10:
        print "B", (int(s[1])/21)*c
    else:
        print "S"

```

This bot is a modification of the 17 strategy. This bot draws until it exceeds a score of 15 (f) and then bets int(c\*(score/21)) chips. This way the bot will bet aggressively wherever possible.

# Answer
> 1 votes
# JustAnotherCardCounter, Python

```
import sys
s = sys.argv

if s[0] <= 11 and len(s[1]) == 2:
  print("D") # another card is always safe here
elif s[0] <= 11:
  print("H") # same
elif s[0] == 21:
  print("B ", s[4]) # can't lose, so go all out
  print("S") # and wait for the cash to roll in
cardset = s[2]
prevcardset = ""
cards = {
"A": 0,
"2": 0,
"3": 0,
"4": 0,
"5": 0,
"6": 0,
"7": 0,
"8": 0,
"9": 0,
"T": 0,
"J": 0,
"Q": 0,
"K": 0}
# here i go, cheating fate (again)
for card in "A23456789TJQK":
  cards[card] += (cardset.count(card) - prevcardset.count(card))
counts = list(cards.values()) # get the values
if (counts[:20 - s[0]] * 4/3) >= counts[20 - s[0]: # here's where the magic happens
  print("H")
else:
  if s[4] * (1 - s[0]/21) < 10:
    print("B ", s[4]) #we'll go out on a loss regardless, might as well try and get more when we win
    print("S")
  else:
    print("B ", (s[4]*(s[0]/21)) # we can afford to stay low, so we keep ourselves in the game.
    print("S")

```

This bot does what it says on the tin. Effectively a combination of LinearBet and some of BlackJackDavey.

Probably won't do well.

Feel free to tell me where this breaks (if it does).

---
Tags: code-challenge, game, king-of-the-hill
---


title: Who wins a Spades trick

text:
# Question
Title: Who wins a Spades trick
Write code to determine who wins a four-card trick in a game of Spades. Fewest bytes wins.

The input is a string that lists the four cards played in sequence like `TH QC JH 2H` (Ten of Hearts, Queen of Clubs, Jack of Hearts, Two of Hearts). A card is given by two characters: a suit from `CDHS` and a value from `23456789TJQKA`. You are guaranteed that the input is valid and the cards are distinct.

You should output a number 1, 2, 3, or 4 for the winner of the trick. In the example `TH QC JH 2H`, the jack of hearts wins the trick, so you should output 3.

Your input and output must be exactly as described, except trailing newlines are optional.

Here are the Spades rules for winning a trick. The winning card is the highest card of the four, with some caveats. Spades is the *trump suit*, so any spade outranks any non-spade. The suit of the first card played is the *lead suit*, and only cards of that suit or spades are eligible to win the trick. Cards of the same suit are compared by their values, which are given in increasing order as `23456789TJQKA`.

Test cases:

```
TH QC JH 2H
3
KC 5S QS 9C
3
QD 2D TD 5D
1
9S 5D AD QS
4
3D 4C 3H JH
1
9S 4S TS JS
4
5H 9H 2C AD
2
5S 4C 3H QD
1
2H 2S KH AH
2

```

# Answer
> 10 votes
# Pyth, ~~28~~ ~~27~~ 25 bytes

```
J"KTAZ"hxcz)eo_XN+@z1JJcz

```

Try it online: Demonstration or Test Suite (first 4 chars are the test suite construct)

Thanks to @isaacg for a trick, which saved 2 chars.

The main idea is to modify chars of each hand such a in way, that the winning hand has the maximal value.

The values of the hands `23456789TJQKA` is already nearly sorted. I just have to replace `T` with `A`, `K` with `T` and `A` with `Z`, resulting with `23456789AJQSZ`.

The order of suits `CDHS`are for the most not really important. `S`, the most powerful suit, which is already the maximal value. Important is to give the suit of the first hand the second most powerful value. So I translate this suit into `K`.

All hands also have to be read reverse, since the suit is more powerful than the value.

```
                           implicit: z = input string
J"KTAZ"                    J = "KTAZ"
             o         cz  orders the hands N of split(z) by:
              _              the reversed of
               XN+@z1JJ      N, where the values z[1]+J are replaced by J
            e              last element (winning hand)
        xcz)               index of the winning hand in split(z)
       h                   + 1

```

# Answer
> 6 votes
# CJam, ~~34~~ 33 bytes

```
lS/_{)2$0='S+\#\"TQKA"_$er+}$W>#)

```

**Algorithm**

The logic is simple. I have a custom sort going on, in which I first give priority to the second character representing the suit. In this, Spades gets the highest priority and then the first thrown suite. Rest all are `-1`. Then I sort on the first character with swapping of `T` with `A` and `Q` with `K` to have lexical sorting.

**Code explanation**

First off, lets see what is the lexical order of the face values of the cards:

```
"23456789TJQKA"$

```

> 23456789AJKQT

So, all numbers are at correct position. `J` is also at correct position. We need to swap `K` and `Q` and `J` and `A` to get lexical order.

```
lS/_{)2$0='S+\#\"TQKA"_$er+}$W>#)
lS/                                 "Read an input line and split on spaces";
   _{                      }$       "Copy the array and sort it using this custom logic";
     )                              "Take off the last character of each hand.";
      2$0=                          "Get the suit of the first hand";
          'S+                       "Add Spades suit to it";
             \#                     "Get the index of the current hand suit.
                                     1 for Spades, 0 for first hand suit, -1 otherwise";
               \                    "Put face value of this hand on top of stack";
                "TQKA"              "Put string TQKA on stack";
                      _$            "Copy and sort. This essentially reverses the string
                                     TQKA to form AKQT. This is 1 byte shorter than _W%";
                        er+         "Swap T with A and K with Q and add to the
                                     suit index calculated previously";
                                    "After the above tuple, sorting will automatically
                                     convert the tuple to string and sort lexically";
                             W>     "Get the array containing only the last element";
                               #)   "Get the index of this hand in original set and
                                     increment to convert it to 1 based";

```

Try it online here

# Answer
> 3 votes
# JavaScript (ES6), 112

Scan the list and return the position of the highest value found.

Run snippet to test (in Firefox)

```
F=t=>t.split(' ').map((c,i)=>(n='23456789TJQKA'.search(c[0])+(c[1]>'H'?40:c[1]==t[1]&&20))>m&&(m=n,r=i+1),m=0)|r

C.innerHTML=['TH QC JH 2H','KC 5S QS 9C','QD 2D TD 5D','9S 5D AD QS','3D 4C 3H JH','9S 4S TS JS','5H 9H 2C AD','5S 4C 3H QD'].map(h=>h+' -> '+F(h)).join('\n')
```

```
<pre id=C></pre>
```

# Answer
> 3 votes
# Perl, 73 bytes

```
#!perl -pl
/\B./;s/$&/P/g;y/TKA/IRT/;$_=reverse;@a=sort split;/$a[-1]/;$_=4-"@-"/3

```

Try me.

Converts the card names so the game value order follows the alphabetical order, then picks the highest by sorting and looks for it in the original string for position.

# Answer
> 2 votes
# Ruby, 59+2=61

With command-line flags `na`, run

```
p (1..4).max_by{|i|$F[i-1].tr($_[1]+'SJQKA','a-z').reverse}

```

# Answer
> 2 votes
# J, 47 bytes

```
1+[:(i.>./)_3+/\16!@-]i.~'SXAKQJT9876543'1}~1&{

```

Usage:

```
   (1+[:(i.>./)_3+/\16!@-]i.~'SXAKQJT9876543'1}~1&{) 'TH QC 9S 8S'
3

```

Method:

* For every input char we assign a value based in its position in the `'S[second char of input]AKQJT9876543'` string. Non-found chars get the value `last position + 1` implicitly. Further characters have much less value (`value=(16-position)!`).
* Compute the sum for the 3 input-char triplet and one duplet (e.g. `TH_` `QC_` `9S_`and `8S`).
* Choose the 1-based index of the maximal value.

(J unfortunately can't compare chars or strings directly. It can only check for their equality which ruled out some other approaches for this challenge.)

Try it online here.

# Answer
> 2 votes
**C#, 237**

```
using System;namespace S{class P{static void Main(string[] a){var V="23456789TJQKA";int x=0;int y=0;var z=a[0][1];for(int i=0;i<4;i++){int q=V.IndexOf(a[i][0])+2;var w=a[i][1];q*=w==z?1:w=='S'?9:0;if(q>y){x=i;y=q;}}Console.Write(x+1);}}}

```

How it works: Iterate each hand to calculate the "value" of the card.. store the highest valued index. A cards value is determined as the rank of the card multiplied by 0 if it is not a spade or the opening suit, 1 if it is the opening suit and 9 if it is a spade but not the opening suit. (9 choosen b/c 2\*9=18\> A=14 & 9 is a single char)

# Answer
> 1 votes
# Pyth, 36 33 bytes

```
KczdhxKeo,x,ehK\SeNXhN"TKA""AYZ"K

```

Fairly straightforward approach, uses sorting with a custom key function, then finds the index of the highest value.

# Answer
> 1 votes
# Pyth, 31 bytes

```
hxczdeo}\SNo}@z1Zox"TJQKA"hNScz

```

Try it here.

How it works:

The proper way to read this procedure is back to front. The procedure sorts the desired card to the end of the list, then pulls it out and finds its index in the original list.

* `cz`: This generates the list of card strings. `c`, chop, is normally a binary function (arity 2), but when called on only one input, serves as the `.split()` string method.
* `S`: This applies the normal sorting behavior, which sorts lower numbered cards before higher ones.
* `ox"TJQKA"hN`: This orders the cards by the index (`x`) in the string `"TJQKA"` of the first letter of the card (`hN`). For cards with numbers, the first letter is not found, giving the result `-1`. Since Pyth's sorting function is stable, the numbered cards' order is not affected.
* `o}@z1Z`: Next we order by whether the suit of the first card played (`@z1`) is in the card in question. Since `True` sorts behind `False`, this sends cards of the lead suit to the back.
* `o}\SN`: This is the same as the sort before, but it sorts on whether the letter `S` is in the card, sending spades to the back.
* `hxczde`: This extracts the last card sorted this way (`e`), finds its index in the list of cards (`xczd`) and increments by 1 (`h`), giving the desired player location.

# Answer
> 1 votes
# Python, 172 bytes

```
l=input().split(" ")
s="23456789TJQKA"
h=l[0]
for c in l:
  if c[1] not in [h[1],"S"]:
    continue
  if s.index(h[0])>s.index(c[0]):
    continue
  h=c
print(l.index(h)+1)

```

There wasn't a Python answer here, so I fixed that :)

Simply compares the cards, discarding them if they are of a different suit to the current highest (and not a spade), then if they are of a lower value. At the end, simply get the highest card, and add 1 to its index.

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


title: Bridge Hand Scoring

text:
# Question
Title: Bridge Hand Scoring
One of the things that makes contract bridge very interesting is its highly complicated "artificial" meta game. This system of scoring hands is a small part of it.

Bridge is a trick-taking card game. Each player gets a hand of 13 cards, and the game starts with the *bidding*. The bidding determines how the rest of the game plays, and so is a crucial part of it. In order to ensure that you and your partner do not bid too high (or too low), this artificial scoring system was developed to tell you how good your hand is.

## Scoring

Here's a sample hand:

```
S:KQT5
H:J72
D:965
C:AK8

```

The S, H, D, C represent the suits (spades, hearts, diamonds and clubs) and the rest are the cards in those suits. So this hand has a queen of spades (Q), king of spades (K), ten of spades (T), five of spades, jack of hearts, seven of hearts, etc.

The scoring system works as follows:

* You get 4 points for every ace (A) you have, 3 points for every king (K), 2 points for every queen (Q) and 1 point for every jack (J). No other cards give points.
* Every card after the fourth in a suit gives you 1 point. So if you have six hearts, you'd get 2 points.
* A suit where you only have 2 cards gives you 1 point (this is a doubleton). A suit where you have just 1 card gives you 2 points (this is a singleton). If you have no cards in a certain suit, you get 3 points (this is a void). (Usually these are only counted once you've agreed on a suit with your partner, but I'm including them to make the challenge more interesting.)

So, the above hand has 13 points.

## Challenge

Given a bridge hand in the format shown above, calculate how many points the hand has. The suits will always be listed in the order spades, hearts, diamonds and clubs, and the cards will always be sorted in the order A, K, Q, J, T, 9 - 2.

## Sample Inputs and Outputs

```
S:KQT5
H:J72
D:965
C:AK8
       \-> 13

S:AKQT6
H:54
D:J83
C:732
       \-> 12

S:
H:KQT8754
D:A86
C:432
       \-> 15

S:9876
H:843
D:652
C:432
       \-> 0

S:AKQT5
H:AQJ6
D:Q3
C:AK
       \-> 28

```

This is , so shortest code in bytes wins.

# Answer
## Jelly, ~~27~~ ~~25~~ 21 bytes

*Thanks @Dennis for -3 bytes!*

```
L_5.AḞW+“JQKA”i$€Sµ€S

```

This takes input as a list of lines. To take input as a multiline string, precatenate a `ṣ⁷µ`.

Making a table of the frequency points:

```
Cards:    0  1  2  3  4  5  6 ... 4+k
Points:   3  2  1  0  0  1  2 ... k

```

we can see that they're equal to `abs(c-3.5)-.5`, where c is the number of cards. Since each line contains two extra characters, and the number of points is always an integer, this is `floor(abs(l-5.5))` where l is the line length.

Note that Jelly's indices are 1-based, and also the behavior of vectorized functions on mismatched dimensions: the extra elements of the longer list are unaffected. So `[1] + [3,2,0,0]` gives `[4,2,0,0]`.

```
                  µ      The program is two monadic fs applied in turn; an atop.
L_5.AW+“JQKA”i$€S       Helper function:
                 €        For €ach line:
L                         Get the line Length.
 _5.                      Subtract 5.5 (Numeric literals' decimal parts default to .5)
    A                     Apply Absolute value
     Ḟ                    Floor
      W                   Then Wrap it in an array. "S:AKQT6" gives [1].
        “JQKA”i$          Monadic function: index into the string "JQKA".
                €         Apply ^ over €ach char of the line; [3,2,0,0,0].
       +                  Add the two arrays together; [4,2,0,0,0].
                 S        Sum; 6.
                    S    Main link: Sum all results

```

Try it here.
> 4 votes

# Answer
## ES6, ~~107~~ ~~99~~ 89 bytes

```
s=>(t=0,[...s].map(c=>t+="JQKA".search(c)+1),s.split`
`.map(l=>t+=(l=l.length-6)^l>>4),t)

```
> 3 votes

# Answer
## Pyth, ~~27~~ ~~25~~ 24 bytes

```
sms+a5.5ldshMxL"JQKA"d.z

```

We calculate the values separately for each suit, then add them.

```
  s m                 sum of map lambda d:  (d is a line of input)
      +                 add the
        s a                 floor of the absolute difference between
            5.5               5.5
            l d               and len(d)
          s hM xL           to the sum of the indices each incremented by one
                  "JQKA"      of each char in d in the string "JQKA"
                  d
      .z

```

Test suite.
> 2 votes

# Answer
# Retina, ~~77~~ 59 bytes

```
T`AKQJTd`5-1
:(.){0,3}(.)?
$#1$#1$#2 3$0
\S
$0$*1
+`1 1

1

```

Explanation by lines/line pairs:

* In the first line we convert chars `AKQJT987655432` to `5432111111111`. This means for every suit we have a sum. If we have `0 1 2 3 4 5 6 7 ...` cards in this suit, the sum is off by `+3 +1 -1 -3 -4 -4 -4 -4 ...` from the correct score.
* In lines 2 and 3 to correct this we add 3 to every line and before a space we add values which we will subtract. This subtracted value is twice the length of cards with a max of 3, and 1 more if there are at least 4 cards.
* In lines 4 and 5 we convert digits to unary dropping everything else except the separator space.
* In lines 6 and 7 we do unary subtraction.
* In line 8 we count up the `1`'s which gives the result.

Try it online here.
> 1 votes

# Answer
# APL (Dyalog Classic), 24 bytes

```
+/(⌊∘|5.5-≢¨),5|'JQKA'⍳∊

```

Try it online!

uses ⎕io=1
> 1 votes

# Answer
# Stax, 18 bytes

```
½Γ}♣▓="pì∩û╨▐M↨}╚-

```

Shortest answer so far, defeated Jelly (although I expect to be defeated soon ...)

Run and debug online!

## Explanation

Uses the unpacked version to explain.

```
LZF{"JQKA"I^+i5-:++F5+
L                         Collect input in a list (if this is not needed, we can yet save another byte)
 Z                        Put a zero under the top of the stack, used as the accumulator
  F                       Loop for every suit
   {               F      Calculate the "score" for the string describing the suit
    "JQKA"I^              Find the 1-based index of current character in "JQKA", 0 for not found
            +             Add to the accumulator
             i5-:+        Subtract 5 from the current 0-based index, and take the sign
                  +       Add to the accumulator
                    5+    Add 5 extra points for each suit

```

This is achieved by translating

> * Every card after the fourth in a suit gives you 1 point. So if you have six hearts, you'd get 2 points.
> * A suit where you only have 2 cards gives you 1 point (this is a doubleton). A suit where you have just 1 card gives you 2 points (this is a singleton). If you have no cards in a certain suit, you get 3 points (this is a void).

To

> * Score 3 extra points for each suit
> * Each card before the fourth in a suit gives you -1 point, each card after the fourth gives you 1 point, the fourth card scores 0.

Then we can make use of the property of the signum function.

By doing this we can avoid explicit handling of number of cards saving a few bytes.
> 1 votes

# Answer
# Python, 123 bytes

```
k=input()
l=k.split("\n")
print(4*k.count("A")+3*k.count("K")+2*k.count("Q")+k.count("J")+sum([max(len(m)-6,0) for m in l])

```

`.count` is a wonderful function for these purposes, and I don't use `[2:]` for the sum of lengths because I can just subtract an extra 2.

Overall, this answer just does it the simple way.
> 0 votes

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


# Question
Title: Maximal number of regions obtained by joining n points around a circle by straight lines
Let's define *f(n)* as the maximal number of regions obtained by joining n points around a circle by straight lines. For example, two points would split the circle into two pieces, three into four, like this:

Make sure when you are drawing the lines, you don't have an intersection of more than two lines.

## Your task

Given a number *n*, print *f(n)*.

Test cases:

```
 n | f(n)
---+-----
 1 |   1
 2 |   2
 3 |   4
 4 |   8
 5 |  16
 6 |  31
 7 |  57
 8 |  99
 9 | 163

```

You can see more here.

Using built-in sequence generators is not allowed.

Remember, this is , so the code with the smallest number of bytes wins.

If you guys want the formula, here it is:

>

# Answer
> 6 votes
# Mathematica, 23 bytes

```
Tr@Binomial[#,{0,2,4}]&

```

Uses the formula in the question.

# Answer
> 4 votes
## JavaScript (ES6), 29 bytes

```
n=>(((n-6)*n+23)*n/6-3)*n/4+1

```

Uses a formula given in OEIS.

# Answer
> 4 votes
# Jelly, 6 bytes

```
5Ḷc@’S

```

Try it online! | Verify test cases

### Explanation

Uses the OEIS formula `((n-1)C4 + (n-1)C3 + ... + (n-1)C0)`.

```
5Ḷc@’S    Main link.  Args: n

5         Yield 5.
 Ḷ        Lowered range: yield [0,1,2,3,4].
    ’     Yield n-1.
   @      Swap operands of the preceding dyad, 'c'.
  c       Combinations: yield [(n-1)C0, (n-1)C1, (n-1)C2, (n-1)C3, (n-1)C4].
     S    Sum: return (n-1)C0 + (n-1)C1 + (n-1)C2 + (n-1)C3 + (n-1)C4.

```

# Answer
> 3 votes
# Jelly, 6 bytes

```
c3ḶḤ¤S

```

Try it online! or verify all test cases.

### How it works

```
c3ḶḤ¤S  Main link. Argument: n

    ¤   Combine the three links to the left into a niladic chain.
 3        Yield 3.
  Ḷ       Unlength; yield [0, 1, 2].
   Ḥ      Unhalve; yield [0, 2, 4].
c       Combinations; compute [nC0, nC2, nC4].
     S  Sum; return nC0 + nc2 + nC4.

```

# Answer
> 3 votes
# MATL, 7 bytes

```
q5:qXns

```

Try it online! Or verify all test cases.

### Explanation

Uses the formula (from OEIS): *a*(*n*) = *C*(*n*−1, 4) + C(*n*−1, 3) + ... + C(*n*−1, 0)

```
q      % Implicit input. Subtract 1
5:q    % Array [0 1 2 3 4]
Xn     % Binomial coefficient, vectorized
s      % Sum

```

# Answer
> 3 votes
# Java 7,~~50~~ 47 bytes

```
int c(int n){return(n*n*(n-6)+23*n-18)*n/24+1;}

```

Uses the formula (from OEIS)

# Answer
> 3 votes
# \>\<\>, ~~27~~ 26+3 = 29 bytes

3 bytes added for the -v flag

```
::::6-**$f8+*f3+-+*f9+,1+n

```

Try it online!

A byte saved thanks to *Martin Ender*.

# Answer
> 3 votes
# R, 25 bytes

```
sum(choose(scan(),0:2*2))

```

`scan()` takes the input `n` from stdin, which is passed to `choose` along with `0:2*2`. This latter term is `0` to `2` (i.e. `[0, 1, 2]`) multiplied by 2, which is `[0, 2, 4]`. Since `choose` is vectorized, this calculates `n choose 0`, `n choose 2`, `n choose 4`, and returns them in a list. Finally, `sum` returns the sum of these numbers, surprisingly enough.

I don't think that this can be golfed further but I would be very happy to be proven wrong!

# Answer
> 3 votes
# tinylisp, 73 bytes

```
(load library)
(d D(q((N)(+(/(*(s N 1)N(s N 2)(s N 3))24)(/(*(s N 1)N)2)1

```

Try it online!

From Giuseppe.

# tinylisp, 90 bytes

```
(d C(q((N K)(i K(i N(a(C(s N 1)(s K 1))(C(s N 1)K))0)1
(d D(q((N)(a(a(C N 0)(C N 2))(C N 4

```

Try it online!

# Answer
> 2 votes
# dc, 21

```
?ddd6-*23+*6/3-*4/1+p

```

RPN-ised version of @Neil's answer.

### Test output:

```
$ for i in {1..9}; do dc -e "?ddd6-*23+*6/3-*4/1+p" <<< $i; done
1
2
4
8
16
31
57
99
163
$

```

# Answer
> 2 votes
# J, 9 bytes

```
+4&!+2!<:

```

Uses the formula `C(n-1, 2) + C(n, 4) + n = C(n, 0) + C(n, 2) + C(n, 4)`.

## Usage

```
   f =: +4&!+2!<:
   (,.f"0) >: i. 10
 1   1
 2   2
 3   4
 4   8
 5  16
 6  31
 7  57
 8  99
 9 163
10 256
   f 20
5036

```

## Explanation

```
+4&!+2!<:  Input: integer n
       <:  Decrement n
     2     The constant 2
      !    Binomial coefficient C(n-1, 2)
 4&!       Binomial coefficient C(n, 4)
    +      Add them
+          Add that to n and return

```

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
2Ý·scO

```

Try it online!

**Explanation**

Straight implementation of the OEIS formula `c(n,4) + c(n,2) + c(n,0)`

```
2Ý       # range: [0,1,2]
  ·      # multiply by 2: [0,2,4]
   s     # swap list with input
    c    # combinations
     O   # sum

```

# Answer
> 2 votes
# TI-89 Basic, 57 Bytes

```
:Def a(a)=Func
:Return nCr(n,0)+nCr(n,2)+nCr(n,4)
:End Func

```

Throwback to old times.

# Answer
> 2 votes
# Excel, 31 bytes

```
=(A1^2*(A1-6)+A1*23-18)*A1/24+1

```

Link to Spreadsheet

Using one of OEIS formulas

# Answer
> 2 votes
# Factor \+ `math.combinatorics math.unicode`, 29 bytes

```
[ "\0"[ nCk ] with map Σ ]

```

Try it online!

You might not be able to see them here, but there are literal 2 and literal 4 control codes embedded in the string. It's a shorter version of `{ 2 4 0 }`. You can see them for sure on TIO.

# Answer
> 1 votes
# Actually, 6 bytes

```
D╣5@HΣ

```

Try it online!

Explanation:

```
D╣5@HΣ
D       decrement input
 ╣      push that row of Pascal's triangle
  5@H   first 5 values
     Σ  sum

```

# Answer
> 1 votes
# Vyxal `d`, 4 bytes

```
3ʁdƈ

```

Try it Online!

Simply an implementation of the formula.

# Answer
> 0 votes
# Scala, 35 bytes

```
(n:Int)=>(n*n*(n-6)+23*n-18)*n/24+1

```

Uses the same formula as numberknot's java answer.

# Answer
> 0 votes
# Octave, 27 bytes

```
@(m)binocdf(4,m-1,.5)*2^m/2

```

This is an anonymous function.

**Try it at Ideone**.

### Explanation

This is based on the OEIS formula *a*(*m*) = *C*(*m*−1, 4) + *C*(*m*−1, 3) + ... + C(*m*−1, 0), where *C* are binomial coefficients. The binomial distribution function

for *k* = 4, *n* = *m*−1 and *p* = 1/2 gives 2*m*−1*a*(*m*).

---
Tags: code-golf, math, geometry
---


title: Output a Steiner quadruple system

text:
# Question
Title: Output a Steiner quadruple system
A *Steiner quadruple system* \\$SQS(n)\\$ is a collection of subsets (*blocks*) of size 4 of a set \\$S\\$ of size \\$n\\$ such that every subset of \\$S\\$ of size 3 is in exactly one block. It is easy to show that the number of blocks is \\$\frac14\binom n3\\$ and that a necessary condition for an \\$SQS(n)\\$ to exist is \\$n\equiv2,4\bmod6\\$. It is much harder to show that that condition is also sufficient, which is what Haim Hanani did in 1960.

Hanani's proof is almost completely inductive: the only explicitly listed \\$SQS(n)\\$ is an \\$SQS(14)\\$ with 91 blocks. It can't be memorised, however, so I want a program to generate such a system for me.

## Task

Output all blocks of some \\$SQS(14)\\$ – how it is constructed is irrelevant.

Output should consist of 91 blocks of four values each. You may use any 14 distinct values. Formatting is flexible, but there must be a clear separation between blocks, and it must be clear which four values are in each block.

This is ; fewest bytes wins. You must run your code to completion and include its output in your answer.

## Example

I have found an \\$SQS(14)\\$ whose blocks arise from the orbits of the base blocks \\$1235, 126C, 12AB, 12DE, 12FG\\$ under the permutations \\$(1234567)(ABCDEFG)\\$ and \\$(1A)(2F5G3D)(4B6E7C)\\$. The following are two possible output formats for this system:

```
1235 2346 3457 4561 5672 6713 7124
AGFD GFEC FEDB EDCA DCBG CBAF BAGE
126C 237D 341E 452F 563G 674A 715B
AGC6 GFB5 FEA4 EDG3 DCF2 CBE1 BAD7
12AB 23BC 34CD 45DE 56EF 67FG 71GA
15AE 52EB 26BF 63FC 37CG 74GD 41DA
13AC 35CE 57EG 72GB 24BD 46DF 61FA
12DE 23EF 34FG 45GA 56AB 67BC 71CD
15FC 52CG 26GD 63DA 37AE 74EB 41BF
13GB 35BD 57DF 72FA 24AC 46CE 61EG
12FG 23GA 34AB 45BC 56CD 67DE 71EF
15GD 52DA 26AE 63EB 37BF 74FC 41CG
13DF 35FA 57AC 72CE 24EG 46GB 61BD

```

```
[[0, 1, 2, 4], [1, 2, 3, 5], [2, 3, 4, 6], [3, 4, 5, 0], [4, 5, 6, 1], [5, 6, 0, 2], [6, 0, 1, 3], [7, 13, 12, 10], [13, 12, 11, 9], [12, 11, 10, 8], [11, 10, 9, 7], [10, 9, 8, 13], [9, 8, 7, 12], [8, 7, 13, 11], [0, 1, 5, 9], [1, 2, 6, 10], [2, 3, 0, 11], [3, 4, 1, 12], [4, 5, 2, 13], [5, 6, 3, 7], [6, 0, 4, 8], [7, 13, 9, 5], [13, 12, 8, 4], [12, 11, 7, 3], [11, 10, 13, 2], [10, 9, 12, 1], [9, 8, 11, 0], [8, 7, 10, 6], [0, 1, 7, 8], [1, 2, 8, 9], [2, 3, 9, 10], [3, 4, 10, 11], [4, 5, 11, 12], [5, 6, 12, 13], [6, 0, 13, 7], [0, 4, 7, 11], [4, 1, 11, 8], [1, 5, 8, 12], [5, 2, 12, 9], [2, 6, 9, 13], [6, 3, 13, 10], [3, 0, 10, 7], [0, 2, 7, 9], [2, 4, 9, 11], [4, 6, 11, 13], [6, 1, 13, 8], [1, 3, 8, 10], [3, 5, 10, 12], [5, 0, 12, 7], [0, 1, 10, 11], [1, 2, 11, 12], [2, 3, 12, 13], [3, 4, 13, 7], [4, 5, 7, 8], [5, 6, 8, 9], [6, 0, 9, 10], [0, 4, 12, 9], [4, 1, 9, 13], [1, 5, 13, 10], [5, 2, 10, 7], [2, 6, 7, 11], [6, 3, 11, 8], [3, 0, 8, 12], [0, 2, 13, 8], [2, 4, 8, 10], [4, 6, 10, 12], [6, 1, 12, 7], [1, 3, 7, 9], [3, 5, 9, 11], [5, 0, 11, 13], [0, 1, 12, 13], [1, 2, 13, 7], [2, 3, 7, 8], [3, 4, 8, 9], [4, 5, 9, 10], [5, 6, 10, 11], [6, 0, 11, 12], [0, 4, 13, 10], [4, 1, 10, 7], [1, 5, 7, 11], [5, 2, 11, 8], [2, 6, 8, 12], [6, 3, 12, 9], [3, 0, 9, 13], [0, 2, 10, 12], [2, 4, 12, 7], [4, 6, 7, 9], [6, 1, 9, 11], [1, 3, 11, 13], [3, 5, 13, 8], [5, 0, 8, 10]]

```

If you have your system in list-of-lists format like the second example you may verify it is a Steiner quadruple system here.

---

Thanks to @DLosc for help with the phrasing.

# Answer
# Python, 85 bytes

```
print({(*sorted((i*3**j+j)%14for i in[1,5,j%5^22,9910>>j%5*4]),)for j in range(210)})

```

Try it online!

Outputs {(0, 1, 4, 5), (6, 8, 11, 12), (1, 7, 9, 11), (2, 3, 12, 13), (2, 4, 9, 11), (0, 6, 7, 13), (4, 5, 11, 12), (4, 8, 10, 12), (8, 9, 10, 11), (2, 6, 9, 13), (1, 2, 5, 7), (3, 5, 7, 11), (1, 3, 7, 13), (0, 1, 2, 3), (1, 4, 8, 11), (0, 2, 11, 13), (2, 7, 10, 13), (1, 6, 8, 13), (2, 7, 11, 12), (8, 9, 12, 13), (0, 1, 12, 13), (0, 2, 4, 10), (4, 6, 11, 13), (0, 4, 6, 8), (1, 4, 9, 12), (2, 4, 6, 12), (4, 5, 10, 13), (3, 4, 10, 11), (4, 7, 12, 13), (0, 8, 10, 13), (1, 2, 10, 12), (0, 1, 10, 11), (0, 2, 8, 12), (5, 7, 8, 10), (10, 11, 12, 13), (0, 4, 7, 11), (6, 7, 10, 11), (3, 4, 8, 13), (0, 1, 7, 8), (3, 9, 11, 13), (3, 7, 8, 12), (0, 3, 4, 12), (0, 2, 5, 6), (0, 4, 9, 13), (0, 1, 6, 9), (0, 3, 8, 9), (2, 4, 7, 8), (0, 5, 8, 11), (5, 6, 9, 11), (1, 3, 8, 10), (1, 5, 8, 12), (1, 3, 11, 12), (1, 3, 4, 6), (1, 2, 8, 9), (0, 3, 7, 10), (0, 3, 5, 13), (2, 5, 10, 11), (6, 7, 8, 9), (2, 3, 4, 5), (1, 9, 10, 13), (2, 3, 6, 7), (1, 5, 6, 10), (4, 6, 9, 10), (3, 5, 6, 8), (3, 6, 9, 12), (0, 5, 9, 10), (0, 6, 10, 12), (5, 7, 9, 13), (0, 5, 7, 12), (5, 6, 12, 13), (0, 9, 11, 12), (7, 9, 10, 12), (3, 6, 10, 13), (4, 5, 8, 9), (0, 3, 6, 11), (3, 4, 7, 9), (7, 8, 11, 13), (1, 4, 7, 10), (2, 3, 8, 11), (1, 6, 7, 12), (2, 3, 9, 10), (1, 5, 11, 13), (2, 5, 8, 13), (2, 5, 9, 12), (2, 6, 8, 10), (1, 2, 6, 11), (1, 3, 5, 9), (3, 5, 10, 12), (1, 2, 4, 13), (4, 5, 6, 7), (0, 2, 7, 9)}.
> 14 votes

# Answer
# Vyxal, 182 bytes

```
»∨vw\\ẇẆ|ετfẆτ›≥Πo∩Ṗ…›Ẏ⟑ȮĠḃ…°Ṗ5=₴ƛ¯⇩7¡∇∞}⁺εḭ>∑‛u²%¤ßǔ]‡∨ε⁼Ġ†ȧ£€Ż₁T±↑⁋N∵ɽE"@∩⁺ ≤Ǐ0¬ė⅛6⌈0ż⇧⌊≈ŀ¬∑ȮW√꘍↓ṗX→≥bOÞẇṀÞ≈¢e5Ṙẏð₀ꜝ→£∴∑↑›∇₇⋏o½↓t¼¨8¾‹O¾ṪO\ȧ₁↑żẆðŀErc⊍≤λ?↓ṙ…k;,ε÷5M<ṅǒR‡,∩ŻIλ»14τṘ4ẇ

```

Try it Online!

This just hardcodes the result.

```
»...»       # Base-255 compressed integer
     14τ    # Convert to base 14
        Ṙ   # Reverse (because leading zero)
         4ẇ # Chunks of length 4

```

Or, if we're allowed to take a few universe lifetimes:

# Vyxal, 20 bytes

```
14ɾ364↔'4ẇ3vḋÞf:U⁼;h

```

Try it Online!

This is a horrendously inefficient bruteforcer. It computes all \\$14^{364}\\$* sets of 14 symbols of length 364, for each gets combinations of three elements and checks if they all appear once.

The last two bytes can be removed if we're allowed to output all such sets.

```
14ɾ                  # 1...14
   364↔              # Combinations of length 364
       '          ;h # Find one such that...
        4ẇ           # When grouped into lengths of 4
          3vḋÞf      # And all subsets of length 3 within those lists
               :U⁼   # Does it include all subsets exactly once?

```

* Roughly 10^400, so give it a few universe lifetimes
> 3 votes

# Answer
# JavaScript (ES6), 229 bytes

Returns a rearranged version of the example \\$SQS(14)\\$ with symbols \\$1\\$ to \\$9\\$ and \\$a\\$ to \\$e\\$.

```
x=>`2zmGWS01bV02fOWIS3j01dGF4uHUF4yC01b4kQVbm1hk01dHA01b3b015F01b3jXFG5cFU4yFCj61hk01aV01b3bSCF5dFF5dFFpt1ikAV4gZCF5dFF6m27gVV4h01bFcw27gVV4z2l82sgU5r742en6m2sf`.match(/[A-Z]|[012]?../g).map(s=>(x=parseInt(s,36)-~x).toString(15))

```

Try it online!
> 2 votes

# Answer
# Charcoal, 180 bytes

```
⪪”$↶⧴F»ＺÀ{ＸＢS↧⁺ＭDu➙{ν%↘Ｄ12Ｗ?xV_*o}ηφ|Xη&S↗[-W⦄[×±α_M«Sl5 rυ№|↷ηx?«Xü¡×=ＩvＭ±＆3i◧5¿Ｃ№⟦sB⁴σχ？‽∨Ｋ↷¤⌊﹪➙νηＴ\⎚ι‴;Ｚ8←$�✳L\`κⅈ5·⊖；,⊙ς7qo⊞▶ïsG⁻Yωr§ς1Ｃ-Cτ＆≔⊞7ＡηγpβＤ9a›ω ≔1“Þω⬤m@‖ＰEI↙⊕≕¦·G*Ｆρ”⁴

```

Try it online! Link is to verbose version of code. Outputs values `A`-`N`. Explanation: Splits a compressed string into chunks of 4.
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, combinatorics, open-ended-function, combinatorial-design
---


title: Find my other token (Cops)

text:
# Question
Title: Find my other token (Cops)
Robbers thread

Cops,

Choose two strings of code, one public and one secret. We will call them P and S. You will be writing a program using only repetitions of these strings.

For example: if you choose P=`hello`and S=`world`, valid programs would be `hello`, `world`, `helloworld`, `worldhello`, `helloworldworldhello`, `hellohellohelloworld`, etc. You are not allowed to add anything else to your code or modify these strings, so `hello world`, `HelloWorld`, `heellowoorld` and `elloword` would all be invalid programs.

### The program

Using only strings P and S, write a program which takes a list of 5 or more non-repeating positive integers, and returns them reordered such that the maximum of the list is in the center, the elements before it are in ascending order, and the elements after it are in descending order. You can output any list that meets these requirements. You may assume the list has an odd number of elements.

Examples (your outputs may differ):

```
input: [1,2,3,4,5]
output: [1,2,5,4,3]

input: [7,6,5,4,3,2,1]
output: [2,4,6,7,5,3,1]

input: [1,3,5,7,9,2,4,6,8]
output: [1,2,3,7,9,8,6,5,4]

```

In your answer, specify which language is used, your exact P string, the bytecount of your S string, and how many of each P and S you used.

Do **not** show your actual code, and do **not** show your S string.

### Scoring

Your score is the combined length of your P and S strings in bytes. If your answer has not been cracked in a week, you may mark it as safe. Lowest scoring safe answer wins.

# Answer
> 6 votes
# , 10 + 24 bytes, safe

```
x=scan();x

```

Try it online!

The 'P' string is used once; the 'S' string is 24-bytes long and used twice.

---

## Solution

> We achieve the task by making every second element negative, and then sorting the reciprocals. In this way, the largest values (whose reciprocals are closest to zero) are sorted to the middle. After sorting, we need to undo the negatives and undo the reciprocals to get the original elements back, in their new sorted order.
> Intuitively, we could do all this in one step: reciprocal -\> every\_2nd\_negative -\> sort -\> reciprocal -\> absolute\_value; or in actual R code: `x=abs(1/sort(1/x*c(-1,1)))`.
> However, since the order of the initial array doesn't matter (we're going to rearrange it anyway), we can do the reciprocal only once in a first step (so we end up with rearranged reciprocals of the input values), and then repeat the entire step again. So: two rounds of: every\_2nd\_negative -\> sort -\> reciprocal -\> absolute\_value; or in actual R code: `x=abs(1/sort(x*c(-1,1)))`.
> This saves 2-bytes (at the expense of uselessly sorting & flipping the signs twice in the first step), hopefully making it impossible to find a solution as short that will work in only one step. Of course, we need to be certain that the R code is fully-golfed: so, the final secret string 'S' is: `=abs(.5/sort(x*-.5:1));x`.

Try it online!

# Answer
> 5 votes
# JavaScript (ES6), 66 + 39 bytes Cracked

Each string is used once.

```
f=a=>(g=a=>a+a?_([_(a,26393),...g(a)],29493784462):a)(_(a,942973))

```

Try it online!

## Solution

### Clue 1

> The non-obfuscated code is:
>
> ```
> f=a=>(g=a=>a+a?[a.pop(),...g(a)].reverse():a)(a.sort((a,b)=>b-a))
> ```

### Clue 2

> The numbers encode the strings `"pop"`, `"reverse"` and `"sort"` in base 32.

### Secret string

> ```
> _=(a,x)=>a[x.toString(32)]((a,b)=>b-a);
> ```

# Answer
> 5 votes
# Python 3, 25 + 22 Safe (Orginal solution)

```
def f(a):a.sort();return

```

Both strings are used once each. No list slicing used.

Solution:

> `def f(a):a.sort();return a+[a.pop() for z in a]`

Try it online!

# Python 3, 25 + 16 Cracked!

```
def f(a):a.sort();return

```

Both strings are used once each

Try it online!

# Answer
> 4 votes
# Haskell, 108 + 14

*This is old enough to be safe but I'm leaving it open, because that's more fun anyway*

Not too hard `;)`. I give you some helper functions here and you have to define the body of `f` in terms of them.

```
x#(y:z)|y>x=y:(x#z)
x#z=x:z
(x!y)(z:w)=z#y!x$w
((x:y)!(z:w))_|x<z=z:x:w?y|1>0=x:z:w?y
x?(y:z)=y:x?z
x?_=x
f=

```

It's 1 of each string. Which makes this pretty much just a fill in the blank challenge. Unfortunately it's kind of hard to make something which repeats segments in Haskell. But hopefully this should at least be a fun puzzle.

# Answer
> 4 votes
# Javascript, 27+32 bytes, safe (link to solution)

```
x=>x.sort((a,b)=>a-b).map(x

```

I decide to allow crack if a quite different solution comes, though it's now claimed safe

# Javascript, 27+36 bytes, cracked

```
x=>x.sort((a,b)=>a-b).map(e

```

# Javascript, 26+37 bytes, cracked

```
x=>x.sort((a,b)=>a-b).map(

```

Try it online!

# Answer
> 3 votes
*This is my first time doing a cops and robbers and I'm still a little confused so correct me if I did something wrong*

## Python 3, 21+33 bytes - Cracked!

```
def f(i):m=len(i)//2;

```

Both strings are used once.

Attempt it online!

## Python 3, 20+36 bytes - Cracked!

```
def f(a):m=len(a)//2

```

Both strings are used once.

Attempt it online!

## Python 3, 21+43 bytes

```
def f(a):m=len(a)//2;

```

Both strings are used once.

Attempt it online!

# Answer
> 3 votes
# Husk, 2 + 5 bytes, safe

```
øO

```

Try it online!

The 'P' string (above: 2 bytes) and the 'S' string (5 bytes) are used twice each.

Husk \- like many golfing languages - has a short direct solution to the task: `Ċ2S+↔O` (6 bytes), and, annoyingly, the usually-fussy Husk interpreter is sufficiently lenient to allow this as a runnable program in combination with anything else on subsequent lines: try it here.
Thus, any 'S' string needs to be shorter than this (or, actually, this plus a newline character) to avoid being trivially-cracked.
Luckily, I don't think Husk has any easy way to implement 'execute this as Husk code' or similar, so I hope that brute-forcing the 5-byte solution should be difficult, at least within Husk itself...

---

## Solution

> This is a variant of the 'fold across each value of the sorted data, alternately appending to the front or to the back of the output-so-far' approach.
> This requires that the data is sorted in descending order, so that the first value added to the output is the largest, and then successively smaller values are added to the front & back. However, Husk's single-byte 'sort' command (`O`) sorts in ascending order.
> So, instead of explicitly using a descending sort (which in Husk would be 'sort on greater than', or `Ö>`), we achieve the same thing by sorting reciprocals in two passes.
> In the first pass, the data are sorted with the (modified) smallest element in the centre, but the results are the reciprocals of all the data. In this way, in the second pass, the data are re-sorted with the largest original element (now the smallest because it's the reciprocal) in the centre, and all the elements are re-reciprocal-ed to restore their original values.
> The code for each pass is `F~:↔\øO`, and secret string 'S' is the first 5 bytes of this: `F~:↔\`.
>
> ```
>
>       O   # sort in ascending order,
> F         # then fold over the values,
>      ø    # using an empty list as an intial result-so-far, by
>  ~:       # prepending
>     \     # the reciprocal of each value
>    ↔      # to the reverse of the result-so-far
> ```

Try it online!

# Answer
> 2 votes
# J, 1 + 9, cracked

```
~

```

Each string used once.

So, a 10 byte golf that ends in `~`. Easy, easy.

# Answer
> 2 votes
# Husk, 1 + 5 bytes

Try it online!

The 'P' string (above: 1 byte) is used once; the 'S' string (5 bytes) is used twice.

A better-scoring, different (...or is it...?) approach to my previous Husk answer.
Shorter should be easier-to-crack, possibly...

---

Note to Husk golfers and wannabee Husk golfers\*: The week is now up without any crack yet, so I will offer a **100 rep** bounty for the first crack of this, or **200 rep** if it's the cracker's first Husk post.

\*wannabee Husk golfers: Here are the docs and tutorial...

# Answer
> 1 votes
# Bash, 1 + 29

```
'

```

Each string appears once. So, a 30 byte bash golf that begins or ends with a single quote.

To clarify, this doesn't have to be pure bash, but can include standard posix utils (awk, sed, grep, tr, etc, but no python or ruby or perl, etc). Input can be taken as one number per line, space-separated chars, comma-separated chars, or anything else reasonable.

# Answer
> 1 votes
# Pip `-xp`, 11 + 4 bytes (cracked)

```
FiRSNalPBi&

```

The P-string (11 bytes) is used once; the S-string (4 bytes) is used twice.

Attempt This Online!

---

My original solution:

> S-string `R:l;`, full program `FiRSNalPBi&R:l;R:l;`: Each time through the loop, reverse `l` in-place. After the loop, reverse `l` in-place one more time and autoprint it. The semicolon is an expression separator.

# Answer
> 1 votes
# Pip `-xp`, 8 + 7 bytes (cracked)

```
SN:a;R:a

```

The P-string (8 bytes) and the S-string (7 bytes) are used once each.

Attempt This Online!

---

Dominic van Essen's crack is quite clever and is also very different from my intended solution. I'm going to think if there's a way to reuse the same idea before I decide whether to reveal it.

---
Tags: cops-and-robbers
---


title: Quote-Safe Quines

text:
# Question
Title: Quote-Safe Quines
Your task is simple: write a program (or function) that takes no input and outputs (or returns) its source code. The catch is that when the program is wrapped in `"quotes"` (Unicode character 34), it should again output its (now quoted) source code.

Standard rules for quines apply. This is , so the shortest program (in bytes) wins.

# Answer
# Noodel, ~~9~~ 7 bytes

This version works the same way as the other, just that I forgot that *Noodel* has a way to run a block of code once and I made the language...

~~`Ḷ1ḥ-Ð1ḥ@€`~~

```
ḷḥ-Ðḥ@ḅ

```

Try it:)

---

### How it Works

```
ḷḥ-Ðḥ@ḅ # Single statement that builds itself as a string.
ḷ       # Loop the following block of code unconditionally.
 ḥ-     # Push the string literal of the token preceding this one which pushes "ḷ" onto the stack.
   Ð    # Push the stack as an array to stdout (since is an array it is done by reference).
    ḥ@  # Push the string literal for this block of code which pushes "ḥ-Ðḥ@ḅ" onto the stack.
      ḅ # Break out of the given loop. (The stack is now ["ḷ", "ḥ-Ðḥ@ḅ"]).

        # The top of the stack is popped off and displayed which modifies the array to produce {["ḷ"], "ḥ-Ðḥ@ḅ"} in stdout.

```

---

### Quote-Safety

Placing the `"` character before and after the program works because *Noodel* has a set of of characters dedicated to what I call *printables*. These are immediately parsed as string literals when placed by themselves and allow for easily printing something to the screen. So unlike most languages, *Noodel* sees the normal *ASCII* set that is considered print worthy as direct string literals (except for space and line feed) therein quoting the code is merely seen as pushing on strings.

```
"ḷḥ-Ðḥ@ḅ"

"         # Pushes on the string literal "\"" onto the stack.

 ḷḥ-Ðḥ@ḅ  # Same execution as before, simply builds the Quine for this loop.
 ḷ        # Loop the following block of code unconditionally.
  ḥ-      # Push the string literal of the token preceding this one which pushes "ḷ" onto the stack.
    Ð     # Push the stack as an array to stdout (since is an array it is done by reference).
     ḥ@   # Push the string literal for this block of code which pushes "ḥ-Ðḥ@ḅ" onto the stack.
       ḅ  # Break out of the given loop. (The stack is now ["\"", "ḷ", "ḥ-Ðḥ@ḅ"]).

        " # Pushes on the string literal "\"" onto the stack.

          # The top of the stack is popped off and displayed which modifies the array to produce {["\"", "ḷ", "ḥ-Ðḥ@ḅ"], "\""} in stdout.

```

"Try it:)"

---

### Snippets

```
<div id="noodel" code='ḷḥ-Ðḥ@ḅ' input="" cols="10" rows="1"></div>
<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```

---

```
<div id="noodel" code='"ḷḥ-Ðḥ@ḅ"' input="" cols="10" rows="1"></div>
<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 6 votes

# Answer
# Python ~~2~~ 3, ~~181~~ ~~152~~ ~~130~~ ~~124~~ ~~122~~ ~~100~~ ~~98~~ ~~96~~ 84 bytes

*-12 bytes thanks to Jakque.*

```
a=1;""";a=0;" """;p='"a=1;""";a=0;" """;p=%r;print(p[a:~a]%%p)#".';print(p[a:~a]%p)#

```

Try it online! The TIO comes with a header and footer that automatically test the validity of the quine. You can clear them to just run the quine.

This code works by (ab)using the triple-quoted strings and string literal concatenation in Python.

* `";b=""";b=" """;` ignores `';b='` and sets `b` to `' '`.
* `"";b=""";b=" """;` ignores the empty string and sets `b` to `';b=" '`.

The rest of the code then implements the traditional Python quine using `%r` string formatting, with some additional code that strips the extra quotes depending on `b`.

## Older version from 2017, 122 bytes

```
""" """>" "or exec("oct=0");p='"""" """>" "or exec("oct=0");p=%r;a=oct==0;print(p[a:~a]%%p)#".';a=oct==0;print(p[a:~a]%p)#

```

Try it online!

`""" """` is equal to `' '` and `"""" """` is equal to `'" '`.

The code does use `exec`, but not for the "non-quiney" way of executing data as code, just for setting a variable from inside an expression. The `exec` is properly encoded in the data, too.

The first statement compares the string, possibly with a quote prepended, to `" "`, and sets the variable `oct` accordingly. (The variable could've been any short builtin.) The final part then checks if `oct` is unchanged.

An alternative version using the "cheaty" `exec` comes in at 126 bytes with less repeated code:

```
""" """>" "and exec("oct=0");s='"""" """>" "and exec("oct=0");s=%r;p=%r;exec(p)#".';p='a=oct!=0;print(s[a:~a]%(s,p))';exec(p)#

```

Try it online!
> 14 votes

# Answer
# StandardML, ~~182 176~~ 108 bytes

```
";str(chr 34)^it;(print(it^it);fn x=>print(x^it^x^it))";str(chr 34)^it;(print(it^it);fn x=>print(x^it^x^it))

```

Unquoted version: Try it on codingground.
Quoted version: Try it on codingground.

Note that the output looks something like this

```
> val it = "{some string}" : string
> val it = "{some string}" : string
{output to stdout}> val it = fn : string -> unit

```

because the code is interpreted declaration by declaration (each `;` ends a declaration) and shows the value and type of each declaration.

---

### Background

In SML there is a quine of the form `<code>"<code in quotes>"`:

```
str(chr 34);(fn x=>print(x^it^x^it))"str(chr 34);(fn x=>print(x^it^x^it))"

```

and one in the form `"<code in quotes>"<code>`:

```
";str(chr 34)^it;print(it^it)";str(chr 34)^it;print(it^it)

```

Both rely on the fact that the `<code>`-part contains no quotes and can thus be quoted with out the need for escaping anything, the `"` needed to output the quine are given by `str(chr 34)`.

They also heavily rely on the implicit identifier `it` which is used when no explicit identifier is given in a declaration.

In the first quine `str(chr 34);` binds `it` to the string containing `"`, `fn x=>` starts an anonymous function taking one argument `x`, then concatenates `x^it^x^it` and prints the resulting string. This anonymous function is directly applied to a string containing the program code, so the concatenation `x^it^x^it` yields `<code>"<code>"`.

The second quine starts with just the program code as string `";str(chr 34)^it;print(it^it)";` which is bound to `it`. Then `str(chr 34)^it;` concatenates a quote to the start of the string and as again no explicit identifier is given, the resulting string `"<code>` is bound to `it`. Finally `print(it^it)` concatenates the string with itself yielding `"<code>"<code>` which is then printed.

---

### Explanation

***Edit:** No longer up to date with the 108-byte version, however one might understand it too after reading this explanation.*

The quote-safe quine combines both of the above approaches and is itself of the form `"<code>"<code>`. Putting this in again in quotes yields `""<code>"<code>"`, so we get an empty string and then a quine of the other form.

That means the program is either given its own source in the form `"<code>` by the identifier `it`, or `it` is just `"` and we are given our own source `<code>` as argument and must thus be a function which handles such an argument.

```
(if size it>1then(print(it^it);fn _=>())else fn x=>print(it^it^x^it^x^it))

```

To identify in which case we are, we check whether the size of `it` is larger than 1. If not then `it` is `"` and we are in the second case, so the `else`-part returns an anonymous function `fn x=>print(it^it^x^it^x^it)` which is then called because its followed by source as string. Note the leading `it^it^` which is needed for the empty string at the start of the of the program.

If `size it` is larger than 1 we are in the `then`-part and just perform `print(it^it)`, right? Not quite, because I neglected to tell you that SML is strongly typed which means that a conditional `if <cond> then <exp_1> else <exp_2>` must always have the same type which again means that the expressions `<exp_1>` and `<exp_2>` need to have the same type. We already know the type of the `else` part: An anonymous function which takes a string and then calls `print` has type `string -> <return type of print>`, and `print` has type `string -> unit` (`unit` is in some way similar to `void` in other languages), so the resulting type is again `string -> unit`.

So if the `then` part was just `print(it^it)` which has type `unit`, we would get a type mismatch error. So how about `fn _=>print(it^it)`? (`_` is a wildcard for an argument that is not used) This anonymous function on its own has type `'a -> unit` where `'a` stands for an arbitrary type, so in the context of our conditional which enforces a `string -> unit` type this would work. (The type variable `'a` gets instantiated with type `string`.) However, in this case we would not print anything as the anonymous function is never called! Remember, when we go in the `then`-part the overall code is `"<code>"<code>`, so the `<code>`-part evaluates to a function but, as nothing comes after it, its not called.

Instead we use a sequentialisation which has the form `(<exp_1>; ...; <exp_n>)` where `<exp_1>` to `<exp_n-1>` may have arbitrary types and the type of `<exp_n>` provides the type of the whole sequentialisation. From a functional point of view the values of `<exp_1>` to `<exp_n-1>` are simply discarded, however SML also supports imperative constructs so the expressions may have side effects. In short, we take `(print(it^it);print)` as the `then`-part, thus printing first and then returning the function `print` which has the correct type.
> 8 votes

# Answer
# , ~~27~~, 23 bytes

```
éPñi"éP241"qpá"lxx|xÿ

```

Try it online!

Since this contains some unprintable characters, here is a readable version:

```
éPñi"éP<C-v>241<esc>"qpá"lxx|xÿ

```

and here is a hexdump:

```
00000000: e950 f169 22e9 5016 3234 311b 2271 70e1  .P.i".P.241."qp.
00000010: 226c 7878 7c78 ff                        "lxx|x.

```

So the very first thing we need to do is to determine if the first character is a quote. `éP` inserts a 'P' character, but `"éP` is a NOOP. After that, we run a slight modification on the standard extendable quine, which is:

```
ñi<C-v>241<esc>"qpÿ

```

We're going to do it slightly differently though. First off we need to insert the starting "éP" text. So we do

```
ñ                        " Start recording into register 'q'
 i                       " Enter insert mode
  "éP<C-v>241<esc>       " Enter the following text: '"éPñ'
                  "qp    " Paste the text in register 'q'
                     á"  " Append a '"'

```

Here is where the branching happens. The text currently in the buffer is

```
"éPñi"éP<C-v>241<esc>"qpá"P
Cursor is here ----------^

```

Unless we wrapped it in quotes, in that case the 'P' would never have been inserted, and the buffer is:

```
"éPñi"éP<C-v>241<esc>"qpá"
Cursor is here ----------^

```

Since we are still recording, we can do whatever we want here, and it will get added to the buffer when the `"qp` happens. So from here it's pretty easy to conditionally delete the quotes:

```
l           " Move one character to the right. If there is no character to the right,
            " then this is effectively a "break" statement, stopping playback of the recording
 xx         " Delete two characters (the '"P')
   |        " Move to the first character on this line
    x       " Delete one character
     ÿ      " End the program

```
> 7 votes

# Answer
# JavaScript (ES6), ~~239~~ 237 bytes

```
Set=``;eval(";a='Set=``;eval(~;a=1;S=String.fromCharCode;q=S(34);r=Set&&q;s=S(39);alert(r+a.replace(/[^ -}]/g,q).replace(1,s+a+s)+r);~)';S=String.fromCharCode;q=S(34);r=Set&&q;s=S(39);alert(r+a.replace(/[^ -}]/g,q).replace(1,s+a+s)+r);")

```

Take care to try each version in a fresh environment (e.g., a new browser tab)

There has got to be at least one way to simplify this...
> 4 votes

# Answer
# Perl 5, 59 bytes

```
";$\=q;";;$_=q(print$\,'";$\=q;";;$_=q('."$_);eval#");eval#

```

Try it online!

## Quoted

```
"";$\=q;";;$_=q(print$\,'";$\=q;";;$_=q('."$_);eval#");eval#"

```

Try it online!

## Explanation

In the original, there is an unused string `";$\=q;"` separated by `;;` before the standard quine body which first `print`s `$\` (which is empty by default) followed by the unused string and the body followed by `#`.

In the quoted string, there is an unused string `""`, separated by `;` then `$\` is set to `q;";` which is Perl's custom quotes `q;...;` wrapping the double-quote char. Then the quine body is built and `$\` is automatically `print`ed after all content adding the final `"` in the quoted string.
> 2 votes

# Answer
# Python 2, 68 bytes & Python 3, 70 bytes

## Python 2, 68 bytes:

```
x=""#";x='"'
s='x=""#";x=\'"\'\ns=%r;print x+s%%s+x#';print x+s%s+x#

```

Try it online!

## Python 3, 70 bytes:

```
x=""#";x='"'
s='x=""#";x=\'"\'\ns=%r;print(x+s%%s+x)#';print(x+s%s+x)#

```

Try it online!

## How does it work? :

* Without quotes: `x=""#";x='"'` will stop the execution at the coment `#` char =\> `x=""`
* With quotes: `"x=""#";x='"'` have just 2 string concatened `"x="` and `"#"` which don't do anything, and an assignation : `x='"'`

Now `x` is filled with the good char (quote or empty).

We use then the standard python quine : `s='s=%r;print(s%%s)';print(s%s)` adding a few extras to make it work here, for example `#` at the end to avoid an EOF Error when a `"` is added at the end of the program

Then, we just print our quine adding `x` at the start and at the end of the string
> 2 votes

# Answer
# Vyxal `D`, 29 bytes

```
`Dqp^≈[_\\"pǏ]₴`Dqp^≈[_\"pǏ]₴

```

Try it Online!

Explained:

```
`...`Dqp^≈[_\"pǏ]₴
`...`                 Push half the source code
     D                Make 3 copies of the source code
      qp              Uneval the first copy (quote, escape) and prepend it to the second
        ^             Reverse the stack
         ≈[_\"pǏ]     Execute if all elements are the same.
                      Since this is not the case, it just pops the third copy of the source code
                 ₴    Print the source

```

Quoted version: ("Try it Online!")

```
"`...`Dqp^≈[_\"pǏ]₴"
"                       Push the set [0, 0]
 `...`                  Push the source code
      D                 Make 3 copies of the source code
       qp               Uneval the first copy and prepend it to the second
         ^              Reverse the stack, putting [0, 0] on the top
          ≈[     ]      Execute if all elements of the top of the stack are the same.
                        This is the case because of the [0, 0] pushed by "
            _           Remove the third copy of the source from the stack
             \"         Push `"`
               pǏ       Prepend and enclose the source with `"`
                  ₴     Print the source
                   "    Push [0, 0], having no effect because the source is already printed

```
> 2 votes

# Answer
# Haskell, 142 bytes

```
--"#p=p['"']>>"--\""#p
k#p=p x>>print x>>p k;main="--"#putStr;x="--\"#p=p['\"']>>\"--\\\"\"#p\nk#p=p x>>print x>>p k;main=\"--\"#putStr;x="
--

```

Try it online!

```
"--"#p=p['"']>>"--\""#p
k#p=p x>>print x>>p k;main="--"#putStr;x="--\"#p=p['\"']>>\"--\\\"\"#p\nk#p=p x>>print x>>p k;main=\"--\"#putStr;x="
--"

```

Try it online!

This uses a pretty simple detection method.

The first line is normally a comment.

```
--"#p=p['"']>>"--\""#p

```

However when a quote is added to the front

```
"--"#p=p['"']>>"--\""#p

```

It becomes the declaration of an operator `(#)`. So what this program does is defines `(#)` such that it prints the normal source for when called with `"--"#putStr`, however when the quotes appear the new definition supersedes it and prints the source with quotes.
> 2 votes

# Answer
# Vyxal `D`, ~~18~~ 17 bytes

## Normal

```
`q‛:Ė+$[‛""$j,`:Ė

```

Try it Online!

## Quoted

```
"`q‛:Ė+$[‛""$j,`:Ė"

```

Try it Online!

## Explanation :

```
# Normal

`q‛:Ė+        `   # structure for a quine  => [ <quine> ]
               :Ė # add a copy of the structure on the stack and exec it
 q                # push the quoted string on the stack => [ `<quine>` ]
  ‛:Ė+            # add ':Ė' to the string on the stack => [ `<quine>`:Ė ]
      $           # swap the two values on top of he stack => [ `<quine>`:Ė , 0 ]
       [          # pop and check if it is nul (it is) => [ `<quine>`:Ė ]
        ‛""$j,    # irrevelent here
                  # implicit output

# Quoted

"                 # listify the two elements on top of the stack => [ [0,0] ]
`q‛:Ė+        `   # structure for a quine  => [ [0,0] , <quine> ]
               :Ė # add a copy of the structure on the stack and exec it
 q                # push the quoted string on the stack => [ [0,0] , `<quine>` ]
  ‛:Ė+            # add ':Ė' to the string on the stack => [ [0,0] , `<quine>`:Ė ]
      $           # swap the two values on top of he stack => [ `<quine>`:Ė , [0,0] ]
       [          # pop and check if it is nul (it is not as it's a list) => [ `<quine>`:Ė ]
        ‛""       # add `""` to the stack => [ `<quine>`:Ė, `""` ]
           $j     # swap the two elements and join => [ "`<quine>`:Ė" ]
             ,    # print => []
                " # listify the two elements on top of the stack => [ [0,0] ]
                  # no implicit output as it has already printed via ,

```
> 2 votes

# Answer
# Zsh, 76 bytes

```
: "||z=\" #"
s=': "||z=\" #"
s=\47%s\47
printf $z$s$z $s
'
printf $z$s$z $s

```

Try it online!

"Try it online!"

Note the trailing newline.

Without the quotes, the first line is a call to the built-in no-op `:`, which ignores its string argument `||z=" #`. The variable `z` remains empty.

With quotes, the first line is:

* `": "`: execute `:`  (note the space), which is a non-existent command
* `||`: if this fails (which it will, since `:`  doesn't exist), then:
* `z=\"`: set the variable `z` to a single double-quote `"`
* `#"`: comment; ignored

The extra `"` on the last line is unmatched, but zsh helpfully ignores that until after the program has executed because it's a separate command line.

The rest is a pretty standard shell quine, but we surround the string with `$z` so it gets double quotes if necessary.
> 1 votes

---
Tags: code-golf, string, quine, source-layout
---