# Question
Title: Implement the Conjunction of a Three-Valued Logic
Your task, should you choose to accept it, is to take two input values \\$a\\$ and \\$b\\$, where \\$a\\$ and \\$b\\$ are in the set \\$\\{T, U, F\\}\\$, and compute and output their logical conjunction in a three-valued logic system.

A three valued logical conjunction is this transformation:

| a | b | output |
| --- | --- | --- |
| U | U | U |
| U | F | F |
| F | U | F |
| U | T | U |
| T | U | U |
| F | F | F |
| F | T | F |
| T | F | F |
| T | T | T |

## I/O Rules

You have to take as an input two characters \\$a\\$ and \\$b\\$, where \\$a\\$ and \\$b\\$ are `T`, `U`, or `F`.

You have to output one of `F`, `T`, or `U`, with an optional trailing newline.

These very restrictive I/O rules help prevent trivial solutions.

### Example Program (in Nim)

```
proc f(s: string): char =
  if s[0]=='F' or s[1]=='F':return 'F'
  if s[0]=='U' or s[1]=='U':return 'U'
  if s[0]=='T' and s[1]=='T':return 'T'

```

Attempt This Online!

# Answer
> 15 votes
# Python, 22 bytes

```
lambda s:s["T"<s<"UT"]

```

Try it online!

# Answer
> 7 votes
# Jelly, 6 bytes

```
O%4µÞṪ

```

Try It Online!

```
O%4µÞṪ  Main Link
    Þ   Sort by
O       ord (codepoint)
 %4     modulo 4
     Ṫ  Take the last character

```

-1 byte thanks to emanresu A by not closing the string
-3 bytes thanks to Kevin Cruijssen by sorting the original characters instead of indexing back into "FUT"

This at its core works the same as the original "map by `O%4` → take max → index back into `FUT`" but instead of actually indexing it just sorts by the `O%4` key which puts the max (the answer) at the end which is extracted with .

# Answer
> 7 votes
# Python 2, 24 bytes

```
lambda s:s[s in'TUF TF']

```

Try it online!

**Alternative Solution**

```
lambda s:s[hash(s)/22%2]

```

# Answer
> 5 votes
# x86 32-bit machine code, 9 bytes

```
37 38 D1 37 91 0F 42 C2 C3

```

Try it online!

Uses the `fastcall` calling convention, this takes two characters in CL and DL and returns a character in AL.

In assembly:

```
f:  aaa
    cmp cl, dl
    aaa
    xchg ecx, eax
    cmovc eax, edx
    ret

```

The character codes of F, U, T are 0x46, 0x55, 0x54 respectively. Notice that the low nybbles are in descending order.

`cmp cl, dl` sets flags based on the subtraction of the two given characters. In particular, the auxiliary carry flag (AF) is set based on carries across the centre of the byte, and it exactly indicates which character should be the result.

The difficulty lies in getting that information out of AF. Unlike the rest of the status flags, AF cannot be used as the condition for a jump, move, or `SETcc`. It is used mainly by several instructions intended for handling binary-coded decimal.

`aaa` is one of those instructions. (Its mnemonic stands for ASCII Adjust after Addition.) Helpfully, its opcode is only one byte. Its effect is: If AF=1 or the low nybble of AL is at least 10, add 0x106 to AL. Also, set both AF and CF based on the same condition. Afterwards, zero the high nybble of AL.

The first `aaa` makes sure that the low nybble of AL is less than 10, so that after the `cmp cl, dl`, the second `aaa` sets CF to equal AF. Finally, the value of CF can be used to select the correct result.

# Answer
> 4 votes
# Pyth, 5 bytes

```
hox1C

```

Try it online!

```
      Q   implicit input
 o        sort by key lambda N:
     N      implicit element
    C       character code point
  x1        bitwise XOR with 1
h         first element

```

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

```
s=>s[s>"T"^s>"UF"]

```

Try it online!

# Answer
> 3 votes
# 05AB1E (legacy), 7 bytes

```
'FDl‡àu

```

Try it online! Explanation:

```
'F      Push literal character `F`
  D     Duplicate
   l    Lowercase the duplicate
    ‡   Transliterate `F` to `f` in the input
     à  Take the maximum
      u Uppercase

```

# Answer
> 3 votes
# Vyxal, 6 bytes

```
≬C4%Þ↑

```

Try it Online!

## How?

```
≬C4%Þ↑
≬      # Three element lambda:
 C     # Convert to character code
  4%   # Modulo 4
       # Lambda implicitly ends here
    Þ↑ # Maximum of the (implicit) input by this function

```

Also 6 bytes:

```
µC4%;t

```

Try it Online!

## How?

```
µC4%;t
µ   ;   # Sorting lambda
 C      # Character code
  4%    # modulo four
     t  # Last item

```

# Answer
> 3 votes
# Ruby, 24 bytes

```
->n{"FFTU"[n.sum/13-10]}

```

Input is taken as a single string. `n.sum` Adds together the ASCII codes of the input. This sum is modified by arithmetic, then used to index the string.

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, ~~15~~ 13 bytes

```
1`T

O`.
1!`.

```

Try it online! Link includes test cases. Explanation:

```
1`T

```

Delete the first `T`, if any.

```
O`.
1!`.

```

Take the minimum.

# Answer
> 2 votes
# Charcoal, ~~8~~ 7 bytes

```
⌊∨⁻θT¦T

```

Try it online! Link is to verbose version of code. Explanation: If the string only contains `T`s then output `T` otherwise output the minimum of the other character(s).

```
   θ    Input string
  ⁻     Remove any occurrences of
    T   Literal string `T`
 ∨      Logical Or
      T Literal string `T`
⌊       Take the minimum
        Implicitly print

```

# Answer
> 2 votes
# MathGolf, 6 bytes

```
áÉ$4%╞

```

Port of hyper-neutrino♦'s Jelly answer, after I golfed it a bit more.

Try it online.

**Explanation:**

```
á       # Sort the (implicit) input-string by,
 É      # using the following 3 character as inner code-block:
  $     #  Convert the character to a codepoint-integer
   4%   #  Modulo-4 ("F"→70→2; "T"→84→0; "U"→85→1)
     ╞  # Remove the first character of the sorted string
        # (after which the entire stack is output implicitly as result)

```

# Answer
> 2 votes
# C (gcc), 22 bytes

```
f(a,b){a=a%4<b%4?b:a;}

```

Try it online!

Inputs two characters.
Returns their logical conjunction.

# Answer
> 2 votes
# AWK, 22 bytes

```
$0=/F/?"F":/U/?"U":"T"

```

Try it online!

*As short as Python!* #TeamAWK

Sets the input `$0` to the result of that ugly conditional. Because the assigned value is not false (i.e., not null/empty nor zero), AWK considers it a true pattern, and prints `$0`.

```
$0=             Assigns to $0 the result of:
   /F/?         Is there an F in the input?
       "F"      If so, it's now F.
      :         Otherwise...
       /U/?     Is there an U in the input?
           "U"  If so, it's now U.
          :     Otherwise...
           "T"  It's T, then.

```

# Answer
> 2 votes
# Vyxal, 7 bytes

```
\F:ɽĿGɾ

```

Ported from Neil's 05AB1E answer; make sure to upvote that answer as well!

Explanation:

```
\F      Push literal character `F`
  :     Duplicate
   ɽ    Lowercase the duplicate
    Ŀ   Transliterate `F` to `f`
     G  Take the maximum
      ɾ Change to uppercase

```

Try it online!

# Answer
> 2 votes
Since this function's output is always one of the inputs, it can be executed using a pure regex. This is done by picking an `F` if one exists, or otherwise picking a `U` if one exists, or otherwise picking a `T`.

# Regex (Perl / PCRE / Boost), ~~13~~ 11 bytes

```
.?\KF|T?\K.

```

-2 bytes thanks to m90!

Returns the result in the match.

Try it online! \- Perl
Try it on regex101 \- PCRE
Try it online! \- Boost

The `\K` feature is used to discard the first character of the input if `.?` or `T?` needed to be used to skip it.

# Regex (Java / Python / Ruby / .NET / ECMAScript 2018), ~~18~~ 15 bytes

```
(.?(?=F)|T?)(.)

```

-3 bytes thanks to m90's idea

Returns the result in capture group 2.

Try it online! – Try It Online") - Java
Try it online! \- Python
Try it online! \- Ruby
Try it online! \- .NET
Try it on regex101 \- ECMAScript 2018

This is based on the PCRE regex, using lookahead and group capture to replace the inavailability of `\K`.

## Regex (.NET), 15 bytes

```
.?(F)|T?(?<1>.)

```

Returns the result in capture group 1.

Try it online!

It was only possible to make a shorter .NET version thanks to m90's suggestion. This is done using the .NET-specific feature of aliasing a capture group. It could be done in PCRE using a Branch Reset Group, `(?|.?(F)|T?(.))`, but that's 15 bytes, longer than the existing 11 byte solution.

This is now merely tying with the above solution.

# Answer
> 2 votes
# brainfuck, 97 bytes

```
,[->+>+<<]>>>,[->+>+<<]++++++++++[-<------->>>-------<<]<[>>>[<<+++++[-<--->>>---<<]<[>>>[-]]]]<.

```

Takes in inputs as you would expect, and outputs as you would expect.

Copy the input characters to do math on them while preserving the original.

The math is just subtracting 70 ('F'), returning 'F' if either is 0 now, then subtracting 15 ('U' - 'F' == 15), returning 'U' if either is 0 now, otherwise return 'T'.

It's 3:30 a.m. as I'm writing this, so I may comment the code when I wake up.

Try it online!

A slightly different approach with 98 bytes

```
,[->+>>+<<<],[->>+>>+<<<<]>>>>>++++++++++[-<-------<------->>]<[<[>>+++++[-<---<--->>]<[-]]]<<.

```

# Answer
> 2 votes
# brainfuck, ~~75~~ 69 bytes

6 bytes saved by improving `U -> F` conversion from subtract 1x15 to subtract 3x5.

```
,>,[<<+>->-]<[>-[--->+<]<-[>]>[>+<<]<++[>]>[>+<<]>>-[++[<----->-]]]<.

```

Try it online!

Developed at https://minond.xyz/brainfuck/ (additional `>` characters are needed at the beginning and end of the program there due to lack of support of negative memory indices and to avoid auto re-run.)

Subtracts one input from the other.

* If they are the same, output one of the inputs
* If they differ by 1 (`UT` or `TU`) output `U`
* Otherwise output `F`

**Commented**

```
,>,               Input into cells 0 and 1
[<<+>->-]         Decrement cell 1 while copying its contents into cell minus 1; Simultaneously decrement cell 0
<                 Leave the pointer at cell 0 which contains the difference between the inputs
[                 If difference is nonzero
  >-[--->+<]          Subtract 1 from cell 1 giving 255 then loop until cell 1 is 0 and cell 2 is 255/3 = 85 ASCII U
  <-[>]>[>+<<]        Subtract 1 from cell 0; If nonzero take step to right; now take a further step right
                      If cell 0 was nonzero we are now at cell 2 containing 85; add 1 to cell 3 then step back left
  <++[>]>[>+<<]       Add 2 to cell 0; if nonzero use the same procedure as above to increment cell 3
  >>                  Move to cell 3; If cell 2 remained nonzero through all steps above cell 3 is now 2 otherwise 1
  -[++[<----->-]]     Subtract 1 from cell 3; If nonzero boost it to 3 then subtract 3x5=15 from cell 2
]                     changing it to 70 ASCII F
<.                Take 1 step left from current position and output result

```

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), 67 bytes

```
 i =input
 i 'F' . x :s(o)
 i 'U' . x :s(o)
 x ='T'
o output =x
end

```

Try it online!

# Answer
> 2 votes
# C, 25 bytes

```
f(x,y){return y-x&8?x:y;}

```

Try it online!

This uses the same observation as my previous answer: the character codes of F, U, T are 0x46, 0x55, 0x54 respectively, and their low nybbles are in descending order.

The low nybble of the result of the subtraction is -2, -1, 0, 1, or 2 (modulo 16), and its high bit (the 8s bit) indicates whether it is one of the negative possibilities.

# Answer
> 1 votes
# Python, 37 bytes

```
lambda s:s=="TT"and"T"or"UF"["F"in s]
```

Or alternatively for the same byte count

```
lambda s:["UF"["F"in s],"T"][s=="TT"]

```

Attempt This Online!

# Answer
> 1 votes
# C (GCC), ~~38~~ ~~33~~ 29 bytes

```
f(char*s){*s=s[*s%4<s[1]%4];}
```

Attempt This Online!

Returns the desired output in `*s`.

# Answer
> 1 votes
# Nim, 55 bytes

```
proc f(a,b:char):char=(if int(a)%%4<int(b)%%4:b else:a)
```

Attempt This Online!

Port of this C answer.

# Answer
> 1 votes
# A0A0, 92 bytes

```
I1L84S2M2V0G0
G-1G-1G-1G-1G-1
I1
G5
I1V0P0
G-1G-1
I1L84S2M2V0G0
G-1G-1G-1G-1G-1
P70

G2

P85

```

We first read input from stdin and then compare the ascii value of the character against 84 ('T').

```
I1  L84 S2  M2  V0  G0
G-1 G-1 G-1 G-1 G-1

```

'F' will be less than this and the operand becomes -1. 'T' is the same, so the opernad becomes 0 and 'U' is higher, so the operand becomes 1. We then jump to three different places depending on this value. The first place is when the character is 'F'.

```
I1
G5

```

Since every comparison against F will be an F, we only ask input because we must read two numbers - the input is never stored. We then jump five lines below which prints F.

```
I1  V0  P0
G-1 G-1

```

If the first input was T, then the result will simply by the second input. We read the second input and print it.

```
I1  L84 S2  M2  V0  G0
G-1 G-1 G-1 G-1 G-1

```

If the input is U, then we need to do a slightly more complex check. We read input and do another comparison against 84, jumping to three different places. Since we now know that the first input is U, each of these places can directly print the appropriate result: 'F' for 'F' and 'U' for both 'T' and 'U'. There are some slight optimizations made by only having a print instruction for each character once and then jumping towards this print from other places. Since the code has few lines, the instructions for jumping will be two bytes, whereas printing will be three bytes due to the double digit ascii value.

# Answer
> 1 votes
# Factor, 25 bytes

```
[ [ 4 mod ] supremum-by ]

```

Try it online!

# Answer
> 1 votes
i matched the best `awk`'s 20-bytes with a very different approach

```
echo 'U\nB\nF'
U
B
F

echo 'U\nB\nF' | mawk -F\[^FU] NF=NF OFS=T | gcat -n

     1  U
     2  T
     3  F

```

---
Tags: code-golf, logic-gates, logic
---


# Question
Title: Length of Longest Non-Repeating Substring
Your task is to take as input a single string (or list of characters, list of code points, etc.) and return the length of the longest substring with no character appearing more than once.

**Aside:** This challenge is similar to Longest Non-Repeating Substring, but *without* the source restriction ranking submissions by their own longest non-repeating substring.

---

### Assumptions

* You may assume that the input contains only lowercase letters and is non-empty (ie. the input will match the regex `(a-z)+`).
* This challenge will use the following definition for substring: "A *contiguous* sequence of characters contained in the input string"
* By "non-repeating" I mean that no letter of the substring is repeated more than once

### Examples

If the input is `abcdefgabc` then the longest substrings with no repeating characters are `abcdefg` and `bcdefga` (their positions in the string are `[abcdefg]abc` and `a[bcdefga]bc`). The length of these substrings is `7`, so the output would be `7`.

If the input is `abadac` then the longest substrings with no repeating characters are `bad` (`a[bad]ac`) and `dac` (`aba[dac]`) so the output is `3`.

If the input is `aaaaaa` then the longest substring with no repeating characters is `a` so the output is `1`.

If the input is `abecdeababcabaa` then the longest substrings with no repeating characters are `abecd` (`[abecd]eababcabaa`) and `cdeab` (`abe[cdeab]abcabaa`). The output is thus `5`.

### Test Cases

```
abcdefgabc -> 7
aaaaaa -> 1
abecdeababcabaa -> 5
abadac -> 3
abababab -> 2
helloworld -> 5
longest -> 7
nonrepeating -> 7
substring -> 8
herring -> 4
abracadabra -> 4
codegolf -> 6
abczyoxpicdabcde -> 10

```

### Scoring

This is . Shortest answer in bytes for each language wins

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

```
f=lambda s:s>''and max(n:=f(s[:-1]),len({*s[~n:]}))

```

Try it online!
> 8 votes

# Answer
# Jelly, 6 bytes

```
ẆQƑƇṪL

```

A monadic link accepting a list of characters (or whatever), which yields the length.

**Try it online!**

### How?

```
ẆQƑƇṪL - Link: list
Ẇ      - all sublists (ordered by length)
   Ƈ   - filter keep those which are:
  Ƒ    -   invariant under:
 Q     -     deduplication
    Ṫ  - tail
     L - length

```
> 5 votes

# Answer
# Julia 1.0, ~~98~~ ~~74~~ 73 bytes

```
~=length
!s=max(.~filter(z->[z...]==z∪z,[s[x:y] for x=1:~s,y=1:~s])...)

```

Try it online!

* -3 bytes thanks to @amelies: replace `unique` with  (`union`)
* -4 bytes thanks to @amelies: replace `collect` with splat operator `...`
* -6 bytes thanks to @amelies: replace `in` with `=` in array comprehension
* -5 bytes thanks to @amelies: vectorize the reassigned operator (`~` =\> `.~`)
* -2 bytes thanks to @amelies: unary operators don't need parentheses
* -4 bytes thanks to @amelies: condense ranges to remove a `for` statement
* -1 byte thanks to @MarcMush: replace `∪(z)` with `z∪z`
> 4 votes

# Answer
# Wolfram Language (Mathematica), 49 bytes

```
Tr[1^Last@Select[Subsequences@#,DuplicateFreeQ]]&

```

Try it online!
> 3 votes

# Answer
# C (gcc), 80 bytes

```
m;f(char*s){int F[128]={},i=0;for(;s[i]*!F[s[i]]++;i++);i=i?i>(m=f(s+1))?i:m:0;}

```

Try it online!

---

### C (gcc), 83 bytes

An alternate non-recursive answer, although 3 bytes longer.

```
m;f(char*s){for(m=0;*s;)for(char*t=s++,F[128]={};*t*!F[*t]++;m=m>t++-s?m:t-s);++m;}

```

Try it online!
> 3 votes

# Answer
# Python, 63 bytes

```
f=lambda s:len({*s})<len(s)and max(f(s[1:]),f(s[:-1]))or len(s)

```

**Try it online!**
> 2 votes

# Answer
# Haskell, ~~83~~ 75 bytes

-8 using guarded list comprehension for the length.

```
import Data.List
f[]=0
f x=sum[1|nub x==x,_<-x]`max`f(tail x)`max`f(init x)

```

Try it online!
> 2 votes

# Answer
# , 88 bytes

```
function(l)max(apply(combn(seq(l),2),2,function(v)all(table(l[v[1]:v[2]])<2)*diff(v)))+1

```

Try it online!

Input is vector of individual letters.

Commented:

```
max(                              # maximum value of:
  apply(                          # loop over
    combn(seq(l),2)               # all pairs of values in 1:length(l)
                                  # (so all possible start & end indices of contiguous subsets)
    ,2,function(v)                # for each pair assigned to 'v':
      all(table(l[v[1]:v[2]])<2)  # table() counts the different items in each subset v[1]:v[2]
                                  # so: 'all(table()<2)' indicates a nonrepeating subset
      *diff(v)                    # multiply by diff(v) = end-start = subset size -1
  ))+1                            # so finally we have to add 1 to get the subset size

```
> 2 votes

# Answer
# Gaia, 11 bytes

```
$:u/¦l¦¦_⌉)

```

Try it online!

I feel like there's probably a byte or two that can be removed...
> 2 votes

# Answer
# Husk, 8 bytes

```
▲mLfS=uQ

```

Try it online!

```
▲mLfS=uQ
▲           # maximum value of
 mL         # lengths of
   f   Q    # all contiguous sublists of input that are
    S=u     # equal to themselves without duplicates

```
> 2 votes

# Answer
# Vyxal `l`, 8 bytes

```
ǎ'¨=U;ÞG

```

Try it Online!
> 2 votes

# Answer
# Pyth, 7 bytes

```
le{I#.:

```

Test suite

##### Explanation:

```
le{I#.:  | Full code
le{I#.:Q | with implicit variables
---------+-----------------------------------------------------------------------
     .:Q | All substrings of input
    #    | Filter over
  {I     |  whether the substring is the same as itself without duplicate letters
le       | Length of the last (longest) substring

```
> 2 votes

# Answer
# Japt v2.0a0, 9 bytes

```
ã Ôæ_¶âÃl

```

Try it
> 1 votes

# Answer
# Retina, 28 bytes

```
Lw`.+
A`(.).*\1
O^$`
$.&
\G.

```

Try it online! Link includes test cases. Explanation:

```
Lw`.+

```

List all nontrivial substrings.

```
A`(.).*\1

```

Delete those which duplicate characters.

```
O^$`
$.&

```

Sort in descending order of length.

```
\G.

```

Count the first length.

The longest length can also be found using these stages for the same byte count:

```
%C`.

```

Take the length of each remaining substring.

```
N^`

```

Sort in descending order.

```
1G`

```

Keep the first length.
> 1 votes

# Answer
# Bash \+ Core utilities, 46 bytes

```
sed -E ':a;s/(\w)(\w*)\1/\1\2\n\2\1/;ta'|wc -L

```

Try the test cases online!
> 1 votes

# Answer
# 05AB1E, 9 bytes

```
ŒʒDÙQ}€gà

```

Try it online!

# Explanation

```
Œ         All sublists
 ʒ        Filter:
  DÙ      Is the uniquified version
    Q}    Equal to the original?
      €g  Map length
        à Maximum

```
> 1 votes

# Answer
# perl -n -Mfeature=say -MList::Util=max, 55 bytes

```
m;.+(??{$&=~/(.).*\1/||push@&,length$&})(?!);;say max@&

```

Try it online!

Reads lines from `STDIN`, writing results to `STDOUT`.

For each line, it iterates over every sub string (`/.+(?!)/` will do that; `/(?!)/` will never match). For each sub string, if it doesn't contain a duplicated character (`/(.).*\1/` matches if there is a duplicated character), it stores the length of the sub string. We'll print the maximum of those values.
> 1 votes

# Answer
# Stax, 11 bytes

```
éôU)¥¼ó8∩╦z

```

Run and debug it
> 1 votes

# Answer
# Factor, 48 bytes

```
[ all-subseqs [ all-unique? ] find-last length ]

```

Try it online!

* `all-subseqs` Get all the substrings of the input from shortest to longest
* `[ all-unique? ] find-last` Find the last one whose elements are unique
* `length` Get its length
> 1 votes

# Answer
# Brachylog, 7 bytes

```
⊇S&sS≠l

```

Try it online!

Another 7 bytes solution:

```
sᶠ≠ˢlᵐ⌉

```

Try it online!

### Explanation

Unfortunately, `s - substring` does not enumerate substrings of consecutive elements in descending order of length (if it did, we would have a 3 byte solution), but rather enumerates based on the indices. Therefore, we first state that we want a `⊇ - sublist`, which does not force consecutiveness, but which enumerates from longest to smallest.

```
⊇S         S is a subset of the input (from longest to smallest)
  &        And
   sS      S is also a substring of consecutive elements of the input
     ≠     All elements of S are different
      l    Output the length of S

```

The second solution is a more "declarative" approach:

```
sᶠ         Find all substrings of consecutive elements from the input
  ≠ˢ       Select all substrings with all-different elements
    lᵐ     Map length
      ⌉    Max

```
> 1 votes

# Answer
# JavaScript (ES6), 72 bytes

```
f=s=>/(.).*\1/.test(s)?Math.max(f(s.slice(1)),f(s.slice(0,-1))):s.length

```

Try it online!

---

# JavaScript (ES6), 61 bytes

A port of @dingledooper's clever Python answer is 11 bytes shorter.

```
f=s=>p=s?f(s.slice(1))>(q=new Set(s.slice(0,p+1)).size)?p:q:0

```

Try it online!
> 0 votes

# Answer
# Charcoal, 20 bytes

```
Ｉ⌈Ｅθ⌊Ｅθ§⌕Ａ⁺✂θκＬθ¹λλ¹

```

Try it online! Link is to verbose version of code. Works by finding the maximum earliest duplicated character of the string and its nontrivial suffixes. Explanation:

```
   θ                    Input string
  Ｅ                     Map over characters
      θ                 Input string
     Ｅ                  Map over characters
            θ           Input string
           ✂ κＬθ¹       Substring starting at outer index
          ⁺      λ      Append current character
        ⌕Ａ        λ     Find all matches of the current character
       §           ¹    Take the second
    ⌊                   Take the minimum
 ⌈                      Take the maximum
Ｉ                       Cast to string
                        Implicitly print

```
> 0 votes

# Answer
# T-SQL, 118 bytes

Input is taken from table `T` (according to the Code Golf rules for SQL): column `P` represents position and column `V` represents each character.

```
SELECT TOP 1B.P-A.P+1FROM T A, T B ORDER BY(SELECT COUNT(*)-COUNT(DISTINCT V)FROM T WHERE T.P>=A.P AND T.P<=B.P),1DESC

```

DB Fiddle
> 0 votes

# Answer
# Ohm v2, 16 bytes

```
l@€³sÇ;{⁇DU⁼;»l↑

```

Try it online!

Took me this long to realise `»` goes *before* the component. Almost submitted a 17 byte answer using `€l;`.

## Explained

```
l@€³sÇ;{⁇DU⁼;»l↑
l@                # Push the range [1, len(input)]
  €   ;           # To each number:
   ³sÇ            #   Get all substrings of length number of the input
       {          # Deep flatten that
        ⁇DU⁼;     # And only keep substrings that have all unique characters
             »l   # Push the length of each unique character substring
               ↑  # and get the biggest length

```
> 0 votes

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


title: This cat has bugs? Really?

text:
# Question
Title: This cat has bugs? Really?
# Challenge:

Read input (within visible ASCII range) and output with a few modifications:

1. In each set of 10 characters of the input randomly (50/50):
    * replace one character\* (with a random\** one within visible ASCII range) (ex. `lumberjack` becomes `lumbeZjack`)
    * or remove one character (ex. `lumberjack` becomes `lmberjack`)

* If the set is of less than 10 characters, you don't have to modify it, but you can.
\** The character can be the same as the one input, as long as it's still random.

# Example:

Input: `Go home cat! You're drunk!`
Output: `Go hom cat! YouLre drunk!`
(just a example, since output could be random, don't use as a test case)

# Rules:

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

```
VczTpXNOT?<JOr\ \ÞKC127JK

```

Test suite available here.

Thanks to Maltysen for shaving off 2 bytes.

# Explanation

```
VczTpXNOT?<JOr\ \ÞKC127JK    z autoinitalizes to input, T autoinitializes to 10
 czT                         chop input into strings of length 10, returned as list of strings
V                            for each string N in this list:
            Or\ \Þ            randomly pick a char between ' ' (32) and 'Þ' (222)
           J                  and assign it to variable J
                  KC127       assign the DEL char to variable K
         ?<J      K           if J < K:
     XNOT              J       replace a random character in N with J
         ?<J      K           else:
     XNOT               K      replace a random character in N with K
    p                         print this string with no trailing newline

```

As is often the case, I feel that this is a bit of a naive method and may be improved upon. Usually I find something obvious while typing up the explanation but nothing jumped out at me this time.
> 4 votes

# Answer
## \*\>\<\>, ~~44~~ ~~46~~ ~~52~~ 50 bytes

```
rl5(?voooo/!|Ou+1Ox:@=?~o~oooo!
ol5(?v" ":/
o;!?l<

```

Try it here!

This uses any ascii character near/above space for the random characters. This always edits the 6th character, unless it's the end of a string and that string's length isn't a multiple of 10. This has a 50% chance to remove the 7th character instead of editing the 6th.

### Input

> The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE). The standard addressed many problems found in the diverse floating point implementations that made them difficult to use reliably and portably. Many hardware floating point units now use the IEEE 754 standard.

### Output

> The IEE Standardfor Float$ng-Point Aithmetic (EEE 754) i a technicl standar! for floa!ing-point!computati#n establised in 1985by the Insitute of !lectrical#and Electrnics Engi!eers (IEE%). The st!ndard add!essed man! problems#found in !he divers! floating oint impl!mentation" that mad# them dif!icult to ue reliabl# and port!bly. Many!hardware foating po#nt units %ow use th! IEEE 754"standard.

Edit: ~~This answer probably isn't always in the visible ascii range, editing...~~ Fixed.

Edit2: ~~Didn't see there needs to be a 50/50 chance to remove a character, editing again...~~ I believe everything is in order now :).
> 3 votes

# Answer
# Perl 6,  ~~78~~  67 bytes

```
{[~] map {~S/.**{(^.chars).pick}<(./{(' '..'~').pick x Bool.pick}/},.comb(10)}

```

```
{[~] .comb(10)».&{~S/.**{10.rand}<(./{(' '..'~').pick x 2.rand}/}}

```

Try it

## Explanation:

```
{
  [~]                  # reduce with string concatenation operator

  .comb(10)\           # take input and break it into chunks of up-to 10 chars

  ».\                 # on each of them call the following

  &{
    ~                  # Stringify the following

    S/                 # substituted
      .                # any char
        **             # repeated
           { 10.rand } # a random number of times

      <(               # ignore all of that

      .                # the char to be removed/replaced
    /{

      ( ' ' .. '~' ).pick  # choose a character
      x                    # string repeated
      2.rand               # zero or one times

    }/

  }
}

```
> 2 votes

# Answer
# Pyth - 21 bytes

```
smO,XdOTOr;\~.DdOTcQT

```

Try it online here.
> 2 votes

# Answer
# Python 3, 75 bytes

The 75-byte applies the transformation to the first character of each group, and only picks from 2 random characters, such as in the Jelly answer (which OP allowed):

```
from random import*
f=lambda s:s and choice(['','a','b'])+s[1:10]+f(s[10:])

```

**Try it online!**

This is a recursive function which, every iteration, prepends either nothing, `'a'`, or `'b'`, and then calls itself with the first 10 characters sliced off. The final iteration short circuits at `s and` (an empty string is falsy), avoiding infinite recursion.

The result of all the separate calls are then concatenated, and returned to the context which called the function.

# 120 bytes

Of course, that feels a bit like cheating, so here's one which is completely random:

```
from random import*;r=randint
def f(S):a=S[:10];R=r(0,len(a)-1);print(end=a[:R]+chr(r(32,126))*r(0,1)+a[R+1:]);f(S[10:])

```

**Try it online!**
> 2 votes

# Answer
# Vyxal, 13 bytes

```
₀ẇ⟑ẏ℅kP¤"℅℅Ȧ₴

```

Try it Online!

```
₀ẇ            # Chunks of length 10...
  ⟑           # Over each...
           Ȧ  # Replace at ...
   ẏ℅         # random index in the input
          ℅   # A random item of...
         ℅    # A random item of...
     kP       # Printable ascii
       ¤"     # Or the empty string
            ₴ #

```
> 2 votes

# Answer
# Jelly, ~~15 14~~  13 bytes 13 characters

```
2X
s⁵µ¢1¦ṫ¢µ€

```

**TryItOnline!**

Replaces or removes the first of every ten characters including that of the last 1-9 if there is such a chunk. Chooses from the, admittedly small, subset of characters: `1`; `2`.

### How?

```
2X         - Link 1, flip a coin: no arguments
 X         - random choice from
2          - 2 (treated as the integers [1,2])

s⁵µ¢1¦ṫ¢µ€ - Main link: string of printable ASCII
s⁵         - split (s) into chunks of size ten (⁵)
  µ     µ  - monadic chain separation
         € - for each chunk
   ¢       -     last link as a nilad
    1¦     -     apply to index 1 (replace 1st of the 10 char chunk with the chosen integer)
       ¢   -     last link as a nilad
      ṫ    - tail - if it was 1 this has no effect (50%)
                  - if it was 2 this discards the replaced character (50%)
           - implicit print

```

---

To choose from all of printable ASCII rather than just `1` and `2` (still replacing or removing the 1st character of each chunk) in 21 bytes:

```
s⁵µ32r126¤ỌX¤1¦ṫ2X¤µ€

```

---

For a fully random version (50/50 remove/replace, uniform random printable ASCII, and a uniformly random character location within each chunk) I have 30 bytes (probably non-optimal):

```
95R+31ỌX;

s⁵µṙ⁵X¤©Ṗ2X¤Ŀṙ®C¤µ€

```

This rotates each chunk left by a random amount, pops the last character off and then calls a random one of the first two links, one of which is empty and the other which concatenates with a random printable ASCII character; it then rotates the chunk right again.
> 1 votes

# Answer
**Clojure, ~~135~~ 139 bytes**

Edit: Forgot to use `partition-all` instead of `partition`.

```
(fn[i](apply str(flatten(map #(let[r rand-int [b e](split-at(r 9)%)][b(if(<(rand)0.5)""(char(+(r 25)97)))(rest e)])(partition-all 10 i)))))

```

Ungolfed:

```
(def f (fn[i]
         (->> i
              (partition-all 10)
              (map #(let [[begin end] (split-at (rand-int 9) %)]
                      [begin (if (< 0.5 (rand)) "" (char (+(rand-int 25)97))) (rest end)]))
              flatten
              (apply str))))

```

Man those function names are long... Anyway, it splits input into partitions of 10 characters, splits them at random point into two halves, randomly injects an empty string or a random character between them and discards the first character of the 2nd half.
> 1 votes

# Answer
## Mathematica 133 Bytes (129 characters)

```
StringReplacePart[#,Table[If[(r=RandomInteger)[]<1,"",FromCharacterCode@r@128],c=⌊StringLength@#/10⌋],Array[{g=10#-9+r@9,g}&,c]]&

```

76 characters to write the names of 8 functions :/

Using the `⌊..⌋` instead of `Floor[]` saves 5 characters, 1 byte.
> 1 votes

# Answer
# Python3, ~~188~~ ~~186~~ ~~184~~ 114 characters

```
from random import*
s=input()
for c in[s[i:i+10]for i in range(0,len(s),10)]:print(end=choice(["","x","y"])+c[1:])

```

~~Seems too long. Could probably be shortened a lot with a lambda.~~

Apparently the OP has allowed choosing the random character from a list of two characters and the index of the character to be replaced can be a constant. After the modifications, my answer would've looked exactly the same as @FlipTacks Python submission, so this is the form I'm staying with.

@FlipTack saved 5 bytes!
> 1 votes

# Answer
# Python 3, 129 bytes

```
def f(s):f=id(s)%9+1;print(''.join(j[0:f-1]+chr(33+id(s)%94)*(id(s)//10%2)+j[f:]for j in [s[i:i+10]for i in range(0,len(s),10)]))

```

In order to save some bytes, instead of importing Python's random module, I just did some modulo operations on the id of the string, which should be different every time. For example the program will decide whether or not to remove a char or replace one based on whether or not `id(string)//10` is even (I integer divide by 10 as the last digit will always be even).
> 1 votes

# Answer
# Ruby `-pl`, 52 bytes

```
gsub(/.{10}/){_1[rand 0..9]=[*" "..?~,""].sample
_1}

```

Attempt This Online!
> 1 votes

# Answer
# Pip, 46 bytes

```
Fi(a<>t){IRR2YiRARR#iRCPAEL{YiRARR#ix}b:bAEy}b

```

Try It Online!

How?

```
Fi(a<>t){IRR2YiRARR#iRCPAEL{YiRARR#ix}b:bAEy}b
Fi      {                                   }  - For each in
      t                                        - Var for 10
   a<>t                                        - Split input into 10 pieces
         I                                     - If truthy
          RR2                                  - 0 or 1
             Y                                   - Yank (equivalent to (y:a)):
               RA                                 - Replace item in at index
              i                                   - First input
                 RR#i                             - Random int from 0 to length of input
                     RCPA                         - Random Printable ASCII character
                         EL{         }         - Else
                            Y                    - Yank:
                              RA                  - Replace item in at index
                             i                    - First input
                                RR#i              - Random int from 0 to length of input
                                    x             - Empty string
                                      b:       - Assign b to
                                        bAEy   - Append y to b
                                             b - Output b

```
> 1 votes

# Answer
# 05AB1E, 13 bytes

```
TôεžQΩæΩ9ÝΩǝ?

```

Also (potentially) modifies the last part if it's less than 10 characters.

Try it online or see 10 example outputs at once.

**Explanation:**

```
Tô             # Split the (implicit) input-string into parts of size 10
               # (where the trailing part is potentially smaller)
  ε            # Foreach over the parts:
   žQ          #  Push the printable ASCII string constant
     Ω         #  Pop and push a random character from it
      æ        #  Get the powerset of this character, resulting in a pair of an empty
               #  string "" and the character
       Ω       #  Pop and push a random item from this pair
        9Ý     #  Push list [0,1,2,3,4,5,6,7,8,9]
          Ω    #  Pop and push a random digit from this list
           ǝ   #  Replace the character at that (0-based) index with the chosen ASCII
               #  character or the empty string
               #  (if the index is ≥ the length, it does nothing)
            ?  #  Pop and print the modified part

```
> 1 votes

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


# Question
Title: Fourth grade math homework for the week: A most inefficient traveling salesman
My daughter had the following assignment for her math homework. Imagine six friends living on a line, named E, F, G, H, J and K. Their positions on the line are as indicated (not to scale) below:

Thus, F lives five units from E, and two units from G, and so forth.

Your assignment: craft a program that identifies a path that visits each friend exactly once with a total length of *n* units, taking the locations of the friends and *n* as inputs. It should report the path if it finds it (for example, for length 17 it might report "E,F,G,H,J,K", and it should exit gracefully if no solution exists. For what it's worth, I completed an ungolfed solution in Mathematica in 271 bytes. I suspect it's possible much more concisely than that.

# Answer
> 1 votes
# J, 54 bytes

Outputs one correct route. If no route exists it outputs nothing.

```
   f=.4 :'{.(x=+/|:2|@-/\"#.s A.y)#(s=.i.!6)A.''EFGHJK'''

   62 f 0 5 7 13 16 17
GJEKFH

```

52-byte code that outputs all routes (one per line):

```
f=.4 :'(x=+/|:2|@-/\"#.s A.y)#(s=.i.!6)A.''EFGHJK'''

```

38-byte code that outputs positions instead letters:

```
f=.4 :'p#~x=+/|:2|@-/\"#.p=.(i.!6)A.y'

```

# Answer
> 7 votes
# Mathematica, 55 or 90 bytes

Mathematica you said? ;)

```
FirstCase[Permutations@#,p_/;Tr@Abs@Differences@p==#2]&

```

This is an anonymous function that first takes the positions of the friends (in any order), and then the target length. It returns `Missing[NotFound]`, if no such path exists.

```
FirstCase[Permutations@#,p_/;Tr@Abs@Differences@p==#2]&[{0, 5, 7, 13, 16, 17}, 62]
(* {7, 16, 0, 17, 5, 13} *)

```

I can save four bytes if returning all valid paths is allowed (`FirstCase` -\> `Cases`).

Returning an array of strings is a bit more cumbersome:

```
FromCharacterCode[68+#]&/@Ordering@FirstCase[Permutations@#,p_/;Tr@Abs@Differences@p==#2]&

```

# Answer
> 5 votes
# Python 2, ~~154~~ 148 bytes

### (or 118 bytes for the general solution)

This program accepts a line with a list and an integer like '\[0, 5, 7, 13, 16, 17\], n' on stdin and prints a path on the output of length n or nothing if impossible.

```
# echo "[0, 5, 7, 13, 16, 17], 62" | python soln.py
['G', 'J', 'E', 'K', 'F', 'H']

```

It is challenging to write small programs in Python that require permutations. That import and use is very costly.

```
from itertools import*
a,c=input()
for b in permutations(a):
 if sum(abs(p-q)for p,q in zip(b[1:],b))==c:print['EFGHJK'[a.index(n)]for n in b];break

```

The source for the OP requirement before the minifier:

```
from itertools import*

puzzle, goal = input()
for option in permutations(puzzle):
    if sum(abs(p-q) for p,q in zip(option[1:], option)) == goal :
        print ['EFGHJK'[puzzle.index(n)] for n in option];
        break

```

The general solution (not minified):

```
from itertools import*

puzzle, goal = input()
for option in permutations(puzzle):
    if sum(abs(p-q) for p,q in zip(option[1:], option)) == goal :
        print option;
        break

```

Due to the simple algorithm and vast number of combinations, execution for more than 20 initial positions will be very slow.

# Answer
> 4 votes
# J (48 or 65)

I hypothesize that this can be golfed a hell of a lot more. Feel free to use this as a jumping off point to golf it further

```
]A.~[:I.(=([:([:+/}:([:|-)}.)"1(A.~([:i.[:!#))))

```

Or with letters:

```
([:I.(=([:([:+/}:([:|-)}.)"1(A.~([:i.[:!#)))))A.[:(a.{~65+[:i.#)]

```

## What it does:

```
   62 (]A.~[:I.(=([:([:+/}:([:|-)}.)"1(A.~([:i.[:!#))))) 0 5 7 13 16 17
 7 16  0 17  5 13
 7 16  5 17  0 13
 7 17  0 16  5 13
 7 17  5 16  0 13
13  0 16  5 17  7
13  0 17  5 16  7
13  5 16  0 17  7
13  5 17  0 16  7

```

(I hope this I/O format is okay...)

## How it does it:

```
(A.~([:i.[:!#))

```

Generates all permutations of the input

```
([:+/}:([:|-)}.)"1

```

Calculates the distance

```
(]A.~[: I. (= ([:distance perms)))

```

Sees which results are the same as the input, and re-generates those permutations (I suspect some characters can be shaved off here)

With letters:

```
((a.{~65+[:i.#))

```

Create a list of the first n letters, where n is the length of the input list

```
indices A. [: letters ]

```

does the same as above

# Answer
> 3 votes
# Octave, 73

```
function r=t(l,d,s)r=perms(l)(find(sum(abs(diff(perms(d)')))==s,1),:);end

```

There's really no un-golfing this, so let me try to explain... from inside to out, we permute all the distances, then for each permutation, we take the differences between houses, take the absolute value as a distance, add them up, find the index of the first permutation with the desired distance, and permute the letters and find that particular permutation of letters.

```
octave:15> t(["E" "F" "G" "H" "J" "K"],[0 5 7 13 16 17],62)
ans = HEJFKG

```

which is 13-0-16-5-17-7 =\> 13+16+11+12+10=62.

```
octave:16> t(["E" "F" "G" "H" "J" "K"],[0 5 7 13 16 17],2)
ans =

```

(blank for impossible inputs)

# Answer
> 2 votes
# Matlab (86)

```
x=input('');X=perms(1:6);disp(char(X(find(sum(abs(diff(x(X).')))==input(''),1),:)+64))

```

Example in which a solution exists:

```
>> x=input('');X=perms(1:6);disp(char(X(find(sum(abs(diff(x(X).')))==input(''),1),:)+64))
[0, 5, 7, 13, 16, 17]
62
DBFAEC
>>

```

Example in which a solution doesn't exist:

```
>> x=input('');X=perms(1:6);disp(char(X(find(sum(abs(diff(x(X).')))==input(''),1),:)+64))
[0, 5, 7, 13, 16, 17]
100
>>

```

---

# Matlab (62)

If the **output format can be relaxed** by producing positions instead of letters, and producing an empty matrix if no solution exists:

```
X=perms(input(''));X(find(sum(abs(diff(X.')))==input(''),1),:)

```

Example in which a solution exists:

```
>> X=perms(input(''));X(find(sum(abs(diff(X.')))==input(''),1),:)
[0, 5, 7, 13, 16, 17]
62
ans =
    13     5    17     0    16     7

```

Example in which a solution doesn't exist:

```
>> X=perms(input(''));X(find(sum(abs(diff(X.')))==input(''),1),:)
[0, 5, 7, 13, 16, 17]
62
ans =
   Empty matrix: 0-by-6

```

---

# Matlab (54)

If it's acceptable for the program to provide **all valid paths**:

```
X=perms(input(''));X(sum(abs(diff(X.')))==input(''),:)

```

Example in which a solution exists:

```
>> X=perms(input(''));X(sum(abs(diff(X.')))==input(''),:)
[0, 5, 7, 13, 16, 17]
62
ans =
    13     5    17     0    16     7
    13     5    16     0    17     7
    13     0    17     5    16     7
    13     0    16     5    17     7
     7    16     5    17     0    13
     7    16     0    17     5    13
     7    17     5    16     0    13
     7    17     0    16     5    13

```

# Answer
> 1 votes
# Haskell, 109 bytes

```
import Data.List
a%b=abs$snd a-snd b
n#l=[map(fst)p|p<-permutations(zip['E'..]l),n==sum(zipWith(%)p(tail p))]

```

Usage example: `17 # [0, 5, 7, 13, 16, 17]` which outputs all valid paths, i.e. `["EFGHIJ","JIHGFE"]`. If there's no valid path, the empty list `[]` is returned.

The list of letters includes `I` (hope that's fine).

How it works: make a list of `(name, position)` pairs, permute and take those where the path length equals `n` and remove the position part.

# Answer
> 1 votes
# Python \+ `golfing-shortcuts`, 123 bytes

A port of Logic Night's answer.

```
from s import*
def F(A,C):
 for B in Im(A):
  if s(abs(P-Q)for P,Q in z(B[1:],B))==C:p(['EFGHJK'[li(A,N)]for N in B]);break

```

---
Tags: code-golf, graph-theory, path-finding
---


title: Permutapalindromic numbers

text:
# Question
Title: Permutapalindromic numbers
Given an integer `N` as input, output the `N`th permutapalindromic number.

A permutapalindromic number is a strictly positive integer such that there is at least one permutation of its digits that results in a palindrome (i.e. a number that is its own reverse).

For example, `117` is a permutapalindromic number since its digits can be permuted into `171`, which is a palindrome.

We consider that numbers like `10` are not permutapalindromic numbers, even though `01 = 1` is a palindrome. We impose that the palindromic permutation must not have a leading zero (as such, `0` itself is not permutapalindromic).

Numbers that are already palindromes are also permutapalindromic, since permuting nothing is valid.

### Inputs and outputs

* `N` may be either 0-indexed or 1-indexed. Please indicate which of the two your answer uses.
* The input can be taken through `STDIN`, as a function argument, or anything similar in your language of choice. The output can be written to `STDOUT`, returned from a function, or anything similar in your language of choice.
* The input and output must be in the decimal base.

### Test cases

The following test cases are 1-indexed. Your program must be able to pass any of the test cases presented here in at most 1 minute.

```
N      Output

1      1
2      2
3      3
4      4
5      5
6      6
7      7
8      8
9      9
10     11
42     181
100    404
128    511
256    994
270    1166

```

### Scoring

This is , so the shortest answer in bytes wins.

# Answer
> 9 votes
# 05AB1E, ~~15~~ ~~14~~ 13 bytes

Saved a byte thanks to **Emigna**! Code:

```
µNœvyJÂïÊP}_½

```

Explanation:

```
µ               # c = 0, when c is equal to the input, print N.
 N              # Push N, the iteration variable.
  œ             # Push all permutations of N.
   vyJ    }     # For each permutation...
      Â         #   Bifurcate, which is short for duplicate and reverse.
       ï        #   Convert the seconds one to int, removing leading zeros.
        Q       #   Check if they are not equal.
         P      #   Product of the stack.
           _    # Logical not.
            ½   # Pop a value, if 1 then increase c by 1.

```

Uses the **CP-1252** encoding. Try it online!.

# Answer
> 8 votes
# Brachylog, 19 bytes

```
~l<:1at.
.=pPrPl~l?

```

Try it online!

Takes about 17 seconds for `N = 270`.

### Explanation

* Main predicate:

```
~l            Create a list whose length is Input.
  <           The list is strictly increasing.
   :1a        Apply predicate 1 to each element of the list.
      t.      Output is the last element of the list.

```
* Predicate 1:

```
.=            Input = Output = an integer
  pPrP        A permutation P of the Output is its own reverse
      l~l?    The length of P is equal to the length of the Input

```

# Answer
> 7 votes
## Pyth, 14

```
e.ff&_ITshT.p`

```

Try it here or run a Test Suite

### Expansion:

```
e.ff&_ITshT.p`ZQ   # Auto-fill variables
 .f            Q   # Find the first input number of numbers that give truthy on ...
           .p`Z    # Take all the permutations of the current number
   f&              # Keep those that give a truthy value for both:
     _IT           # Invariance on reversing (is a palindrome)
        shT        # The integer value of the first digit (doesn't start with zero)
                   # A list with any values in it it truthy, so if any permutation matches
                   # these conditions, the number was a permutapalindrome
e                  # Take only the last number

```

# Answer
> 6 votes
# Brachylog, ~~21~~ 20 bytes

**1 byte thanks to Fatalize.**

Did you design the challenge for Brachylog?

```
:1yt.
0<.={@epcPrP!}

```

Try it online!

270 takes about half a minute here.

```
Z = 1166
real    0m27.066s
user    0m26.983s
sys     0m0.030s

Exit code:     0

```

### Predicate 0 (main predicate)

```
:1yt.
:1y    find the first Input solutions to predicate 1
   t.  unify the output with the last element

```

### Predicate 1 (auxiliary predicate)

```
0<.={@epcPrP!}
0<.              0 < Output
  .=             Assign a value to Output (choice point)
    {        }   Inline predicate:
     @e              Digits of the Output
       p             A permutation (choice point)
        c            Concatenate (fails if leading zero present)
         P           store as P
          rP         assert that P reversed is still P
            !        remove the choice point in this predicate, so
                     that it will not return twice for the same number.

```

# Answer
> 6 votes
## JavaScript (ES6), 99 bytes

```
f=(n,i=1)=>(n-=/^.0+$/.test(i)</^((.),\2,)*(.)(,\3)?(,(.),\6)*$/.test([...i+''].sort()))?f(n,i+1):i

```

Explanation:

```
f=(n,i=1)=>             look for n numbers starting at 1
 (n-=                   test whether current guess is
  /^.0+$/.test(i)<      not a round number and
  /^((.),\2,)*          pairs of comma-separated digits
   (.)(,\3)?            possible single digit
   (,(.),\6)*$/         pairs of comma-separated digits
   .test(               matches the comma-joined
    [...i+''].sort()))  digits in ascending order
 ?f(n,i+1)              if not n numbers found try next number
 :i                     found it!

```

# Answer
> 5 votes
# R, 145 bytes

```
g=function(n){d=b=0
while(d<n){b=b+1
if(sum(a<-table(strsplit(n<-as.character(b),""))%%2)==nchar(n)%%2&(!names(a)[1]==0|a[1]|sum(!a)>1))d=d+1}
b}

```

ungolfed

```
f=function(b){
    a<-table(strsplit(n<-as.character(b),""))%%2
    sum(a)==nchar(n)%%2&(!names(a)[1]==0|a[1]|sum(!a)>1)
}
g=function(n){
    d=b=0
    while(d<n){
         b=b+a
         if(f(b)) d=d+1
    }
    b
}

```

Essentially -- a function checking membership in permutapalindromic set, and a while loop incrementing until it finds the nth member.

# Answer
> 4 votes
# Dyalog APL, 51 bytes

One-indexed.

```
{⍵⊃{⍵/⍨{(⍵≤9)∨(1<≢c~'0')∧1≥+/2|+⌿c∘.=∪c←⍕⍵}¨⍵}⍳5×⍵}

```

> `{` a function where ⍵ represents the argument
>
> > `⍵⊃{` use the argument to pick from the result of the function
> >
> > > `⍵/⍨{` filter the argument with the result of the function
> > >
> > > > `(⍵≤9)∨` the argument is less or equal to 9, OR
> > > >
> > > > `(1<≢c~'0')∧` there remains more than one digit when zeros are removed AND
> > > >
> > > > `1≥+/` 0 or 1 is the sum of
> > > >
> > > > `2|` the oddnesses of
> > > >
> > > > `+⌿` of the column sums of
> > > >
> > > > `c∘.=∪c` the comparison table of *c* and the unique elements of *c*, where *c*...
> > > >
> > > > `←⍕⍵` is the string representation of the argument
> > >
> > > `}¨⍵` applied to each of the arguments
> >
> > `}⍳5×⍵` applied to {1, 2, 3, ..., 5 times the argument}
>
> `}` \[end of function\]

Finishes all the test cases instantly on TryAPL

# Answer
> 4 votes
# Python 2.7, ~~163~~ 154 bytes:

```
from itertools import*;I,F,Q=input(),[],2
while len(F)<I:F=[g for g in range(1,Q)if any(i==i[::-1]*(i[0]>'0')for i in permutations(`g`))];Q+=1
print F[-1]

```

Simple enough. Basically uses a `while` loop to repeatedly create arrays containing permutapalindromic numbers the the range `[1,Q)` until `Q` is large enough such that the array contains `Input` number of items. It then outputs the last element in that array.

Try It Online! (Ideone)

# Answer
> 4 votes
# JavaScript (ES6), 92

```
n=>eval("for(a=0;n-=(a++<9||(b=[...a+``].sort().join``)>9&!b.replace(/(.)\\1/g,``)[1]););a")

```

*Less golfed*

```
n=>{
  for( a = 0;
       n -= // decrement n (and exit when 0) if the check below is true == a is permutapalindromic
            (a ++ < 9 // single digit (meanwhile, increment a)
             || // or...
             ( b=[...a+``].sort().join`` )// build a string with the digits sorted
               > 9 // required at least 2 non zero digits
             & ! b.replace(/(.)\1/g,``)[1] // removed all digits pair, there must be just 1 or no single digits remaining
            );
     );
   return a;
}

```

**Test**

```
f=n=>eval("for(a=0;n-=(a++<9||(b=[...a+``].sort().join``)>9&!b.replace(/(.)\\1/g,``)[1]););a")

function update() {
  O.textContent=f(+I.value)
}

update()
```

```
<input id=I oninput=update() type=number value=100>
<pre id=O></pre>
```

# Answer
> 4 votes
# Japt, 13 bytes

```
_ì á fÎdêQ}iU

```

Try it

0-indexed

```
_ì á fÎdêQ}iU
_         }iU # Find the N-th number that meets this condition:
 ì            #  Get the digits as an array
   á          #  Get all permutations of that array
     f        #  Keep only permutations where:
      Î       #   The first digit is not zero
       d      #  Return true if any remaining permutation:
        êQ    #   Is a palindrome

```

# Answer
> 3 votes
# Perl 6, 66 bytes

```
{(1..*).grep(*.comb.permutations.grep({+.join.flip eq.join}))[$_]}

```

0 based

## Explanation:

```
# bare block lambda which takes an implicit parameter ｢$_｣
{
  # all numbers greater than 0
  (1..*)\

  # remove any which aren't permutapalindromic
  .grep(

    # ｢*｣ here starts a Whatever lambda
    *\
    # split into list of digits
    .comb\
    # get all of the permutations of the digits
    .permutations\
    # find out if there are any palindromes
    .grep(

      # another bare block lambda taking ｢$_｣ as implicit parameter
      {
        # compare the current permutation with its reverse stringwise
        # numify only one side to get rid of leading ｢0｣
        +$_.join.flip eq $_.join
      }
    )

  # get the value at the index
  )[$_]
}

```

## Test:

```
#! /usr/bin/env perl6
use v6.c;
use Test;

my &permutapalindromic = {(1..*).grep(*.comb.permutations.grep({+.join.flip eq.join}))[$_]}

my @tests = (
  1   => 1,
  2   => 2,
  3   => 3,
  4   => 4,
  5   => 5,
  6   => 6,
  7   => 7,
  8   => 8,
  9   => 9,
  10  => 11,
  42  => 181,
  100 => 404,
  128 => 511,
  256 => 994,
  270 => 1166,
);

plan +@tests + 1;

my $start-time = now;
for @tests -> $_ ( :key($input), :value($expected) ) {
  # zero based instead of one based, so subtract 1
  is-deeply permutapalindromic( $input - 1 ), $expected, .gist;
}
my $finish-time = now;

my $total-time = $finish-time - $start-time;

cmp-ok $total-time, &[<], 60, 'Less than 60 seconds for the tests';
diag "$total-time seconds";

```

# Answer
> 3 votes
# Brachylog v2, 16 bytes

```
<~l<₁{≜.pX↔Xp}ᵐt

```

Try it online!

Borrows Fatalize's `~l` trick because my attempt at a -based solution is a bit too slow...

```
<                   The input is less than
 ~l                 the length of some list
   <₁               which is strictly increasing
     {       }ᵐ     where each element:
      ≜.            is an integer chosen such that
        pX          some permutation X
          ↔X        is X reversed,
            p       a permutation of which is the element.
               t    Output the final element of that list.

```

# Answer
> 3 votes
# Vyxal, ~~10~~ 9 bytes

```
SṖ'Ṙ⌊=)ȯt

```

Try it Online!

You say any test case presented in the challenge should pass in under a minute? *All* test cases presented in the challenge pass in under 30 seconds. That's what I call gaming (no doubt the other answers do too though lol).

## Explained

```
SṖ'Ṙ⌊=)ȯt
      )ȯ  # Starting at 1, get the first (input)th numbers where:
SṖ        #   From the permutation of the digits of the number,
  '       #   There exists at least 1 such that:
   Ṙ⌊     #   The reverse (cast to int)
     =    #   Equals that permutation
        t # Print the tail of the list

```

# Answer
> 3 votes
# Gaia, 15 bytes

```
:vdṙ=
ṙf↑¦Σ
↑#)

```

Try it online!

First ever code golf, so please tell me if I'm doing anything wrong.

## Explained

```
:vdṙ= # Helper function 2 (hf2)
:     # Push two copies of the function argument
 vdṙ  # str(int(argument[::-1]))
    = # does that equal the original function argument?
-----
ṙf↑¦Σ # Helper function 1 (hf1)
ṙf    # Get all permutations of the string representation of the function argument
  ↑¦  # Map hf2 to each item
    Σ # and summate the result
-----
↑#)   # Main function
↑#    # First (input) items where hf1 is true
  )   # get the last item of that

```

# Answer
> 2 votes
# Javascript (using external library - Enumerable) (142 bytes)

```
   n=>_.Sequence(n,i=>{l=i+"";p=_.Permutations(_.From(l),l.length).Any(y=>y.First()!="0"&&y.SequenceEqual(y.Reverse()));if(p){return i;}}).Last()

```

Link to lib:https://github.com/mvegh1/Enumerable/

Code explanation: \_.Sequence creates an enumerable for a count of "n" elements, based on the predicate of signature ("i"teration~~,"a"ccumulated array~~). Cast the current iteration to a string, and create an enumerable of all permutations from it. Test if any of the permutations satisfy the test of not starting with "0" and that the reversal of the permutation equals the permutation. Return the last element in the sequence because that is the desired output as per OP

# Answer
> 2 votes
# Haskell, ~~89~~ 87 bytes

```
import Data.List
(filter(any(show.floor.read.reverse>>=(==)).permutations.show)[0..]!!)

```

# Answer
> 2 votes
## Python 2, 93 bytes

```
S=sorted
f=lambda n,i=1:n and-~f(n-(S(`i`)in[S(`k`)for k in range(9*i)if`k`==`k`[::-1]]),i+1)

```

1-indexed. Depending on your system, the last test case may exceed the allowed recursion depth.

Does not compute permutations. Instead, uses the fact that two strings are permutations if they are equal when sorted. To test if a number is permutapalindromic, checks if its sorted digits equal the sorted digits of any palindrome up to a bound.

---

**96 bytes:**

```
f=lambda n,i=1:n and-~f(n-(sum(`i`.count(`d`)%2for d in range(10))<2*(set(`i`[1:])!={'0'})),i+1)

```

1-indexed. Depending on your system, the last test case may exceed the allowed recursion depth.

This doesn't look at permutations and instead uses the following characterization:

> A number is *permutapalindromic* exactly when
>
> * At most one of its digits appears an odd number of times, and
> * It does not have the form d00...00 with one or more zeroes.

This is true because a palindrome must pair off digits from the start and end, except for a possible center digit. The exception comes from the requirement that the leading digit be nonzero, and so some nonzero digit must appear twice unless the number is single-digit.

# Answer
> 2 votes
# Jelly, 14 bytes

```
1DŒ!ŒḂ×ḢƊ€ẸƲ#Ṫ

```

Try it online!

## How it works

```
1DŒ!ŒḂ×ḢƊ€ẸƲ#Ṫ - Main link. Takes an argument n on the left
           Ʋ   - Group the previous 4 links into a monad f(k):
 D             -   Convert k to digits
  Œ!           -   Permutations of k's digits
        Ɗ€     -   Over each permutation p:
    ŒḂ         -     Is p a palindrome?
      ×Ḣ       -     And is the first digit non-zero?
          Ẹ    -   Is that true for any permutation?
1           #  - Count up k = 1, 2, 3, ... until n k return true under f(k)
                 Return those k
             Ṫ - Return the n'th k

```

# Answer
> 2 votes
# Perl 5 `-p`, 69 bytes

```
1while$_-=(join'',sort++$\=~/./g)=~s/(.)\1//gr=~y///c<2*$\!~/^.0+$/}{

```

Try it online!

# Answer
> 2 votes
# Python \+ `golfing-shortcuts`, 128 bytes

A port of R. Kap's answer.

```
from s import*
I,F,Q=e(i()),[],2
while l(F)<I:F=[G for G in r(1,Q)if a(I==I[::-1]*(I[0]>'0')for I in Im(repr(G)))];Q+=1
p(F[-1])

```

# Answer
> 1 votes
**C, 254 bytes**

```
#define W while
#define R return
f(j){int c=0,a[16]={0};do++a[j%10],++c;W(j/=10);if(c>1&&a[0]>=c-1)R 0;c%=2;W(j<10)if(a[j++]%2&&(!c||++c>2))R 0;R 1;}g(n){int k=0,i=1;W(k<n)if(f(i++))++k;R i-1;}main(a){printf("N>");scanf("%d",&a);printf("%d\n",g(a));}

```

# Answer
> 1 votes
# Jelly, 13 bytes

```
Dœ^/LỊaṢ-ịø#Ṫ

```

Try it online!

Out of curiosity, I decided to see how far I could get without actually computing permutations, and two hours of head bashing later it ties caird's existing answer (modulo a golf to use `ø`). The logic boils down to checking two conditions:

* At most one digit occurs an odd number of times.
* There must be multiple nonzero digits if at least one digit is zero.

and stuck in a blender for five minutes on high, that's:

```
           #     Count up collecting the first n integers
          ø      starting from 0 which satisfy:
D                Do the digits
 œ^/             reduced by symmetric multiset difference
    LỊ           have length ≤ 1?
       Ṣ         Sort the digits,
      a          replace them all with 0 if the previous condition is not met,
        -ị       and take the second to last element (wrapping around if length 1),
           #     succeeding if it's nonzero.
            Ṫ    Return the last result.

```

---
Tags: code-golf, number, permutations, palindrome
---


title: Hello world with a twist

text:
# Question
Title: Hello world with a twist
**Your goal**: to write a piece of code that will result in the classic result of "Hello, world!" being printed to STDOUT or equivalent.

**Rules**: Code must be entirely in printing ASCII. All code must be functional - removal of any single counting character must change the result or cause the code to not function. All variables must be used after assignment. Character and String literals must be necessary to the output - that is, replacement of any character literal or any character within a string literal with another character must be capable of changing the result (and not via the effect of escape sequence - replacing character with backslash or equivalent)

(NOTE: Final rule was edited in)

**Scoring**: This is where it gets interesting. Highest score wins as determined by number of characters, as per typical code-bowling rules. But repeated use of characters will result in point deductions. Specifically...

1. Repeated use of any alphanumeric character (a-z, A-Z, 0-9) will result in a deduction of 3 points per repeat (first use does not result in a deduction).
2. Repeated use of basic punctuation (\[!?.-,":';\]) - including the brackets - will result in a deduction of 2 points per repeat.
3. Repeated use of other ASCII characters {\`~@#$%^&\*_+=|\\/\>\<} - including the curly brackets - will result in a deduction of 4 points per repeat.
4. Repeated use of spaces, tabs, and newlines will result in a deduction of 1 point per repeat. That is, only the first use of a space, tab, or newline will count towards your total.

Note: comments do not count towards total, although the characters marking the start/end of a comment do. For instance, in C/C++, If you have `/* This is a comment */`, then it will count two slashes and two asterisks, but nothing between them.

Some **examples** (note: using Julia as sample language)...

```
print("Hello, world!");

```

Total visible characters: 22
Contains Space: +1
Repeated alphanumerics: -12 for llor
Repeated punctuation: -2 for "
Final score: 22+1-12-2 = 9

```
print("Hel",char(108),"o, wor",0x108,"d!"); # 0x108 makes a Uint8 that prints as ASCII

```

Total characters: 43 (does not count any characters after #, which is the comment character)
Contains Space: +1
Repeated alphanumerics: -18 for rr1008
Repeated punctuation: -24 for ()""""",,,,,
Final score: 43+1-24-18 = 2

```
xy=STDOUT
m="Hello, world!"
print(xy,m);

```

Total visible characters: 37
Contains Newline: +1
Contains Space: +1
Repeated alphanumerics: -18 for xyllor
Repeated punctuation: -4 for ",
Repeated other ASCII: -4 for =
Final score: 37+1+1-18-4-4 = 13

A couple of invalid pieces of code...

```
x=2;print("Hello,world!")

```

Problem: `x` is assigned, but not used.

```
print("Hello,"*" world!")

```

Problem: `*` is unnecessary, result will be the same without it.

```
k=1
if k>0
  print("Hello, world!")
else
  print("abcghjmquvxyzABCDEFGIJKLMNOPQRSTUVWXYZ_+*-&|")
end

```

Problem: The second `print` command will not run. Also, removing characters in quote in second `print` command will not change output.

```
x="Hello, world!";
print(x)

```

Problem: removal of newline will not change result or cause error (in Julia, semicolon is only necessary if multiple commands are on the same line, otherwise just suppresses return value).

```
print("Hellos\b, world!")

```

Problem: `s` character does not affect result, as it gets erased by `\b`. This is acceptable if done through code (`"Hello",char(100),"\b, world!"`), but cannot be done via string literals or character literals.

**Convenient score-calculator** \- http://jsfiddle.net/4t7qG/2/ \- thanks to Doorknob

# Answer
# Perl - 96

(Pretty good, given the theoretical max 97 score)

```
s{}[Hel0o, w3$=d!];y<"#%&'*.124578:?@BCDEFGIJKLMNOQ/-9>(
    6PRSTUVWXYZ^_`abfghjmqvxz|~\cAk-u)+print

```

(Note that second line starts with an actual `\t` tab character)

The code is 98 characters long and contains every ascii char exactly once, plus an extra `-`.
98 - 2 = 96

There are no *string* literals here, but removal of **any** single character breaks the program.

### Deobfuscation

There are 3 statements in this program (well, actually 2 but I abused `+` as some kind of statement separator)

1. `s{}[Hel0o, w3$=d!]`
This is a very stretched case of the sed operator. It is more commonly written as `s/a/b/`, or `s:a:b:`, but perl allows much more fantasy here: `s(a)(b)` `s(a)^b^` `s(a)[b]`, and even `s qaqbq`.
It replaces an empty string (inside `{}`) with `Hel0o w360d!` (inside `[]`) (`$=` interpolates to `60` by default). Because of the lack of an `~=` operator, it operates on `$_`.
2. `y<"#%&'*.124578:?@BCDEFGIJKLMNOQ/-9>(\n\t6PRSTUVWXYZ^_`abfghjmqvxz|~\cAk-u)`
This is also a very stretched case, but of a `tr` operator, which is also called `y` (`y< >( )`).
Let's look at the replacement table:
`" # %&'*.124578:?@BCDEFGIJKLMNOQ /-9`
`\n\t6PRSTUVWXYZ^_`abfghjmqvxz|~\cA k-u`
I have moved some characters around so that existing string is not broken. The only actually working part here is `/-9` -\> `k-u`. It replaces `0` with `l`, `3` with `o`, and `6` with `r`.
Again because of lack of the `~=` operator, it operates on `$_`
So now we have the complete phrase in the `$_` variable.
3. `print`
Lack of arguments makes it print just the `$_` variable.
> 17 votes

# Answer
**This answer was created before adding of the rule about string literals and does not participate in the contest.**

```
#include <iostream>
int main(){std::cout<<56+"  !$%^&*?12347890-_QWERTYUIOPASDFGJKLZXVBNM,.qypfghjk:zvbHel\x6Co, world!";}

```

It's completely legit. :P If you remove any character from that string, it will print `ello, world!`.
> 8 votes

# Answer
# CJam, 94

```
{'H"EJO, WoRLD!"el96A+c/~_-3=0$@}"#
`&^<>|;:?.()[]\1aBCdfFgGhiIjkKmMnNpPqQrsStTuUvVwxXyYzZ"254b87%*

```

Try it online! Note that there should be a tabulator right before the linefeed. SE doesn't like tabulators, so you'll have to insert it manually.

* 100 characters long
* repeated alnum: -0 ()
* repeated punctuation: -6 (""")
* repeated other: -0 ()
* repeated whitespace: -0 ()

Total score: 94

I've used the following code to check that none of the characters inside the string can be removed:

```
"#
`&^<>|;:?.()[]\1aBCdfFgGhiIjkKmMnNpPqQrsStTuUvVwxXyYzZ"
:A,,{_A\<A@)>+254b87%}%`

```

It prints an array showing the number of times *Hello, world!* would get printed if the character corresponding to the index were removed.
> 4 votes

# Answer
# Befunge-98, 97 points!

```
"v!dlrow ,h
B[CDEFGIJkLMNOPH
$<QRSTUV@|5cg1fe':-%\64*ab+7_/89}{0  j2
WXYZK`.=#>]
s()impq	n 3~
Atuxz&;y^ ?

```

Try it online!

The tab is between the `q` and the `n`.

Uses a similar trick to the previous Befunge answer to pad the lines with the leftover characters, but avoids using duplicate characters in the executing section. Removing any of the non-executing characters results in the executing parts being out of place, usually ending up in infinite loops or printing the wrong output.

### How It Works

Really, the only executing part looks like:

```
"v!dlrow ,h
         k     H
$<      @|5cg1fe':-%\64*ab+7
         >]
        ^ ?

```

First it uses a wrapping string literal to add `, world!` to the stack. This avoids two `"`s.

```
$<      @|5cg1fe':-%\64*ab+7

```

This adds `Hello` to the stack using a variety of methods to avoid duplicate characters. `$` pops the excess space caused by the wrapping string literal.

`7+` adds 7 to the `h` from the end of the string literal to create the `o` . `ba*46\%:` calculates 111, the ascii value of `l` and duplicates it.

`'e` adds e to the stack.

`f1g` gets the character at 1,15 which is the `H`

It then reuses the `,` in the string to print out the whole `Hello, world!`. The rest is just direction changes to navigate to the ending `@`.
> 4 votes

# Answer
# Ruby, ~~28~~ 41

Just to start off the answers with a solution in the spirit of the question:

```
print"He#{?l*2}o, "+'world!'if[$`&(9<=>6)^7|~8-5/3.1%0x4]

```

Scoring (I think I got this right):

* 57 characters long
* repeated alnum: -12 (`orli`)
* repeated punctuation: -4 (`"'`)
* repeated other: -0
* repeated whitespace: -0
> 3 votes

# Answer
# PHP, 1 (yes, one point!)

Using magic characters to generate a checksum, which in binary form matches "Hell", "o, w", "orld", and "! ".

Usually I like to find loopholes, but this time I decided to play by the spirit and intent of the contest. Every character and its position is essential to the output. The only places you can substitute are variable names which are not literal values, the whitespace between `php` and `foreach` which `PHP` treats as equivalent, and use of `'` vs `"` which `PHP` treats as similar.

```
<?php foreach(array('_MC:`~+V4@SbHR/l[J','dN#UB`5!Rv^NG@D}','9gm6L&-kuD','8OM97g.q]XQ0')as$j)print(hash("crc32",$j,1))?>

```

FYI, these are some other magic strings and hashes of interest:

```
E.D}S:  Hell
9UDIRQ: Hell
N\7&*`%:    orld
UWX[E^O:    orld
mAHzDEb:    !
uLJ7Ck&:    Hell
B+bG5mYJ:   Hell
:OvMzuOR:   !
TgYR9g!6k:  o, w
NkFN`!8mI:  o, w
N#VA\j~}J[: Hell
vEl*]@0XQ5: o, w
9gm6L&-kuD: orld
*}{Xg@HN`\: !
Pj@Y44uA6YJ:    Hell
|7OX0VF8gv}:    !
DLRJAjgMj}\:    !
!0bT*D}O4Lw:    orld
YGN97^v7ZY`:    Hell
++~bL/kP:|]W:   o, w
8OM97g.q]XQ0:   !
l^m-DqZ^g[&+:   !
Ewu]Rv~*DHQ7:   Hell
JIqjgF|S!\`8l:  Hell
b4l!MEG7vTu6/:  Hell
+B:zEq*J\k-Cm:  !
_}E7wZD76^`Y9AU:    orld
q:Nq-~+_S7~N9Hz:    !

```
> 3 votes

# Answer
# Ruby, 78

More rules abuse, I feel like, not sure exactly what the patch'd be. Takes a long string and checks the sum of the result, so any deletion or change will cause the program to fail. Could probably be optimized a little to remove duplication of some letters and get whitespace in there.

```
puts('Hello, world!')if%["\#$&*+-/:;<>?@ABCDEFGIJKLMNOPQRSTUVWXYZ^_`abcghjknqvxyz{|}~123].sum==4980

```
> 1 votes

# Answer
# PHP, 2257

Loophole: the backslash was omitted from the specifications and the score calculator!

This code counts the number of occurrences of backslashes in each string and prints an ASCII equivalent. Replacing any backslash with another character, or deleting a backslash, either causes a parse error or changes the result.

A neat feature about backslashes and `PHP` is that they need to be escaped, so that doubles the score automatically! You can re-double, triple, etc., the score by multiplying the number of backslashes, but didn't want to be greedy, and I think it might exceed the limits of what you can enter.

```
<?php foreach(array('\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\')as$x)print(chr(substr_count($x,"\\")))?>

```
> 1 votes

# Answer
# Befunge - 87

```
"dlrow ,olleH"bk,                                                                   v
!#$%&'()*+-./0123456789:;  <=>?ABCDEFGIJKLMNOPQRSTUVWXYZ[\]^_`acfghijmnpqstuvxyz{|}~@

```

The first line is worth four points due to all the repetition, but there are no duplicated characters on the second line. The only string literal in this code is `dlrow ,olleH`, which gets reversed and printed as output. Removing any one character will disconnect the `v` at the end of the first line from the `@` at the end of the second, causing the program to never terminate. If the `v` itself is removed, then the code will go in to an infinite loop printing the correct output.
> 1 votes

# Answer
# Acc!!, -138 (and yes that's negative 138)

While this may not exactly be the best score I've ever gotten in PPCG, I doubt it can get any higher than this in *Acc*!!

```
108
Write 72
Write 101
Count i while i-2 {
	Write _
}
Write _+3
Write 44
Write 32
Write 119
Write 111
Write 114
Write _
Write 100
Write 33

```

Try it online!
> 0 votes

# Answer
# Aceto, 3

Finally managed to get a positive score!

```
"Hello, "-J' sJ"world!"∑-JUJpn

```

Try it online!
> 0 votes

# Answer
# Pascal, 17

One of the few occasions on this site a verbose case-insensitive language is “useful”. This is a `program` adhering to ISO standard 7185 “Pascal”:

```
PROGrAM{}Z(oUTput);BEgIN
WRiTe('Hello, world!':1*82-75+6)EnD.

```
> 0 votes

---
Tags: printable-ascii, hello-world, code-bowling, pangram
---


title: Golf an Anagram Quine

text:
# Question
Title: Golf an Anagram Quine
In this question I asked you to guess an anagram quine based on its output. However it looks like we don't have a question asking to golf an anagram quine yet. So your task will be to make the shortest anagram quine that you can.

### What is an anagram quine?

An anagram quine is a non empty program that prints an anagram of its source code, other than its original source.

Here's an example of an anagram quine in Python 2:

```
print`'`print`*2'*2`

```

You should not read your own source for this challenge.

# Answer
> 31 votes
# Pyth, 2 bytes

```
)(

```

Outputs

```
()

```

Try it online!

```
)  # Ends statement, does nothing in this program
 ( # Create an empty tuple
   # Implicitly print the empty tuple

```

# Answer
> 9 votes
# \>\<\>, ~~9~~ ~~8~~ 7 bytes

*Golfed 1 byte thanks to @WheatWizard by using `!` and incrementing it to get `"`*

*Golfed 1 byte thanks to @ConorO'Brien by using `#` instead of `<!`*

```
":1->o#

```

Try it online!

Outputs `"#o>-1:`.

### Explanation

```
":1->o#"        Push this string (note that the IP wraps around)
:               Duplicate the top value of the stack (35 from the "#")
1-              Subtract one from it to get 34 ('"')
>o#             Print every character on the stack until the program cannot pop any more and still tries to pop a value from the stack afterwards
                The program exits with an error from not being able to pop a value from an empty stack

```

# Answer
> 9 votes
# , 4 bytes

```
2ii2

```

Outputs:

```
i2i2

```

Try it online!

# Answer
> 9 votes
# Brainfuck, 158 bytes

```
>>--<<-[[<+>->+>->+++<<<]>-]<<<<<<[--->>.<<]>>++<<<[->>>.<<<]>>-<<<[--->>>.<<<]>>>--<<<<[++>>>>.<<<<]>>>>+++>--.[---<.>]>+.......++.......<<<>>>>>>>>>-----+++

```

Try it online!

It may not be the shortest version, but at least it works.

*Fun fact*, the output code can actually be executed (and it does terminate).

## Output

```
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>--------------------------++++++++++++++++++<....................[[[[[[[]]]]]]]

```

## Explanation

```
>>--<<-[[<+>->+>->+++<<<]>-]    Initializes the tape with the
                                help of a recurrence relation.
<<<<<<[--->>.<<]>>++<<<[->>>
.<<<]>>-<<<[--->>>.<<<]>>>--    Prints the characters using
<<<<[++>>>>.<<<<]>>>>+++>--.    classic loops.
[---<.>]>+.......++.......

<<<>>>>>>>>>-----+++            Junk to complete the anagram.

```

# Answer
> 8 votes
# Python 3, 32 bytes

```
print("""p"r"i"n"t"2(")*"""*2)

```

Prints `p"r"i"n"t"2(")*p"r"i"n"t"2(")*\n`, sorted output: `\n""""""""""""(())**22iinnpprrtt`

# Answer
> 7 votes
# Ruby, 8 bytes

```
p"p*2"*2

```

Try it online!

This prints

```
"p*2p*2"

```

## Explanation

This works similar to the python answer in the question. It will make the string `p*2p*2` then using Ruby's `p` will print the representation of the string.

# Answer
> 6 votes
## JavaScript (ES6), ~~40~~ 32 bytes

```
f=($=`($)=>{$=$+"${"``"}$"}`)=>$+$

```

No messing around with Function.toString either. As a bonus, the code inside the string almost looks legal. Edit: Saved 8 bytes by using `+` instead of `repeat(2)`.

# Answer
> 4 votes
# Klein, 7 + 6 = 13 bytes

Here's an answer based on the \>\<\> answer.

```
":1+@!

```

Try it online!

This outputs

```
:1+@!"

```

# Answer
> 4 votes
# Japt, ~~10~~ 9 bytes

Found a better way :-)

```
Q+2ç"Q+2ç

```

Outputs `"Q+2çQ+2ç`. Test it online!

### Explanation

```
Q+2ç"Q+2ç    // Implicit: Q = quotation mark
    "Q+2ç    // Take this string.     Q+2ç
  2ç         // Repeat it twice.      Q+2çQ+2ç
Q+           // Prepend a quote.      "Q+2çQ+2ç
             // Implicit: output result of last expression

```

Could also be `Qi2ç"Qi2ç`, which prints `Qi2çQi2ç"`. This one is closer to the standard Japt quine:

```
"iQ ²"iQ ²

```

But I do not believe there is any easy way to wedge the quotation mark in the middle of the string for a 9-byte quine.

# Answer
> 3 votes
## Ruby, 20 bytes

```
$><<%q($><<%q()*2)*2

```

This outputs

```
$><<%q()*2$><<%q()*2

```

Taking advantage of Ruby's `%q(...)` string syntax, which supports nested parentheses.

# Answer
> 3 votes
## Retina, 8 bytes

```

_

$nn$

```

Try it online!

Prints

```

n$_
n$

```

Both contain one `_`, two `n`, two `$` and three linefeeds.

Note that a linefeed followed by almost any other character is a trivial solution, but it's questionable whether it's valid, because the second character only encodes itself and the linefeed doesn't really encode either output character.

## Explanation

```

_

```

Replace the empty input with a `_`.

```

$nn$

```

Match an empty string, which happens both before or after the `_` and insert a linefeed (`$n`), an `n`, and a `$`. Since we first inserted that `_`, this adds each of those characters twice, so the `n` and `$` account for the `$n`, and we get two of the three linefeeds we need in the output. The third linefeed is printed because Retina prints a trailing linefeed by default.

We could also use `n$n$` in this stage, which would then print:

```
n
$_n
$

```

# Answer
> 3 votes
# Python Repl, 4 bytes

This is my first Code Golf solution, so I hope it meets the rules. In the Python 2 or 3 interactive interpreter:

```
>>> (1),
(1,)

```

The output is an anagram of the input.

---

Another:

```
>>> 2*'2*'
'2*2*'

```

In Python 2:

```
>>> type('rst <>'),
(<type 'str'>,)

```

In Python 3:

```
>> {1, 0}
{0, 1}

```

Update 2017-06-15: Yet another:

```
>>> 01.
1.0

```

# Answer
> 2 votes
# Haskell, ~~38~~ 39 bytes

```
main=print$[0,0]>>"main=print$[0,0]>>"

```

Try it online! Output:

```
"main=print$[0,0]>>main=print$[0,0]>>"

```

Edit: +1 byte because I previously forgot about the implicit trailing newline of `print`.

---

**Alternative:** (Same byte count but does not contain ASCII-owl)

```
main=print$e++e;e="main=print$e++e;e="

```

Try it online!

Output:

```
"main=print$e++e;e=main=print$e++e;e="

```

# Answer
> 2 votes
# 05AB1E, 10 bytes

```
'∞∞''∞'JJ∞

```

Try it online!

# Output:

```
∞∞''JJ''∞∞

```

---

# Explanation:

```
Code       | Explanation                | Stack
-----------+----------------------------+-------------------
'∞         | Push literal '∞'.          | ["∞"]
  ∞        | Mirror.                    | ["∞∞"]
   ''      | Push literal "'".          | ["∞∞","'"]
     ∞     | Mirror.                    | ["∞∞","''"]
      'J   | Push literal 'J'.          | ["∞∞","''","J"]
        J  | Join it all together.      | ["∞∞''J"]
         ∞ | Mirror.                    | ["∞∞''JJ''∞∞"]
-----------+----------------------------+-------------------
           | Implicit print.            | ∞∞''JJ''∞∞

```

# Answer
> 2 votes
# Groovy, ~~24~~ 20 bytes

```
{"""{""*""2""}"""*2}

```

*-4 thanks to CalculatorFeline, the whitespace wasn't needed after all!*

# Output:

```
{""*""2""}{""*""2""}

```

# Explanation:

Anonymous closure that, when called, returns `{""*""2""}` two times (concatenated).

# Answer
> 2 votes
## CJam, 6 bytes

```
"_`"_`

```

Try it online!

Prints

```
_`"_`"

```

### Explanation

```
"_`"   e# Push this string.
_      e# Duplicate.
`      e# Stringify it, which wraps it in quotes.
       e# Implicitly print stack contents.

```

# Answer
> 1 votes
# PHP, 44 bytes

```
<?=str_repeat('<?=\str_\repeat(\'\',2);',2);

```

Try it online!

# Answer
> 1 votes
# Fission 2, ~~9 8~~ 6 bytes

```
R"'!+O

```

Try it online!

# Explanation

An atom is created at `R`, which moves right. This atom then comes across a `"`, which starts printing mode. In printing mode, all characters (until the matching `"`) are printed. This means it prints `'!+OR` in this case. Then, all that is left is printing `"`, which is done by the remaining characters. `'!` sets the atom's mass to the character code of `!`, and `+` increments it to the character code of `"`. Then, the character code is output by `O` and the atom is destroyed, ending the program.

(Actually, this is just a rotation of the shortest quine)

# Answer
> 1 votes
## Bash, 36 bytes

```
tee f<<<'tee f<<<""cat f'"''"
cat f

```

This outputs

```
tee f<<<""cat f''
tee f<<<""cat f''

```

(and creates the file `f` as a side effect, but that's allowed per meta.)

Both the program and output have a trailing newline.

Thought process: I figured that the easiest way to output a string two times, aside from assigning it to a variable, was to do

```
tee f<<<string
cat f

```

The string needs to be quoted because it will contain spaces and `<` characters, so then I had

```
tee f<<<'tee f<<<cat f'
cat f

```

which almost works, except it doesn't output the quotes. Fortunately, Bash supports string literal concatenation by simply placing them next to each other, so appending `"''"` to the herestring and inserting `""` inside the single quote part yields this solution.

# Answer
> 1 votes
# Befunge, 11 bytes

```
' 2+">:#,_@

```

Prints:

```
+2 '@_,#:>"

```

Explanation:

```
' 2+"        Put a " on the stack (32 + 2)
    "        Put the rest of the code on stack (wrap-around string)
     >:#,_   Print stack
          @  End

```

# Answer
> 1 votes
# CJam, 8 bytes

```
"2*`"2*`

```

Try it online!

### Explanation

Similar to the Python example in the question

```
"2*`"     e# Push the string "2*`"
     2*   e# Repeat it twice
       `  e# Get its string representation (wrap in quotes)

```

The output is `"2*`2*`"`.

# Answer
> 1 votes
# QBIC, 8 bytes

```
?A+@?A@+

```

I just figured out how to do a proper quine in QBIC. Making an anagram out of it is done by simply switching around the characters in the string literal. There are 24 possible anagrams this way.

# Answer
> 1 votes
# Befunge-98, 8 bytes

```
"'$<@,k7

```

Try it online!

# Answer
> 1 votes
# Ohm, 14 bytes

```
"æ3M.Cæ"æ3M."C

```

Try it online!

Output:

```
æ3M.CæC.M3æ"""

```

### Explanation

```
"æ3M.Cæ"æ3M."C
"æ3M.Cæ"       # Pushes "æ3M.Cæ"
        æ      # Palindrone of that string
         3M    # 3 times...
           ."   # Push " on the stack
             C  # Concatenate with the string above

```

# Answer
> 1 votes
# JavaScript (ES6), 15 bytes

```
f=(s='f=')=>f+s

```

**Outputs:**

```
(s='f=')=>f+sf=

```

**Snippet:**

```
f=(s='f=')=>f+s

console.log(f());
```

# Answer
> 1 votes
# Mathematica, 2 bytes

```
.0

```

Output:

```
0.

```

A number starting with a decimal point such as `.123` is interpreted as `0.123`, so `.0` is interpreted as `0.0`. Since the part of the number after the decimal point is zero, Mathematica does not print it.

# Answer
> 1 votes
# JavaScript (yet another one), 11 bytes

```
f=_=>'=f'+f

```

Called with `f()`, outputs

```
=f_=>'=f'+f

```

```
f=_=>'=f'+f

console.log(f());
```

# Answer
> 1 votes
Python 3, 31 bytes

```
a='a=%r;pritn(a%%a)';print(a%a)

```

# Answer
> 1 votes
# Stax, ~~8~~ 4 bytes

```
.S.S

```

Run and debug online!

A direct port of this answer.

Old version, 8 bytes

```
..b..LbL

```

Run and debug online!

Alternative version with a pretty cheap trick that can be applied to proper quines in almost any language.

```
"43bL"34bL

```

Run and debug online!

Because `"34bL"34bL` is a proper quine in Stax.

Yet another version, using only single-char string literals.

```
''c'Lc'cccLcLL

```

Run and debug online!

## Explanation

```
.S.S        Generates powerset ["","S","S.","."]
            Implicit flatten and output

..b         Push string ".b"
   ..L      Push string ".L"
      b     Duplicate both strings
       L    Concatenate all 4 strings to a single one.

```

# Answer
> 1 votes
## , 2 bytes

```
1-

```

## Explanation

```
a   % (Implicit) argument of the input
    % The input is automatically set to 0
    % if it isn't specified
 1- % Minus 1 over the input (i.e. 0-1 = -1)

```

Output:

```
-1

```

# Answer
> 1 votes
# Keg, 8 bytes

```
`.,:`:,.

```

Try it online!

A rearrangement of the usual quine.

# Answer
> 0 votes
# 05AB1E, 13 bytes

```
"34çJ∞"34çJ∞

```

Outputs:

```
34çJ∞""∞Jç43

```

Try it online!

```
"34çJ∞"      # Push this string                 | [ 34çJ∞ ]
       34ç   # Push a quote (")                 | [ 34çJ∞, " ]
          J  # Join                             | [ 34çJ∞" ]
           ∞ # Mirror                           | [ 34çJ∞""∞Jç43 ]
             # Implicitly output with a newline

```

# Answer
> 0 votes
# C, 60 bytes

```
main(s){printf(s="main(s){s=printf(%c%s%1$c,34,s);}",34,s);}

```

Just the shortest C quine with trivial modifications.

Output:

```
main(s){s=printf("main(s){s=printf(%c%s%1$c,34,s);}",34,s);}

```

Try it online!

# Answer
> 0 votes
# shortC, 34 bytes

```
Bs){Rs="Bs){s=R%c%s%1$c,34,s",34,s

```

Output:

```
Bs){s=R"Bs){s=R%c%s%1$c,34,s",34,s

```

Try it online!

# Answer
> 0 votes
# str, 10 bytes

```
`2xr;`2xr;

```

Try it online! Outputs ``2xr;2xr;``

```
`2xr;`2xr;
.........;   preamble
`2xr;`       a string containing those character
      2x     repeat twice
        r    print the representation of that doubled string
         ;   end preamble (no program)

```

# Answer
> 0 votes
# Jelly, 7 bytes

```
“ØvṚ”Ṙv

```

Try it online!

# Answer
> 0 votes
# Braingolf, ~~36~~ 32 bytes

```
"V#!1+!@@R!&@&@;"V#!1+!@@R!&@&@;

```

Try it online!

Outputs `""V#!1+!@@R!&@&@;V#!1+!@@R!&@&@;`, which is the source, but with both `"` at the start, the `;` is required at the end to prevent a trailing newline

## Explanation:

```
"V#!1+!@@R!&@&@;"V#!1+!@@R!&@&@;
"V#!1+!@@R!&@&@;"                 Pushes the charcode of each char in the string
                 V                Create stack2 and switch to it
                  #!              Push charcode of !
                    1+            Increment to charcode of "
                      !@@         Print twice, popping the 2nd time
                         R        Return to stack1
                          !&@&@   Print entire stack twice, popping the 2nd time
                               ;  Suppress implicit output to prevent trailing newline

```

Alternatively (not sure this one actually meets the requirement of it being a proper quine):

## Braingolf, 2 bytes

```

1

```

`\n1`, outputs `1\n`

## Explanation:

```
\n1
\n   No-op, does nothing
  1  Pushes 1
     Implicit output of last item on stack plus trailing newline

```

# Answer
> 0 votes
# Java 8, 88 bytes

```
v->{String s="-v>{String s=%c%s%1$c;return s.format(s,34,s);}";return s.format(s,34,s);}

```

Outputs with both `v` and `-` swapped as anagram:

```
-v>{String s="-v>{String s=%c%s%1$c;return s.format(s,34,s);}";return s.format(s,34,s);}

```

**Explanation:**

Try it online.

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

# Answer
> 0 votes
# Microscript II, 8 bytes

```
"phq"pqh

```

# Microscript, 11 bytes (also a reverse quine):

```
0"Caxq"Caxq

```

# Answer
> 0 votes
# Jelly, 6 bytes

```
00,”ṘṘ

```

Try it online!

Output is

```
0,”Ṙ0Ṙ

```

# Answer
> 0 votes
# GolfScript, 8 bytes

```
{}*{.*}.

```

Output is `{.*}{.*}`

Works because the first three characters are garbage to find a way to get another set of braces in the program that don't show up.

If you don't care about whitespace, then `{+}{.}+.` outputs `{+ .}{+ .}`, which was my first attempt.

Try it online!

# Answer
> 0 votes
# Excel, 38 bytes

```
=REPT("=REPT(CHAR(34),2)&"&CHAR(34),2)

```

Output is:

```
=REPT(CHAR(34),2)&"=REPT(CHAR(34),2)&"

```

If you sort and concatenate the characters from either, you get this:

```
""&&(((()))),,==223344AACCEEHHPPRRRRTT

```

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