title: Case invert your quine

text:
# Question
Title: Case invert your quine
Write a quine which attempts to invert the case of as many ascii characters in the source code as possible. For example in javascript:

```
(x=function(y){return ('(x='+y+')(x)').toUpperCase();})(x)

```
* Standard quine rules apply.
* The score is given by *number of bytes in the source code* \- *number of case inversions*. For example, the quine above has a score of 29.
* The program with the lowest score wins. If two programs have the same score then the shorter one wins.

# Answer
> 29 votes
# \>\<\>, score 479 - 479 = 0

```
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllbfppllfepeeppppgglcepppbeppppppppppplfdppedpddpgglcdppbdpfcpecpggldcppllccpbcpplfbpebppldbppcbpggcbglefgpgbeglefgpgcbglefgpgggggedglefgpgccglefgpgfdglefgpgebglefgpgecglefgpggdcglefgpgceglefgpgeeglefgpgbcglefgpgfbglefgpgcdgfefgpbdgeefgpfegdefgpccgcefgpfdgbefgpdbgaefgpppddglefgpgbcglefgpgfcglefgpgdbglefgpgdcglefgpgecglefgpgddglefgpgdbglefgplffpbfgffgefgpcbgefgefgp

```

Try it online!

### How it works

Very few useful instructions in \>\<\> are letters. However, we still have the `l`, pushing the length of the stack to the stack. As such, it's possible to (very verbosely) push arbitrary values to the stack. Thus, strings can be encoded in a similar fashion to brainfuck, using `a` to increase the length of the stack, and `g` or `p` to reduce it.

As per usual quine rules, `g` is not used to read the source code itself, instead maintaining registers at locations such as`bb` and `bc` and so on.

The string encoded is the prefix:

`"r&:20&3-:&?.p48*-od0l2)?.;lllll"]"`

Which after over 7,000 instructions outputs the original string in upper case.

# Answer
> 10 votes
# Gol\>\<\>, ~~77~~ 75 - 75 = 0

```
urassssissezplzelssmzmzpssazmkqjmkrmbrrrrrtsuotlballsssssassmzpsssssbssmzpu

```

Try it online!

Based on Bubbler's answer, this goes even further by also putting the `"` at the start of the code to get a score of `0`!

### Explanation

```
ur       Move over one on the stack tape and reverse the stack
  assssissez      Push 10+16*4=74,-1+16*2=31,!(15)=0
            p     And put the 74 (J) at position 0,31

lz            Push 0 if there is anything on the stack
  e           Push 14 for later
   lssmzmz    Push 2+16*2=34, !(-1)=0, !(-1)=0
          p   Put the 34 (") at position 0,0

sss           Add 3*16 to the -1 from earlier
   az         Push !(10)=0
     mkq      Some no-ops
        J     And jump to 0,47 if the stack was initially empty

lballsssssassmzp  Put T at position 0,43
sssssbssmzpu      Put S at position 0,44
u                 Move one over on the stack again (effectively resetting the stack)

"                 Wrap, pushing everything to the stack
 r                Reverse
  .........       Put everything again
           J      But this time don't jump, since the stack is not empty

mk           Copy the bottom of the stack (u)
  rm         Push a -1 to the bottom of the stack
    brrrrr   No-ops

T   t      Finally, loop over the stack,
 Suo       Capitalising then outputting everything until we get to the -1

```

# Answer
> 10 votes
## 80186+ machine code (MS-DOS .COM format), 115-115=0

It was a bit tricky to do this, as I only had access to `INC`, `DEC`, `PUSH`, certain `POP` variations, `POPA`, `IMUL`, and certain conditional jumps. Fortunately, `IMUL` could do the heavy lifting for this challenge!

I encoded the actual code that does the printing in a series of values that get multiplied together. I compute those values (which get truncated to 16-bit values), store them on the stack which I moved to be just above the code, and then jump to the generated code to print the program's code in the opposite case.

Machine code:

```
hrXhCNhGUhnPhPwhYkhvLhKwaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaPQRjZTUVjfaiQVGARiQSCARiQPQARiQMJARiQJZARiQGuARiQDkARiQAWARpI

```

Assembler source:

```
IDEAL
P186

MODEL   TINY
CODESEG
ORG 100H

MAIN:
        ; Encoded code:
        ;   MOV SI,100H
        ;   MOV CX,73H
        ; PRINT:
        ;   LODSB
        ;   XOR AL,20H
        ;   INT 29H
        ;   NOP
        ;   LOOP PRINT
        ;   INT 20H
               ; Offset Bytes Multiplier
    PUSH 5872H ; +41    BE 00 4157H
    PUSH 4E43H ; +44    01 B9 416BH
    PUSH 5547H ; +47    73 00 4175H
    PUSH 506EH ; +4A    AC 34 415AH
    PUSH 7750H ; +4D    20 CD 414AH
    PUSH 6B59H ; +50    29 90 4151H
    PUSH 4C76H ; +53    E2 F8 4143H
    PUSH 774BH ; +56    CD 20 4147H

REPT 30
    POPA ; Adjust stack to point to end of generated code
ENDM

    PUSH AX
    PUSH CX
    PUSH DX
    PUSH 5AH
    PUSH SP
    PUSH BP
    PUSH SI
    PUSH 66H
    POPA ; Use POPA as POP DX and POP DI are not in [A-Za-z]
    IMUL DX,[BX+DI+56H],4147H
    PUSH DX
    IMUL DX,[BX+DI+53H],4143H
    PUSH DX
    IMUL DX,[BX+DI+50H],4151H
    PUSH DX
    IMUL DX,[BX+DI+4DH],414AH
    PUSH DX
    IMUL DX,[BX+DI+4AH],415AH
    PUSH DX
    IMUL DX,[BX+DI+47H],4175H
    PUSH DX
    IMUL DX,[BX+DI+44H],416BH
    PUSH DX
    IMUL DX,[BX+DI+41H],4157H
    PUSH DX
    JO $+4BH ; Jump to start of generated code

END MAIN
ENDS

```

# Answer
> 8 votes
# Gol\>\<\>, score 34 - 33 = 1

```
"mrllssslssscsmzpdsmzprrrrrrtsuota

```

Try it online!

Outputs the following and exits by error, which is every char uppercased except the leading `"`.

```
"MRLLSSSLSSSCSMZPDSMZPRRRRRRTSUOTA

```

### How it works

The lines marked with `*` are the differences from the previous version.

```
"..."    Push every char except `"`
mrl      Push -1, reverse stack, push stack length (34 = `"`)
* lsss   Push stack length (35) and add 16 three times (83 = S)
* lsss   Push stack length (36) and add 16 three times (84 = T)
* csmzp  Push 13, add 16 (29), push -1, boolean negate (0), and
         replace the command at (29,0) by T
* dsmzp  Push 14, add 16 (30), push -1, boolean negate (0), and
         replace the command at (30,0) by S
* rrrrrr  Reverse the stack 6 times;
          no-op to move the positions to overwrite
TSuot    Infinite uppercase-print loop; halt by error at -1
a        Not executed

```

---

# Gol\>\<\>, score 34 - 31 = 3

```
"mrlTSuotaaaaaaaaaaaaaaaaaaaaaaaaa

```

Try it online!

Outputs the following and exits by error.

```
"MRLTSUOTAAAAAAAAAAAAAAAAAAAAAAAAA

```

Every lowercase letters are uppercased, so the only chars that are not modified are `"TS`.

### How it works

```
"..."  Start string literal, push every char in the source code (except `"`),
       wrap around and end string literal
mr     Push -1 and reverse the stack
       (setup the chars for printing from top, and bury the trap at the bottom)
l      Push length of stack, which gives 34 == `"`
T...t  Infinite loop until it errors in the middle:
 Su     Uppercase the char at the top (errors when trying to uppercase -1)
 o      Pop and print as char
a...   Not reached

```

~~I suspect 2 or lower might be possible.~~

# Answer
> 7 votes
# V (vim), score 3

```
2i2I

```

Try it online!

4 bytes with 1 case inversion. Twice inserts (`2i`) the string `2I`.

# Answer
> 5 votes
# Ruby, score <sup>~~24~~ ~~20~~ ~~16~~ ~~12~~</sup> 11

*Saved a byte thanks to a comment by @Sisyphus on another answer.*

```
eval S="print'EVAL s=%p'%S.swapcase"

```

Try it online!

36 bytes with 25 case inversions. The case of every letter is changed in the output.

# Answer
> 5 votes
# 05AB1E, 16 - 6 = 10

```
0"D34çýu"D34çýu

```

(trailing newline)

# Explanation

```
0"D34çýu"D34çýu # full code
0"D34çý "D34çý  # standard 05AB1E quine
       u      u # uppercase string in stack
                # implicit print

```

Not the *best* golf, but it is my *first* golf so have mercy please.

Try It Online!

---

# 05AB1E (legacy), 16 - 8 = 8

```
0"D34çýš"D34çýš

```

(trailing newline)

# Explanation

```
0"D34çýu"D34çýu # full code
0"D34çý "D34çý  # standard 05AB1E quine
       š      š # switch case builtin
                # implicit print

```

Thanks to Kevin Cruijssen for -2 score. Doesnt work with current 05AB1E becuase the switch case function is  which makes the byte count larger

Try It Online!

# Answer
> 5 votes
# Husk, Score = ~~3~~ 2

```
foccmawSeohs"foccmawseohs

```

Try it online!

So many letters!

Thanks Dominic van Essen for -1 to the score.

### Explanation

The standard quine in Husk is `S+s"S+s"`: it takes the string `S+s`, and concatenates it with its version surrounded by quotes. The swapcase command `\` would be easy to add here, but being an escape character as well it needs to be doubled inside the quoted string, resulting in too many unswappable character for my tastes.

What we do instead is convert each character to uppercase (with the conveniently lowercase builtin `a`), and then we just need to make sure to use only lowercase letters as much as possible. We can get rid of a final `"` by using `h` (init) on the quoted string, then the rest of the code is devoted to getting rid of that `+` symbol to concatenate strings.

```
foccmawSeohs"foccmawseohs
            "foccmawseohs    A string
       Se                    put it in a 2-elements list
         ohs                 with the quoted version of itself, minus the last quote
      w                      Join the two strings with a space
    ma                       Convert each character to uppercase
f                            And keep only those characters that are truthy when...
 occ                          converted to charcode and back

```

The last part is just an identity function (but `I` would be uppercase), and spaces are falsy in Husk, so we are just keeping all non-space characters in the string.

I'd love to get rid of the `S` but I don't see how, and I don't think it is possible to have a quine without quotes, barring convoluted conversions from numbers that would score terribly in this challenge... (Prove me wrong and you get a bounty!)

# Answer
> 4 votes
# JavaScript (Node.js), 70 - 38 = 32

```
f=x=>`f=${f}`.replace(/(.)/g,y=>y<'`'?y.toLowerCase():y.toUpperCase())

```

Try it online!

BTW: This is my first contribution and I'm a bit confused. I made sure to swap every possible character. The example only uppercases. If you don't *need* to actually swap cases, then one can get 11-0=11 with a simplified variant of an answer given above:

```
f=x=>"f="+f

```

# Answer
> 3 votes
# Python 2, Score 52 - 33 = 19

```
s='S=%r;PRINT S%%S.SWAPCASE()';print s%s.swapcase()

```

Try it online!

Case inverts every letter in the quine.

# Answer
> 3 votes
# Perl 5, 37 bytes, 20 swapped case, Score 17

Thanks to @Dominic van Essen for -1!

```
eval($a=q{print uc"eval(\$a=q{$a})"})

```

Try it online!

# Answer
> 2 votes
# Keg, score 4

```
`④`④

```

Try it online!

4 bytes with 0 case conversions.

The standard quine without case conversion easily beats any Keg approaches that would have case conversion: by the time you've thrown case conversion techniques into the mix, you might as well have just written a standard quine with no fancy details.

# Answer
> 2 votes
# , score = 78 - 53 = 25

```
a='a=%s;cat(toupper(sprintf(a,squote(a))))';cat(toupper(sprintf(a,sQuote(a))))

```

Try it online!

# Answer
> 2 votes
# Javascript, 27 - 13 = 14

```
f=x=>`f=${f}`.toUpperCase()

```

Try It Online!

# Answer
> 2 votes
# Vyxal, 10 bytes − 8 inversions = score 2

```
`NDqp`NDqp

```

Try it Online!

# Answer
> 2 votes
# 05AB1E, Score = ~~very big number - very big number~~ 4508 - 4508 = 0

```
XaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXODTnBsbRvTTTTngmngmnngmngDUTnBsTTnnngmgTnBsTTTngmnnnngmgDVTnBsTTTnnngmngmngTnBsYTnBsTXmRykTnBXaKsYTnBsJ

```

Try it online!

EDIT: Can now finish in the lifetime of the universe!

Explaination:

```
XaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXO
            pushes 395523372811533155555555231622231622232316222316395655233728555523232316221655233728555555231622232323231622163957552337285555552323231622231622231655233728605523372855592253342055233759104628605523372845
D           duplicate it
TnB         and convert one of the duplicated to base 10^2 = 100, which is this code case inverted
s           swap, moving to front the number
b           convert it to binary
R           and reverse the binary
v           for each digit
 TTTT       push 10,10,10,10^1
 n          square, 10,10,10,10^2
 g          length, 10, 10, 10, 3
 m          exponent, 10,10,10^3
 n          square, 10,10,10^6
 gm         10^length, 10,10^7
 n          square, 10, 10^14
 n          square, 10, 10^28
 gm         10^length, 10^29
 n          square, 10^58
 g          59
 DU         duplicate and save in variable X
 TnB        convert to base 100, "x"
 s          and swap, so the stack is "x", "<string>"
 TTnnngmg   push 10, in the same way as 59
 TnBs       convert from base 100 and swap, so the stack is "x", "A", "<string>"
 TTTngmnnnngmg  push 50, in the same way as 59 and 10
 DV          save in variable Y
 TnBs       convert from base 100 and swap, so the stack is "x", "A", "o", "<string>"
 TTTnnngmngmng  push 39
 TnBs      convert from base 100 and swap, so the stack is "x", "A", "o", "d", "<string>"
 Y         push variable Y, 50
 TnBs      convert from base 100 and swap, "x", "A", "o", "d", "o", "<string>"
 TXmRyk    X if the current bit is 0, else 0
 TnBXaK    convert from base 100 and remove zeros, "X" if the value is 0 else ""
 sYTnBs    add "o" again
 J         join everything

```

# Answer
> 1 votes
# Python 3.8 (pre-release), 44 - 25 = 19 bytes

SwapCase all the char of the quine leaving only the non-alpha chars unchanged

```
exec(a:="input('EXEC(A:=%r)'%a.swapcase())")

```

Try it online!

# Answer
> 0 votes
# Japt, score 16 - 6 = 10

Sadly, a standard quine with no toggling scores the same (10 bytes), but this is way more fun. Every letter is toggled.

```
"i34d¹²u"i34d¹²u
"i34d¹²u"        // Take this string, shortly just the program string after the quote
         i       // Prepend
          34d    // a quote char,
             ¹   // and then (closing parens)
              ²u // repeat the result twice and uppercase it.

```

Try it here.

# Answer
> 0 votes
# Haskell, score 29

```
import Data.Char;main=putStr x>>print x;x=map toUpper"import data.char;main=putstr x>>print x;x=map toupper"

```

Try it online!

The non-flipped bytes are:

```
 D.C;=S >> ;= U" .;= >> ;= "

```

# Answer
> 0 votes
# Python 2, 43 - 27 = 16 bytes

```
a="print'A=%r;EXEC A'%a.swapcase()";exec a

```

Try it online!

Same answer than my Python 3 solution ... but ths time I can remove the parenthesis of the `exec` function and the `print` function (costing one char for the trailing newline)

---
Tags: string, code-challenge, quine
---


title: Stars Make Stars

text:
# Question
Title: Stars Make Stars
## Introduction

The idea is to use the asterisk character (star) `*` to display an ascii-art star at a specified dimension. The dimension is an input number greater than or equal to \\$1\\$ that specifies the height in lines of the upper point of the star. The stars here are intended to be six pointed stars with larger sizes looking better from a picture perspective.

In all cases the ascii-art representation of the stars are to appear as two triangles that overlap as shown in the following examples.

## Parametrics

The following picture and table of data describes attributes for the first seven sizes of the star. Each of the parameters grows in an arithmetic progression as \\$N\\$ increases, **except \\$N=1\\$ is different**.

## Examples

For an input of 1 (the degenerate case) the program output should be as follows:

```
  *
*****
*****
  *

```

Input of 2:

```
    *
   ***
*********
 *******
*********
   ***
    *

```

(3)

```
       *
      ***
     *****
***************
 *************
  ***********
 *************
***************
     *****
      ***
       *

```

(5)

```
             *
            ***
           *****
          *******
         *********
***************************
 *************************
  ***********************
   *********************
    *******************
   *********************
  ***********************
 *************************
***************************
         *********
          *******
           *****
            ***
             *

```

## Challenge

Your task is to create a function or program that will accept the number N as input and then output the appropriately sized star using just  characters and the `*` character.

* You may assume that the input value is always a positive integer.
* Trailing whitespace on the output lines is OK.
* The program algorithm should be general enough for any \\$N\\$ input to produce the star art output. Practical limitations exist of course due to display output size.
* Output should print to STDOUT.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply.

## Scoring

This is so the code with the shortest number of bytes wins!

# Answer
> 7 votes
# Haskell, 114 bytes

Builds a function `g` which takes an number and produces a `IO` monad that prints the star to STDOUT. I think this is ok.

```
f=replicate
a%b=mapM_(\n->putStrLn$f(a-n)' '++f(2*n-3)'*')$zipWith max<*>reverse$[2..a]++f b 0
g 1=4%1
g a=(3*a)%a

```

Try it online!

## Explanation

First lets talk about the lambda.

```
\n->putStrLn$f(a-n)' '++f(2*n-1)'*'

```

This takes a number, `n`, to be drawn as stars. We print twice that many stars and then 1 more and pad it on the right to the size of the image. We pad this on the right by `a` spaces to center the line of stars. We can use this lambda to draw each line.

From this lambda we create `(%)`. `(%)` starts with doing `mapM_` with our lambda to turn a profile into the shape.

Now all we need to do is make a list of the profile for the star. We can do this by making a triangle first with `[1..a]`, then padding it with some zeros `++replicate b 0`. If we take the profile of the triangle and reverse it we get the other half of the star. To super impose them we just make a new profile where each entry is the max of the two triangles. This is `zipWith max`.

We then call this in one of two ways: as `3%1` for input of `1` and with `(3*a-1)%a` otherwise.

From here we do a little bit of fiddling with some of the values to shave some bytes. Since `3*a-1` is rather long we offset some of our other values by 1 so that everything cancels and we get the intended behavior with `3*a` instead. Namely we start our list at `2` instead of `1` and do `2*n-3` instead of `2*n-1` to make up for the change.

## Alternative version, 114 bytes

This one builds a point-free function `(%)<*>min 2`

```
f=replicate
a%b=mapM_(\n->putStrLn$f(3*a-n)' '++f(2*(n-b)+1)'*')$zipWith max<*>reverse$[b..3*a]++f a 0
(%)<*>min 2

```

Try it online!

## Handles all \\$N\>1\\$, 98 bytes

```
f=replicate
g a=mapM_(\n->putStrLn$f(3*a-n)' '++f(2*n-3)'*')$zipWith max<*>reverse$[2..3*a]++f a 0

```

Try it online!

## Handles all cases like the \\$N=1\\$ case, 98 bytes

```
f=replicate
g a=mapM_(\n->putStrLn$f(3*a-n)' '++f(2*n-1)'*')$zipWith max<*>reverse$[1..3*a]++f a 0

```

Try it online!

# Answer
> 7 votes
# 05AB1E, 21 bytes

```
3*s≠-L·<sÅ0«Âø€à'*×.C

```

Try it online! or as a Test Suite

**Explanation**

```
3*                     # multiply input by 3
  s≠-                  # subtract 1 if the input isn't 1
     L                 # push range [1 ... (3*n-(n!=1))]
      ·<               # multiply by 2 and subtract 1 to get odd numbers
        sÅ0«           # append n zeroes
            Âø         # zip with a reversed copy
              €à       # get the largest number in each pair
                '*×    # repeat "*" for each number in the list
                   .C  # format centered

```

# Answer
> 6 votes
# , ~~125~~ ~~107~~ 101 bytes

```
function(n,S=3*n+!n-1,P=pmax(I<-c(2:S*2-3,!1:n),rev(I)),`~`=strrep)write(paste0(' '~S-1-P/2,'*'~P),1)

```

Try it online!

* -24 thanks to @Giuseppe

---

Previous (different) approach :

# , ~~150~~ ~~148~~ ~~136~~ ~~135~~ ~~130~~ 128 bytes

```
function(n,G=n<2,K=4*n-1+G)for(i in 1:K-1)cat(`[<-`(rep(' ',W<-3*n-2+G),1+W+c(-i:i*(i<K-n),-(j=K-i-1):j*(i>=n)),'*'),sep='','
')

```

Try it online!

* -14 thanks to @Kirill L.
* -1 thanks to @t-clausen.dk
* -7 thanks to @Giuseppe

# Answer
> 5 votes
# Python 2, ~~101~~ ~~99~~ 97 bytes

```
n=input()
x=2*(n>1)
for i in range(1,8*n,2):print('*'*[i,8*n-i-x][i+x>n*6or i/n/2%2]).center(6*n)

```

Try it online!

<sub>-2 bytes, thanks to Lynn</sub>

# Answer
> 5 votes
# JavaScript (V8),  ~~101~~  108 bytes

*EDIT: +7 bytes to print to STDOUT*

```
n=>print((k=3*n+!~-n,g=y=>++y<k+n?`
`.padEnd(w=k-Math.max(y>n&&n-y+k,y<k&&y)).padEnd(2*k+~w,'*')+g(y):'')``)

```

Try it online!

### Commented (without `print`)

```
n => (                    // n = input
  k =                     // k is half the maximum width of the star + 1.5
    3 * n + !~-n,         // k = 3n if n > 1 or 4 if n = 1
  g = y =>                // g = recursive function taking y
    ++y < k + n ?         //   increment y; if y is less than k + n:
      `\n`                //     append a line feed
      .padEnd(            //     append w - 1 leading spaces:
        w =               //       where w is defined as
          k -             //       k minus
          Math.max(       //       the maximum of:
            y > n         //         - true (coerced to 1) if y > n
            && n - y + k, //           or n - y + k otherwise (bottom triangle)
            y < k &&      //         - true (coerced to 1) if y < k
            y             //           or y otherwise (top triangle)
          )               //       end of Math.max()
      )                   //     end of padEnd()
      .padEnd(            //     append 2 * (k - w) - 1 stars
        2 * k + ~w,       //       by padding to 2 * k - w - 1
        '*'               //
      ) +                 //     end of padEnd()
      g(y)                //     append the result of a recursive call
    :                     //   else:
      ''                  //     stop recursion
)``                       // initial call to g with y = [''] (zero-ish)

```

# Answer
> 3 votes
# Jelly, 21 bytes

```
×3’+ỊR;Ṭ»Ṛ$”*ẋz⁶ṚZŒBY

```

A full program accepting a positive integer which prints to STDOUT.

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

### How?

```
×3’+ỊR;Ṭ»Ṛ$”*ẋz⁶ṚZŒBY - Main Link: integer, n   e.g. 3
 3                    - three                        3
×                     - multiply (n by)              9
  ’                   - decrement                    8
    Ị                 - insignificant (abs(n)<=1)?   0
   +                  - add                          8
     R                - range                        [1,2,3,4,5,6,7,8]
       Ṭ              - un-truth (n)                 [0,0,1]
      ;               - concatenate                  [1,2,3,4,5,6,7,8,0,0,1]
          $           - last two links as a monad:
         Ṛ            -   reverse                    [1,0,0,8,7,6,5,4,3,2,1]
        »             -   maximum (vectorises)       [1,2,3,8,7,6,7,8,3,2,1]
           ”*         - an asterisk character        '*'
             ẋ        - repeat (vectorises)          ["*","**",...]
               ⁶      - a space character            ' '
              z       - transpose with filler        ["***********"," ********* ",...]
                Ṛ     - reverse                      ["   *   *   ","   ** **   ",...]
                 Z    - transpose                    ["       *","      **",...]
                  ŒB  - bounce (vectorises)          ["       *       ","      ***      ",...]
                    Y - join with newline characters "       *       \n      ***      \n..."
                      - implicit print

```

# Answer
> 2 votes
# Canvas, ~~25~~ 23 bytes

```
Ｒ：｛⁸３×４Ｍ∔］∔｛*×］↔⁸１≡？╪］┼

```

Try it here!

15 bytes without handling `1`

# Answer
> 2 votes
# Jelly, 21 bytes

```
×’»ɗ3”*xⱮz⁶ɓ⁶x;»Ṛ$ŒBY

```

Try it online!

A monadic link accepting a single integer as its left argument and returning a newline-separated Jelly string with the star as its output. When run as a full program implicitly prints the star to STDOUT.

### Explanation

```
   ɗ3                 | Last three links as a dyad with 3 as right argument:
×                     |   Multiply (by 3)
 ’                    |   Decrease by 1
  »                   |   Maximum of this (and 3)
     ”*xⱮ             | An implicit range from 1 to this many asterisks
         z⁶           | Zip with space as filler
           ɓ          | Start a new dyadic chain with the input as left argument and the list of asterisks as right argument
            ⁶x        | Input many spaces
              ;       | Concatenated to the asterisk list
                 $    | Last two links as a monad:
               »Ṛ     |   Maximum of this list and its reverse
                  ŒB  | Bounce each list (i.e. mirror it without duplicating the middle entry)
                    Y | Join with newlines

```

# Answer
> 2 votes
# Charcoal, 25 bytes

```
Ｇ↙θ←⁺⊗θ¬⊖θ↑⊗θ↘⊕θ*‖Ｏ¬Ｃ⁰¬⊖θ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｇ↙θ←⁺⊗θ¬⊖θ↑⊗θ↘⊕θ*

```

Draw an irregular pentagon representing the top right quarter of the star, but special-casing `1` to make the row an extra column wider.

```
‖Ｏ¬

```

Reflect to complete the star.

```
Ｃ⁰¬⊖θ

```

More special-casing to make the star for `1` an extra row taller.

Alternative solution, also 25 bytes:

```
∧¬⊖θ*Ｇ↗↓⊖×³Ｎ*‖Ｏ‖ＯＯ↓∧⊖θ⊖⊗θ

```

Try it online! Link is to verbose version of code. Explanation:

```
∧¬⊖θ*

```

Print an extra `*` for the case of `1`.

```
Ｇ↗↓⊖×³Ｎ*

```

Draw the left half of a triangle of the appropriate size.

```
‖Ｏ

```

Reflect to complete the triangle.

```
‖ＯＯ↓∧⊖θ⊖⊗θ

```

Overlap it with its reflection, except in the case of `1`, in which case just reflect it.

14 bytes without special-casing for `1`:

```
Ｇ<⊖×³Ｎ*‖ＯＯ↑⊖⊗θ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｇ<⊖×³Ｎ*

```

Draw a triangle of the appropriate size.

```
‖ＯＯ↑⊖⊗θ

```

Overlap it with its reflection.

# Answer
> 2 votes
# Japt `-R`, 25 bytes

+5 bytes for `n=1` :\

```
õ cUon3*U-´UÎ)®ç* êÃê!U û

```

Try it

```
õ cUon3*U-´UÎ)®ç* êÃê!U û     :Implicit input of integer U
õ                             :Range [1,U]
  c                           :Concatenate
   Uo                         :  Range [0,U)
     n                        :  Subtract each from
      3*U-                    :    Multiply U by 3 and subtract
          ´U                  :      Decrement U
            Î                 :      Get sign
             )                :End concat
              ®               :Map each Z
               ç*             :  Repeat "*" Z times
                  ê           :  Palindromise
                   Ã          :End map
                    ê!U       :If decremented U is 0, append reverse, else, palindromise
                        û     :Centre pad each line with spaces to the length of the longest
                              :Implicitly join with newlines and output

```

# Answer
> 2 votes
# T-SQL, 194 bytes

`@` is the input value

`@c` handles the width of the top triangle

`@d` handles the width bottom triangle

`@e` contains the output either `@c` or `@d` \- this saves a few bytes

`@f` handles the special case of 1 as input. `@c*@=3` determines when to use `@f`. 5 bytes cheaper than writing `@c=3and @=1`

```
DECLARE @ INT=8

,@c INT=1,@e INT=1,@d INT,@f INT=0SET @d=@*8-3r:PRINT
space(@*3-@e/2+@f/2)+replicate('*',@e-@f)SELECT
@c=nullif(@c,@*6-3)+2,@f=iif(@c*@=3,2,0),@d-=2-@f,@e=iif(@c>@d
or @c/2<@,@c,@d)IF @d>0goto r

```

**Try it online**

# Answer
> 2 votes
# Perl 6, 74 bytes

```
{$_ Z~|[R,] $_}o{.&{|((' 'x--$+$_*3~'*'x$++*2+1)xx$_*3-($_>1)),|($ xx$_)}}

```

Try it online!

Literally creates a triangle with the right proportions and overlaps it with a upside-down copy using the string or operator (`~|`). Outputs as a list of lines with a leading and trailing line whitespace.

### Explanation:

```
                {.&{                                                     }  # Anonymous code block
                      (                        )xx$_*3-($_>1)   # Repeat n*3-(n!=1) times
                       ' 'x--$+$_*3      # With a decreasing indentation
                                   ~'*'x$++*2+1  # Append an increasing triangle
                                       # This creates the triangle
                                                            ,|($ xx$_)  # And add some padding lines
{             }o   # Pass the triangle to the combining function
    Z~|            # Zip string bitwise or
 $_                # The list
       [R,] $_     # With its reverse

```

# Answer
> 2 votes
# , ~~53~~ 50 bytes

```
' *'{~[:(+.|.),.@#&0,~[:(|.,}.)"1*@<:>:/~@i.@-~3*]

```

Try it online!

## ungolfed

```
' *' {~ [: (+. |.) ,.@#&0 ,~ [: (|. , }.)"1 *@<: >:/~@i.@-~ 3 * ]

```

## how

Use a function table (like a 3rd grade times table) to construct half the triangle by using `>:` (greater than or equal) as the function. Then reverse each row, chop of the last column, and stitch the two sides together to get the full triangle (but made of 1 and 0). Add `n` rows of zeros at the bottom. Finally reverse the whole thing, and overlay it on the original, using boolean or `+.` to get the result. Then turn the 1 to `*` and 0 to spaces.

# Answer
> 2 votes
# Vyxal `j`, 53 bytes

```
1=[ðd×+:,×5*:,,,|(⁰3*⇩n-ð*nd›×*+)⁰(nð*6⁰*3-nd-×*+)Wøm

```

Try it Online!

# Answer
> 0 votes
# Haskell, 105 bytes

```
f n|h<-3*n-min 2n=mapM putStrLn[([x+1..h]>>" ")++do[-x..x];"*"|x<-zipWith max<*>reverse$[0..h]++[1-n..0]]

```

Try it online!

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


title: Coding Convention Conversion

text:
# Question
Title: Coding Convention Conversion
In that Coding Golf, you should convert one coding convention with TitleCase to lower\_case\_with\_underscores. And... vice versa!

# Specification

Change the casing in a following way:

* If underscore character is a delimiter, change the casing to Title Case without any of delimiter.
* If there are multiple words with no delimiter, change the casing to lower case and add an underscore character as a delimiter.
* In case of only one word (or one character): change the casing to Title Case if the word starts with lower case; change the casing to lower case if the word starts with the upper case.

Allowed characters:

* A to Z
* a to z
* underscore (`_`).

Input with mixed cased words are disallowed. Examples of disallowed cases:

* `Coding_Convention_Conversion`
* `a_BC`

# Example Cases

```
Input                        | Expected Output
===========================================================
CodingConventionConversion   | coding_convention_conversion
coding_convention_conversion | CodingConventionConversion
abc                          | Abc
Abc                          | abc
ABC                          | a_b_c
a_b_c                        | ABC
a                            | A
A                            | a

```

# Rules

* It is allowed to use `ToUpper`, `ToLower` and `ToTitleCase` functions.
* Using regular expressions is allowed.
* : shortest code in bytes wins!

# Answer
# Pyth, 25 bytes ~~29 33 35 40~~

*Saved 2 bytes thanks to @Dennis*

*Saved 4 bytes thanks to @FryAmTheEggman*

```
?rIz0smrd4cz\_tsXzrG1*\_G

```

Try it online
> 4 votes

# Answer
# Jolf, 35 bytes

*Saves 1 byte thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ*. This is encoded in ISO 8859-7.

```
? hI'_ΜGI'_dpyH0pxRGIL0"(?=[A-Z])'_

```

Woohoo my first Jolf program!

## Explanation

```
   // I = input
? hI'_                              // If input contains _
       GI'_                          // Split on _
      Μ    d                         // Loop, then join
            pyH0                     // Make the first character uppercase
                                    // ELSE...
                  RGIL0"(?=[A-Z])    // Split *after* all uppercase chars
                                 '_  // join with _
                px                   //Make lowercase

```

Try it online
> 8 votes

# Answer
# Retina, 37

Thanks to @ MartinBüttner for saving 4 bytes!

```
^|[A-Z]
_$0
T`Ll`lL`_.
^_|_(?=[A-Z])

```

(Note the trailing newline.)

Try it online. Note this includes extra `m``  to configure a couple of lines to treat each input line separately so all testcases may be run in one go. This is not a requirement of the question, so these are not counted in the score.

* Lines 1 and 2 insert `_` either at the beginning of input or before uppercase letters. All words are now `_`-separated, regardless of case.
* Line 3 swaps case of the first letter in each word.
* Lines 4 and 5 remove `_` either at the start of input, or when followed by an uppercase letter.
> 7 votes

# Answer
# GNU Sed, 46

Thanks to @TobySpeight for saving 2 bytes!

Score includes +1 for `-E` (or `-r`) option to `sed`.

```
s/(^|_)([a-z])/\u\2/g
t
s/[A-Z]/_\l&/g
s/^_//

```

Try it online.

Fairly straightforward sed:

* Line 1 substitutes beginning of line or `_`, followed by a lowercase letter with the upper case of that letter. The `g` flag to `s` performs this substitution for each instance found
* `t` jumps to the `:` unnamed label if there were any matches for the above substitution. This label is implicitly at the end.
* Otherwise all uppercase letters are substituted with `_` the lower case of that letter
* This leaves a leading `_` before the first letter. `s/^_//` removes that.
> 5 votes

# Answer
# JavaScript (ES6), 87 bytes

```
s=>s.replace(/[A-Z]|(^|_)(.)/g,(c,_,l,i)=>l?l.toUpperCase():(i?"_":"")+c.toLowerCase())

```

## Explanation

Depending on which part of the regex matched, it replaces the match with the opposite case.

```
s.replace(
  /[A-Z]|(^|_)(.)/g,
  (c,_,l,i)=>
    l?
      (i?"_":"")+c.toLowerCase()
    :l.toUpperCase()
)

```

## Test

```
var solution = s=>s.replace(/[A-Z]|(^|_)(.)/g,(c,_,l,i)=>l?l.toUpperCase():(i?"_":"")+c.toLowerCase())
```

```
<input type="text" id="input" value="coding_convention_conversion" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 4 votes

# Answer
# PHP 160 bytes

not the shortest but for completeness here my solution in PHP, $s holds the string to convert:

```
trim(preg_replace_callback('/((^[a-z]|_[a-z])|([A-Z]))/',function($m){return empty($m[2])?'_'.strtolower($m[3]):strtoupper(str_replace('_','',$m[2]));},$s),'_')

```
> 3 votes

# Answer
# Ruby, ~~101~~ ~~87~~ 75 bytes

```
->s{s.gsub(/^.|[A-Z]/,'_\0').gsub(/_./,&:swapcase).gsub(/_(?=[A-Z])|^_/,'')}

```

Unfortunately, this does exactly the same thing as the Retina solution, as that method ended up being shorter than anything else I came up with.
> 2 votes

# Answer
# Python 3, 130 bytes

Quick and dirty attempt using regex to split at the caps. Pretty brute force: if anyone can come up with a different approach I'm sure this can be beaten.

```
import re
lambda s:('_'.join(re.findall('[A-Z][a-z]*',s)).lower(),''.join([a[0].upper()+a[1:]for a in s.split('_')]))[s.islower()]

```
> 2 votes

# Answer
# 3, 15 chars / 32 bytes (noncompetitive)

```
⟮ѨǱï⟯≠ï?Ⅰ:ѨȎѨƎï

```

`Try it here (Firefox only).`

v3 was released after this challenge, with a bunch of bugfixes and library updates.

# Explanation

This is just a mashup of builtins.

```
⟮ѨǱï⟯≠ï?Ⅰ:ѨȎѨƎï // implicit: ï=input
⟮ѨǱï⟯≠ï?        // check if ï is NOT in snake_case
       Ⅰ       // if so, then convert to snake_case
        :ѨȎѨƎï // otherwise, convert to camelCase and make the first letter UPPERCASE

```
> 2 votes

# Answer
# Jelly, 24 bytes

```
e€ØAḊkŒlj”_$ʋ⁾_ yŒtḲƲ}Ẹ?

```

Try it online!
> 2 votes

# Answer
# Python 3, 86 bytes

```
lambda s,u='_':''.join([u[i>u:]+i.lower()for i in(s<u)*s]or[u]+s.title().split(u))[1:]

```

Try it online!

Also works in Python 2.

Making use of the convenient fact that the ascii value for `_` (95) is right in between those of the uppercase (65-90) and lowercase (97-122) letters, which allows for easy string comparisons.
> 2 votes

# Answer
# Perl 6,  ~~73 72 71~~  68 bytes

```
{.comb(/<:Lu><:Ll>*|<:Ll>+/).map({/<:Lu>/??.lc!!.tc}).join('_'x?/<:Lu>/)} # 73
{.comb(/<:Lu><:Ll>*|<:L>+/).map({/<:Lu>/??.lc!!.tc}).join('_'x?/<:Lu>/)}  # 72
{/<:Lu>/??S:g/(^)?(<:Lu>)/{$0||'_'}$1.lc()/!!S:g/[^|_](<:Ll>)/$0.tc()/}   # 71
{.comb(/<:Lu><:Ll>*|<:L>+/).map({/<:Lu>/??.lc!!.tc}).join('_'x!/_/)}      # 68

```

### Usage:

```
# give it a lexical name
my &code = {...}

for <CodingConventionConversion coding_convention_conversion abc Abc ABC a_b_c a A>
{ say .&code }

```

```
coding_convention_conversion
CodingConventionConversion
Abc
abc
a_b_c
ABC
A
a

```

### Explanation:

```
{
  .comb( / <:Lu><:Ll>* | <:L>+ / ) # grab the "words" only
  .map({
      /<:Lu>/ # if the word has uppercase
    ??
      .lc     # lowercase the whole word
    !!
      .tc     # otherwise titlecase the word
   })
  .join(  # join the words
    '_'   # with '_'
    x     # repeated
    !/_/  # zero times if it had a _, otherwise once
  )
}

```

You may be wondering why I used the Unicode properties (`<:Lu>`, `<:Ll>`) instead of just a character class. In Perl 6 they are no longer spelled `[a-z]` they are spelled `<[a..z]>` which is 1.6 times as big. The brackets `[ … ]` are used for non-capturing grouping instead which was spelled as `(?: … )` in Perl 5.
> 1 votes

# Answer
# Japt, 40 bytes

```
UfV="%A" ?UrV@'_s!Y +Xv} :Ur"^.|_."_sJ u

```

Test it online!

# How it works

```
           // Implicit: U = input string
UfV="%A"   // Set variable V to the string "\\A", and get all matches in U.
?          // If the list is not null:
UrV@     } //  Replace each match X and its index Y with this function:
'_s!Y +Xv  //   Return "_".slice(!Y) (1 for Y=0, 0 for anything else) + X.toLowerCase().
:          // Otherwise:
Ur"^.|_."  //  Replace the char at the beginning and each char following an underscore with:
_sJ u      //   The last char of the match (the letter) .toUpperCase().

```
> 1 votes

# Answer
# Perl 5, 42 bytes

40 bytes plus 2 for `-p` (thanks, dev-null)

```
s/[A-Z]/_\l$&/g||s/(^|_)(.)/\u$2/g;s/_//

```
> 1 votes

# Answer
# Forth (gforth), 129 bytes

```
: f bounds dup c@ 32 xor emit 1+ ?do i c@ '_ < if ." _"i c@ 32 + emit then i c@ '_ > if i 1- c@ '_ = 32 * i c@ + emit then loop ;

```

Try it online!

### Code Explanation

```
: f              \ start a new word definition
  bounds         \ convert string address and length to beginning and ending address
  dup c@         \ get the first character
  32 xor emit    \ convert to the opposite case and output
  1+             \ add 1 to beginning of string (skip starting char)
  ?do            \ begin counted loop over string character addresses
    i c@ '_ <    \ check if char is uppercase
    if           \ if it is:
      ." _"      \ output underscore
      i c@       \ get current char
      32 + emit  \ convert to lowercase and output
    then         \ end if block
    i c@ '_ >    \ check if lowercase (not '_')
    if           \ if it is:
      i 1- c@    \ get the previous character
      '_ = 32 *  \ if it's an underscore, multiply by 32 (true = -1 in forth)
      i c@ +     \ add result to current char (make uppercase if previous was '_')
      emit       \ output resulting char
    then         \ end if block
  loop           \ end loop
;                \ end word definition

```
> 1 votes

# Answer
# Pip, 37 bytes

```
'_Na?UC@_.@>_Ma^'_(LC_MRXU.XL.'+a)J'_

```

Try it online!

Lot of underscores in this one.
> 1 votes

# Answer
# K (ngn/k), 43 bytes

```
{("_"/(&x<_x)__x;,/`c$t-32*~<'t:"_"\x)x~_x}

```

Try it online!

* `x~_x` check if the input `x` is all lowercase
* `(...;...)` index into this two-item list depending on that value (i.e., return the first item in the list if `x` contains an uppercase letter, and the second item if it does not)
* When `x` contains an uppercase letter:
    + `(&x<_x)` identify indices of uppercase letters
    + `(...)__x` split the lowercased input on those indices
    + `"_"/` join the resulting chunks with underscores
* When `x` is all lowercase:
    + `t:"_"\x` split input on underscores, storing in variable `t`
    + `t-32*~<'t` capitalize the first letter in each chunk (this converts to integers)
    + `,/`c$` convert back to characters, flattening the list
> 1 votes

# Answer
# Japt, 37 bytes

```
a'_ Ä?Uq'_ ®hZu g} q:Uò@Yc <#a} q'_ v

```

Try it online!

Explanation:

```
There are some unicode chars that a shortcuts for common groups of chars,
like Ä is +1. This is the expanded version.

     // U = input string
a'_  // get index of "_" in string, -1 if not found
+1   // add 1 to make -1 falsy
?    // if truthy, ie. if there is an underscore in the input text
Uq'_ // split on underscores
m_   // map
h    // replace character (first char by default)
Zu g // the first letter of the string converted to uppercase (Zug)
} q  // close function and join
:    // else, ie. the string doesn't have any underscores
Uò   // runs func on every pair of chars, splits them if it returns true
@Yc <#a } // returns true if the second char code is less than "a", ie. uppercase
q'_  // join with underscores
v    // make lowercase

implicit print

```

First Japt program, I beat the creator, and Zu g!
> 1 votes

# Answer
# Japt, ~~27~~ 26 bytes

I fear I may have gone in the wrong direction with this; stuck on 27 and can't seem to do any better.

```
r"^.|_.|%A"ÈÌc^H i'_pY©XÊu

```

Try it

```
r"^.|_.|%A"ÈÌc^H i'_pY©XÊu     :Implicit input of string
r                              :Replace
 "^.|_.|%A"                    :RegEx /^.|_.|[A-Z]/g
           È                   :Pass each match X at 0-based index Y through the following function
            Ì                  :  Last character of X
             c                 :  Charcode
              ^H               :  Bitwise XOR with 32
                 i             :  Prepend
                  '_p          :    "_" repeated
                     Y©        :      Logical AND of Y and
                       XÊ      :      Length of X
                         u     :      Mod 2

```
> 1 votes

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


title: Find top student from three test marks

text:
# Question
Title: Find top student from three test marks
First save the following text into a file called `marks.csv`

```
Smith,6,9,24
Jones,9,12,20
Fred,5,9,20

```

Each line contains a students name and three marks they scored. Find the top student by simply summing the three marks and then output their name. In this case the output is:

```
Jones

```

I would like to see somebody beat my Python solution but any language will be allowed :) If anybody beats my Python solution I will accept their answer but for now I will just accept the shortest code.

# Answer
# K, 37

```
m[0;*>+/1_m:("SIII";",")0:`marks.csv]

```
> 4 votes

# Answer
## Cat (5 characters)

```
Jones

```

You don't specify that the code has to work on other datasets as well ;-)

Save code in a file `FILE` and execute with:

```
cat FILE

```
> 2 votes

# Answer
## *Mathematica*, 44

```
SortBy[Tr/@Import@"marks.csv",First][[-1,2]]

```

If I were allowed to save the data in *Mathematica*'s native format in a file named `z` I could use:

```
SortBy[Tr/@<<z,First][[-1,2]]

```
> 2 votes

# Answer
## Ruby 1.9 (~~71~~ 62)

```
$><<open('marks.csv').max_by{|l|eval l[/,.*/].tr ?,,?+}[/\w+/]

```
> 2 votes

# Answer
**PHP, ~~103~~ 95**

I know PHP is not the best tool for this problem, however I would appreciate any tip to improve my answer :)

First version (103)

```
<?$h=fopen('marks.csv','r');for(;$f=fgetcsv($h);$m[$f[0]]=array_sum($f));echo array_search(max($m),$m);

```

Improved version, inspired by @Leigh's solution (95) - considering low error level:

```
<?$h=fopen('marks.csv',r);for(;$f=fgetcsv($h);$m[array_sum($f)]=$f[0]);ksort($m);echo end($m);

```

Easier to read version:

```
<?
$h=fopen('marks.csv',r);
for(; $f=fgetcsv($h); $m[$f[0]]=array_sum($f));
echo array_search(max($m),$m);

```

Thanks
> 1 votes

# Answer
## PHP, ~~97~~ 93

Original

```
foreach(file('marks.csv')as$l){$x=str_getcsv($l);$r[array_sum($x)]=$x[0];}ksort($r);echo end($r);

```

Inspired by milo5b

```
for($f=fopen('marks.csv','r');$l=fgetcsv($f);)$r[array_sum($l)]=$l[0];ksort($r);echo end($r);

```

And how to run without tags.

`cat golf.php | php -a`
> 1 votes

# Answer
# Mathematica 59 49 53 chars

```
Sort[{Tr@Rest@#, #[[1]]} & /@ Import@"marks.csv"][[-1, 2]]

```

Because csv is a subject to various interpretations, I'm including the exact file contents of o.csv:

```
{{"Smith", 6, 9, 24}, {"Jones", 9, 12, 20}, {"Fred", 5, 9, 20}}

```
> 1 votes

# Answer
# JavaScript (Node.js), ~~146~~ ~~134~~ 133 bytes

(feedback welcome)

```
s=a=>eval(a.split`,`.slice`1`.join`+`);_=>(""+require("fs").readFileSync("marks.csv")).split`
`.sort((a,b)=>s(b)-s(a))[0].split`,`[0]

```

Try it online!
> 1 votes

# Answer
## Python, 82

```
print max((sum(eval(m)),n)for n,m in(l.split(',',1)for l in open("marks.csv")))[1]

```
> 0 votes

# Answer
**Awk, 64**

```
$ awk -F, '{s=$2+$3+$4;if(s>m){m=s;n=$1}}END{print n}' marks.csv

```
> 0 votes

# Answer
## R, 58

```
j=read.csv("marks.csv",F);j[which.max(rowSums(j[,2:4])),1]

```

Alternatively (62 characters):

```
j=read.csv("marks.csv",F);j[which.max(apply(j[,2:4],1,sum)),1]

```
> 0 votes

# Answer
# k (47 chars)

Allows for ties

```
(*x)'&(|/i)=i:+/'+:1_x:("SIII";",")0:`marks.csv

```
> 0 votes

# Answer
This might be orthodox and first of it kind on Code golf. Below will work find under circumstances where CSV file - been imported into as a table ( External Table) on Oracle.

M := Marks.csv Table a-d := CSV Fields

PLSQL **60** Characters

```
SELECT a,max(b+c+d) FROM M WHERE ROWNUM<=1 GROUP BY a,b,c,d;

```
> 0 votes

# Answer
***C#*** Two different versions

***Version:1 245*** Characters

```
using System;using System.Linq;namespace X{class Y{static void Main(){Console.Write((from l in System.IO.File.ReadAllLines("m.csv")let x =l.Split(',')select new{f=x[0],a=x.Skip(1).Sum(Z=>Int32.Parse(Z))}).OrderByDescending(p=>p.a).First().f);}}}

```

***Version:2 214*** Characters

```
using System;using System.Linq;namespace X{class Y{static void Main(){Console.Write(System.IO.File.ReadAllLines("m.csv").OrderByDescending(z=>z.Split(',').Skip(1).Sum(y=>Int32.Parse(y))).First().Split(',')[0]);}}}

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: Generate the names of the keys on a piano
On a standard 88 key piano, each key has a scientific name.

The first three keys are A0, B♭0, and B0. The keys then proceed through C1, D♭1, D1, E♭1, E1, F1, G♭1, G1, A♭1, A1, B♭1, B1, and start over again at C2. This continues up through B7, and the final key is C8.

Any flat can instead be written as a sharp of the preceding note, e.g. D♭4 can also be written C♯4. If necessary, you can write "D♭4" as "Db4".

Your program should build an ordered sequence (array, list, vector, etc.) containing the key names (as strings, symbols, or some similar data structure) in order.

Program length should be measured in *characters*, to avoid penalizing people who properly generate ♯ or ♭ rather than # or b. However, Unicode recoding is forbidden.

# Answer
## Bash shell script (58)

```
echo {8..0}{B,♭B,A,♭A,G,♭G,F,E,♭E,D,♭D,C}|rev|cut -b40-410

```

If you do not have `rev`, you can instead use `tac -rs.` at a cost of five characters.

Bending the rules, I can subtract thirteen characters (for a score of 45):

```
echo {8..0}{B,♭B,A,♭A,G,♭G,F,E,♭E,D,♭D,C}|rev

```

If you really need a bash array, add six characters to the score (for a score of 64):

```
a=(`echo {8..0}{B,♭B,A,♭A,G,♭G,F,E,♭E,D,♭D,C}|rev|cut -b40-410`)

```
> 6 votes

# Answer
### GolfScript, 60 57 characters

```
"A BbB C DbD EbE F GbG Ab"88,{1$2<@2>1$+\{8%},@9+12/+}%\;

```

The snippet produces the following array (see here):

```
["A0" "Bb0" "B0" "C1" "Db1" "D1" "Eb1" "E1" "F1" "Gb1" "G1" "Ab1"
"A1" "Bb1" "B1" "C2" "Db2" "D2" "Eb2" "E2" "F2" "Gb2" "G2" "Ab2"
"A2" "Bb2" "B2" "C3" "Db3" "D3" "Eb3" "E3" "F3" "Gb3" "G3" "Ab3"
"A3" "Bb3" "B3" "C4" "Db4" "D4" "Eb4" "E4" "F4" "Gb4" "G4" "Ab4"
"A4" "Bb4" "B4" "C5" "Db5" "D5" "Eb5" "E5" "F5" "Gb5" "G5" "Ab5"
"A5" "Bb5" "B5" "C6" "Db6" "D6" "Eb6" "E6" "F6" "Gb6" "G6" "Ab6"
"A6" "Bb6" "B6" "C7" "Db7" "D7" "Eb7" "E7" "F7" "Gb7" "G7" "Ab7"
"A7" "Bb7" "B7" "C8"]

```

*Edit:* Changed from `" "/""*` to `{8%},` to remove space.
> 5 votes

# Answer
# Mathematica 95 112 100 97 104 chars

Admittedly not very streamlined:

```
Take[Flatten@Table[# <> ToString@k & /@
Partition[Characters[" CDb DEb E FGb GAb ABb B"], 2], {k, 0, 8}], {10, 97}]

```

The Flat symbol, although it occupies a single character, is transcribed to SO as `\[Flat]` so I used the letter "b" here.

Output:

```
Length@%
(* out *)
88

```
> 4 votes

# Answer
# Python 103 96 94 78

```
[x+y for y in'0123456789'for x in'C Db D Eb E F Gb G Ab A Bb B'.split()][9:97]

```

updated according to Ev\_genus's suggestion

updated according to Howard's suggestion
> 4 votes

# Answer
# Ruby: ~~75~~ 71 characters

```
[*?0..?9].product(%w{C Db D Eb E F Gb G Ab A Bb B}).map{|a,b|b+a}[9,88]

```

(Base idea borrowed from Matt's solution.)
> 4 votes

# Answer
## J, 81 76 63 62 61 58 characters

```
_11}.9}.(_2]\,|:9#"0'C DbD EbE F GbG AbA BbB '),.12#1":i.9

```

Output:

```
A 0
Bb0
B 0
C 1
Db1
D 1
Eb1
E 1
...
G 7
Ab7
A 7
Bb7
B 7
C 8

```

Probably a bit of room for shortening here.
> 3 votes

# Answer
# C (92 84 characters)

Not impressive, could be reduced further.

```
main(i){for(i=9;printf("%c%c%d\n","CDDEEFGGAABB"[i%12]," b b  b b b "[i%12],i/12),++i<97;);}

```

Using Dietrich Epp's suggestion :

```
main(i){for(i=9;printf("%.2s%d\n","C DbD EbE F GbG AbA BbB "+2*i%24,i/12),++i<97;);}

```

It produces the following output :

```
A 0
Bb0
B 0
C 1
Db1
D 1
Eb1
E 1
F 1
Gb1

... // lines skipped

Eb7
E 7
F 7
Gb7
G 7
Ab7
A 7
Bb7
B 7
C 8

```
> 3 votes

# Answer
## *Mathematica*, 88

88 characters for 88 keys :-)

```
(Row@{#2,#1}&@@@Tuples@{0~Range~8,StringSplit@"C D♭ D E♭ E F G♭ G A♭ A B♭ B"})[[10;;97]]

```
> 3 votes

# Answer
# C, 105 chars

## \- failing on size, so ended up aiming for a wtf different solution.

Probably only works on little-endian arch (e.g. intel) due to assumptions of treating int as small string... Assumes C program is called with no arguments, i.e. that w=1

```
t=12352,f;
main(w){
  t=t&64?t>>8:(w=1+w%7,(w-3)%3?t<<8|98:t+(w==3));
  f=t<<8|w+64;
  puts(&f);
  f-14403?main(w):0;
}

```

Output:

```
A0
Bb0
B0
C1
Db1
D1
Eb1
E1
F1
Gb1
G1
Ab1
--lines skipped--
Bb7
B7
C8

```

## Edits

* -9 chars - removing some brackets and reorganising an 'if'
* -18 chars - code shuffling, sub 64 from w and pass as main arg
* -13 chars - Use 't' to carry state rather than 'f'
> 2 votes

# Answer
## Haskell: 72 chars

```
take 88$drop 9[p++show o|o<-[0..],p<-words$"C D♭ D E♭ F F♯ G G♯ A B♭ B"]

```
> 1 votes

# Answer
# Clojure - 71 chars

```
(for[c(range 10)n["C""Db""D""Eb""E""F""Gb""G""Ab""A""Bb""B"]](str n c))

```
> 1 votes

# Answer
## Perl, 57+1

Just dug this up, a nice golfing exercise. Requires `-E` for `say` -- counted in score.

`say+(CDbDEbEFGbGAbABbB=~/(.b?)/g)[$_%12],$_/12%9for 9..96`
> 1 votes

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

```
(o=`C,Db,D,Eb,E,F,Gb,G,Ab,A,Bb,B`.split`,`)=>o.flatMap((x,i)=>o.map(n=>n+i)).slice(9,97)

```

Try it online!
> 0 votes

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


# Question
Title: Write the shortest text getter/setter on an element for the DOM
Just like jQuery's `$.fn.text`, write one or two functions that can get and set the text on an element.

You can't use `textContent` or `innerText`, and even less `innerHTML`.

Plain javascript. No DOM library. It has to work on major browsers. (No need to care about old IE.)

Shortest code wins.

Enjoy!

# Answer
## JavaScript (167)

```
function t(e,h,f){if(h||h==''){while(f=e.lastChild)e.removeChild(f);e.appendChild(document.createTextNode(h))}h=e.data||'';for(c in f=e.childNodes)h+=t(f[c]);return h}

```

Usage :

```
var textContent = t(yourElement); // get the text content
t(yourElement, ''); // clear
t(yourElement, newText); // sets a new text

```

Note that there is no pollution of the global namespace

Demonstration, with a multi-level DOM tree and a few tests
> 4 votes

# Answer
## JavaScript (175)

```
function t(e,v,f){if(!v&&v!=''){v=e.data||'';for(c in f=e.childNodes)v+=t(f[c]);return v}else{ while(c=e.lastChild)e.removeChild(c);e.appendChild(document.createTextNode(v))}}

```

I have significantly less morality than @dystroy, so I didn't bother with **var**. I did have to scope **f** though, and I did it somewhat cleverly.

That said, our answers are pretty similar, and I'm not sure there's much of a better way to go about it.

With collection recognition **(173)**:

```
function t(e,v){if(!v&&v!=''){v=e.data||'';for each(c in e.childNodes)v+=t(c);return v}else{ while(c=e.lastChild)e.removeChild(c);e.appendChild(document.createTextNode(v))}}

```
> 2 votes

# Answer
# JavaScript (V8), 143 bytes

```
t=(e,h)=>h?.sub?[...e.children].map(c=>e.removeChild(c))&&e.appendChild(document.createTextNode(h)):(e.data||'')+[...e.childNodes].map(c=>t(c))

```
> 1 votes

---
Tags: code-golf, javascript
---


title: Quit Whining; Start Quining

text:
# Question
Title: Quit Whining; Start Quining
**Goal**:

Write a function or program that, given an integer `n`, will output a program in the same language that is a quine with a period of `n`.

**Description of Output Program**:

The output program needs to be a program that, when run, ... will output a program... that will output a program... etc, until the `n`th program is the original (first) output program. So this is, in a way, a *modular quine*. That's how I think of it, anyway.

The resulting programs should all be distinct.

**Example:**

Input: `2`

Program: `modulus_quine(n)`

Output: `P``Q``P` → ...

**Scoring:**

This is , so shortest code (for the generating program) wins.

Brownie points (-0 bytes, +1 thumbs up?) are given to anyone whose generating program IS their modular quine. This is where your program takes the input and outputs the first modular quine in the sequence, which outputs the next, etc. The resulting output programs must not prompt the user for input (until it gets back to the generator.)

# Answer
# GolfScript, 16 bytes

```
{%}+")1$~":x`+0x

```

Try it online in Web GolfScript.

### Example run

```
$ echo -n 3 | golfscript quining.gs
{3 % ")1$~"}0)1$~
$ echo -n 3 | golfscript quining.gs | golfscript
{3 % ")1$~"}1)1$~
$ echo -n 3 | golfscript quining.gs | golfscript | golfscript
{3 % ")1$~"}2)1$~
$ echo -n 3 | golfscript quining.gs | golfscript | golfscript | golfscript
{3 % ")1$~"}0)1$~

```

### Generator

```
                 # (implicit) Read from STDIN.
{%}+             # Concatenate the read input with the block.
                 # For example, "3"{%}+ -> {3 %}.
    ")1$~":x     # Push that string and save it in the the variable `x'.
            `+   # Inspect the string and concatenate it with the block.
                 # For example, {3 %}'")1$~"'+ -> {3 % ")1$~"}
              0x # Push a 0 and the string stored in `x'.

```

### Modular quine

For example, the modular quine `{3 % ")1$~"}0)1$~` works as follows.

```
{          }      # Define a block.
 3 %              # Take the integer on the stack modulo 3.
     ")1$~"       # Push that string.
            0)    # Push 0 and increment. Pushes 1.
              1$~ # Copy the block from the bottom of the stack and execute it.

```

The original copy of the block, the modified integer and the string the block pushed are printed, resulting in `{3 % ")1$~"}1)1$~`.

All printed programs have a trailing linefeed, which GolfScript prints automatically.
> 6 votes

# Answer
# Ruby, 100 bytes + brownie points

Generating program/zero-state:

```
;puts <<2.sub(/2*/){$&[/./]?$':?2*gets.to_i}*2,2
;puts <<2.sub(/2*/){$&[/./]?$':?2*gets.to_i}*2,2
2

```

Output for input of 3:

```
222;puts <<2.sub(/2*/){$&[/./]?$':?2*gets.to_i}*2,2
222;puts <<2.sub(/2*/){$&[/./]?$':?2*gets.to_i}*2,2
2

```

This program, when run, will not ask for input but output itself with the initial 222 on the first 2 rows replaced with 22. That will output a version where each row begins with 2, which will output the original program.

"2" lives a varied life here as (in order of appearance) a repeated digit in a no-op numeric literal, a HEREDOC reference, a regex literal, a character literal, a numeric argument to String#\*, a numeric argument to `puts`, a character in a HEREDOC string, and finally a HEREDOC delimiter.
> 3 votes

# Answer
# Underload, 29 bytes

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

```

Underload has no method to take input from the user, so I wrote a function rather than a complete program. The input is taken from the stack, the output is placed onto the stack (and can be printed with `S`).

Here's how to call it for an input of 1, `()`:

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

```

and it produces the following quine:

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

```

which runs like this:

```
(a(:^)*a(S)*^):^
(a(:^)*a(S)*^)(a(:^)*a(S)*^)^
(a(:^)*a(S)*^)a(:^)*a(S)*^
((a(:^)*a(S)*^))(:^)*a(S)*^
((a(:^)*a(S)*^):^)a(S)*^
(((a(:^)*a(S)*^):^))(S)*^
(((a(:^)*a(S)*^):^)S)^
((a(:^)*a(S)*^):^)S
program exits, with output (a(:^)*a(S)*^):^

```

As you can see, the modular quine of order 1 (i.e. just a normal quine) works by first generating a copy of itself, then generating a function to print that output, then running that function.

For higher orders, we just repeat the "generating a function to print that output" step (which is written in Underload as `a(S)*`). Here's how we call it for order 4 (`(:::***)` is 4):

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

```

Here's the program produced:

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

```

which, when run, produces the following programs in turn:

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

```

The same technique probably works in other languages, although maybe not so concisely.

~~As a side note, Underload only has eight commands, so a hypothetical golfing version that represented each using 3 bits would use 29×3÷8 = 10⅞ bytes. That would make it the shortest solution here.~~ Although it only has nine commands, one (`()`) uses two different characters, so the previous calculation isn't quite correct.
> 3 votes

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

```
b=0;exec(s:=f"print('b=%d;exec(s:=%r)'%(-~b%{input()},s))")

```

Try it online!
> 2 votes

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

```
a=f'a=%r,-~%d%%{input()};print(a[0]%%a)';exec(a%(a,0))

```

Try it online!

Let say input is `3` this will output :

```
a='a=%r,-~%d%%3;print(a[0]%%a)',-~1%3;print(a[0]%a)

```

which will output :

```
a='a=%r,-~%d%%3;print(a[0]%%a)',-~2%3;print(a[0]%a)

```

which will output :

```
a='a=%r,-~%d%%3;print(a[0]%%a)',-~0%3;print(a[0]%a)

```

... and so on

## How it works :

This solution uses the same idea than an other solution of mine on an other challenge

The main idea is to modify the second element of the tuple `a` each iterration inside the string with `'-~%d'%a`. `-~x` corresponds to an incrementation of 1.

Then we loop using a modulo equal to our input (using f-string to replace it in the base program)
> 2 votes

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


title: 5 Day Weather Forecast

text:
# Question
Title: 5 Day Weather Forecast
> Weather forecasting: Wrong too often to rely on, right too often to ignore.

Given a high and low temperature and one of four weather conditions per day, output an ASCII-art graphical five day weather forecast. The structure of the four graphical indicators are shown below.

```
 \ /
 -O-       Sunny
 / \

\ /
-O(==)     Partly Cloudy
(====)

  (==)     Cloudy
(====)

  (==)
(====)     Rainy
/////

```

The forecasting chart is as follows: each graphical indicator is centered in its own 9x5 box, with 5 boxes across the chart. Each box is separated by `|` characters. Below the graphical indicator is a three-letter abbreviation for the day of the week (`MON, TUE, WED, THU, FRI, SAT, SUN`) centered in its own 9x1 box. The temperatures are below the day of the week centered in their own 9x2 box. An example is shown below.

```
---------------------------------------------------
|         |         |         |         |         |
|    (==) |    (==) |  \ /    |   \ /   |   \ /   |
|  (====) |  (====) |  -O(==) |   -O-   |   -O-   |
|         |  /////  |  (====) |   / \   |   / \   |
|         |         |         |         |         |
---------------------------------------------------
|   MON   |   TUE   |   WED   |   THU   |   FRI   |
---------------------------------------------------
|  H 75   |   H 69  |  H 77   |   H 80  |  H 85   |
|  L 57   |   L 53  |  L 61   |   L 63  |  L 66   |
---------------------------------------------------

```

Note that "centered" can be taken loosely -- see in the example how the graphical alignment and the temperature horizontal alignment are somewhat flexible.

Additionally, since I'm from the US and therefore use Fahrenheit, you can safely assume that the temperatures are all double-digit, so `9 < t < 100`.

### I/O and Rules

*The I/O examples here are demonstrative of the above example chart.*

* Input can be taken in any reasonable format and by any convenient method. For example,
1) you could use numbers for the days of the week, the high and low temperatures, and the four conditions, and take input as five tuples, like `[0, 75, 57, 2], [1, 69, 53, 3], ...`
2) you could take input as five tuples using words, like `['MON', 75, 57, 'CLOUDY'], ['TUE', 69, 53, 'RAINY'] ...`
3) you could take input as just the first day, and a list of high temperatures, a list of low temperatures, and a list of conditions, like `1, [75, 69, ...], [57, 53, ...], [2, 3, ...]`
4) etc.
* Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, returned as a list of strings, returned as a single string, etc.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# Emojicode, ~~1202~~ 974 bytes

```
afD MON   TUE   WED   THU   FRI   SAT   SUN  f / \   \ /   -O-  (====)\ /   -O(==)        (==)(====)/////   (==)(====)l ---------------------------------------------------u      s |  S  |   wH L lLs u s u s u s u s u sLoi⏩-2 4o s◀1ios j⏩0 5▶1ioofa j 0i s◀1ioow ia j i 10SooDa j 1 so0i1i0iLll

```

Takes input as a list of lists of integers in the format of `condition day high low` where condition is an integer between 0 and 4. Try it online!
> 5 votes

# Answer
# JavaScript (ES8), ~~304~~ ~~263~~ 222 bytes

Takes input as an array of 5 `[w,d,h,l]` entries, where **d** is the day as a string and **w**, **h**, **l** are integers representing the weather (0-indexed, with 0 = sunny), high temperature and low temperature respectively. Returns an array of strings.

```
a=>',0,04,05,06,0,,01,,0H 2,0L 3,'.split`,`.map(s=>(s=a.map(p=>s.replace(/\d/g,n=>+n?p[n]||'  (==),(====),/////,\\ /,-O(==), \\ /, -O-, / \\,'.split`,`['765143810210'[p[0]*3-n+6]]:'|  ').padEnd(10,' -'[+!s])).join``)+s[0])

```

### Demo

```
let f =

a=>',0,04,05,06,0,,01,,0H 2,0L 3,'.split`,`.map(s=>(s=a.map(p=>s.replace(/\d/g,n=>+n?p[n]||'  (==),(====),/////,\\ /,-O(==), \\ /, -O-, / \\,'.split`,`['765143810210'[p[0]*3-n+6]]:'|  ').padEnd(10,' -'[+!s])).join``)+s[0])

O.innerText =
  f([
    [2,'MON',75,57],
    [3,'TUE',69,53],
    [1,'WED',77,61],
    [0,'THU',80,63],
    [0,'FRI',85,66]
  ]).join('\n');
```

```
<pre id=O></pre>
```

### How?

We define:

* `L = ',0,04,05,06,0,,01,,0H 2,0L 3,'.split(',')`

An array of strings describing each line of the board, in which:

+ 0 = prefix string: `"| "`
    + 1 = day of week
    + 2 = high temperature
    + 3 = low temperature
    + 4 = top pattern of the graphical indicator
    + 5 = middle pattern of the graphical indicator
    + 6 = bottom pattern of the graphical indicator
* `W = ' (==),(====),/////,\\ /,-O(==), \\ /, -O-, / \\,'.split(',')`

An array of strings describing the patterns of the graphical indicators.
* `P = '765143810210'`

A string describing the indices of the patterns in **W** for each graphical indicator, grouped by 3 and stored in reverse order.

The main function now reads as:

```
a => L.map(s =>                   // for each substring s in L
  (s = a.map(p =>                 //   for each array of parameters p in a:
    s.replace(                    //     replace in s
      /\d/g, n =>                 //       each digit n with:
        +n ?                      //         if n is non-zero:
          p[n] ||                 //           the n-th parameter in p, if defined
          W[P[p[0] * 3 - n + 6]]  //           or a graphical indicator pattern
        :                         //         else:
          '|  '                   //           the prefix string '|  '
    )                             //     end of replace()
    .padEnd(10, ' -'[+!s])        //     pad the result with either spaces or '-'
  ).join``)                       //   end of inner map(); join the results and save in s
  + s[0]                          //   append the first character
)                                 // end of outer map()

```
> 4 votes

# Answer
# Charcoal, ~~110~~ 94 bytes

```
↑χＦ⁵«Ｎθ↘→↘Ｐ⎇θ⁺⁺⎇⊖θ  ¦\ /¶-o“⎇)Ｄ№⸿≡⬤»”×/×⁵⁼θ³“2⸿φ*ＥＣ+@OΠ≦”Ｍ¹¦⁵ＰＳ¶¶ＥHL⁺⁺κ ＳＭ⁶±¹↑χ»Ｆ6231«Ｐ←⁵¹ＭＩι↓

```

Try it online! Link is to verbose version of code. Edit: Saved 16 bytes by avoiding repeating the cloud. Explanation:

```
↑χ

```

Print the left-hand column of `|`s.

```
Ｆ⁵«

```

Loop over the 5 days.

```
Ｎθ

```

Input the weather condition, numbered 0 to 3 using the same order as the question.

```
↘→↘Ｐ⎇θ

```

If the weather condition is not sunny:

```
⁺⁺⎇⊖θ  ¦\ /¶-o

```

If the weather condition is partly cloudy then print a partial sun.

```
“⎇)Ｄ№⸿≡⬤»”

```

Print a cloud.

```
×/×⁵⁼θ³

```

If the weather is rain then print it.

```
“2⸿φ*ＥＣ+@OΠ≦”

```

Otherwise print the sun.

```
Ｍ¹¦⁵ＰＳ

```

Read and print the day.

```
¶¶ＥHL⁺⁺κ Ｓ

```

Loop over and input and print the temperatures.

```
Ｍ⁶±¹↑χ»

```

Print the next column of `|`s.

```
Ｆ6231«

```

Loop over the characters `6`, `2`, `3` and `1`.

```
Ｐ←⁵¹

```

Print a row of `-`s.

```
ＭＩι↓

```

Cast the character to integer and move ready to print the next row.
> 3 votes

# Answer
# Python 3, ~~636~~ ~~610~~ ~~534~~ ~~464~~ 379 bytes

```
def w(s,l,h,a):
 g='|';A='   ';p,q,r=[A+'\ /'+A,'  \ / '+A,A+' (==) ',A+' (==) '],[A+'-O-'+A,'  -O(==) ','  (====) ','  (====) '],[A+'/ \\'+A,'  (====) ',A*3,'  /////  '];n='-'*51;R=n,;w=x=y=z=''
 for e in s:x+=g+p[e];y+=g+q[e];z+=g+r[e];w+=g+A*3
 R+=x+g,y+g,z+g,w+g;x=u=v=''
 for i in range(5):x+=g+a[i];v+='|  H '+h[i]+A;u+='|  L '+l[i]+A
 print('\n'.join(R+(x+g,n,u+g,v+g,n)))

```

**Input Format:-** The first list takes the weather conditions day wise -
**0 - Sunny
1 - Partly cloudy
2 - Cloudy
3 - Rainy.**

Second and third list take the highest and lowest temperatures respectively(as strings). Don't do anything with the fourth list - its mainly to store the days of the week.

Try It Online

Note:- A very special thanks to Mr.XCoder, ovs and pizzapants184 for helping reduce a lot of bytes.
> 2 votes

# Answer
# Clean, 328 bytes

```
import StdEnv,Text
s="----------"
u=" (====)"
v="(==)"
j=['-|||||-|-||-']
$[[d,h,l,w]:t]=[[z:cjustify 10(fromString x)]%(0,9)<+y\\x<-[s,"":[["\\ /","-O-","/ \\"],["\\ /  "," -O"+v,u]:map((++)["   "+v,u])[[""],["/////"]]]!!w]++["",s,"MONTUEWEDTHUFRI"%(d*3,d*3+2),s,"H "<+h,"L "<+l,s]&y<-if(t>[])($t)(map((<+)"")j)&z<-j]

```

#

```
join"\n"o$

```

Try it online!

As a partial function literal, taking `[[Int]]` and returning `String`.
> 0 votes

# Answer
# Vyxal, 206 bytes

```
→a\-51*D:,\|w6ẋfð9*j:,`\ /   *\ /   *      *  (==)
-O-   *-O(==)*  (==)*(====)
/ \\   *(====)*(====)*///// `↵ƛ×/;ƛ£←aƛ¥ni;` |  `j`|  `p` |`+,;_,,?ƛð3*pð3*+;\|j\|p\|+,,`|  H %   `5*?%\|+,`|  L %   `5*?%\|+,,

```

Try it Online!

A giant mess. Please don't ask.
> 0 votes

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


title: Start from ones

text:
# Question
Title: Start from ones
Given a strictly positive integer **n**, follow these steps:

1. Create an array **A** with **n** **1**s.
2. If **A** only has one element, terminate. Otherwise, starting from the first element, replace each pair of **A** with its sum, leaving the last element as is if **A**'s length is odd, and repeat this step.

The output should contain **A**'s state after each step in order from the first step to the last. Usage of standard loopholes is forbidden. This is a challenge, so the solution with the fewest bytes in each language wins.

## Test cases

Each line in the output of these examples is a state. You can output via any reasonable format.

Input: `1`

```
[1]

```

Input: `4`

```
[1, 1, 1, 1]
[2, 2]
[4]

```

Input: `13`

```
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[2, 2, 2, 2, 2, 2, 1]
[4, 4, 4, 1]
[8, 5]
[13]

```

Input: `15`

```
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[2, 2, 2, 2, 2, 2, 2, 1]
[4, 4, 4, 3]
[8, 7]
[15]

```

# Answer
# 05AB1E, 7 bytes

```
Å1Δ=2ôO

```

Try it online!
> 6 votes

# Answer
# MATL, 10 bytes

```
:g`t2estnq

```

Try it online!

### How it works

```
:     % Input n (implicit). Range [1 2 ... n]
g     % Convert to logical. Gives [1 1 ... 1]
`     % Do...while
  t   %   Duplicate
  2   %   Push 2
  e   %   Reshape as 2-column matrix, in column-major order, padding with 0 if needed
  s   %   Sum of each column
  t   %   Duplicate
  n   %   Number of elements
  q   %   Subtract 1. This will be used as loop condition
      % End (implicit). If top of the stack is not zero run new iteration
      % Display stack, bottom to top (implicit)

```
> 4 votes

# Answer
# Python 3, 57 bytes

```
def f(i,j=1):print(i//j*[j]+[i%j][:i%j]);i>j and f(i,j*2)

```

Try it online!

# Python 2, 51 bytes

```
def f(i,j=1):print i/j*[j]+[i%j][:i%j];i>j>f(i,j*2)

```

Try it online!

*-6 bytes total thanks to tsh*

Recursive function. For each step, it constructs a list of powers of `2`, such that the sum is smaller than or equal to the given integer. It then appends the remainder, if it is larger than `0`.
> 4 votes

# Answer
# Jelly, 6 bytes

```
L€+2/Ƭ

```

**Try it online!**
> 3 votes

# Answer
# Wolfram Language (Mathematica), ~~55~~ 54 bytes

```
Last@Reap[1~Table~#//.a_:>Tr/@Sow@a~Partition~UpTo@2]&

```

Try it online!

~~Finally, `Sow`/`Reap` beats an alternative!~~

Returns a singleton list containing a list of the steps.
> 3 votes

# Answer
# JavaScript, 55 bytes

```
f=(n,t=1,r=n)=>r>t?t+[,f(n,t,r-t)]:n>t?r+`
`+f(n,t+t):r

```

Try it online!

This is basically the golfed version of following codes:

```
function f(n) {
  var output = '';
  t = 1;
  for (t = 1; ; t *= 2) {
    for (r = n; r > t; r -= t) {
      output += t + ',';
    }
    output += r;
    if (n <= t) break;
    output += '\n';
  }
  return output;
}

```
> 3 votes

# Answer
# Pyth, 10 bytes

```
.u+McN2m1

```

Try it online!

```
.u          # Apply until a result is repeated, return all intermediate steps: lambda N,Y:
  +M        # map by + (reduce list on +):
    cN2     # chop N (current value) into chunks of 2, last one is shorter if needed
       m1Q  # map(1, range(Q)) (implicit Q = input)

```

-1 byte thanks to FryAmTheEggman
> 3 votes

# Answer
# , ~~20~~ 17 bytes

```
_2+/\&.>^:a:<@#&1

```

Try it online!

*-5 bytes thanks to Bubbler*
> 3 votes

# Answer
# , 65 bytes

-1 byte thanks to Giuseppe.

```
n=scan();while(T<2*n){cat(rep(+T,n%/%T),if(n%%T)n%%T,"\n");T=2*T}

```

Try it online!

Avoids recursion. In R, `%/%` is integer division and `%%` is the modulo. For each power of 2 `k=2^i`, we need to print `n%/%k` times the value `k`, and then `n%%k` if that value is non zero. Do this for all powers of 2 smaller than \\$2n-1\\$.

Here I am using `T` instead of `k`, since it is initialized as `TRUE` which is converted to 1. I still need to print `+T` instead of `T` to avoid a vector of `TRUE`s in the output.
> 3 votes

# Answer
# K (oK), ~~15~~ 17 bytes

```
{{+/'0N 2#x}\x#1}

```

Try it online!
> 3 votes

# Answer
# JavaScript (V8), 109 bytes

```
f=n=>g(Array(n).fill(1));g=(a,i=1)=>{console.log(a);if(a[i]){for(;a[i];)a.splice(i-1,2,a[i-1]+a[i++]);g(a);}}

```

Try it online!
> 3 votes

# Answer
# Jelly, 6 bytes

-1 byte thanks to Erik the Outgolfer.

```
1x+2/Ƭ

```

Try it online!
> 2 votes

# Answer
# Japt `-R`, 13 bytes

```
_ò mx}hUõÎü)â

```

Try it
> 2 votes

# Answer
# Brachylog, 17 bytes

```
;1j₍ẹẉ₂{ġ₂+ᵐ}ⁱ.ẉȮ

```

Try it online!

As horribly long as this is, I still feel a bit clever for using `.ẉȮ`: the obvious way to print something, then check if its length is 1 would be `ẉ₂l1`, `ẉ₂~g`, or `ẉ₂≡Ȯ`, where the  in the last one is necessary because `ẉ₂` unifies its input and output *before* it prints them, and `Ȯ` is pre-constrained to be a list of length 1, so the unification fails if the input is not a list of length 1. At the end of a predicate, this feature of `ẉ₂` can be circumvented, however, by using the output variable instead of subscripting : `.ẉȮ` first unifies its input with the output variable, then prints the output variable, and only afterwards unifies the output variable with `Ȯ`.
> 2 votes

# Answer
# Stax, 10 bytes

```
Çë⌐ⁿ┤5π»Å╡

```

Run and debug it

## Procedure:

1. Generate 0-based range.
2. Repeatedly halve each element until all items are zero.
3. Calculate run-lengths for each unique array.

## Annotated Source:

```
r       main:[0 .. 5]
{{hmgu  main:[[0 .. 5], [0, 0, 1, 1, 2, 2], [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0]]
m:GJ    main:"1 1 1 1 1 1"

```
> 2 votes

# Answer
# Haskell, 75 bytes

```
g.pure
g x|x!!0<2=[x]|1>0=(g$(\z->filter(0/=)[-div(-z)2,div z 2])=<<x)++[x]

```

Try it online!

Works backwards from the list `[n]` until it reaches a list of just ones.

Going forwards, I could get 80 bytes using `chunksof` from `Data.List.Split`:

```
import Data.List.Split
f x=g$1<$[1..x]
g[n]=[[n]]
g x=x:(g$map sum$chunksOf 2 x)

```

Try it online!
> 2 votes

# Answer
# Perl 6, 38 bytes

```
{1 xx$_,*.rotor(2,:partial)>>.sum...1}

```

Try it online!

There's some shortcut to partial rotoring that I'm not remembering right now...

### Explanation:

```
{                                    }  # Anonymous code block
                                 ...    # Return a sequence
 1 xx$_,            # Starting with a list of 1s with input length
        *           # Where each element is
         .rotor(2,:partial)        # The previous list split into chunks of 2 or less
                           >>.sum  # And each chunk summed
                                    1  # Until the list is length 1

```
> 1 votes

# Answer
# Charcoal, 19 bytes

```
ＮθＩＥ↨⊖⊗θ²Ｅ⪪Ｅθ¹Ｘ²κＬλ

```

Try it online! Link is to verbose version of code. Uses Charcoal's default output format, which is one number per line, with subarrays double-spaced from each other. Explanation:

```
Ｎθ                  Input `n` into a variable
       θ            `n`
      ⊗             Doubled
     ⊖              Decremented
    ↨   ²           Converted to base 2 (i.e. ceil(log2(input)))
   Ｅ                Map
           Ｅθ¹      List of `1`s of length `n`
          ⪪         Split into sublists of length
               ²    Literal `2`
              Ｘ     To power
                κ   Loop index
         Ｅ          Map over each sublist
                 Ｌλ Take the length
  Ｉ                 Cast to string for implicit print

```
> 1 votes

# Answer
# Perl 5, 46 bytes

```
say$_="1 "x<>;say while s/(\d+) (\d+)/$1+$2/ge

```

Try it online!

Output is space separated.
> 1 votes

# Answer
# Keg, 30 bytes

```
(|1){!1>|^(:. ,")^
,(!2/|+")}.

```

Try it online!

I've actually been meaning to complete this challenge for a while (I mean, I emailed myself the link to it so I would remember), but I've never gotten around to doing so until now!
> 1 votes

# Answer
# GolfScript, 24 bytes

A horribly long answer... golfed out 1 byte by using a hard-to-read output format

```
~[1]*{..2/{{+}*}%\,(}do;

```

Try it online!

## Explanation

```
~                        // Dump the contents of the input string
 [1]*                    // Create a 1-list with the length of the input string
     {              }do  // do ... while
                 \,(     // the length of the array is larger than 1
      .                  // Extra evolution step that we need to keep
       .                 // Create a copy of the input
        2/               // That splits into parts of 2 items
          {    }%        // For each over the splitted array:
           {+}*          // Reduce the item with addition
                         // e.g. [1] -> [1], [1 2] -> [3], etc.
                       ; // Discard the abundant copy

```
> 1 votes

# Answer
# APL, 28 chars

```
{1≢≢⎕←⍵:∇+/(⌈.5×≢⍵)2⍴⍵,0}⍴∘1

```

vector of 1s

```
⍴∘1

```

output the argument and check if length is different than 1: if so, go on

```
1≢≢⎕←⍵:

```

get half of the length and round up

```
⌈.5×≢⍵

```

reshape into a nx2 matrix adding a trailing 0 if needed

```
(⌈.5×≢⍵)2⍴⍵,0

```

sum of row by row

```
+/

```

recurse
> 1 votes

# Answer
# V (vim), 93 bytes

```
:s/1\n/a
D@"i1 <esc>
qqYplllA]<esc>0i[<esc>:s/\(\d\+\) \(\d\+\) /\1+\2,/g
C<c-r>=<c-r>"
<Esc><c-o>V}J0i <esc>@qq@qdd:s/ i1/1

```

Try it online!

Special casing 1 for `<c-o>` was a bit annoying, but the rest plays out smoothly. Possible byte saves can be in the large regex, and maybe removing the 1 special case.

Outputs as space separated lists.
> 1 votes

# Answer
# Vyxal, 7 bytes

```
1ẋ≬2ẇṠ↔

```

Try it Online!

```
1ẋ      # n 1s
      ↔ # Collect while unique:
  ≬---  # Next three as function
    ẇ   # Cut into chunks of length
   2    # 2
     Ṡ  # Sum each chunk

```
> 1 votes

# Answer
# Ohm v2, 8 bytes

```
@Dv·Ω2σΣ

```

Try it online!

If output in scientific notation is allowed, otherwise:

# Ohm v2, 9 bytes

```
@Dv·Ω2σΣì

```

Try it online!
> 0 votes

# Answer
# Gaia, 12 bytes

```
ċ)¦⟨:q2/Σ¦⟩ª

```

Try it online!

```
ċ)¦		| generate array of n 1's (really, generate array of n 0's and increment each)
   ⟨      ⟩ª	| do the following until you get to a fixed point:
    :q		| dup and print with a newline
      2/	| split into groups of 2, with last group possibly being smaller
	Σ¦	| take the sum

```
> 0 votes

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


title: Pickleball Doubles Scoring

text:
# Question
Title: Pickleball Doubles Scoring
Pickleball doubles is a game where only the serving side can score. The server calls the score as a triple of numbers, the serving side's score, the receiving side's score, and \\$1\\$ or \\$2\\$ to indicate whether the server is the first or second of their side to serve. If the server's side wins a point, their score is incremented and the same player serves again. If the receiving side wins a point, no score is incremented but the serve transfers to the other player if the past server was the first or goes to the receiving side if the past server was the second of their team to serve. To even things out, the first serve is at \\$0,0,2\\$ so the serving side gets only one set of serves. Game is the first side to \\$11\\$ but the team must be leading by \\$2\\$ to win. There is a special state END where the game is over which is indicated here by \\$0,0,0\\$.

Write a routine that determines whether one score call can follow another. You will be given two lists of three numbers, which will be integers in the range \\$0-30\\$. The first list will be the score called before one serve, the second will be the score called before the next serve. You must return a truthy value if the second call can follow the first and a falsey value if the second call cannot follow the first.

If the first call is \\$a,b,1\\$ and the server's side wins the next call would be \\$a+1,b,1\\$ unless the server's side wins the game, which is when \\$a \ge 11\\$ and \\$a \gt b+1\\$. In that case the next call is END. If the first call is \\$a,b,1\\$ and the receiver's side wins the next call is \\$a,b,2\\$. If the first call is \\$a,b,2\\$ and the server's side wins the next call is \\$a+1,b,2\\$ unless the server's side wins the game, which is when \\$a \ge 11\\$ and \\$a \gt b+1\\$. In that case the next call is END. If the first call is \\$a,b,2\\$ and the receiver's side wins the next call is \\$b,a,1\\$. If the first call is END (the start of a game) the next call is \\$0,0,2\\$. If either call is not a legal call in any game you must return a falsey answer.

This code golf, so the usual rules apply. You may take your input and provide output in any convenient format.

## Test cases:

```
Input               Output
==============================
[0,0,0] [0,0,2]     True
[0,0,0] [0,0,1]     False
[0,0,0] [1,0,2]     False
[0,0,2] [1,0,2]     True
[0,0,2] [1,0,1]     False
[0,0,2] [0,1,2]     False
[0,0,2] [0,0,2]     False
[0,0,2] [0,0,1]     True
[3,4,1] [3,4,2]     True
[3,4,1] [4,4,1]     True
[3,4,2] [4,4,2]     True
[3,4,2] [4,3,1]     True
[3,4,2] [4,3,2]     False
[3,4,3] [4,4,3]     False
[3,4,1] [4,4,2]     False
[3,4,1] [4,3,2]     False
[10,3,1] [0,0,0]    True
[10,3,1] [10,3,2]   True
[10,3,2] [3,10,1]   True
[10,3,2] [3,10,2]   False
[10,10,1] [0,0,0]   False
[10,10,1] [11,10,1] True
[10,10,1] [10,10,2] True
[11,10,2] [10,11,1] True
[11,10,1] [11,10,2] True
[10,11,2] [11,11,2] True
[10,11,1] [0,0,0]   False
[18,18,1] [19,18,1] True
[19,18,1] [0,0,0]   True
[19,18,2] [18,19,1] True
[12,8,1]  [12,8,2]  False
[12,8,2]  [8,12,1]  False
[11,10,1] [12,10,1] False
[8,12,1]  [8,12,2]  False

```

# Answer
> 5 votes
# , 87 84 95 92 91 95 bytes

```
e.(-.@w*]-:]**@{:+2<{:)#([:(*1-w=.((10<>.)*1<|@-)/@}:)]+#:@4),:(2={:){(+0 0 1*2^0={:),:1:2}2&A.

```

Try it online!

+11 thanks to Arnauld finding a case I'd missed in input validation, which was not covered by the original test cases

## the idea

* Generate all possible successors of the first list.
* Check if the second list is a member of those.
* To handle input validation, null out the successor list when the input is invalid.

## J details

* `(2={:){(+0 0 1*2^0={:),:1:2}2&A.` \- Generate the "server lost" case:
    + `1:2}2&A.` \- Sub-case 1: Serve changes. Swap elements 1 and 2 `2&A.` and reset the final element to 1 `1:2}`.
    + `(+0 0 1*2^0={:)` \- Sub-case 2: Serve increments. Add either `0 0 1`, or, if the final element is 0 `0={:`, add `0 0 2`.
    + `(2={:)` \- Choose sub-case 1 if the final element is 2, and sub-case 2 otherwise.
* `([:(*1-w=.10<{.*1<-/@}:)]+#:@4)` \- Generate the "server won" case:
    + `]+#:@4)` \- Add `1 0 0` (4 in binary) to the input.
    + Next, we'll transform the list to `0 0 0` if the game is over, and as a side effect store the "is game over?" function in `w`, so we can re-use it later for input validation.
    + `w=.((10<>.)*1<|@-)/@}:)` \- Check if this game is over: Is the absolute difference between the first two elements `|@-` greater than 1 `1<` and is `*` either element greater than 10 `10<>.`?
    + `*1-` \- Multiply the input by the inversion of that, so nothing happens when we haven't won, and the input becomes `0 0 0` when we have.
* `(-.@w*]-:]**@{:+2<{:)` Is the input valid?
    + `-.@w*` The input is not a win and...
    + `]-:]**@{:+2<{:)` The input matches `]-:` the input multiplied by the sign of the last element `]**@{:` plus 1 more if the last element is greater than 2 `2<{:`. This means it will only be valid if it is `0 0 0` or if the last element is 1 or 2, and the game is not already won.
    + The validation will now be 0 or 1.
    + `#` Copy our successor list that many times, leaving it unchanged when the input is valid, or nulling it out when it's invalid. Since the second input list will never be an element of the empty list, our overall result (see next step) will always be `0` if the input is invalid.
* `e.` Is the second input list (taken as the left arg) an element of the possible successors? This is our final answer.

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

Returns \\$0\\$ or \\$1\\$.

```
([a,b,c],B,g=x=>a<11|a<b+2&&b<11|b<a+2&&c<3&x+''==B)=>c?(a>9&a>b?g`0,0,0`:g([a+1,b,c]))|g(c-1?[b,a,1]:[a,b,2]):!a&!b&g`0,0,2`

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 166 bytes

```
\d+
$*
A`^(1*),(?=11\1)1{11}|^(?=1{11})(1+)11+,\2,|111;
^(,,;,,11|(1{10},1{0,9}|1(1{10,}),\3),1+;,,|((1{0,9},1*|(1+),1*\6),1+);1\4|(.*),1;\7,11|(1*),(1*),11;\9,\8,1)$

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
A`^(1*),(?=11\1)1{11}|^(?=1{11})(1+)11+,\2,|111;

```

Remove some illegal starting calls, specifically:

* `^(1*),(?=11\1)1{11}` receiving side has already won
* `^(?=1{11})(1+)11+,\2,` serving side has already won
* `111;` illegal service number.

```
^(,,;,,11|(1{10},1{0,9}|1(1{10,}),\3),1+;,,|((1{0,9},1*|(1+),1*\6),1+);1\4|(.*),1;\7,11|(1*),(1*),11;\9,\8,1)$

```

Check whether any legal call remains, specifically:

* `,,;,,11` \- Check for the start of a new game.
* `(1{10},1{0,9}|1(1{10,}),\3),1+;,,` Check for a win.
* `((1{0,9},1*|(1+),1*\6),1+);1\4` Check for a point that's not a win.
* `(.*),1;\7,11` \- Check for a second serve.
* `(1*),(1*),11;\9,\8,1` \- Check for a change of side.

I would have liked to use a conditional lookahead to determine whether the serving side is about to win or not and require that the second call matches `;,,` if they are or that the serving side simply scores a point if not, but for some reason my conditional lookahead started failing when I changed the expression for what to match when the conditional lookahead fails, which seems buggy.

# Answer
> 1 votes
# Python 2, 135 bytes

Takes all six values as seperate arguments, returns a boolean.

```
lambda a,b,s,A,B,S:(9<a-1>b)|(9<A-1>B)<any([a|b|s|A|B<1<S<3,(a,b)==(B,A)[::s-2|1]!=S==3-s<3,3>s>0<[(a+1,S,b)==(A,s,B),A|B|S<1][9<a>b]])

```

Try it online!

`9<a-1>b`: serving side has won (invalid)
`9<A-1>B`: receiving side has won (invalid)
`a|b|s|A|B<1<S<3`: *END* -\> *START*
`(a,b)==(B,A)[::s-2|1]!=S==3-s<3`: receiving side scores point
`3>s>0<[(a+1,S,b)==(A,s,B),A|B|S<1][9<a>b]]`: serving side scores

---
Tags: code-golf
---