title: Restricted Meta-Cat

text:
# Question
Title: Restricted Meta-Cat
Your challenge, should you choose to accept it, is to write a program in a language of your choice that, when given a string (limited to printable ASCII) as input, outputs a new program in the same language that outputs that string *without using any characters from that string in the code.*

But this task is impossible as-is in many languages; for example, if the string to print contains every ASCII character. So instead, your submission will choose a subset of printable ASCII which is guaranteed not to be in the input. Your score will be the size of the set, with lower score being better, and shortest code length (in bytes) as a tiebreaker.

An example solution might be the following:

> ## Python, 64 bytes / score 17
>
> ```
> lambda s:"print('\\"+'\\'.join([oct(ord(c))[2:]for c in s])+"')"
>
> ```
>
> Restricting the set `print()'\01234567`.

Now that's enough dawdling—go program!

## Rules / clarifications

* "Same language" includes any compiler flags used in the submission.
* The outputted program should be a full program with output on STDOUT.

# Answer
# Python, ~~121~~ 90 bytes / score 3

```
lambda s:f"ｐｒｉｎｔ({'+'.join('ｃｈｒ('+'+Ｔｒｕｅ'*ord(c)+')'for c in s)})"

```

Attempt This Online!

*-31 thanks to l4m2*

NFKC normalization! The only reserved characters are `(+)`, and everything else is done with identifiers written ｉｎ ｆｕｌｌｗｉｄｔｈ ｃｈａｒａｃｔｅｒｓ.

Builds codepoints up as sums of `True`.

It feels almost possible to go down to 2... almost. Constructing the codepoints with just `()` seems maybe doable with some kind of `str`/`repr` layering, but it takes either `+` or `,=` to `print` it all on one line... and I also have half a mind to cut `print` out of the picture, but it seems like it would take `,.` to go the `open(1, 'w')` route.
> 10 votes

# Answer
# Jelly, ~~19~~ ~~11~~ 10 bytes / score 0

```
O”‘ẋp”Ọj”®

```

Try it online!

*-1 thanks to Jonathan Allan*

Encodes arbitrary strings as programs with no ASCII whatsoever, using increment spam for charcodes and unparseable nilads to both print and reset to 0.

```
O             Codepoints of the input.
 ”‘ẋ          Repeat ‘ (increment) that many times for each codepoint.
    p”Ọ       Append Ọ (convert from codepoints) to each.
       j      Join on
        ”®    the register nilad (0 unless set otherwise).

```
> 9 votes

# Answer
# Brain-Flak, 78 bytes / score 2

```
{({}<>)<>}<>{<>(((((()()()()()){}){}){})())<>{({}[()])<>((({}[()])()))<>}{}}<>

```

The input cannot contain either of `()`.

Try it online!

And readable version:

```
# Reverse the input
{({}<>)<>}
<>

# For each character...
{
    # Push '()' to alternate stack
    <>
    (((((()()()()()){}){}){})())
    <>

    # While true...
    {
        # Subtract one from the character on top of the stack
        ({}[()])

        # On the alternate stack...
        <>
        # Remove the '(' on top, and insert '()' underneath it, then put it back
        ((({}[()])()))
        <>
    }{}
}<>

```
> 8 votes

# Answer
# ;#+, subset size 2, 40 bytes

```
;;;;;~+++++++>~;~++++:>*(-(;~<#~):<#-*:)

```

Try it online! Input is terminated with a null byte. Assumes the input does not contain `;` or `#`.

## Explanation

As this is a repost of my answer to another question from 2017, you can find a detailed explanation there. On a high level, it just generates constants for `;` and `#`, and for each character in the input, the program outputs that many `;`, followed by a `#`.

;#+ being a superset of ;# allows us to reuse the code from the linked challenge without modification.
> 7 votes

# Answer
# Charcoal, 12 bytes, score 0

```
⭆Ｓ⁺´℅´Ｌ×´¶℅ι

```

Attempt This Online! Link is to verbose version of code. Accepts any Unicode character other than NUL and `℅Ｌ¶` that the output uses (the last one being `\n` in Charcoal's code page; the resulting program can't properly print newlines, but you can use `\r` instead). Run the sample output: Try it online! Explanation:

```
 Ｓ              Input string
⭆               Map over characters and join
   ´℅´Ｌ         Literal string `℅Ｌ`
  ⁺             Concatenated with
        ´¶      Literal string `¶` (bare `¶` would be `\n`)
       ×        Repeated by
           ι    Current character
          ℅     Take the ordinal
                Implicitly print

```

The resulting program contains a number of strings of the form `℅Ｌ¶¶¶...¶¶¶` each of which outputs the Unicode character with the code point given by the number of s.

Since the resulting programs get long quickly, here's a longer program that outputs shorter programs:

```
⭆Ｓ⁺´℅⍘℅ι”y⁰¹²³⁴⁵⁶⁷⁸⁹

```

Try it online! Link is to verbose version of code. Accepts any Unicode character other than NUL and `℅⁰¹²³⁴⁵⁶⁷⁸⁹` that the output uses, although the restriction on `\n` still applies. Run the sample output: Try it online! Explanation: Converts the ordinals of the input characters into Charcoal's digits (which aren't printable ASCII), with  telling the resulting program to convert them back into Unicode.
> 6 votes

# Answer
# Vyxal `Ds`, 67 bitsv2, 8.375 bytes, score 0

```
C\›*`ø⟇₴`+

```

Try it Online!

Bitstring:

```
0101011101110101111010001011001000010010000000010100011110100110010

```

The set is the entire vyxal code page minus `⟇₴ø›`. Vyxal's code page contains printable ascii in the same spots as Unicode which is very convenient.

## Explained

```
C\›*`ø⟇₴`+
C           # Convert to a list of Unicode code points
 \›*        # Repeat › per each character
    `ø⟇₴`+  # And add this string
     ø⟇     #   Index into the vyxal code page
       ₴    #   Print without a newline. This makes the top of the stack empty.

```

Created with the help of Luminespire.
> 5 votes

# Answer
# Ruby, ~~92~~ 50 bytes, score ~~8~~ 7

```
->e{'$><<$==""<<'+(e.bytes.map{|x|[1]*x*?+}*"<<")}

```

Try it online!

### How

In Ruby, the string operator `<<` converts an integer to a codepoint, and appends the corresponding character.

Starting with the empty string, we can append all characters of the original string as numbers, and send the result to standard output (`$>`). Using `$=` (deprecated variable warning) to avoid wrapping the string in brackets, and saves 1 character.
> 5 votes

# Answer
# Python, 87 bytes, score 9 (ASCII only code)

*See Unrelated String's solution for a lower score by using non-ascii characters*

*-4 bytes, thanks to noodle man*
*-9 bytes, thanks to l4m2*

---

```
def f(s):print(f"exec({'+'.join('chr('+'+1'*ord(c)+')'for c in f'print({repr(s)})')})")

```

Attempt This Online!

encodes string using `exc()hr1+`

## Explanation

Encodes string as `exec(chr(1+...+1)+chr(1+1+...)+...)`

The executed code is `print(S)` with `S` being the string-representation of the input. The characters in the string are represented as sums of `1`'s

---

# Python, 85 bytes, score 11

```
def f(s):print(f"exec({'+'.join(f'chr(0b{ord(c):b})'for c in f'print({repr(s)})')})")

```

Attempt This Online!

encodes string using `exc()hr0b1+`
> 3 votes

# Answer
# Java, 202 bytes, score 18

```
interface M{static void main(String[]a){("interface I{static void main(String[]a){System.out.print(\""+a[0].replaceAll("\\\\|\"","\\\\$0")+"\");}}").chars().forEach(c->System.out.printf("\\u%04x",c));}}

```

Attempt This Online!

Java interprets unicode escapes `\uABCD` everywhere, not only in String literals. This way, we can write a program using only the characters `\u0123456789abcdef`.
> 3 votes

# Answer
# Javascript with JsFuck lib, 6 restricted, 43 bytes

```
x=>JSFuck.encode(`x=>`+JSON.stringify(x),1)

```
> 3 votes

# Answer
# Brainfuck, 49 bytes / score 3

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

```

Attempt This Online!
> 3 votes

# Answer
# JavaScript, 66 bytes, score 15

Using the restricted set `alert`\01234567`:

```
s=>"alert`"+s.replace(/./g,c=>"\\"+c.charCodeAt().toString(8))+"`"

```

Uses deprecated octal string literals and alert with a tagged template function call. I was worried that `alert` would stringify the tagged template as `[Object object]` but fortunately for me that did not happen.

I wrote this on my phone so I can’t insert a stack snippet at the moment.
> 2 votes

# Answer
# 05AB1E, score 0 (14 bytes)

```
Ç'ǝ×»“”ÿ”Åγιнç

```

Output of the output program is a list of characters.

Try it online.
Try the outputted program online. (Feel free to remove the `J`oin in the footer to see the actual list output.)

**Explanation:**

```
Ç              # Convert the (implicit) input-string to a list of codepoint-integers
 'ǝ           '# Push string "ǝ"
   ×           # Convert each codepoint to a string with that many "ǝ"
    »          # Join this list of strings with newline delimiter
     “”ÿ”Åγιнç # Push (dictionary) string "”ÿ”Åγιнç",
               # where the `ÿ` is automatically replaced with the earlier string
               # (after which the result is output implicitly)

```

```
”ǝǝǝ...ǝǝǝ
...
ǝǝǝ...ǝǝǝ”     # Push (dictionary titlecase) string with "ǝ" and newlines
Åγ             # Run-length encode it; pushing pair ["ǝ","\n"] and a list of lengths
  ι            # Uninterleave the list of lengths into two parts
   н           # Pop and leave just the first part (the lengths of the "ǝ"-lines)
    ç          # Convert each from a codepoint-integer to a character
               # (after which this list of characters is output implicitly as result)

```

Some notes:

1. `ǝ` is used, since `'ǝ×` nor `'ǝǝ` are dictionary words. But any non-ASCII character that doesn't form dictionary words would be fine here.
2. and  are used to prevent the ASCII-quote `"`. Luckily, none of `”ǝ`/`ǝǝ`/`”Å`/`Åγ`/`γι`/`ιн`/`нç` are dictionary words.
3. An approach similar to the Jelly/Vyxal answers using an increment won't work in 05AB1E, since the increment-by-1 builtin is an ASCII-character: `>`.
> 2 votes

# Answer
# Ly, Length 20 / Score 4

Input cannot have 4 characters `0`&o`.

```
&ir[0u['`o,]p]"&o"&o

```

And at a high level, the code reads all input as codepoints, then converts each character to a `0` and as many "increment the top of stack" instructions as is necessary to get to the codepoint value. Then it appends `&o` to the end to print the entire stack as characters.

```
&ir                   - read input as codepoints, reverse stack
   [         ]        - loop once for each char on the stack
    0u                - push a "0" onto the stack
      [    ]          - while number is >0
       '`o            - print "`" (the increment instruction)
          ,           - decrement the top of stack
            p         - delete the loop variable from the stack
              "&o"    - push "&o" (print whole stack instruction)
                  &o  - print stack

```

Try it online!
> 2 votes

# Answer
# Uiua, 22 bytes, score 4

```
⍜⇌'⊂@"⊂"&p-π\""+π

```

Try it!

restricted set is `&p-"`

this would be much easier if the implicit stack printing didn't put quotes around strings, as it stands i could not get rid of &p, either `-` or `+` for offsetting the codepoints, or `"`, `$` , or `@` and a lot of s
> 2 votes

# Answer
# brainfuck, 76 bytes/ score 2

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

```

Try it online!

All brackets are `<>` balanced so the reordering tool should help
> 2 votes

# Answer
# C (gcc), 171 bytes, score 14 `main(){}prtf&+`

```
#define f(c,d)for(k=c+1;k--;)printf(#d);
n;k;g(){f(n,main)}main(c){for(;c=~getchar(g());){f(,(a){)f(c+38?-2-c:9507,if(++a))f(,if\50)g(++n);f(,(printf(&a))\51{}})}f(,(){})}

```

Try it online!

Try Generated online!
> 2 votes

# Answer
# Japt, ~~25~~ ~~32~~ 29 bytes, score ~~2~~ 1

```
©"ºº»Â½{'ÄpUÌc}¹d¹ã½Ñ{ßU¯J}¹¬

```

Try it

Saved 3 bytes thanks to @Shaggy!

The only ASCII character that the output uses is `d`. I am 99% certain that there is no way to get arbitrary strings without using `d`.

I didn't think that score 1 was possible until I was looking through Japt's docs for a method that could concatenate strings or lists whose name was non-ASCII. When I wrote my first solution, I dismissed what I saw as not being usable for the purpose of creating arbitrary strings. However, when returning to this problem yesterday, I found the method `ã`.

`ã` returns all substrings of a string, optionally taking a length that the substrings must be of. But as it turns out, it also takes an optional second parameter which is prepended to the list of substrings.

This solution recursively generates the resulting program with a string literal containing the boilerplate for the connection of each letter.

The first step is `©`, which does short-circuiting logical AND of the input and what follows. The result is that if the input is an empty string, it is returned, otherwise the program continues execution.

Now the string literal starts. The first bit is `ºº»½Ñ`, followed by an interpolation of the expression `'ÄpUÌc` which essentially converts a character to the string `Ä` repeated the codepoint of the character times. Then follows the string `¹d¹`.

* This section creates the code to have an arbitrary character without using ASCII (except for `d`). A single character is generated using a similar technique to my previous solution by using long lines of `»½ÑÄÄÄÄÄÄ…ÄÄÄÄ¹d¹`, which is essentially getting the character at codepoint `1+1+1+1...+1`, plus a longwinded way to get out of using parentheses.

Next, the string `ã½Ñ` is the code to prepend the rest of the string.

The rest of the string's code is generated by recursing with the last character chopped off (`ßU¯J`).

Finally, the string `¹¬` will join each section from a list to a string.
> 1 votes

# Answer
# Julia 1.0, 75 bytes / score 5

```
!s="µ()=(µ(µ)=µ)"*join(("('µ'-('$('µ'-i+'µ')'-'µ'))" for i=s),'µ')

```

Try it online!

the used ascii characters are `'()-=`. Other characters used are `µ` (a lot) and `ì` to `Ŋ` depending on the needed characters.

creates a function that ouputs the string by concatenating Chars, which are constructed by substracting non-ascii characters, for example `'A' == 'µ'-116 == 'µ'-('ĩ'-'µ')`

concatenation in Julia is `*`, which can be implied in some case. That's why we create the identity function `µ(µ)=µ`:

`µ('a')µ('b') == µ('a')*µ('b') == 'a'*'b' == "ab"`
> 1 votes

# Answer
# Google Sheets, score 13 / 92 bytes

`=let(p,join(,"=",sort("символ("&code(mid(A1,sequence(1,len(A1)),1))&")&")),left(p,len(p)-1))`

Put the input in cell `A1` and the formula in `B1`.

When the input is `abc123`, the formula gives this output:

`=символ(97)&символ(98)&символ(99)&символ(49)&символ(50)&символ(51)`

The set of printable ASCII in the output is `0123456789()&`.

The output is a valid formula in Google Sheets in any locale, including Latin locales such as United States. When the output is evaluated as formula, its result is `abc123`.

The formula uses the equivalent of the `char()` function in Cyrillic, `символ()`, whose name doesn't match any Latin letters (`console.log('символ'.match(/\w/))``null`).
> 1 votes

# Answer
# Unary, \\$8.71412 \times 10^{420}\\$ bytes, score 1

…Obviously, I will not be posting the full code here. Or anywhere. It is `8714123138855978699360164050596229281826476597589481446286633953212548084711579903126530450262195558539773177853879595103615733973606156395440197295886222547053888870061749608029900423204725572303716359786086331805843402197818088474380787864934634643574154692137242860845559867854533001295180659830847166956220859057004333374262038608140098168588215568980939574816997785951406147471781245309306817118354877602371834815751` bytes long. That's a lot of bytes.

Handles all characters as input but `0`, which is the only character that appears in the output. A rare case where Unary does not trivialize a challenge like this? I've had my eyes set on a non-trivial score 1 answer for a while, and Unary is a perfect candidate.

Here is the script I used to generate the program size, and here is the corresponding Brainfuck program (formatted with newlines for readability):

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

```

Assumes an interpreter with dynamic memory (right-infinite) and EOF = 0 (or 0x00 manually appended to the input).

Unfortunately, even this program is obscene, since we do still have 8-bit cells. We store the unary output program as a series of 1s on the tape, which grows exponential with the input size. As a proof of concept, you can Try it online! with input 0x02. This outputs some debug information to show that the corresponding program in Unary is `1 010 010 100 000` (corresponding to `++.>`), which corresponds to the 5,280 0s which follow that debug information.

# Explanation

Here is my fully commented corresponding Brainfuck program:

```
[-][
  ASSUMES:
   - Dynamic Memory Tape (Right-Infinite)
   - EOF = 0x00 and/or null terminated input

  for reference, the Unary bijection:
  | > corresponds to 000
  | + corresponds to 010
  | . corresponds to 100

  our desired output is Nx'0' characters, where
  |        +   +  ...  +   .   >   +   +  ...  +   .   >  ...
  | N = 1 010 010 ... 010 100 000 010 010 ... 010 100 000 ...
  |       {ord n.0 times}         {ord n.1 times}

  assuming dynamic tape memory (but finite cell size), since we need only to output
  in unary, we may store N as a unary integer in tape size

  our bit to unary algorithm can be expressed on a high level:
  | for each bit:
  |   n *= 2
  |   if bit:
  |     n++
  |   end if
  | end for

  we need to be able to stream bits from the input not proportional to the input size
  that is, there is a large, variable number of bits corresponding to each , input
  we will try to process this character-by-character instead of reading all the input
  and generating the corresponding bit string, and iterating over that afterwords, so
  as to hopefully avoid weird tape layouts

  assuming some procedure for emit, our algorithm works as:
  | emit 1
  | for each input character C:
  |   while C is not 0:
  |     emit 010
  |     C -= 1
  |   end while
  |   emit 100
  |   emit 000
  | end for
  | for each bit in unary representation, output '0'

  however, obviously, we do not procedure calls available to us. ideally, we linearize
  our loop to be in terms of processing emitted bits:
  | C = input
  | loop:
  |   if C == 0:
  |     emit_bits = 1 0 0
  |   elsif C == 255:
  |     emit_bits = 0 0 0
  |     C = input
  |     if C is EOF:
  |       break
  |     end if
  |     C = C + 1
  |   else:
  |     emit_bits = 0 1 0
  |   end if
  |   times 3:
  |     double bitstring
  |     if cur_bit:
  |       increment bitstring
  |     end if
  |     move_bit_right
  |   end times
  |   C -= 1
  | end loop

  we can abuse the fact our input is guaranteed to be printable ascii and use 255 (-1)
  as a state value to get an extra 3 bits per input character

  as for implementing this algorithm, our tape layout will be:
     0: L (looping counter for break)
     1: C (input character)
     2: t0 (temp)
     3: t1 (temp)
     4: e0 (emit bit)
     5: e1 (emit bit)
     6: e2 (emit bit)
     7: t3 (3 counter)
     8: 0 (0 padding)
     9: 0 (0 sentinel)
    10: 1 (start of unary representation)
]

real code starts here

+ set L
>, get input
>> move past temps
>>> move past e0 e1 e2
> +++ set counter
> > two 0s of padding
> + emit 1

debug initial unary representation
debug++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------
>debug++++++++++++++++++++++++++++++++.--------------------------------<

L < << <<< <<< < return to looping counter

[
  if else algorithm with (C t0 t1) tape layout
  C>
  temp0> [-]+ temp1> [-] C<< [
    IF C NOT ZERO
    >>
    >[-]  e0 = 0
    >[-]+ e1 = 1
    >[-]  e2 = 0
    <<< <<

    (temp0 temp1) = (1 0) at this point always so we can reuse them
    as long as they are that way to end with
    recall our if else algorithm requires t0 to be 1 initially anyway
    C+ test for c being 255 that is negative 1
    C[  {empty else}  temp0> - C< [temp1>>+C<<-]]
    temp1>>[C<<+temp1>>-]
    temp0<[
      {if 255 sentinel}
      e1>>>-  e1 = 0
      debug++++++++++.----------
      C<<<<[-]
      input ,
      here is where we need to detect EOF and set L accordingly
      we can use the same fact to reuse t0 t1 in our if statement
      C[
        ++ increment C
        temp0>-
        C<[temp1>>+C<<-]
      ]
      temp1>>[C<<+temp1>>-]
      temp0<[
        on EOF break by setting L to 0
        L<<-
        temp0>>
      temp0-]
      + restore temp0
      C<

      temp0>
    temp0-]
    C<
    restoration
    C-
    temp0>+
    <

  temp0> - C< [temp1>> + C<< -] ] temp1>> [C<< +temp1>> -] temp0< [
    IF C ZERO
    temp0
    > temp1
    >[-]+ e0 = 1
    >[-]  e1 = 0
    >[-]  e2 = 0
    <<<<<<
    temp0>>
  temp0-]

  debug contents of (e0 e1 e2)
  >>   debug++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------
  >    debug++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------
  >    debug++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------
  <<<< temp0 debug++++++++++++++++++++++++++++++++.--------------------------------

  >> e0

  ADVANCE THE TAPE
  >>>
  [
    >> seek to 0 sentinel
    +[>[<-]<[->+<]>]> seek right to first 1 in tape
    doubling loop
    [
      - erase current 1
      >[>] navigate to right border 0
      >[>] go past rightmost 1 on copy tape to second right border 0
      +>+  add two entries
      [<] go back to first right border 0
      <[<]> navigate to start of 1 tape
    ]
    tape to start was   e0 e1 e2  1 0  {a0 a1 a2 etc}
    tape to end is      e0 e1 e2  1 0  {0  0  0  etc}  0  {a0 a0 a1 a1 a2 a2 etc}
    +[<[>-]>[-<+>]<]< seek left to 1 sentinel
    <<< seek back to e0

    APPEND A ONE IF E0 IS NONZERO
    [
      <+> save to temp0
      - zero out to close loop
      append a 1
      >>>> seek to 0 sentinel
      +[>[<-]<[->+<]>]> seek to first 1 in tape
      [>] seek to end
      + append 1
      [<] seek to start
      +[<[>-]>[-<+>]<]< seek to count sentinel
      <<< seek back to e0
    ]
    <[->+<] add temp0 to e0 (either computes 0 plus 1 or 1 plus 0 so its idempotent)
    > focus back on e0

    permute e0 e1 e2 to e1 e2 e0
    [-<+>>-<]>[-<+>]<<[->>+<+<] swap{@1 @2}
    >>[-<<+>>>-<]>[-<+>]<<<[->>>+<+<<] swap{@2 @3}
    > refocus e0

    >>> seek to count sentinel
    - decrement
  ]
  reset counter +++
  END ADVANCE THE TAPE
  <<<<<
  C<-
  L<
]

>>>>>>>> move past last data entry
+[>[<-]<[->+<]>]> skip all 0s to our unary tape
for each one on the unary representation
[
  output a 0
  +++++++++++++++++++++++++++++++++++++++++++++++.>
]

```
> 1 votes

# Answer
# Japt, 25 bytes, score 1

Noodle man's idea with a different implementation.

```
'¬iUÔ¬£"¹d¹"i'ÄpXcÃq"ã½Ñ»

```

Try it

## Explanations

### Code

```
'¬iUÔ¬£"¹d¹"i'ÄpXcÃq"ã½Ñ»     :Implicit input of string U
'¬i                           :Prepend to "¬"
   UÔ                         :  Reverse U
     ¬                        :  Split
      £                       :  Map each X
       "¹d¹"i                 :    Prepend to "¹d¹"
             'Äp              :      "Ä" repeated
                Xc            :        Codepoint of X times
                  Ã           :End map
                   q"ã½Ñ»     :Join with "ã½Ñ»"

```

### Output

Coming soon
> 1 votes

# Answer
# Zsh, score 12, 50 bytes

Set is `01234567$'\<`.

```
for c (${(s..)1})l+="\\$[[##8]#c]"
<<<'<<<$'\'$l\'

```

Try it online!

Converts each character into `\[N]NN` octal, evaluated by wrapping the string in `$' '` and printed with `<<<`.
> 1 votes

# Answer
# C (gcc), ~~200 192 184 211~~ 203 bytes, score ~~17~~ 16

```
#define P;printf(
#define Q{for(k=~i;k++P"a"))P
i;k;main(j,v)unsigned**v;{for(v++;i*4<strlen(*v);i++)Q"=a==a;");}P"main(){");for(;i--;)for(j=32;j--;)Q"+=");Q";");}if(i[*v]&1<<j)Q"++;");}}P"puts(&a);}");}

```

Try it online!

The input cannot contain `aimnpstu=+;&(){}`

This produces C programs of the form

```
a=a==a;
aa=a==a;
...
main(){
  a++;...
  aa++;...
  puts(&a);
}

```

Try it online!

Thanks to @l4m2 for score -1 and the note from @NoodleMan.

Less golfed version

```
#define P;printf(
#define Q{for(k=~i;k++P"a"))P
i;k;
main(j,v)unsigned**v;{
  for(v++;i*4<strlen(*v);i++)
    Q"=a==a;");
  }
  P"main(){");
  for(;i--;)
    for(j=32;j--;)
      Q"+=");
      Q";");}
      if(i[*v]&1<<j)
        Q"++;");
      }
    }
  P"puts(&a);}");
}

```

# C (gcc) for Linux x86\_64, ~~271 260 253 239~~ 226 bytes, score 8

```
#define P;printf(
unsigned*b,x;i;main(l,v)int**v;{l=asprintf(&b,"j\1X\xbazokaj\1_耀ok%s^\xf\5Ã",v[1]);for(b[1]=b[3]=l-21;i*4<l;b++){P"mai");for(x=++i;x--P"n"))P"=");for(x='B:5\xc7';*b P"+%d",x),*b-=x)for(;*b<x;x/=10)P";");}}

```

Try it online!

The input cannot contain `aimn=+1;`

This produces C programs of the form

```
main=1+11+...;
mainn=1+1+11+111+...;
...

```

Try it online!

Such programs may require the compiler flag `-zexecstack` and may not work on some Linux distributions.

Now supports strings longer than 127 bytes.

Slightly less golfed

```
#define P;printf(
unsigned*b,x;
i;
main(l,v)int**v;{
  // push 1
  // pop rax
  // mov edx, <len of string>
  // push 1
  // pop rdi
  // call L1
  // <string>
  // L1:
  // pop rsi
  // syscall
  // ret
  l=asprintf(&b,"j\1X\xbazokaj\1_耀ok%s^\xf\5Ã",v[1]);
  for(b[1]=b[3]=l-21;i*4<l;b++){
    P"mai");
    for(x=++i;x--P"n"))
    P"=");
    for(x='B:5\xc7';*b P"+%d",x),*b-=x)
      for(;*b<x;x/=10)
    P";");
  }
}

```
> 1 votes

# Answer
# MetaBrainfuck `-x`, 30 bytes / score 2 (`+.`)

`43{_:+}{n:n{.}+++.---256n~{.}}`

*input as program argument*

produces a Brainfuck program that prints a Brainfuck program that prints the Input, then executes that program

## Explanation

```
43{_:+}                        ## output 42 times + (`_:` discards the loop counter)
       {n:                   } ## for each character `n` in the input
          n{.}                 ## repeat `.` n times
              +++.---          ## increment by 3, print decrement by 3
                     256n~{.}  ## repeat `.` 256-n times

```

`-x` executes the generated Brainfuck program, which outputs a program that for each character `C` in the input increments `C` times prints then increments 256-C times resetting the cell back to zero.

Brainfuck Program created for input "Test" (the output for the program will be the result of executing that Brainfuck program):

```
+++++++++++++++++++++++++++++++++++++++++++....................................................................................+++.---.................................................................................................................................................................................................................................................................................+++.---..............................................................................................................................................................................................................................................................................+++.---.................................................................................................................................................................................................................................................................+++.---............................................................................................................................................

```

Running MetaBrainfuck `-x` on the (uncommented) Brainfuck created by the output of the original program will execute the program without modification and print the input of the original program

---

# MetaBrainfuck `-x` , 24 bytes / score 3 (`+.>`)

`{43{_:+}{.}".>"{>{+}.}>}`

*input as program argument*

produces a Brainfuck program that prints a Brainfuck program that prints the Input, then executes that program

## Explanation

```
{                      }   ## for each character in the input
 43{_:+}                   ## output 42 +  ( `_:` discards the loop counter)
        {.}                ## print . char-code many times
           ".>"{     }     ## for each character C in ".>"
                >{+}.      ## output  > followed by C times + followed by a .
                      >    ## print >

```

the produced Brainfuck program then prints C times `+` followed by `.>` for each character C in the input, the `-x` flag the immediately executes that program.

Program created for input "Test":

```
+++++++++++++++++++++++++++++++++++++++++++....................................................................................>++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++.....................................................................................................>++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++...................................................................................................................>++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++....................................................................................................................>++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

```
> 1 votes

# Answer
# Morsecco: 54 bytes, score 3

Being a three-symbol language, a meta-cat automatically reaches a score of 3:

```
> echo Test | morsecco '. . . - .-. -.- .- -.-. ... .  -.- - ---  -.-. ... ---'
.  -.-.-.. --..-.- ---..-- ---.-.. -.-.  -.- - ---
> morsecco '.  -.-.-.. --..-.- ---..-- ---.-.. -.-.  -.- - ---'
Test

```
* `. .` `E`nters an `E`nter command
* `. - .-.` `R`eads from stdin (special address `T`)
* `-.- .-` `K`onverts from `·T`ext
* `-.-. ...` `C`oncatenates the dot and the converted input with two spaces for multi-token input
* `. -.- - ---`  is the multi-token input for the later `K`onvert to `T`ext and `O`utput
* `-.-. ...` `C`oncatenates this to the existing code
* `---` `O`utput the code

# Morsecco:  ~~217~~  216 bytes, score 0

Yes, we can also do a zero-score version, because morsecco accepts alternatives for it's characters:

* TAB can be used instead of whitespace
* a long dash  (unicode 0x2013) can be used as dash
* the middle dot `·` (unicode 0x00B7) can replace the dot

Of course, this adds a lot of bytes:

```
.  -- . -- .  . . .-- . . . - .-. -.- .- -.-. ... .  -.- - ---  -.-. ...
-- - -.-. - -.- .- . .-..... .- --.. ..
. .---. .- --.. --.
- .- . -........-..-- -- --.. --.
. -.--.--- -- --- --. ..
. -..-
-.- - . - .-- --.

```

The first line remains the same just installing an error handler to silently exit on the end of input to avoid testing for more bytes, but then we need to loop over the string, cutting one byte each time and translating it, because by now morsecco has no substitution command.
> 1 votes

# Answer
# Rattle, 23 bytes, score 3

```
|II^P[gn[b"+"]`b",=">]`

```

Try it Online!

The input cannot contain `+,=` characters.

This generates Rattle code that uses `+` to increment from 0 to the ASCII value of each character before printing the ASCII character with `,` and resetting the counter with `=`. The new code therefore only uses the characters `+,=` for a score of 3.

# Explanation

```
|                     get input
 I                    save input characters to consecutive memory slots
  I^                  get length of input
    P                 set pointer to 0
     [...]`           repeat N times (N = input length)

g                     get the character at the pointer
 n                    get the ASCII value of this character
  [....]`             repeat M times (M = ASCII value of the character)
   b"+"               add "+" to the print buffer
         b",="        add ",=" to the print buffer
              >       move pointer right

```

This generates code of the form `++++++++++,=++++++++,=++++,=` (where there are lots more `+` depending on the ASCII value of the input characters).
> 1 votes

# Answer
# YASEPL, 24 bytes / score 2

```
=b$34»=a'#hashtag!~!a~!~

```

the restricted char set being `#"`. YASEPL is not capable of template strings
> 1 votes

# Answer
# GolfScript, ~~24~~ ~~22~~ ~~18~~ 17 bytes, score 4

```
{("1+"*1n@}/'](+'

```

Try it online!

The restricted set is `(]1+`. I'm pretty sure this is minimal, but GolfScript is a weird language and I'm no expert on it.

This constructs an a program that looks something like:

```
1
1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+](+

```

This pushes arbitrary codepoints to the stack with `1 1+1+...1+`, using a newline as whitespace because it isn't printable. Then, `]` ends a list literal, which turns the whole stack into a list because there was no previous `[`. Finally, `(+` coerces the list of codepoints to a string by adding it to the empty input, and the result is implicitly outputted.

Here's an explanation of the generator code, which I think is probably also as short as it can get:

```
{("1+"*1n@}/
{         }/  # For each character of the (implicit) input:
 (            #   Decrement the codepoint.
  "1+"*       #   Repeat "1+" that many times.
       1n     #   Push the number 1, then push a newline.
         @    #   Move the "1+1+..." string to the top of the stack.

'](+'         # Push the string ](+ to the stack.
              # The entire stack is implicitly outputted.

```

Created with the help of Luminespire.
> 0 votes

---
Tags: code-challenge, code-generation
---


title: Code point sum quine

text:
# Question
Title: Code point sum quine
All the challenges on this site are focused on byte count, or the characters themselves. This one is different. Your challenge is to write a program that produces output which has a code point sum identical to the source's code point sum.

To produce a code point sum:

1. Find the values of the characters in the program's character set.
For example - `FOO` in ASCII: `F` = 70, `O` = 79, `O` = 79
2. Add them all together.
Code point sum of `FOO` in ASCII: `F`+`O`+`O` = 70+79+79 = 228.

An example of an ASCII sum quine would be if the source code was `ABC` and the output was `!!!!!!`. This is because the sum of the the ASCII values of the source (`A` = 65, `B` = 66, `C` = 67, sum = 198) is the same as the sum of the ASCII values in the output (`!` = 33, 33\*6 = 198). `BBB` would also be valid output, as would `cc`.

# Rules

* Your program must not be a reverse, shuffled, error, or any other type of "true" quine. To elaborate: If the output contains all the same characters as the source, it is invalid.
* Your program cannot use any errors/warnings from the compiler/interpreter as the output.
* Your program's source must use the same codepage as the output.
* Your program may use any codepage that was created before this challenge was.
* Your program's output must not contain any unprintable characters (e.g. ASCII 0 through 31, or above 127) aside from linefeeds and tabs.
* Standard loopholes apply.
* If the source and/or output has a trailing linefeed, it must be included in the code point sum.
* Compiler flags need to be included in the final byte count (score), but not the source's code point sum.
* The output/source may not be empty.

# Scoring

Shortest answer in byte count (not code point sum) wins. Please use this header format answers:

```
# Jelly, 12 bytes, sum 56 (SBCS)

```

You can use this tool to calculate ASCII sums.

# Reference

Here are some useful codepage references.

```
/* Configuration */

var QUESTION_ID = 135571; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = (function(){
  var headerTag     = String.raw `h\d`
  var score         = String.raw `\-?\d+\.?\d*` // with negative/floating-point support
  var normalText    = String.raw `[^\n<>]*` // no HTML tag, no newline
  var strikethrough = String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
  var noDigitText   = String.raw `[^\n\d<>]*`
  var htmlTag       = String.raw `<[^\n<>]+>`

  return new RegExp(
  String.raw  `<${headerTag}>`+
  String.raw    `\s*([^\n,]*[^\s,]),.*?`+
  String.raw    `(${score})`+
  String.raw    `(?=`+
  String.raw      `${noDigitText}`+
  String.raw      `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+
  String.raw      `</${headerTag}>`+
  String.raw    `)`
  );
})();

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<i>' + a.language + '</i>').text().toLowerCase();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.uniq > b.uniq) return 1;
    if (a.uniq < b.uniq) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  float: left;
}

#language-list {
  padding: 10px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654">
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>

<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
  </tbody>
</table>
```

# Answer
# Retina, 1 byte, sum = 58 (ASCII)

```
:

```

This counts the matches of `:` in the input (**0**), so it prints

```
0

```

The code points of `:`, `0`, and LF (linefeed) are **58**, **48**, and **10** (respectively), and **58 = 48 + 10**.

Try it online!
> 26 votes

# Answer
# ArnoldC, 316 bytes, sum 20992 (ASCII)

Fun enough.

```
IT'S SHOWTIME
HEY CHRISTMAS TREE s
YOU SET US UP 1
HEY CHRISTMAS TREE iaV
YOU SET US UP 0
STICK AROUND s
GET TO THE CHOPPER iaV
HERE IS MY INVITATION iaV
GET UP 8
ENOUGH TALK
TALK TO THE HAND "H"
GET TO THE CHOPPER s
HERE IS MY INVITATION 2048
LET OFF SOME STEAM BENNET iaV
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED

```

I used this and this to do my calculations. Took me an hour and a half. But fun.

Try It Online!

**How it works**

`STICK AROUND` is a loop, that loops `2048` times on the index `iaV`, but this index steps by `8`. So there is `256` loops, printing `H` and a linefeed (72+10 = 82, 82\*256 = 20992).

This is still *HIGHLY* golfable (by finding other calcs) but it is long and boring to measure your byte sum every time you do a modification.

Please tell me if I'm mistaken anywhere.
> 15 votes

# Answer
# Charcoal, 1 byte, sum = 180 (Charcoal SBCS)

Try it online! In Charcoal's code page,  has a code of `0xB4 = 180`, while the output is 4 `-`s which is `4 * 45 = 180`.
> 9 votes

# Answer
# Python 2, 11 bytes, sum 838 (ASCII)

```
print 76**8

```

prints

```
1113034787454976

```

Not very clever but it works

Try it online!
> 8 votes

# Answer
# CJam/Japt/bc, 2 bytes, sum 97 (ASCII)

`A`

Try it Online (CJam), Try it Online (Japt) (thanks @shaggy),

The bc version works on command line, but not TIO.

Outputs `10`

Source: `A` \+ `Space` = 65 + 32 = 97

Output: `1` \+ `0` = 49 + 48 = 97
> 7 votes

# Answer
# Jelly, 12 bytes, sum 948 (SBCS)

You said:

> Jelly, 12 bytes

then it's Jelly, 12 bytes.

```
\
³³³,:D+++

```

Was fun, since I don't know Jelly at all.

**How it works**

I don't have any idea. But `³` does put 100 in the stack, `,` puts the stack in an array or something, `:` might concatenate the thing while `D` lists every letter of the last numeral (which does not exist), and +++ are for fun. The first and last line does not affect the output :)

Try it Online!

Used this to count.
> 7 votes

# Answer
# Haskell, 9 bytes, byte sum 743 (ASCII)

Code:

```
show$29^9

```

Output:

```
14507145975869

```

Try it online!
> 5 votes

# Answer
*Some of these answers contain characters that will likely be invisible to you (particularly ASCII 17), click the TIO links to see their placement.*

# Klein 100/110, 4 bytes, sum 147

```
1
@

```

Try it online!

Output:

```
1 1

```

# Klein 201, 4 bytes, sum 147

```
1
@

```

Try it online!

Output:

```
1 1

```

# Klein (any topology), 5 bytes, sum 221 (ASCII)

```
111@

```

Try it online!

This prints

```
1 1 1

```
> 5 votes

# Answer
# Cubically, 4 bytes, sum 141 (ASCII)

```
%44E

```

Outputs `3636`. Try it online! And here's the ASCII sum checker I used.

Explanation:

* `%` means 'print face sum as integer'.
* `4` prints the sum of all values on the BACK face (36) twice.
* `E` is a no-op, just used to get the required sum.
> 5 votes

# Answer
# Java 7, ~~88~~ 85 bytes, sum ~~7808~~ ~~7617~~ 7507 (ASCII)

```
class
w{public
static
void
main(String[]H){for(int
B=0;B<77;)System.out.print(B++);}}

```

Almost certainly golfable. It's pretty easy to tweak since we have some spare variables like the name of the class and the name of the program arguments parameter that we can change freely.

Test it online!

Try it online!

---

# Java 8, 84 bytes, sum 7434

Credit goes to Kevin Cruijssen.

```
interface A{static void main(String[]G){for(int A=59;A-->0;)System.out.print("~");}}

```

Test it online!

Try it online!
> 4 votes

# Answer
# Python 2, 11 bytes, byte sum 854 (ASCII)

Code (with trailing newline):

```
print'z'*7

```

Output (with trailing newline):

```
zzzzzzz

```

Try it online!
> 3 votes

# Answer
# brainfuck, 3 bytes - byte sum 255 (ISO-8859-1)

```
-.¤

```

Try it online!

Requires 8-bit cells. Prints the character `ÿ`, which is value 255. `¤` is a no-op to fill the sum.
> 3 votes

# Answer
# Mathematica, 2 bytes, sum=101 (ASCII)

E + Space returns e

```
E

```

# Mathematica, 2 bytes, sum=105 (ASCII)

it works for I, too

I + Space returns i

```
I

```
> 3 votes

# Answer
# , 2 bytes, Sum 255 (Latin1)

Try it online!

Hexdump:

```
00000000: 1ee1                                     ..

```

The first character is `ctrl-^`, or LATIN1/ASCII code-point `0x1E`. The second character is `alt-a`, or the LATIN1 character `0xE1`. This program outputs `ÿ`, which is `0xFF` in LATIN1.

How does it work?

The first character is a no-op. It has no effect on the program at all. The second character is the *append single character* command. But we don't specify what character to append. So, due to implicit endings, it appends the character that V uses to signal the program is over, which just so happens to be `0xFF`.
> 3 votes

# Answer
# 05AB1E, 5 bytes, sum 256 (05AB1E Base-255 Translation)

```
ΔTnon

```

Try it online!

---

This outputs: `1606938044258990275541962092341162602522202993782792835301376`

Which, using 05AB1E's code-page results in: `[1, 6, 0, 6, 9, 3, 8, 0, 4, 4, 2, 5, 8, 9, 9, 0, 2, 7, 5, 5, 4, 1, 9, 6, 2, 0, 9, 2, 3, 4, 1, 1, 6, 2, 6, 0, 2, 5, 2, 2, 2, 0, 2, 9, 9, 3, 7, 8, 2, 7, 9, 2, 8, 3, 5, 3, 0, 1, 3, 7, 6]`

Which is: `256`

---

Where the code is: `ΔTnon`

With code-points: `[79, 29, 49, 50, 49]`

Which is: `256`
> 3 votes

# Answer
# Taxi, 543 bytes, sum 47124 (ASCII)

```
374 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 r 1 l 1 l 2 l.Pickup a passenger going to The Underground.'~' is waiting at Writer's Depot.Go to Writer's Depot:w 1 r 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n.[a]Pickup a passenger going to Cyclone.Pickup a passenger going to Post Office.Go to Zoom Zoom:n.Go to Post Office:w 3 l 2 r 1 l.Go to The Underground:n 1 r 1 l.Switch to plan "R" if no one is waiting.Pickup a passenger going to The Underground.Go to Cyclone:n 3 l 2 l.Switch to plan "a".[R]

```

Try it online! (Score verification)

The output is 374 tildes `~`.
> 3 votes

# Answer
# Factor, 7 bytes, sum 250

```
7/2 .

```

Try it online!

Outputs `3+1/2` and a newline.

Factor has a rational number type. When an improper fraction (numerator \> denominator) is printed, it is converted to a mixed fraction form (integer part + proper fraction part).

Since the easiest way to adjust the byte value sum is to add spaces or newlines (which are the only token separators in Factor), I tried various fractions until the code's sum is higher than the output's sum by a multiple of 10, and added a couple newlines at the end.
> 3 votes

# Answer
# Jelly, 3 bytes, sum = 152 (ASCII)

```
58+

```

Try it online!
> 2 votes

# Answer
# Brain-Flak (Rain-Flak), 79 bytes

```
(((((((((((((((((((((((((((((((((()()()()){}){})))))))))))))))))))))))))))))))

```

Try it online!

This prints `16` and a newline 31 times.

# Brain-Flak (BrainHack), 55 bytes

```
(((((((((((((((((((((()()()()){}){})))))))))))))))))))#

```

Try it online!

This prints `16` and a space 18 times.

# Also 55 bytes

```
((((((((((((((((((((((()()()){}){}))))))))))))))))))))

```

Try it online!

This prints `12` followed by a space 19 times.
> 2 votes

# Answer
# Vim, 3 bytes, sum 234 (ASCII)

```
3iN

```

Output:

```
NNN

```

Try it online!
> 2 votes

# Answer
# Carrot, 4 bytes, sum = 279 (ASCII)

```
]^*2

```

Try it online!

Prints `]]]`.
> 2 votes

# Answer
# Cubix, 20 bytes, code point sum 1505

```
OuOOQ++OOOOU@>!OOO<

```

Contains the unprintable character `DEL` (ascii 127).

`Q` pushes `"` (the largest constant available in cubix), then repeatedly prints out (`O`) `68` or `102` enough times to get it to `68686868686868102102102102102` which is 1505; through some trial and error I realized that I needed 81 more points than `.` (a Cubix no-op and ASCII `46`) which resulted in needing `DEL`, which is still a no-op in Cubix.

Try it online!

On a cube:

```
    O u
    O O
Q + + O O O O U
@ > ! O O O  <
    . .
    . .

```
> 2 votes

# Answer
# dc, 7 bytes, sum 720 (ASCII)

```
[my]fff

```

(91+109+121+93+(102\*3)=720)

Outputs:

```
my
my
my

```

((109+121+10)\*3=720)
> 2 votes

# Answer
# Cubix, 11 bytes, byte sum 954 (ASCII)

Code:

```
vOw~N(!@O^|

```

Output:

```
998877665544332211

```

Verified here!

Try it online!

Cubified:

```
    v O
    w ~
N ( ! @ O ^ | .
. . . . . . . .
    . .
    . .

```
* `N` initializes the stack with 10
* `(!` decrement and test for truthy
    + `@` on zero halt
* `O^O` output current number redirect to top face and output again
* `vw` redirect back to the `(` decrement to begin the loop again

Watch it run
> 2 votes

# Answer
# Cubically, 3 bytes, sum = 105 (ASCII)

```
%4

```

The third byte is **DLE**, which has code point **16**, so the code point sum of the source code is
**37 + 52 + 16 = 105**.

The program prints

```
36

```

whose code point sum is **51 + 54 = 105**.

Try it online!
> 2 votes

# Answer
# INTERCAL, ~~47~~ ~~46~~ 45 bytes, sum = 2945 (ASCII...?)

```
PLEASE,8<-#38DO,8SUB#8<-#6DOREADOUT,8DOGIVEUP

```

Try it online!

Prints seven null bytes followed by thirty-one underscores. One of six possibilities generated by a somewhat revised awful hacky Python script.
> 2 votes

# Answer
# Labyrinth, 6 bytes, sum 271 (ASCII)

```
92
9!@

```

Try it online!

Outputs `92299` (the number 92, then the number 299, without separators).

I experimented with small layouts that print some digits in the code twice until I got

```
99
9!@

```

whose output's ASCII sum is 7 higher than code's. Decreasing a digit on the top row by one decreases two digits in the output, which leads to the solution above.
> 2 votes

# Answer
# Ly, ~~10~~ 5 bytes, byte sum ~~679~~ 381 (ASCII)

```
97^u:

```

Outputs:

```
4782969

```

Try it online!
> 1 votes

# Answer
# Husk, 4 bytes, sum 334 (Husk SBCS)

```
up63

```

Output:

```
[3,7]

```

The value of a digit is given by `0x3?` (where `?` stands for that digit) and `u`,`p`,`[`,`]`,`,` have values `0x75`,`0x70`,`0x5b`,`0x5d`,`0x2c` \- thus the sums are:

```
0x75 + 0x70 + 0x36 + 0x33        = 0x14e
0x5b + 0x33 + 0x2c + 0x37 + 0x5d = 0x14e

```

Try it online!
> 1 votes

# Answer
## JavaScript (ES6), 6 bytes, sum = 385 (ASCII)

```
Y=>1E7

```

Outputs `10000000`. There are other 6 byte answers such as `h=>1e8`. Try this code point counter:

```
<input oninput=o.textContent=[...this.value].reduce(function(s,c){return(s+c.charCodeAt())},0)><pre id=o>0
```
> 1 votes

# Answer
# cQuents, 5 bytes, sum 238 (ASCII)

```
#3::$

```

Outputs `1,2,3`, or in cQuents terms, prints the first three terms of the sequence `1,2,3,4,5,6...`.

Now listen. This was, literally, the first program I tried. The reason I tried it was because this was the program I used for Output with the same length as code. And it freaking worked.

Try it online!
> 1 votes

# Answer
# Help, WarDoq!, 5 bytes, sum 1052 (Latin1)

```
l³ÿÿÿ

```

Prints

```
Hello World

```

Try it online!

Help, WarDoq! can add two numbers and test for primes, so it is considered as a valid programming language per this meta post.
> 1 votes

# Answer
# Gaia, 4 bytes, sum 176 (SBCS)

```
6 5%

```

## Explanation

In Gaia's codepage, linefeed has a code point of x7F (127 in decimal). Printable ASCII characters have the same code point as in ASCII.

This computes 6 modulo 5, which is 1, and prints `1` with a trailing linefeed.

Byte values of the characters in the codepage (in decimal):

`6 5%`: 54 + 32 + 53 + 37 = 176

`1`: 49 + 127 (linefeed) = 176
> 1 votes

# Answer
# Trumpscript, 131 bytes, sum 10600 (ASCII)

```
They wants to make war 110000000;make dark 10000000;as long as,dark less war;:make dark,dark plus 1000000;say "00"!america is great

```

Is this real life?

Check with this.

Thanks @MagicOctopusUrn for telling me *that* exists.
> 1 votes

# Answer
# PHP, ~~12~~ 9 bytes, sum 481

```
<?=10**9;

```

prints `1000000000`

Try it online.

other solutions:

```
PRINT 5**19;    # 12 bytes, sum 731, output 19073486328125
Print 4/31;     # 11 bytes, sum 815, output 0.12903225806452
Print 8/7;      # 10 bytes, sum 774, output 1.1428571428571
<?=5<<29;       #  9 bytes, sum 523, output 2684354560

```
> 1 votes

# Answer
# Whitespace, 105 bytes, sum 2232 (ASCII)

```

```

Well you can't see the code but it's here .\_.

I did put two `<tab>`s at the end (that doesn't affect the program) to match sum.

**Explanation**

The program counts from 1 to 24. I used the example you can find in this tutorial at the Annotated Example section.
For those who don't want to check this tutorial:
It puts your number onto the stack, then loop until `<line10>`'s number is reached by the number on the stack. The loop prints your number on the stack to stdout, increments it by 1, and puts a space and a linefeed.

Try it online!

Counted with this.
> 1 votes

# Answer
# Cubically (6 bytes, sum 309)

I thought I'd do this in your language just for fun. Turns out the solution is pretty simple since `%` can print out up to two characters for every one character.

```
F1%441

```

Output:

```
363621

```
> 1 votes

# Answer
# ArnoldC, 185 bytes, sum 14508

```
IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 6
STICK AROUND i
TALK TO THE HAND "२"
GET TO THE CHOPPER i
HERE IS MY INVITATION i
GET DOWN 1
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED

```

Try it online!

Code sum

Output sum

Special thanks to V. Courtois and their answer, in particular for providing the sum count scripts.

Pseudocode:

```
start
var i
i = 6
while i
    print "२\n"
    i
    = i
        - 1
    (end assignment)
(end loop)
(end program)

```

At this point, I don't see a way to further golf it, as the rest is boilerplate for ArnoldC... ArnoldC surprisingly supports unicode output, so it was just finding a unicode character which, when repeated 5 times, summed to the same as the code.

---

If printable unicode is off-limits:

# ArnoldC, 187 bytes, sum 12300

```
IT'S SHOWTIME
HEY CHRISTMAS TREE q
YOU SET US UP 150
STICK AROUND q
TALK TO THE HAND "H"
GET TO THE CHOPPER q
HERE IS MY INVITATION q
GET DOWN 1
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED

```

Try it online!

Verification
> 1 votes

# Answer
# Perl 5, 8 bytes, sum = 688 (ASCII)

Input:

```
say"q"x6

```

Output:

```
qqqqqq

```

`x` is the repetition operator in perl. So `"q"x6` is the same as `qqqqqq`. `say` prints the string with a following line feed.
> 1 votes

# Answer
# Z80Golf, 4 bytes, sum 354 (ASCII)

```
00000000: 3676 7e38                                6v~8

```

Try it online!

The output is `vvv`.

Slightly modified from my 3-byte Output same length as code.

### Disassembly

```
start:
  ld (hl), $76  ; 36 76
  ld a, (hl)    ; 7e
  db $38        ; 38 ; jr c, 0

```

As always, `(hl)` allows to use the memory address 0 similar to a register with pre-loaded value. In this case, the program overwrites its first opcode to `halt`, and then loads the same value to `a`. Usual stack underflow causes `v` to be printed three times and return to the start of program.

The last instruction is a no-op added to match the sum. The alternative 3-byte `vvv` program (in the link above) is unusable here because the difference `$7a` translates to `ld a, d`, which interferes with the preceding `ld a, $76` (and it can't be moved in order to halt correctly).
> 1 votes

# Answer
## Keg, 4 bytes, sum=272

Note: This is kept as 4 general pure ASCII one-byte encoding bytes. Keg has multiple code pages, and the user can alternate between them. The pure ASCII+EASCII code page is one of them.

```
\*

```

There are control characters in between the characters `\` and `*`. The bytecode of 136 is counted as 2 bytes.

Try It Online!

## How did I get this program?

First of all, the challenge wants us to solve an equation, and the sum of all of the numbers in the source code equals a mystery number passed through a mystery function. I chose the multiply-two function because it is powerful enough to allow the solving of the equation. This is what I get as a draft (replace 2 with its control-character form mentally):

```
\?2*

```

(I prepended an escaping instruction before the mystery character because I want the character to be pushed no matter what the character is. My previous attempt of the mystery character without escaping had failed. The character was `,`, which is a Keg instruction.) Obviously the ord codes of `\`, `2`, and `*` are 92, 2, and 42 respectively, so we've complete half of the equation:

```
x+92+2+42

```

The other half is simply multiplying x by 2.

```
2x=x+2+92+42
 x=136

```

Therefore I escaped the 136 character, which is unprintable. So I need to verify the solution in case the result is wrong:

```
2*136=136+2+92+42
  272=272

```

The solution is valid, therefore the program is a valid code point sum quine solution.
> 1 votes

# Answer
# Python 3, 13 bytes, sum 950 (ASCII)

```
print('_'*10)

```

Try it online!
> 1 votes

# Answer
# Lost, ~~31~~ 30 bytes, sum 1598

```
///x///<<<///
>!?<@]]1111<%
//

```

Try it online!

Output:

```
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

```
> 1 votes

# Answer
# Klein, 3 bytes, sum 138

```
$@&

```

Try it online!

This outputs `0 0` with a trailing newline (`48 32 48 10`). The executing parts are `$`, which swaps the top two values of the stack (taking implicit zeroes from the bottom) and `@`, which terminates the program and prints the stack. `&` is just there to balance out the codepoint sum, and isn't a valid instruction in Klein, nor is it actually parsed. Since the pointer doesn't wrap around any edge, this works in any topology of Klein.
> 1 votes

# Answer
# Deadfish~, 5 bytes, sum = 574 (ASCII)

```
{ion}

```

Try it online!

Prints from 1 to 10, no spaces. `n` is a no-op (like most characters in deadfish~) which puts the code point sum where it needs to be.
> 1 votes

# Answer
# Runic Enchantments, 6 bytes, sum=380

```
"Dz":@

```

Try it online!

`D` has a code-point-sum double that of `"` while `z` has the code-point-sum equal to `:` plus `@`. Duplicating the string (resulting in `DzDz`) then provides one copy to count for its own characters in the source and one copy to count for the remainder of the program. Getting a lower sum will be difficult, but I don't preclude it.

For comparison, the 6 byte quines are `"'<~@>` and variants of `'<~@|"` (any IP redirection command that turns a left-pointing IP into a right-pointing IP all work).
> 1 votes

# Answer
# Zsh, 11 bytes

```
<<< $[1e12]

```

Try it online!

Outputs `1000000000000.` followed by a newline.
> 1 votes

# Answer
# ARBLE, 4 bytes, Sum 186

```
''+A

```

Outputs

```
""+A

```

Each `"` is 5 codepoints smaller than their respective `'`, `-5*2` and the output includes a newline, `+10`, which equals the source.

`+A` has to to be included as an implicit argument is needed to stringify as it does.

Try it online!
> 1 votes

# Answer
# Vyxal, 1 byte, sum 58

```
:

```

Try it Online!

Outputs `0\n`, which has codepoint sum 48+10=58, which is the codepoint of `:`.
> 1 votes

# Answer
# Triangular, 6 bytes, sum 306 (ASCII)

```
FA%%%<

```

Prints `151515`. Check it here and Try it online!

Formats into this triangle:

```
  F
 A %
% % <

```

The IP starts reading southwest from the topmost character. `<` directs it east, so the code is read like this:

```
F%%%

```

`F` pushes 15 to the stack, `%` prints it. `A` was the necessary character to get the byte sums even.
> 0 votes

# Answer
# Bitwise, 117 bytes, sum 5796 (ASCII)

```
MOV 1 &46 &1
LABEL &1
MOV 2 &1 &1
LABEL &2
NOT 1 *1
AND *1 2 *2
XOR 1 2 1
SL *2 &1 2
JMP @2 2
OUT &126 &1
JMP @1 1
;$

```

Outputs 46 tildes (`~`). Try it online!

This will be alot shorter once I add functions to Bitwise...

```
MOV 1 &46 &1     move l46 into r1 when l1 is truthy
LABEL &1         create label 1
MOV 2 &1 &1      move l1 into r2 when l1 is truthy
LABEL &2         \
NOT 1 *1          \
AND *1 2 *2        \_ all this code performs r1 = r1 - r2
XOR 1 2 1          /
SL *2 &1 2        /
JMP @2 2         /
OUT &126 &1      print l126 (~) when l1 is true
JMP @1 1         jump to jp1 when r1 is truthy
;$               byte fill :P

```

`l` is short for literal, `r` is short for register, `jp` is short for jump point. I'll update with a better explanation later.
> 0 votes

# Answer
# Bash + coreutils, 13 bytes, sum = 1090 (ASCII)

```
yes c|   head

```

Note the three spaces after the pipe.

Output:

```
c
c
c
c
c
c
c
c
c
c

```

Output is 10 c's and 10 line feeds, ascii 99 and 10 respectively, for a total of 1090. Input is 121+101+115+32+99+124+32+32+32+104+101+97+100=1090.
> 0 votes

# Answer
# Actually, ~~6~~ 4 bytes

Simply outputs 512. Adds 2 NOPs in order to get to that number.

```
9╙Ω☼

```

Try it online!

## Explanation

```
9╙   512 is 2**9
  Ω  Unfortunately opcode 250 is an implemented instruction;
     opcode 234 has to be used instead.
   ☼ Opcode 16 just for the bytecount; this is also not an instruction.

```
> 0 votes

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


title: Generalized Quine Generator

text:
# Question
Title: Generalized Quine Generator
# The Challenge

In this challenge, you specify a *source language* `S` and a *target language* `T`. Your task is to write the following program `P` in the language `S`. If a valid program `Q` in the language `T` is given as input to `P`, it will output a valid program `R` in the language `T` which takes no input and outputs `Q(R)`, that is, the program `Q` applied to the source code of `R`. *In addition*, you should present in your answer a nontrivial example program `Q` (the more interesting, the better, although you score no points for this), the resulting program `R`, and the output of `R`. This is code-golf, so the shortest code for `P` wins.

In other words, this is a challenge about writing a "universal quine constructor" that can create arbitrary types of generalized quines.

# Clarifications

* Your source and target languages may be identical.
* The program `P` should take one string as input (from STDIN or equivalent), and output one string (to STDOUT or equivalent), as should every output program `R`.
* The input programs `Q` should also transform a string to another string, but their form is more flexible: they can be string-to-string functions, code snippets that modify a variable with a certain name, snippets that modify the data stack if your target language has one, etc. You can also further restrict the form of the `Q`'s by stating that, for example, they may not contain any comments. However, you must be able to implement any computable string-to-string function as an input program `Q`, and you must *explicitly* state how they function and what further constraints you place on them.
* The output program `R` should really be a (generalized) quine, so it must not read any input (user input, files etc.) unless `Q` does so.
* Standard loopholes are disallowed.

# An Example

Suppose I choose Python as my source language, and Haskell as my target language, and I further require that the input program should be a one-line definition of a `String -> String` function named `f`. If I give the string-reversing program

```
f x = reverse x

```

as input to my Python program `P`, it will output the source code of another Haskell program `R`. This program prints to STDOUT the source code of `R`, but reversed. If `P` is given the identity function

```
f x = x

```

as input, the output program `R` is a quine.

# Answer
> 7 votes
# Source = Target = CJam, ~~19~~ ~~17~~ 16 bytes

```
{`"_~"+}`)q\"_~"

```

This assumes that the input program `Q` (given on STDIN) is some CJam snippet which expects a string on the top of the stack and leaves another string on top of the stack.

Test it here.

## Examples

1. The identity would just be an empty snippet, so leaving STDIN empty prints

```
{`"_~"+}_~

```

Which is the standard quine, with an additional `+`.
2. To reverse a string in CJam, you can use `W%`, so putting that on STDIN, this yields:

```
{`"_~"+W%}_~

```

which we can run to obtain

```
~_}%W+"~_"`{

```
3. As a third example, say we use a snippet which intersperses a string with spaces: `' *`. Running `P` with that as input, we get

```
{`"_~"+' *}_~

```

which in turn prints

```
{ ` " _ ~ " + '   * } _ ~

```
4. It now also works if `Q` contains line breaks (although that's never necessary in CJam). Here is a program with a line break, which removes all line breaks from a string (in an unnecessarily convoluted way - split into lines, then join):

```
N/
""
*

```

This results in the following `R`:

```
{`"_~"+N/
""
*}_~

```

which in turn prints

```
{`"_~"+N/""*}_~

```

## Explanation

Let's look at the produced output first:

The standard CJam quine is

```
{`"_~"}_~

```

It works as follows:

* Push the block `{`"_~"}`.
* Duplicate it with `_`.
* Execute the copy with `~`.
* Now inside the block, ``` turns the first block into its string representation.
* `"_~"` pushes the two characters of the source that are not part of the block (and hence missing from the string representation).
* The two strings are printed back to back at the end of the program.

<sup>In the basic quine the ``` is unnecessary, because if you just leave the block as it is, it's printed all the same at the end of the program.</sup>

The output of my program `P` is a modified version of this snippet. First, I've added a `+` to the block, which concatenates the two strings into one string containing the entire source. Note that this will be true no matter what I do inside the block, because that will all get added to the string representation obtained with ```. Now I can simply put the program/snippet `Q` inside the block after the `+`, so that it can modify the source string before it is printed. Again, since `Q` goes inside the block, it will be part of said source string.

In summary, `P` prints

```
{`"_~"+Q}_~

```

Now, for how I go about constructing this output in `P`:

```
{`"_~"+}         "Push the block without Q.";
        `        "Turn it into a string. This is shorter than writing a string right away,
                  because I'd have to escape the quotes, and I'd need two quotes instead of
                  one backtick.";
         )       "Pop off the last character (the brace) and push it on the stack.";
          q      "Read input Q.";
           \     "Swap Q with the brace.";
            "_~" "Push the final two characters.";

```

The four strings are printed automatically (back-to-back) at the end of the program.

# Answer
> 4 votes
# Haskell expressions → Haskell expressions, 41 bytes

```
((++)<*>show).('(':).(++")$(++)<*>show$")

```

Try it online!

### How it works

`P $ "Q"` = `((++)<*>show).('(':).(++")$(++)<*>show$") $ "Q"` constructs `"R"` by

1. `(++")$(++)<*>show$")`: appending the string `")$(++)<*>show$"`,
2. `('(':)`: prepending the character `'('`, and
3. `(++)<*>show` (= `\x->x++show x`): appending a quoted version of that,

resulting in `"R"` = `"(Q)$(++)<*>show$\"(Q)$(++)<*>show$\""`.

`R` = `(Q)$(++)<*>show$"(Q)$(++)<*>show$"` works by

1. taking the string `"(Q)$(++)<*>show$"`,
2. `(++)<*>show`: appending a quoted version of that,
3. applying `Q` to that,

resulting in `Q "(Q)$(++)<*>show$\"(Q)$(++)<*>show$\""` = `Q "R"`.

(The parens around `Q` are necessary because `Q` might contain `$` just as easily as `R` does, and `$` is unfortunately right-associative.)

### Demo

```
λ> putStrLn $ ((++)<*>show).('(':).(++")$(++)<*>show$") $ "id"
(id)$(++)<*>show$"(id)$(++)<*>show$"
λ> putStrLn $ (id)$(++)<*>show$"(id)$(++)<*>show$"
(id)$(++)<*>show$"(id)$(++)<*>show$"
λ> putStrLn $ ((++)<*>show).('(':).(++")$(++)<*>show$") $ "reverse"
(reverse)$(++)<*>show$"(reverse)$(++)<*>show$"
λ> putStrLn $ (reverse)$(++)<*>show$"(reverse)$(++)<*>show$"
"$wohs>*<)++($)esrever("$wohs>*<)++($)esrever(
λ> putStrLn $ ((++)<*>show).('(':).(++")$(++)<*>show$") $ "length"
(length)$(++)<*>show$"(length)$(++)<*>show$"
λ> print $ (length)$(++)<*>show$"(length)$(++)<*>show$"
44

```

# Answer
> 3 votes
# Jelly, 9 bytes

```
“ṚƓ^ṾṂ’³3

```

Try it online!

Q is a 7 function (i.e. that doesn't look beyond the top stack element, and does I/O via the stack), and is given as a command-line argument.

## Explanation

### The 7 program

The universal quine constructor in 7 that I use here is:

```
717162234430…3

```

The first thing to note is that the leading 7 is the equivalent of leading whitespace, and doesn't have any effect on the program. The only reason it's there is to obey PPCG's rules against literal-only quines (it's encoded by the second `1` in the program rather than itself).

The rest of the program is a single stack element (it has balanced `7`s and `6`s), which does the following when run:

```
717162234430…3
 1716           Push a stack element "7" onto the stack
     2          Copy it
      23        Pop and output one of the copies (selecting format 7)
        4430    Prepend it to the top of stack
             3  Output it

```

In other words, this stack element is a program that prints the top of the stack, with `7` prepended, in output format 7 (which means "print literally, using the same encoding as the source code", and thus is clearly the best encoding for quines). It's fairly fortunate here that we can reuse the literal `7` for two purposes (the output format, and the leading whitespace.) Clearly, by inserting something just before the final `3`, we can output a function of `7` \+ the input, rather than just outputting `7` and the input directly.

How does this stack element get at its own source code? Well, when the end of the program is reached, 7 `eval`s the top stack element by default. However, it's not actually popped from the stack in the process, so the stack element literal that was `eval`led is still there. (In other words, the program isn't reading its own source – as evidenced by the fact that it's unable to see the `7` at the start of the program, which is a stack element separator rather than part of a literal – but rather, it consists mostly of a literal that gets `eval`led by default.)

### The Jelly program

This is perhaps one of the least Jelly-like Jelly programs I've written; it consists of three nilads (`“ṚƓ^ṾṂ’`, `³`, `3`), which are just output in sequence because no operations are performed on them. The `3` is obvious enough, just being an integer constant. The `³` is also simple if you know Jelly: it's Jelly's explicit notation for the first command-line argument (which is where Jelly typically takes its input). The rest of the Jelly program represents the bulk of my 7 universal quine constructor: by exploiting the fact that all the commands in 7 can be represented using ASCII digits, we can interpret `717162234430` not as a series of commands, or even as an octal number (like it conceptually is), but as a decimal number, meaning that we don't need any special formatting for the output. That decimal number becomes `“ṚƓ^ṾṂ’` in Jelly's compressed integer notation.

## Example

If we give `24053` as program Q, we'll get the following output:

```
717162234430240533

```

Try it online!

`2405` concatenates the top stack element to itself:

```
2405   Stack   Explanation
       x
2      x|x     Duplicate top of stack
 4     x||x    Swap two stack elements, with an empty element between
  0    x|(X)   Escape the top stack element, then concatenate the top two
   5   xx      Execute the top stack element

```

(The last step might look a little confusing; what's happening is that escaping a stack element converts each command in it from "run this command" to "append this command to the top of the stack", so each command appends itself to the original top stack element as it runs.)

As such, running the resulting program R gives us two copies of R:

```
7171622344302405371716223443024053

```

# Answer
> 2 votes
# Source = Target = JavaScript, 66

```
console.log("function a(){console.log("+prompt()+"(a+'a()'))}a()")

```

## Assumptions for Q:

* `Q` should be a string-to-string JavaScript anonymous function.

# Examples:

* *Reverse*. Q = `function(s) { return s.split('').reverse().join(''); }`

In this case, `P(Q)` (or `R`) will be: `function a(){console.log(function(s) { return s.split('').reverse().join(''); }(a+'a()'))}a()`, and by executing it, we will get: `)(a}))')(a'+a(} ;)''(nioj.)(esrever.)''(tilps.s nruter { )s(noitcnuf(gol.elosnoc{)(a noitcnuf` which is exactly the same as `Q(R)`.

* *Identity*. Q = `function(s) { return s; }`

in this case, `P(Q)` (or `R`) will be: `function a(){console.log(function(s) { return s; }(a+'a()'))}a()` which is a **JavaScript Quine**. Needless to say, `Q(R)` will be the same, since Q is the Identity function.

---

# Some notes:

STDIN in JavaScript is traditionally `prompt()`, however, I allowed myself to refrain from the tradition of `alert()` as STDOUT, in order to make the process of run output as a progrem using copy-paste easier. (I do realize I can **save up to 12 characters** when changing to `alert()`).

I can also make things much shorter in ES6, but I want to stay with Native JavaScript for now. I'm considering submitting a S=Scala,T=ECMA6 answer in future, just for the experience.

I also realize JavaScript can almost never beat **CJam** in , but I had to take this challenge! It was surly a fun one.

# Answer
> 2 votes
# RProgN 2, 11 bytes

```
'{`{.%s}{'F

```

## Program Explanation

```
'{`{.%s}{'F
'{`{.%s}{'  # Push the string "{`{.%s}{" to the stack.
          F # Format the input with the top of the stack as a template. Which produces {`{.<INPUT>}{

```

## Quine Explanation

The quine that's produced is simple, yet uses the functionality of unmatched function handlers in RProgN2 to create a short and sweet quine, called a "Looping" quine. It's a surprisingly similar concept to a \>\<\> quine.

```
{`{.}{
{`{.}   # Push the function {`{.} to the stack.
     {  # Try to define a new function, fail, loop back to index 1. (Which in turn, skips the function definition.)
 `{     # Push the string "{" to the stack.
   .    # Concatenate the top two values of the stack, which stringifies the function, then appends { to it.
    }   # Try to terminate a function, fail quietly, and terminate the program.

```

Of course, because of the structure of this quine, anything but true no-ops (Which don't get stringified) can be placed after the concatenate function, and

## Some quines

* `{`{.i}{`: Outputs `{}i.{`{`. `i` is just the "inverse" function, so this program outputs itself reversed.
* `{`{.S§.}{`: Outputs `..S`{{{}§`. `S` converts the string to a stack of characters, `§` sorts the stack lexographically, then `.` joins it back together, outputting itself sorted.

Try it online!

# Answer
> 2 votes
# JellyUnderload, 15 bytes

```
“(a(:^)*“S):^”j

```

Try it online!

Takes the input Underload function Q as a command-like argument. Q must take input from the stack and push output to the stack, without attempting to inspect deeper stack elements (as they won't exist).

## Explanation

### The Underload

The Underload universal quine constructor used here is:

```
(a(:^)*…S):^

```

Most of the program is a single literal. We follow that by `:^`, which copies it, then evaluates one copy (leaving the other copy on the stack).

When the literal starts evaluating, we run `a` (escape, which brings it back into the same form as the original programA), and `(:^)*` (which appends `:^`), thus reconstructing the entire program's source code. We can then run the function Q to transform this in an arbitrary way, and print the result with `S`.

### The Jelly

I can't use Charcoal this time because a validating Underload interpreter crashes at the end of the program if the program ends with a newline. (Some Underload interpreters, such as the one on TIO, don't enforce this rule, but I wanted to be properly portable.) Unfortunately, Charcoal naturally adds trailing newlines to its output. Instead, I used Jelly, which is almost as terse in simple cases like this; the program consists of a list literal with two elements (`““”`), and joins them on the input (`j`), thus interpolating the user input into the program.

## Example

Using the input `:S^` (print a copy, then evaluate the original), we get the following Underload program:

```
(a(:^)*:S^S):^

```

Try it online!

This prints itself infinitely many times, in a fairly interesting way: after doing the normal quine behaviour, it then runs `eval` on a copy of what it output. That causes the entire reconstructed program to run again, indefinitely (Underload is tail-recursive). Quining yourself and doing an `eval` is actually the only way to do an infinite loop in Underload.

# Answer
> 2 votes
# CJam → CJam, 13 bytes

```
{`"_~"+7}_~qt

```

Try it online!

The input `Q` should be a code snippet that modifies the only string in the stack. `Q` is read from stdin.

### Example

Input:

```
S*W%

```

It adds a space between every two characters, and reverses the string.

Output:

```
{`"_~"+S*W%}_~

```

Output of the generalized quine:

```
~ _ } % W * S + " ~ _ " ` {

```

### Explanation

```
{`"_~"+7}_~      e# Evaluate a generalized quine in CJam that only appends a 7.
q                e# Read the input.
t                e# Replace the 7th character (0-based) with the input.

```

It firstly evaluates the quine, so we can get its string representation without unnecessary double quotes. Then replace the payload with the input.

It could be `{`"_~"+ }_~7qt` where the space is the placeholder of the payload. But changing the payload to `7` saves a byte.

# Answer
> 1 votes
# CharcoalPerl (5), ~~29~~ 33 bytes

```
Ａ$_=q(αＡ);evalβαＳ"\α$_β\n";printβ

```

Try it online!

The Perl program Q should return a snippet that takes input as a string to its right hand side and provides output in the variable `$_`. (Arbitrary Perl functions can be converted to this form via wrapping them as `sub x {…}; $_=x` . In most cases, though, Perl's syntax means that no wrapping is required.)

## Explanation

### The Perl

Here's what the universal Perl quine constructor looks like:

```
$_=q(…"\$_=q($_);eval";print);eval

```

(In most cases you'd want to golf this down to `$_=q(say…"\$_=q($_);eval");eval`, but I'm not sure you can fit arbitrary Perl code into the  there.)

In other words, we have an outside wrapper `$_=q(…);eval` which assigns a string to `$_` and then evaluates it. Inside the wrapper is `"\$_=q($_);eval"`, i.e. a reconstruction of the wrapper together with its contents via using the value we stored in `$_`, plus the code Q specified by the user, plus `print` to print the output. (Unfortunately we can't use `say`; it adds a newline, and that's relevant in quines.)

### The Charcoal

The "point" of this answer was to produce generalized quines in Perl, so once I had a golfed strategy for doing that (one I've used in many other answers), it was time to write the program P, which basically just substitutes a string into a template. What I wanted here was a language which was good at printing constant strings (ideally compressing them a bit), and interpolating user input into them.

After trying a few, I settled on Charcoal, which I've never used before (and which could really do with some documentation); it's designed for ASCII art but capable of writing strings in one dimension too. ASCII characters are printed literally in Charcoal, meaning that printing constant strings takes no boilerplate, and we can use the  command to interpolate a string taken from user input into the program.

It's possible to go (slightly) shorter, though. The Perl universal quine constructor contains two fairly long repeated sections. We can thus use the  command to assign them to variables (e.g. `Ａ…α` assigns to the variable `α`), and simply interpolate the variables into the string we're printing via using their names. That saves a few bytes over just writing the string literally.

Unfortunately, Charcoal also appends a newline to the program, but that's not a huge deal; it simply costs two bytes for an `\n` to add that newline to the input of Q too.

## Example

If we give the input `$_=reverse` (which reverses a string), we get the following output:

```
$_=q($_=reverse"\$_=q($_);eval\n";print);eval

```

Try it online!

which is a quine-alike that prints its source backwards, as expected.

# Answer
> 1 votes
# Vyxal `D` -\> Vyxal `D`, 4 bytes

```
\IpI

```

Try it Online! The D flag is necessary due to vyxal decompressing non-ASCII strings by default.

```
  p  # Prepend
\I   # "I"
   I # Quote and prepend to itself

```

For example, with the input `"`hello`+Ṙ"` (append "hello" and reverse) this outputs ``I\`hello\`+Ṙ`I`hello`+Ṙ`, which:

```
`I\`hello\`+Ṙ`           # "I`hello`+Ṙ"
              I          # Quote and prepend to self, obtaining source code
               `hello`+  # Append "hello"
                       Ṙ # Reverse

```

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


title: Golf you an anagram for great good!

text:
# Question
Title: Golf you an anagram for great good!
# The Task

In this challenge, your task is to write some code which outputs one of its anagrams chosen randomly with uniform distribution but it should never output itself.

---

## Elaboration

Given no input, your program should output any one of the anagrams of its source code. Your program should never output its own source as it is, i.e. it should never be a quine.

---

## Input

Your program must not take any input. However, if your language requires input as a necessity, you may assume that it will be given lowercase `a`. You must not use the input in any way, though.

---

## Output

Your program can output in any way except writing it to a variable. Writing to file, console, screen, etc. is allowed. Function `return` is allowed as well.

---

## Additional Rules

* Your program's source code must have at least 3 **chars** (not 3 bytes).
* Your program's source code must have at least 3 possible anagrams (excluding itself). For example, `aab` does not count as a valid submission as `aab` only has two anagrams other than `aab` (`baa` and `aba`).
* Your program must not produce any error.
* Your program should output its anagrams *exactly*.
* Standard Loopholes and Standard quine rules apply.

---

## Example

Suppose your program's source code is `abc`. It should randomly output any one of the following (with uniform distribution):

1. `acb`
2. `bca`
3. `bac`
4. `cba`
5. `cab`

And, it should never output `abc`.

---

## Winning Criterion

This is , so the shortest code in bytes wins! In case of a tie, the solution which was posted earlier wins!

# Answer
> 5 votes
# Jelly, 15 bytes

```
“v0¡µṾ;ḢŒ!QḊX”v

```

Just to get things started; this is almost certainly beatable. This is basically just a combination of a universal quine constructor and a "pick a random permutation other than the input" function; the latter may be improvable, the former almost certainly is.

## Explanation

**Universal quine constructor**

```
“v0¡µṾ;Ḣ”v
“       ”v   Evaluate the following, given {itself} as argument:
 v0¡µ          No-op (which starts with "v")
     Ṿ         Escape string
      ;Ḣ       Append first character of {the argument}

```

This can be seen to be a quine if run by itself. It's also a proper quine by most definitions I know of; it doesn't read its own source (rather, it contains a literal that's "eval"ed, and is given a copy of itself as an argument), it can carry a payload (as seen here!), and the `v` outside the string literal is encoded by the `v` inside.

**Pick a random anagram**

```
Œ!QḊX
Œ!     All permutations
  Q    Discard duplicates
   Ḋ   Discard the first (i.e. the string itself)
    X  Choose random element

```

This is really inefficient on a string this long, so I haven't been able to test the program as a whole, but I've tested it on shorter strings and it appears to function correctly.

# Answer
> 6 votes
## Python 2, 117 bytes

Surprisingly this solution is shorter than I expected. Shuffles source code, until it differs from the original.

-2 bytes, thanks to @mbomb007
-3 bytes, thanks to @Wondercricket

Try it online

```
s=r"""from random import*;R='s=r\"""'+s+'\"""'+';exec s';L=R
while L==R:L=''.join(sample(R,len(R)))
print L""";exec s

```

This is one of the basic quines in python, that I've modified

```
s = r"print 's = r\"' + s + '\"' + '\nexec(s)'"
exec(s)

```

Generating anagram is done by random module

```
L=R
while L==R:L=''.join(sample(L,len(L)))

```

Where R contains sourcecode

```
s=...
R='s=r\"""'+s+'\"""'+'\nexec s'

```

Triple quotes were needed as I was forced to keep actual lineseparators in code. Anagrams will have 3 lines anyway.

# Answer
> 4 votes
## CJam, 17 bytes

```
{`"_~"+m!(a-mR}_~

```

This isn't going to finish any time soon, so no TIO link this time.

As a consolation, here is a 20 byte solution that does terminate very quickly:

```
{`"_~"+:S{mr_S=}h}_~

```

Try it online!

### Explanation

```
{`"_~"+   e# Standard quine framework, leaves a string equal to the source
          e# code on the stack.
  m!      e# Get all permutations. The first one will always be the original order.
  (a      e# Remove that copy of the source code and wrap it in a new list.
  -       e# Remove all copies of the source code from the list of permutations.
  mR      e# Pick a random permutation.
}_~

```

The 20 byte solution instead shuffles the source code until its different from the original.

# Answer
> 3 votes
# Java 7, ~~376~~ ~~428~~ ~~426~~ 428 bytes

```
import java.util.*;class M{public static void main(String[]a){String s="import java.util.*;class M{public static void main(String[]a){String s=%c%s%1$c,x=s=s.format(s,34,s);for(List l=Arrays.asList(x.split(%1$c%1$c));x.equals(s);s=s.join(%1$c%1$c,l))Collections.shuffle(l);System.out.print(s);}}",x=s=s.format(s,34,s);for(List l=Arrays.asList(x.split(""));x.equals(s);s=s.join("",l))Collections.shuffle(l);System.out.print(s);}}

```

+52 and +2 bytes for two bug-fixes.. I wasn't checking (correctly) if the randomly generating String was equal to the original source-code. The chances of this are astronomical small considering the amount of characters involved, but I have to validate it regardless to comply to the challenge rules.

My first answer in Java..
Try it here.

You can remove both `Collections.shuffle(l)` and add `!` in front of both the `x.equals(s)` to verify that the output indeed equals the program:
Try it here.

**Explanation:**

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

And this part of the code is responsible for outputting a random anagram:

```
// Strings `s` and `x` now both contain the source-code:
x=s=s.format(s,34,s);

// Create a list with the characters of this source-code-String and loop
for(List l=Arrays.asList(x.split(""));
    // as long as String `x` equals String `s`
    x.equals(s);
    // Shuffle the list, and set it to `s` in every iteration of the loop:
    s=s.join("",l))Collections.shuffle(l);
// End of loop (implicit / single-line body)

// And then print the random anagram to STDOUT:
System.out.print(x);

```

# Answer
> 3 votes
# Vyxal `D`, 14 bytes

```
`q‛:Ė+:Ṗ$o℅`:Ė

```

Try it Online!

For a version that doesn't require ~1.2TB of RAM:

# Vyxal `D`, 16 bytes

```
`q‛:Ė+D{|Þ℅~=`:Ė

```

Try it Online!

Both of these use a fairly generic quine structure combined with some "generate some permutation other than the input" code.

### Generic quine structure

```
`        `:Ė # Evaluate the previous code on itself
 q.          # Uneval
     +       # Append
  ‛:Ė        # ":Ė"
      ...    # Apply some transformation

```

```
 Ṗ    # Get all permutations of the input
: $o  # Remove the original string
    ℅ # Choose a random element

```

```
 {      # While
D |  ~= # The current string equals the input
   Þ℅   # Shuffle it

```

# Answer
> 1 votes
# 05AB1E, 22 bytes

```
"34çìDJœ¦.R"34çìDJœ¦.R

```

This creates a list that is too big for TIO, so the link uses a smaller string, but the idea is the same.

Try it online!

```
"34çìDJœ¦.R"           # Push this string
            34ç        # Push "
               ì       # Prepend
                DJ     # Duplicate and join
                  œ¦   # Push all permutations except the original
                    .R # Pick a random element

```

# Answer
> 1 votes
# Javascript (ES6), 128 bytes

```
!function a(){b="!"+a+"()",c=b.split(""),c.sort(()=>Math.round(Math.random())-.5),c!=b.split("")?console.log(c.join("")):a()}();

```

Uses sort() returning random -1,0, or 1 to shuffle the output.

# Answer
> 1 votes
# PowerShell Core, 72 bytes

```
&($f={for(;$r-eq$o){$r=-join(($o="&(`$f={$f})")|% t*y|Random -c 72)}$r})

```

Try it online!

This is a variation of the quine `&($f={"&(`$f={$f})"})`

```
&($f={for(;$r-eq$o){$r=-join(($o="&(`$f={$f})")|% t*y|Random -c 72)}$r})
                             ($o="&(`$f={$f})")                          # Stores the original quine in $o
                    $r=-join(                  |% t*y|Random -c 72)      # Shuffles the characters and store it in $r
      for(;$r-eq$o){                                               }$r   # Exit the while loop and print when the shuffled quine is not the same as the origin quine
&($f={                                                                }) # Quine structure, to create a function and run it automatically

```

A 74 bytes recursive approach

# Answer
> 0 votes
# Bash, ~~27~~ 96 bytes

```
i=`cat $0`&&e=`fold -w1 $0|shuf|tr -d '\n'`&&while [ "$e" = "$i" ]; do `$0`; exit; done&&echo $e

```

`fold` divides the code in lines, `shuf` shuffles the lines, and `tr` put the code back together

fixed the issue of it outputing itself, now it will never output itself

Try it Online!

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