title: Keep the unique characters down

text:
# Question
Title: Keep the unique characters down
It's very simple: Your program or function should generate the following text:

```
Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look.

```

## Fine print

You may write a program or function, which returns the output as a string or printing it to STDOUT (or closest alternative). You may optionally include a single trailing newline in the output.

## Scoring

**The number of bytes in your code** multiplied by **the number of unique bytes in your code**

Lowest score wins.

For example, a brainfuck or a whitespace answer would have a huge advantage here, as the multiplier would be very low (8 and 3 respectively). However, generally, writing programs in those languages produces much longer code which may negate that advantage.

Standard loopholes which are no longer funny are **banned**.

# Answer
# Insomnia, 575 bytes * 4 = 2300

```
dyedd=dyyyye=d=yd=dddde=ded=deey=eyy=de=edd=eydyee=yeyy=yey==ddyee=eydee=y=eyeedd=dde=yddd=eede=yedde=eeyd==yeyy=yyddy=eyy=dy=dddye=dyey=ede=yddd=dde=de=yyye=yyye=ddyyy=dyy=yeyddy=eyyyde=eed=ddd=yd=edyyd=eeydd=yedd=eye=eee=eeyy=yyyedde=d=eyyyedy=d=yddyye==dyyede=ddd=eydd=yd=ddde==eeeeyy=yeyd=deyy=yyy=ydy=dy=dd=e=ey=dddddy=yeey=ey=eed=ddd=eedy=ddddde=ydeyy=edd=ydy=ddy=yeedd=ydde=dde=edyye=ded=yeed=dddddde=eedy=eyde=ydy=ydydd=eyydd=dd=dddd=ddyye=ydeey=ed=eeeye=y=ydydde=eyyd=eyee=dy=edeyed=dyed==eyyddey=dd=yddd=yddd=de=ddedy=eyydd=eeedy==eyyydeee=d=d=eydd=yey=dyy==yyyedy=

```

Uses 4 characters `dye=`.

### Solution 1b (unpublished): 783 bytes * 3 = 2349

```
eeeeyeeyy=eeyy=yeyye=yyyeeyye=eeeye=yeyey=eyeyyy=eyy=eeyeye=yeyeyyy=yyeeye=yeyy=yey==yyeyeyeye=eyyey=y=yyyyyy=y=eyyeyyyyyyye=eeye=yyeeyye=eyeyeyyy==yeyy=yeyyyeyye=yyyeeyy==eeyyeee==eeyye=yyyyeyyeyyye=yyyyyyy=yeye=eyyyyy=eeye=eeyeeeeey=eyeye=eeee=yeyyye=eyyyyye=y=eeeyyy=eyyeyee=yyy=eyye=yeyeeee=yyeyeyyyy=eeyy=yyyyy=eyyyy=yyeeyye=e=eyyyyy=eyey==eyeyy=yyyyyeyeyeye=ye=yyyyyy==eeeeyy=yeye=yeyyey=yyy=eyyyeeeye==yeeyyeyy=e==yeeeyyyeyy=yeey=ey=eee=eyeyy=yyeeee=yeeyyyyy=yee=yeyyy=yeeeeyy=eyeeeeeye=eeeyy=yyeeeeyyye=yey=yyyyeeyye=yyyyyyy=yeee=eeeeyyeye=eyeeye=eeyyeyyy=eeyee=yyyyyeeyy=eee=eeyyeyyyyy=eeey=eyyeeyy=eyyeyyy=eeeeyeee=eeeye=y=yyyeyy=yyeeee=yyeyey=ey=eyyyyyeyyy=yeye==yeeyyyeyy=yeye=yyyyeeyy=eeeyyeeyyy=yeeyeyyy=eeyye=eee=eyyye==eyeyeyyyyy=e=eeyeeye=yeey=eyeyy=eyeye=ey=eyyeye=

```

Only uses 3 characters `ey=`.

### Solution 1: 826 bytes * 3 = 2478

```
yoyoy~oyoyo~oyooyy~ooyyoyy~ooyyyyoy~~yoyyo~ooyoooyooo~yoyyo~oyoyoyyy~yyo~oyyoo~~ooooy~oyyyyy~oyoyoo~~oyyyoooyy~~oyoyooyyy~yyooo~yoyo~yoyyyyo~yooyo~y~yyoyyyooyy~oyyooy~ooyoy~oyyooy~ooyyo~yoyyoo~o~ooyo~yooyyoo~yoyoy~ooyyyyooo~oyoyyo~yyoyyyoo~yyo~yyooyyo~yoyyoooy~~yoyyyooyoyy~oyoyyy~yoooyyoy~yooyy~yooyyo~yyooyyoo~oyoyo~oyyy~oyyo~oyyoyo~oyyyoo~oyoyyoo~yooyo~ooooo~~yoyyoyyoyoo~yoyyooo~y~ooooy~yyyoy~ooooyyoyyoy~oyyoo~oyyoyo~yoyyyooy~oyooo~yoyyoyy~yyyyyo~oyooy~oyoyy~yoyyyoy~ooyoy~yoyyoooy~~oyyyo~ooooooy~yooyoyyoyo~yooyyo~oooyyo~yoyooyyo~oyyy~o~yooooy~oyoyyooooy~~yoyyooyyo~oy~yyyoyyyyy~yoyyyoy~yooo~oooy~oooooyyoyyyo~yoyyo~y~oooyyyoyoo~yyooooyoyy~y~oooyyyoy~~yoy~oyyoyoyyy~yoyyyyy~oyooo~yyyyooo~yooyyoy~yooyo~yoyyyo~yyoyyyo~o~ooooooyoy~oyoyyoy~yyoooo~ooooyy~oyoyoy~ooyyo~yyoooyo~yyyyyo~oyyo~yooyyooyyoy~~ooyyyyoyyy~ooyyo~yyooo~

```

Only uses 3 characters: `yo~`. A program is used to generate this.

Currently, all programs only use instructions 0, 1, 2, 6. In other words, they manipulate the bits in a single byte and print out the result.
> 7 votes

# Answer
# CJam, ~~266~~ ~~281~~ 456 bytes * ~~14~~ ~~12~~ 7 unique = ~~3724~~ ~~3372~~ 3192

Try it online.

```
14301201124204202034420112034224204431020210101232301021240204310431312122132100240400222324402030223103420431324402222132223233141443401210314023001122320404112224314302132421403301243334313000011124244441400003310332301330220022110121411122100040310110020040121444302100143202204330334033211334242120304123121024200421121232100303121022431044444423243331440434010014400~~10~~100~~1~43c~c~4~~41c~100~~1~43c~c~123~~100~~1~43c~c~44~~14~~43c~c100~~40c~c43c~~

```

### Explanation

The strategy I've used is to treat each character in the string as a base-123 digit and encode that as a decimal number in the program. The program then converts that number back to base 123 and maps each base-123 digit back to a character. Because it's hard to explain why the program is in its current state, I'll explain each version of it.

Here's what the end of the program looked like in the first version:

```
...2068438725 123b:c

```

This implements the strategy in the most straightforward way possible. The number, encoded normally in base 10, is converted back to base 123 and each base-123 digit is mapped back to a character. But this uses 4 unique non-digit characters, and being able to get rid of any one of them would likely be worth the size hit due to having to use less straightforward code.

First, I realized that I could get rid of the `b` and the `:` operators by creating them at runtime as their ASCII character values converted back to a character (with the already present `c` operator) and evaluating them with the `~` operator. It turned out to be a little tricky to do this with the `:` operator, since it has to be parsed together with the following `c` operator. I solved this by producing the characters `:` and `c` and then producing and evaluating the character `+`, which concatenates the former two characters into the string `:c` which can then be evaluated properly.

Second, I realized that the `~` operator I just introduced had a handy new overloaded variant: when given a number, it produces the bitwise complement. By using this twice in a row after a number, I could introduce a token break in the source with no resultant computational effect, allowing me to replace the spaces used to separate numbers with `~~`.

The final result is 15 more bytes of code at the end, but this cost is greatly outweighed by the benefit of eliminating 2 unique characters out of 14. Here's a comparison of the end of the first version with the end of the second version:

```
...2068438725  123[ b  ][   :c    ]
...2068438725~~123~~98c~58c99c43c~~

```

Using any fewer than the 2 operators I was using would be impossible, but I still wanted fewer unique characters. So the next step was to eliminate digits. By changing the number's encoding so that each decimal digit was really a base-5 digit, I could potentially eliminate the digits 6-9. Before eliminating anything from the end of the prgoram, it looked like this:

```
...4010014400 10b5b123b:c

```

As mentioned before, eliminating the space is easy. But the `b`, `:`, and `c` would not be so easy, as their character codes are `98`, `58`, and `99`, respectively. These all contained digits marked for elimination, so I had to find ways to derive them all. And the only useful numeric operators with character values not containing 5-9 were decrement, increment, multiply, and add.

For `98`, I initially used `100~~40c~40c~`, which decrements `100` twice. But then I realized I could make yet another use of the `~` operator, as bitwise complement lets me get negative numbers which, when added, let me emulate subtraction. So I then used `100~~1~43c~`, which adds `100` and `-2` and is 2 bytes smaller. For `58`, I used `44~~14~~43c~`, which adds `44` and `14`. And for `99`, I used `100~~40c~`, which decrements `100`.

The final result is pretty big and obfuscated, but the cost of the significantly larger number and processing code were slightly outweighed by the big benefit of eliminating 5 unique characters out of 12. Here's a comparison of the final end of the program before eliminations and after eliminations:

```
...4010014400  10[      b      ][  5  ][     b     ]123[      b      ][            :c            ]
...4010014400~~10~~100~~1~43c~c~4~~41c~100~~1~43c~c~123~~100~~1~43c~c~44~~14~~43c~c100~~40c~c43c~~

```
> 19 votes

# Answer
# Whitespace, 1157 937 bytes * 3 unique = 3471 2811

By popular(?) request, I'm posting my whitespace solution.

In order to reduce the code needed, I hardcoded the entire string as one binary number (7 bits for each byte). A simple loop extracts the characters and prints them.

Source code on filebin.ca.

**NOTE:** The specifications allow for arbitrary large integers, but the Haskell interpreter on the official page is limited to 20 bits. Use, for example, this ruby interpreter on github/hostilefork/whitespaces.

The ruby script to create the whitespace program (l=WHITESPACE, t=TAB, u=NEWLINE, everything after // ignored, writes to a file `prog.h`):

```
str = 'Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look.'

def b2ws(bin)
    bin.chars.map{|x|x=='0' ? "l" : "t"}.join
end
def d2ws(dec,pad=0)
    b2ws(dec.to_s(2).rjust(pad,'0'))
end

bin = str.reverse.chars.map do |x|
    "  " + d2ws(x.getbyte(0),7) + " // char <#{x=="\n" ? "LF" : x}>"
end
data = "lll // pushes string as one large number\n#{bin.join("\n")}\nu"

File.open('prog.h','w') do |fout|
    fout << data << "\n"
    fout << <<-eos

// output string loop
ulllu // label 0

  // extract, print, and remove the last 7 bits of the data
  lul   // dup
  llltlllllllu // push 128
  tltt // mod
  tull  // print as char
  llltlllllllu // push 128
  tltl // div

  // break loop if EOS
  lul   // dup
  utltu // jump to 1 if top of stack is zero

ululu // jump to 0

ulltu // label 1
uuu
    eos
end

```

For illustration, the whitespace program in human-readable form. See below for a simple script to convert it to an actual whitespace program.

```
lll // pushes string as one large number
  ltltttl // char <.>
  ttltltt // char <k>
  ttltttt // char <o>
  ttltttt // char <o>
  ttlttll // char <l>
  ltlllll // char < >
  ttllllt // char <a>
  ltlllll // char < >
  ttlltlt // char <e>
  ttlttlt // char <m>
  ltlllll // char < >
  ttllttt // char <g>
  ttltttl // char <n>
  ttltllt // char <i>
  tttlttl // char <v>
  ttltllt // char <i>
  ttllttt // char <g>
  ltlllll // char < >
  ltllltl // char <">
  ltlttll // char <,>
  tlllttt // char <G>
  tlltttt // char <O>
  tllltll // char <D>
  ltlllll // char < >
  tlttllt // char <Y>
  tlttltl // char <Z>
  tlllllt // char <A>
  tllttll // char <L>
  ltlllll // char < >
  tllltlt // char <E>
  tlltlll // char <H>
  tltltll // char <T>
  ltlllll // char < >
  tltlltl // char <R>
  tllltlt // char <E>
  tltlttl // char <V>
  tlltttt // char <O>
  ltlllll // char < >
  tltlltt // char <S>
  tltllll // char <P>
  tllttlt // char <M>
  tltltlt // char <U>
  tlltltl // char <J>
  ltlllll // char < >
  tlttlll // char <X>
  tlltttt // char <O>
  tlllttl // char <F>
  ltlllll // char < >
  tlltttl // char <N>
  tltlttt // char <W>
  tlltttt // char <O>
  tltlltl // char <R>
  tlllltl // char <B>
  ltlllll // char < >
  tlltltt // char <K>
  tlllltt // char <C>
  tlltllt // char <I>
  tltltlt // char <U>
  tltlllt // char <Q>
  ltlllll // char < >
  tllltlt // char <E>
  tlltlll // char <H>
  tltltll // char <T>
  ltllltl // char <">
  ltlllll // char < >
  ltttltl // char <:>
  ltltllt // char <)>
  ttlltlt // char <e>
  ttllltt // char <c>
  ttllllt // char <a>
  ttlltlt // char <e>
  tttllll // char <p>
  ltlllll // char < >
  ttttllt // char <y>
  ttlttlt // char <m>
  ltlllll // char < >
  tttlltl // char <r>
  ttltttt // char <o>
  ttllttl // char <f>
  ltlllll // char < >
  ttttllt // char <y>
  ttlltll // char <d>
  tttlttt // char <w>
  ttltttt // char <o>
  tttlltl // char <r>
  ltlllll // char < >
  ttltttt // char <o>
  ttltttt // char <o>
  tttltll // char <t>
  ltlllll // char < >
  tttltll // char <t>
  tttlltt // char <s>
  tttltlt // char <u>
  ttltltl // char <j>
  ltltlll // char <(>
  ltlllll // char < >
  ttlltll // char <d>
  ttlltlt // char <e>
  tttltll // char <t>
  ttltttt // char <o>
  tttltlt // char <u>
  tttlllt // char <q>
  ltlllll // char < >
  ttttllt // char <y>
  ttlttll // char <l>
  tttlltt // char <s>
  tttltlt // char <u>
  ttltttt // char <o>
  ttltllt // char <i>
  ttttlll // char <x>
  ttltttt // char <o>
  ttltttl // char <n>
  ttllltl // char <b>
  ttltttt // char <o>
  ltlllll // char < >
  ttltlll // char <h>
  tttltll // char <t>
  ttlltlt // char <e>
  ttllltl // char <b>
  ttllllt // char <a>
  ttttltl // char <z>
  ttltllt // char <i>
  ttlttll // char <l>
  tllltlt // char <E>
u

// output string loop
ulllu // label 0

  // extract, print, and remove the last 7 bits of the data
  lul   // dup
  llltlllllllu // push 128
  tltt // mod
  tull  // print as char
  llltlllllllu // push 128
  tltl // div

  // break loop if EOS
  lul   // dup
  utltu // jump to 1 if top of stack is zero

ululu // jump to 0

ulltu // label 1
uuu

```

---

Basically, the string to output is a long integer, and you need to reduce its score.

> Take a number x, and convert it to base b. Its length will be `floor(log_b(x)+1)`, and it will contain `b` different symbols. So the score is `b*floor(log_b(x)+1)`. `x` is a given large number, and if you plot this for b, you'll find the minimum is pretty much at `b=3` (and `b=2` is almost as good). Ie, the length reduces slightly as you use higher bases (log), but size of the charset increases linearly, so it isn't worth it.

Thus I looked for a language with only 0/1's, but I didn't find any, and then I remembered there was whitespace and tried it. In whitespace, you can enter binary numbers with 0's and 1's directly.

---

# Old code, worse score but more interesting

Old code on filebin.

The ruby script I used for creating the program (l=WHITESPACE, t=TAB, u=NEWLINE, everything after `//` ignored, writes to a file `prog.h`):

```
str = 'Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look.' + "\n"

def shift(x)
    (x-97)%128
end

EOS = "lttltl" #26
STACK = []

bin = str.reverse.chars.map do |x|
    byte = shift(x.getbyte(0))
    rf = STACK.index(byte)
    STACK.unshift(byte)

    y = byte.to_s(2).chars.map{|y|y=='0' ? 'l' : 't'}.join
    ph = "lll#{y}u" # pushing directly
    if rf
        bn = rf.to_s(2).chars.map{|y|y=='0' ? 'l' : 't'}.join
        cp = "ltll#{bn}u" # copying from stack
    end

    if STACK.size>0 && STACK[0]==STACK[1]
        "lul // dup #{x.inspect}"
    elsif cp && cp.size < ph.size
        "#{cp} // copy <#{x.inspect}> (from #{rf})"
    else
        "#{ph} // push <#{x.inspect}> (#{shift(x.getbyte(0))})"
    end
end

File.open('prog.h','w') do |fout|
    fout << "ll#{EOS}u // push EOS" << "\n"
    fout << bin.join("\n") << "\n"
    fout << <<-eos
// output string
ullu // label 0
  // add 97 (128) before printing
  lllttlllltu // push 97
  tlll // add
  llltlllllllu // push 128
  tltt // mod
  tull  // print top of stack

  // break loop if EOS
  lul   // dup
  ll#{EOS}u // push EOS
  tllt // subtract
  utltu // jump to 1 if top of stack is zero
uluu // jump to 0

ulltu // label 1
uuu
    eos
end

```

For illustration, the whitespace program in human-readable form. See below for a simple script to convert it to an actual whitespace program.

```
lllttltlu // push EOS
llltltlltu // push <"\n"> (41)
llltllttltu // push <"."> (77)
llltltlu // push <"k"> (10)
llltttlu // push <"o"> (14)
lul // dup "o"
llltlttu // push <"l"> (11)
lllttttttu // push <" "> (63)
llllu // push <"a"> (0)
ltlltu // copy <" "> (from 1)
llltllu // push <"e"> (4)
lllttllu // push <"m"> (12)
ltlltlu // copy <" "> (from 2)
lllttlu // push <"g"> (6)
lllttltu // push <"n"> (13)
llltlllu // push <"i"> (8)
llltltltu // push <"v"> (21)
ltlltu // copy <"i"> (from 1)
lllttlu // push <"g"> (6)
ltllttlu // copy <" "> (from 6)
llltllllltu // push <"\""> (65)
llltlltlttu // push <","> (75)
lllttllttlu // push <"G"> (102)
lllttltttlu // push <"O"> (110)
lllttlllttu // push <"D"> (99)
ltlltltu // copy <" "> (from 5)
lllttttlllu // push <"Y"> (120)
lllttttlltu // push <"Z"> (121)
lllttlllllu // push <"A"> (96)
lllttltlttu // push <"L"> (107)
ltlltllu // copy <" "> (from 4)
lllttlltllu // push <"E"> (100)
lllttlltttu // push <"H"> (103)
llltttllttu // push <"T"> (115)
ltllttu // copy <" "> (from 3)
llltttllltu // push <"R"> (113)
ltlltllu // copy <"E"> (from 4)
llltttltltu // push <"V"> (117)
ltlltttlu // copy <"O"> (from 14)
ltlltllu // copy <" "> (from 4)
llltttlltlu // push <"S"> (114)
lllttlttttu // push <"P"> (111)
lllttlttllu // push <"M"> (108)
llltttltllu // push <"U"> (116)
lllttltlltu // push <"J"> (105)
ltlltltu // copy <" "> (from 5)
llltttltttu // push <"X"> (119)
ltlltlllu // copy <"O"> (from 8)
lllttlltltu // push <"F"> (101)
ltllttu // copy <" "> (from 3)
lllttlttltu // push <"N"> (109)
llltttlttlu // push <"W"> (118)
ltlltllu // copy <"O"> (from 4)
ltlltllltu // copy <"R"> (from 17)
lllttlllltu // push <"B"> (97)
ltlltltu // copy <" "> (from 5)
lllttltltlu // push <"K"> (106)
lllttllltlu // push <"C"> (98)
lllttltlllu // push <"I"> (104)
ltllttttu // copy <"U"> (from 15)
llltttllllu // push <"Q"> (112)
ltlltltu // copy <" "> (from 5)
ltllttlltu // copy <"E"> (from 25)
ltllttttlu // copy <"H"> (from 30)
ltllttttlu // copy <"T"> (from 30)
llltllllltu // push <"\""> (65)
ltlltllu // copy <" "> (from 4)
llltlttlltu // push <":"> (89)
llltlltlllu // push <")"> (72)
llltllu // push <"e"> (4)
llltlu // push <"c"> (2)
llllu // push <"a"> (0)
llltllu // push <"e"> (4)
lllttttu // push <"p"> (15)
ltlltttu // copy <" "> (from 7)
lllttlllu // push <"y"> (24)
lllttllu // push <"m"> (12)
ltlltlu // copy <" "> (from 2)
llltllltu // push <"r"> (17)
llltttlu // push <"o"> (14)
llltltu // push <"f"> (5)
ltllttu // copy <" "> (from 3)
ltllttlu // copy <"y"> (from 6)
lllttu // push <"d"> (3)
llltlttlu // push <"w"> (22)
llltttlu // push <"o"> (14)
ltlltttu // copy <"r"> (from 7)
ltlltltu // copy <" "> (from 5)
ltlltlu // copy <"o"> (from 2)
lul // dup "o"
llltllttu // push <"t"> (19)
ltllttu // copy <" "> (from 3)
ltlltu // copy <"t"> (from 1)
llltlltlu // push <"s"> (18)
llltltllu // push <"u"> (20)
llltlltu // push <"j"> (9)
llltllltttu // push <"("> (71)
ltlltltu // copy <" "> (from 5)
lllttu // push <"d"> (3)
llltllu // push <"e"> (4)
ltlltttu // copy <"t"> (from 7)
llltttlu // push <"o"> (14)
ltlltttu // copy <"u"> (from 7)
llltllllu // push <"q"> (16)
ltllttlu // copy <" "> (from 6)
lllttlllu // push <"y"> (24)
llltlttu // push <"l"> (11)
llltlltlu // push <"s"> (18)
ltlltltu // copy <"u"> (from 5)
llltttlu // push <"o"> (14)
llltlllu // push <"i"> (8)
llltltttu // push <"x"> (23)
ltlltlu // copy <"o"> (from 2)
lllttltu // push <"n"> (13)
llltu // push <"b"> (1)
ltlltlu // copy <"o"> (from 2)
ltlltlttu // copy <" "> (from 11)
llltttu // push <"h"> (7)
llltllttu // push <"t"> (19)
llltllu // push <"e"> (4)
llltu // push <"b"> (1)
llllu // push <"a"> (0)
lllttlltu // push <"z"> (25)
llltlllu // push <"i"> (8)
llltlttu // push <"l"> (11)
lllttlltllu // push <"E"> (100)
// output string
ullu // label 0
  // add 97 (128) before printing
  lllttlllltu // push 97
  tlll // add
  llltlllllllu // push 128
  tltt // mod
  tull  // print top of stack

  // break loop if EOS
  lul   // dup
  lllttltlu // push EOS
  tllt // subtract
  utltu // jump to 1 if top of stack is zero
uluu // jump to 0

ulltu // label 1
uuu

```

This whitespace program itself is rather simple, but there are three golfing optimizations:

* use `lul` to clone the stack when there's a duplicate character
* use `ltl` to clone the n-th entry of the stack if its shorter than pushing the char directly
* shift down all bytes by 97 (mod 128), makes the binary numbers smaller

---

A simple ruby script to convert my human readable whitespace code to an actual whitespace program (read a file `prog.h` and writes to a file `prog.ws`):

```
WHITESPACE = "l"
NEWLINE = "u"
TAB = "t"

File.open('prog.ws','w') do |fout|
    code = ""
    fin = File.read('prog.h')
    fin.each_line do |line|
        line.gsub!(/\/\/.*/,'')
        line.scan(/#{NEWLINE}|#{WHITESPACE}|#{TAB}/i) do |x|

            code << case x.downcase
            when NEWLINE.downcase
                "\n"
            when WHITESPACE.downcase
                " "
            when TAB.downcase
                "\t"
            else
                ""
            end
        end
    end
    fout << code
end

```
> 16 votes

# Answer
# Ruby 144 Bytes * 39 Unique = 5616

```
puts"Elizabeth obnoxiously quoted (just too rowdy for my peace): \"#{'the quick brown fox jumps over the lazy dog,'.upcase}\" giving me a look."

```

Sometimes the simplest is the best.
> 7 votes

# Answer
# Brainfuck, 1264 bytes * 7 unique = 8848

Yeah, it's a terrible score.

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

```
> 6 votes

# Answer
# \>\<\> (Fish) - 578 bytes * 8 unique = 4624

```
14121412412431421124321110441421130402401433401430421141143114240333221142303303210321143224241321121343212340321131301320302344221132340304221130322340321313221100323234202311321143224241341121131213110444324310422421114441421142412420421114400443412442421112412413421113403423411403121100410413412423432421114431403423412401404412402434312421140413410434324324401431443243*3*3+3*1+00p44*4+3*2+01p44*3*4+1+11p44*3*4+1+21p43+3*2*31p43+3*2*41p43*3*41+1p44*3*4+1+42+1p43+3*2*43+1p43+3*2*1+44+1p43+3*2*1+33*1p43*3*3*3+33*1+1p43*3*3*33*2+1p43+3*3*43*1p44*2*1+43*1+1p44*3+3*2+43*2+1p

```

My score isn't as competitive as I was hoping, but I thought this solution was still interesting enough to post.

## Explanation

The first section of code is a long string of the digits 0-4 that represent a 3 digit base 5 representation for each character in the string. The remaining code takes advantage of the `p` operator in Fish that allows you to edit the program's source code while the program is running. By using that operator, I was able to generate the Fish code necessary to convert the base 5 characters back to base 10 and output them, and then put that code back into the source code at the beginning of the file before the interpreter reached the end of the line and wrapped around. When the interpreter reaches the end of the line, the code has been modified to look like this:

```
v4121412412431421124321110441421130402401433401430421141143114240333221142303303210321143224241321121343212340321131301320302344221132340304221130322340321313221100323234202311321143224241341121131213110444324310422421114441421142412420421114400443412442421112412413421113403423411403121100410413412423432421114431403423412401404412402434312421140413410434324324401431443243*3*3+3*1+00p44*4+3*2+01p44*3*4+1+11p44*3*4+1+21p43+3*2*31p43+3*2*41p43*3*41+1p44*3*4+1+42+1p43+3*2*43+1p43+3*2*1+44+1p43+3*2*1+33*1p43*3*3*3+33*1+1p43*3*3*33*2+1p43+3*3*43*1p44*2*1+43*1+1p44*3+3*2+43*2+1p
>55**$5*++ol?!;

```

When the code wraps around and hits the `v` operator it goes down to the second line, hits the `>` operator and proceeds to loop, each time converting the base 5 encoding back to a base 10 ascii value and then outputting that value. When there are no more values on the stack the `?` operator will skip to the `;` and the program will end.
> 6 votes

# Answer
# , 273 bytes × 7 unique bytes = 1911, noncompeting (language postdates challenge)

```
501513010250341012432044041204045104011053033043511402401130443235151151105240424404004144031133304214014044433043401032201433022042551243201043511102223044114403120042140450415114434050440500114042432010430032533041340424320250451514210501020420444010403043040402343447403

```

Try it online!

Unfortunately, this is an old challenge, meaning that I don't get to win with one of my newest languages. However, the language was created with no knowledge of the challenge (I just randomly stumbled across it in "related questions"), but nonetheless pretty much turned out to be a perfect fit.

7 programs on PPCG normally get submitted in packed format, packing eight commands into three bytes (the language has twelve commands, but only eight can appear in a source file, meaning that three bits are enough). However, the language also supports an octal format in which each command is written as an ASCII digit, and that's what I've used here, meaning that only seven distinct bytes are used (the `6` command isn't necessary in a program that just prints a simple string).

The program is very simple; it consists of two stack elements, a long string that just gets printed verbatim, a `7` to separate the elements (unfortunately unavoidable), and `403` which is a simple way of printing a constant string in 7 (`40` escapes the second stack element, whilst moving it to the top of the stack, then `3` prints it and discards the old first stack element, i.e. the `403` itself).

So how did I get the string as short as 269 bytes? 7 supports multiple I/O formats, and one of its formats is US-TTY, a character set (specifically, a variant of Baudot) which was widely used before ASCII was invented. (The `5` at the start of the second stack element, i.e. the start of the program, specifies the string's encoding; the rest is the string content itself.) It's a five-bit character set, and the commands `0` to `5` can safely be stored in strings whilst being unescaped consistently (so that escaping it once will exactly reproduce the original), so the language uses pairs of commands (36 options) to encode characters of US-TTY (32 options, with 4 being used for directives to the 7 interpreter itself). Of course, there are more than 32 unique characters that people might want to output (and more than 32 characters appear in the string), so two of the characters are "shift codes" that switch between four character sets (uppercase letters, lowercase letters, figures, and a user-defined "figures extension" which 7 uses for the remaining ASCII characters that aren't in the other character sets; however, all the characters in the string are "natively" in US-TTY so the details of the extension didn't matter). Here's the program's output, with non-ASCII characters added to show where shifts occur (and a line break added to make reading easier, which isn't in the original string):

```
Ełlizabeth obnoxiously quoted Ø(Łłjust too rowdy for my peaceØ):
"ŁTHE QUICK BROWN FOX JUMPS OVER THE LAZY DOGØ," Łłgiving me a lookØ.

```

I count ten shifts added to 124 characters of input, a fairly negligible ratio. As such, the ability to use only just over two bytes of input per input character, times 7 unique bytes, means that the score on this challenge is incredibly good. (I guess a language that was designed specifically for this challenge would use some sort of string compression, rather than a pre-existing character set, but even though Baudot and US-TTY weren't designed for golfing, they're still fairly concise.)
> 6 votes

# Answer
# Python 2, ~~163~~ ~~147~~ ~~145~~ 143 bytes * ~~35~~ ~~36~~ 35 unique = ~~5705~~ ~~5292~~ ~~5220~~ 5005

That's probably about as good as I'm going to get it.

### Edits:

1. Removed `.capitalize()` in favor of using `E`.
2. Changed to use `'` instead of backslash escaping quotes.
3. Removed `+` and some spaces to use commas in the `print` statement.

```
print"Elizabeth obnoxiously quoted (just too rowdy for my peace):",'"the quick brown fox jumps over the lazy dog,"'.upper(),"giving me a look."

```
> 3 votes

# Answer
# Python 2, ~~14508 11700 11088 10164 9486 9746 7860~~ 145 bytes * 36 unique = 5220

I saw the title and thought this was an interesting challenge for the rather wordy Python. These are my notes as I tackled this problem.

My first try reduced the uniques to 31:

```
print''.join(chr([69,108,105,122,97,98,101,116,104,32,111,98,110,111,120,105,111,117,115,108,121,32,113,117,111,116,101,100,32,40,106,117,115,116,32,116,111,111,32,114,111,119,100,121,32,102,111,114,32,109,121,32,112,101,97,99,101,41,58,32,34,84,72,69,32,81,85,73,67,75,32,66,82,79,87,78,32,70,79,88,32,74,85,77,80,83,32,79,86,69,82,32,84,72,69,32,76,65,90,89,32,68,79,71,44,34,32,103,105,118,105,110,103,32,109,101,32,97,32,108,111,111,107,46][r])for r in range(124))

```

I thought I could do better. By using `map`, uniques came down to 26:

```
print''.join(map(chr,(69,108,105,122,97,98,101,116,104,32,111,98,110,111,120,105,111,117,115,108,121,32,113,117,111,116,101,100,32,40,106,117,115,116,32,116,111,111,32,114,111,119,100,121,32,102,111,114,32,109,121,32,112,101,97,99,101,41,58,32,34,84,72,69,32,81,85,73,67,75,32,66,82,79,87,78,32,70,79,88,32,74,85,77,80,83,32,79,86,69,82,32,84,72,69,32,76,65,90,89,32,68,79,71,44,34,32,103,105,118,105,110,103,32,109,101,32,97,32,108,111,111,107,46)))

```

At about this time, I noticed in the question text that the score was `uniques * bytes`, not just uniques! That meant my scores for the above were 14508 and 11700. Not very competitive. So I now reduce the bytes by storing the text as a hex string:

```
# 308*36 = 11088
print''.join(chr(int('456c697a6162657468206f626e6f78696f75736c792071756f74656420286a75737420746f6f20726f77647920666f72206d79207065616365293a202254484520515549434b2042524f574e20464f58204a554d5053204f56455220544845204c415a5920444f472c2220676976696e67206d652061206c6f6f6b2e'[i*2:i*2+2],16)) for i in range(124))

```

Size was reduced but more unique characters. But if I used a packed 2 digit decimal string with a 32 offset:

```
# 308*33 = 10164
print''.join(chr(int('37767390656669847200796678798873798583768900818579846968000874858384008479790082798768890070798200778900806965676909260002524037004953413543003450475546003847560042534548510047543750005240370044335857003647391202007173867378710077690065007679797514'[i*2:i*2+2])+32) for i in range(124))

```

This has the same number of bytes but saves 3 uniques.

I hatch a new plan. If I pack a Python long integer with 7 bit characters, I could extract each one by shifting:

```
# 306*31 = 9486
h=1073974643401006528619595312441225198653732186368270382545648881135648217524502741093886285232362673460172159947573049818819511630304840724474679255867143965214892747087773876949021986013520804726327302180335979259392708372721217579101211940864406962137554744750
w=''
while h:w=chr(h&127)+w;h>>=7
print w

```

Well that reduced the score to 9486. An interesting experiment, but nowhere near good enough. Now what if I get rid of the function names and rely on string formatting?

```
# 443 * 22 = 9746
print('%c'*124)%(69,108,105,122,97,98,101,116,104,32,111,98,110,111,120,105,111,117,115,108,121,32,113,117,111,116,101,100,32,40,106,117,115,116,32,116,111,111,32,114,111,119,100,121,32,102,111,114,32,109,121,32,112,101,97,99,101,41,58,32,34,84,72,69,32,81,85,73,67,75,32,66,82,79,87,78,32,70,79,88,32,74,85,77,80,83,32,79,86,69,82,32,84,72,69,32,76,65,90,89,32,68,79,71,44,34,32,103,105,118,105,110,103,32,109,101,32,97,32,108,111,111,107,46)

```

I now have only 22 uniques, but the score does not improve.

Ok, What if I took the obvious way and just printed the string:

```
# 131*60 = 7860
print'Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look.'

```

Score of 7860. I should have done this first. But I would not have learned so much.

I guess I could reduce uniques by 26 if I dynamically produced the upper case parts, so:

```
# 145*36 = 5220
print'Elizabeth obnoxiously quoted (just too rowdy for my peace): '+'"the quick brown fox jumps over the lazy dog,"'.upper()+' giving me a look.'

```

I think Python will not get much better than 5220. The task of minimising the unique characters in Python sure was instructive though.

Update: mbomb007 has a better Python solution scoring 5005. Nice work.
> 3 votes

# Answer
# \>\<\> (Fish) \- 138 Bytes * 65 Unique = 8970

The simple route, i.e. Hello World:

```
!v'Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look.'r!
 >l?!;o

```

Well, for my first foray into \>\<\> this was a challenge. I think I see some improvements, but it was fun learning it :)

Or to make it overly complicated - 1567 bytes * 27 Unique = 42309

```
!\f8+3*:o2*f2*-:o3-:of+2+:ofa+-:o1+:o3+:of+:oc-:o\7+:od-:oc+:o1+:o9+: of-:o6+:o6+:o2-:o7-: od+:o\8-:o4+:o6-:o5+:of -:o1-:o\\6+:ob+ :o2-:o1+:o\:o5-:o:o\3+ :o3-:o8+:of4+-:oab ++:o\f4+-:o9+ :o3+: o\!
!5:of+a+:o1-:off+2+o:f-6-oa-:o8-:of3*1-:oa-:o2-:!fo3*7+:o2+:o:d+o:o5!f+:o7-:off+2+o6+:o8-!f:off!f+2+o4-:off+2+ob+!f:o3+::\ff    f f          f        f  f                  f    f        f     \!f-
 -                                               f                   f                    f     f                 f       ff    3 f          f        f  f                  f    f        f       f
 :                                               +                   +                    +     +                 +       ++    * +          +        +  +                  +    +        +       +
 o                                               2                   2                    2     2                 2       2a    1 2          2        2  2                  2    2        2       2
 c                                               +                   +                    +     +                 +       ++    + +          +        +  +                  +    +        +       +
 +                                               o                   o                    o     o                 o      \oo4-o \ o;         o        o  o                  o    o        o       o
 \:off+2+o9-:ob-:o4-:o2+:o2+:of4*%:of2++:o2,3+:o2 +:o3*f-3-:oc-:o3-:o\c+:o4+:oc-:o6-:o8+:o\9-:of 1++:o3-:o8+:o9-:o\8-:o9+:  o9+: o\e-:ob+:o8- :o3+:o3+ :o\4-:o7+:o2-f-:od+:o\2+:o c-:o3-:o\7+:ob\

```
> 1 votes

# Answer
# 05AB1E, 380 bytes * 11 chars = 4180 score

```
"234413410442342343401431404112421343420421440410421432430413441112423432421431401400112130411432430431112431421421112424421434400441112402421424112414441112422401342344401131213112114314242234112311320243232300112231312304322303112240304323112244320302310313112304321234312112314242234112301230330324112233304241134114112403410433410420403112414401112342112413421421412141"3ô5öçJ

```

Try it online!

Pushes base 5 representation of ASCII chars joined together.
Splits in pieces of 3, converts back to decimal.
Converts ASCII integer back to character.
Joins back together.
> 1 votes

# Answer
# Java 8, 141 bytes * 64 unique characters = 9,024

```
()->{return"Elizabeth obnoxiously quoted (just too rowdy for my peace): \"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG,\" giving me a look.";}

```

141 bytes, 64 unique characters. Approaches other than the simple "return the string" increase the byte count without saving much on characters used.
> 0 votes

# Answer
## Perl 6, 139 bytes * 36 unique = 5004

```
say 'Elizabeth obnoxiously quoted (just too rowdy for my peace): "'~"the quick brown fox jumps over the lazy dog".uc~'," giving me a look.'

```
> 0 votes

# Answer
# Tcl, 345 bytes, 345 x 13 = 4485

```
\160\165\164\163 [\163\165\142\163\164 [\162\145\147\163\165\142 \55\141\154\154 \50\\\144\\\144\51 "055451724142456450 5742565770515765635471 616557644544 \5052656364 645757 6257674471 465762 5571 6045414345\51\72 \"241005 2125110313 0222172716 061730 1225152023 17260522 241005 14013231 041707\"\54 475166515647 5545 41 54575753" \\\\1\\1]]\56

```

Try it online!

---

~~Tcl, 337 bytes, 337 x 15 = 5055
```
\160\165\164\163 [\163\165\142\163\164 [\162\145\147\163\165\142 \55\141\154\154 (\\\144\\\144) "055451724142456450 5742565770515765635471 616557644544 (52656364 645757 6257674471 465762 5571 6045414345)\72 \"241005 2125110313 0222172716 061730 1225152023 17260522 241005 14013231 041707\"\54 475166515647 5545 41 54575753" \\\\1\\1]]\56

```
Try it online!<br>~~

##

~~Tcl, 329 bytes, 329 x 16 = 5264
```
\160\165\164\163 [\163\165\142\163\164 [\162\145\147\163\165\142 \55\141\154\154 (\\d\\d) "055451724142456450 5742565770515765635471 6165576445d (52656364 645757 625767d71 465762 5571 6045414345)\72 \"241005 2125110313 0222172716 061730 1225152023 17260522 241005 14013231 041707\"\54 475166515647 5545 41 54575753" \\\\1\\1]]\56

```
Try it online!<br>~~

---

~~Tcl, 333 bytes, 333 x 16 = 5328
```
\160\165\164\163 [\163\165\142\163\164 [\162\145\147\163\165\142 \55\141\154\154 (\\d\\d) "055451724142456450 5742565770515765635471 6165576445d \5052656364 645757 625767d71 465762 5571 6045414345\51\72 \"241005 2125110313 0222172716 061730 1225152023 17260522 241005 14013231 041707\"\54 475166515647 5545 41 54575753" \\\\1\\1]]\56

```~~

##

Try it online!

---

~~Tcl, 148 bytes, 148 x 37 = 5476
```
puts "Elizabeth obnoxiously quoted (just too rowdy for my peace): \"[string tou "the quick brown fox jumps over the lazy dog"],\" giving me a look."

```
Try it online!<br>~~

##

~~Tcl, 277 bytes, 277 x 21 = 5817
```
\160u\164s [subs\164 [\162\145\147sub \55\141\154\154 (\\d\\d) "0554517241b456450 ob56o7051ous5471 61uo6445d(52us64 64oo 62o67d71 46o62 5571 6045414345): 241005 2125110313 0222172716 061730 1225152023 17260522 241005 14013231 041707\" 475166515647 5545 41 54oo53" \\\\1\\1]]\56

```
Try it online!<br>~~

##

~~Tcl, 371 bytes, 371 x 16 = 5936
```
puts "\105\154\151\172\141\142\145t\150 o\142\156o\170\151ous\154\171 \161uot\145\144 \50\152ust too \162o\167\144\171 \146o\162 \155\171 p\145\141\143\145\51\72 \"\124\110\105 \121\125\111\103\113 \102\122\117\127\116 \106\117\130 \112\125\115\120\123 \117\126\105\122 \124\110\105 \114\101\132\131 \104\117\107\54\" \147\151\166\151\156\147 \155\145 \141 \154oo\153\56"

```
Try it online!<br>~~

##

~~Tcl, 401 bytes, 401 x 16 = 6416
```
puts "\105\154\151\172\141\142\145\164\150 o\142\156o\170\151o\165\163\154\171 \161\165o\164\145\144 \50\152\165\163\164 \164oo \162o\167\144\171 \146o\162 \155\171 \160\145\141\143\145\51\72 \"\124\110\105 \121\125\111\103\113 \102\122\117\127\116 \106\117\130 \112\125\115\120\123 \117\126\105\122 \124\110\105 \114\101\132\131 \104\117\107\54\" \147\151\166\151\156\147 \155\145 \141 \154oo\153\56"

```
Try it online!<br>~~

---

~~Tcl, 403 bytes, 403 x 16 = 6448
```
puts "\105\154\151\172\141\142\145\164\150 o\142\156o\170\151o\165\163\154\171 \161\165o\164\145\144 \50\152\165\163\164 \164oo \162o\167\144\171 \146o\162 \155\171 \160\145\141\143\145\51\72 \42\124\110\105 \121\125\111\103\113 \102\122\117\127\116 \106\117\130 \112\125\115\120\123 \117\126\105\122 \124\110\105 \114\101\132\131 \104\117\107\54\42 \147\151\166\151\156\147 \155\145 \141 \154oo\153\56"

```
Try it online!<br>~~---

~~Tcl, 433 bytes, 433 x 15 = 6495
```
puts "\105\154\151\172\141\142\145\164\150 \157\142\156\157\170\151\157\165\163\154\171 \161\165\157\164\145\144 \50\152\165\163\164 \164\157\157 \162\157\167\144\171 \146\157\162 \155\171 \160\145\141\143\145\51\72 \42\124\110\105 \121\125\111\103\113 \102\122\117\127\116 \106\117\130 \112\125\115\120\123 \117\126\105\122 \124\110\105 \114\101\132\131 \104\117\107\54\42 \147\151\166\151\156\147 \155\145 \141 \154\157\157\153\56"

```
Try it online!<br>~~  Tcl, 473 bytes, 473 x 14 = 6622
```
puts \105\154\151\172\141\142\145\164\150\40\157\142\156\157\170\151\157\165\163\154\171\40\161\165\157\164\145\144\40\50\152\165\163\164\40\164\157\157\40\162\157\167\144\171\40\146\157\162\40\155\171\40\160\145\141\143\145\51\72\40\42\124\110\105\40\121\125\111\103\113\40\102\122\117\127\116\40\106\117\130\40\112\125\115\120\123\40\117\126\105\122\40\124\110\105\40\114\101\132\131\40\104\117\107\54\42\40\147\151\166\151\156\147\40\155\145\40\141\40\154\157\157\153\56

```
Try it online!<br>~~  Tcl, 133 bytes, 133 x 60 = 7980
```
puts "Elizabeth obnoxiously quoted (just too rowdy for my peace): \"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG,\" giving me a look."

```
Try it online!<br>~~
> 0 votes

# Answer
# Perl 5, 137 bytes * 35 unique = 4795

```
say'Elizabeth obnoxiously quoted (just too rowdy for my peace): "',uc'the quick brown fox jumps over the lazy dog','," giving me a look.'

```

Try it online!
> 0 votes

---
Tags: code-challenge, string, kolmogorov-complexity
---


title: Find the sequence

text:
# Question
Title: Find the sequence
The purpose of this challenge is to find the general term of a given arithmetic or geometric sequence.

### Explanation

The formula for an arithmetic sequence is as follows

an = a1 \+ (n-1)d

where a1 is the first term of the sequence, n is the index of the term, and d is the common difference between the terms. For a geometric sequence, the formula for the general term is

an = a1rn-1

where r is the common ratio between the terms of the sequence.

### Challenge

The objective of this challenge is to accept an input of a sequence of numbers, determine whether the sequence is arithmetic or geometric, and then output the formula for the general term. The rules are

* The input will be either a geometric sequence or an arithmetic sequence, nothing else
* The formula can either be returned from a function, or printed to STDOUT or an equivalent
* The input can be taken in any form that is convenient; for example, it could be an argument, taken from STDIN, or hardcoded if the language offers no other way of accepting input
* The input will always be in the format `[3, 4, 5, 6]`, with brackets surrounding comma-separated terms. The spaces separating the terms and the commas are optional. The input will always contain three or more terms.
* The shortest code in bytes wins

### Test cases

```
Input                      Output
[-2, 0, 2, 4, 6, 8]        -2 + 2(n-1) or an equivalent expression
[27, 9, 3, 1, 1/3]              27(1/3)^n-1 or an equivalent expression
[200, 240, 280, 320]       200 + 40(n-1) or an equivalent expression
[2, 6, 18]             2(3)^n-1 or an equivalent expression

```

### Bonus

*-20%* If your answer outputs a simplified version of the formula; for example, it prints

```
6n-2

```

rather than

```
4 + 6(n-1)

```

*-30 bytes* If your answer prints the 20th term of the sequence, in addition to the general term.

If your answer satisfies both of these conditions, the 20% is removed first, and then the 30 bytes are removed.

# Answer
> 1 votes
# 2, 38 chars / 57 bytes

```
î+(x=ì-í≔í-î?`+⟮(n-1)`⟯+(í-î):`(⦃í/î})^Ⅰ

```

`Try it here (Firefox only).`

First answer! I'm still working on bonuses.

# Explanation

```
î+(ì-í≔í-î?`+⟮(n-1)`⟯+(í-î):`(⦃í/î})^Ⅰ // implicit: î=input1, í=input2, ì=input3
î+                                    // Prepend a1
  (ì-í≔í-î                            // Is rate of change constant from term to term?
          ?`+⟮(n-1)`⟯+(í-î)            // arithmetic mean template
                          :`(⦃í/î})^Ⅰ // geometric mean template
                                      // implicit output

```

NOTE:  and  are copy-paste blocks; anything within those blocks is stored to be called for later pasting (using ).

# Answer
> 1 votes
# Mathematica, 75 * 0.8 - 30 = 30 bytes

```
f=Simplify[FindSequenceFunction@{If[2#2==#+#3,2#-#2,#^2/#2],##}/@{n+1,21}]&

```

Test cases:

```
f[-2, 0, 2, 4, 6, 8]
(* {2 (-2 + n), 36} *)

f[27, 9, 3, 1, 1/3]
(* {3^(4 - n), 1/43046721} *)

f[1, 1, 1]
(* {1, 1} *)

```

In Mathematica, `FindSequenceFunction` is a very interesting function.

```
FindSequenceFunction[{1, 1, 2, 3, 5, 8, 13}, n]
(* Fibonacci[n] *)

FindSequenceFunction[{1+a, 1+a^2, 1+a^3, 1+a^4}, n]  (* symbolic! *)
(* 1 + a^n *)

```

# Answer
> 0 votes
## Python, 130\* 0.8 - 30 = 74 bytes

Been a while since I last answer a question and this one has been sitting in my favourites for some time!

Started at **188**

`def m(t):s=str;a=t[0];b=t[1];r=b/a;q=b-a;return((s(q)+'n'+'+'*(0<a-q)+s(a-q),a+q*19),(s(b/r)+'('+s(r)+')^n-1',b*r**18))[t[2]/b==r])`

Uses school maths to determine the coeffs and sticks them together and returns the 20th term.

Sample output: `3n-1 59`, where 59 is the 20th term.

---
Tags: code-golf, math, sequence
---


title: Arithmetic Progressions

text:
# Question
Title: Arithmetic Progressions
Your task is to analyse the input and output the formula for the n-th term if it is an arithmetic sequence, otherwise it should print "NAAP".

---

## Input

Input (from STDIN) will consist of few numbers, between 4 to 10 numbers where each number will be in the range between -1000 and 1000 inclusive, separated by a delimiter (a space or a comma or a semi-colon \[whichever is to your preference\]). Here are some example inputs.

```
12,14,16,18       //valid
-3 4 5 1 -2 -4    //valid
45;35;-35         //invalid (only three numbers are present instead of the minimum of 4 numbers)
2,32;21,321       //invalid (it uses two different delimiters: `,` and `;`)

```

## Output

The program should first check whether the input is an arithmetic progression or not.

Arithmetic Progressions (AP) in a nutshell: Every AP will have a common difference. This is the difference between the $n$ and ${n-1}$ th terms (basically $a(n+1) - a(n)$ where `a` is the function for the sequnce). This difference stays the same for any value of $n$ in an AP. If there is no common difference, then it is **not** an arithmetic sequence. To calculate the value of the n-th term, use this formula $a(n) = a(1) + (n-1)d$ where $a(1)$ is the first term and $d$ is the common difference.

If it **is not** an arithmetic progression, then the program should print the error message "NAAP" (short for "Not An Arithmetic Progression").

If it **is** an arithmetic progression, then the program should print the simplified n-th term of the sequence to STDOUT.

Example:

```
> 1,3,5,7,9
2n-1

```

Explanation: This is an AP because there is a common difference ($3 - 1 = 2$). Then you use the formula $a(n) = a(1) + (n-1)d$

$$a\_n = a\_1 + (n-1)d$$

$$a\_n = 1 + (n-1)2$$

$$a\_n = 1 + 2n - 2$$

$$a\_n = 2n - 1$$

Therefore output is `2n-1` (notice the absence of spaces)

---

Standard loopholes are disallowed by default.

You are allowed to create a function if you want (with the array of numbers as your parameter). If not, then you must create a **full** program that takes input as a string or an array and outputs accordingly.

## Test cases:

1.

```
1,3,5,7,9
2n-1

```

2.

```
1 3 12312 7 9
NAAP

```

3.

```
-6;8;22;36;50
14n-20

```

4.

```
5,1,-3,-7,-11,-15
-4n+9

```

5.

```
-5,-7,-9,-11,-13,-15
-2n-3

```

6.

```
3,3,3,3,3,3,3,3,3
0n+3

```

7.

```
-4,-5,-6,-7
-1n-3

```

---

This is so the shortest code in bytes wins! (sorry for bad math-jax)

Any suggestions are welcome!

# Answer
# Pyth, 30 bytes

```
?tJ{-VtQQ"NAAP"+hJ%"n%+d"-hQhJ

```

Test suite

To check whether it's a arithmetic procession, this uses a vectorized subtraction between each element and the previous, `-VtQQ`. A ternary checks if there are multiple values in the result (`?tJ{`) and prints `NAAP` if so. Then, to get the `+` or `-` right, the mod-formating `%+d` is used.
> 5 votes

# Answer
## Haskell, 103 bytes

```
z=(tail>>=).zipWith
f l@(a:b:_:_:_)|and$z(==)$z(-)l=show(b-a)++'n':['+'|b-a<=a]++show(a+a-b)
f _="NAAP"

```

Usage example:

```
f [-6,8,22,36,50]   ->   "14n-20"
f [60,70,80,90]     ->   "10n+50"
f [2,3,4,6,7,8]     ->   "NAAP"

```

As always in Haskell, fancy output formatting (e.g. mixing numbers with strings) eats a lot of bytes (around 40). The program logic is quite compact:

```
f l@(a:b:_:_:_)           -- pattern match an input list with at least 4 elements,
                          -- call the whole list l, the first two elements a and b
z=(tail>>=).zipWith       -- the helper function z takes a function f and a list l
                          -- and applies f element wise to the tail of l and l

           z(-)l          -- make a list of neighbor differences
     z(==)                -- then compare these differences for equality
 and                      -- and see if only True values occur

       show ...           -- if so format output string

f _="NAAP"                -- in all other cases ( < 4 elements or False values)
                          -- return "NAAP"

```
> 3 votes

# Answer
# Japt, ~~60~~ ~~52~~ 51 bytes

```
V=N¤£X-NgY+1};W=Vg;Ve_¥W} ?W+'n+'+sU<W +(U-W :"NAAP

```

Try it online!

Input can be given with whichever separator you like, as that's how the interpreter is designed ;)

### Ungolfed and explanation

```
V=N¤  £    X-NgY+1};W=Vg;Ve_  ¥ W} ?W+'n+'+sU<W +(U-W :"NAAP
V=Ns2 mXYZ{X-NgY+1};W=Vg;VeZ{Z==W} ?W+'n+'+sU<W +(U-W :"NAAP

            // Implicit: N = list of inputs, U = first input
V=Ns2       // Set variable V to N, with the first 2 items sliced off,
mXYZ{       // with each item X and index Y mapped to:
X-NgY+1}    //  X minus the item at index Y+1 in N.
            // This results in a list of the differences (but the first item is NaN).
W=Vg;       // Set W to the first item in V (the multiplication part).
VeZ{Z==W}   // Check if every item in V is equal to W.
?W+'n+      // If true, return W + "n" +
'+sU<W      //  "+".slice(U<W) (this is "+" if U >= W, and "" otherwise)
+(U-W       //  + (U minus W [the addition part]).
:"NAAP      // Otherwise, return "NAAP".
            // Implicit: output last expression

```
> 2 votes

# Answer
## TI-BASIC, 70 bytes

```
Input X
ΔList(∟X->Y
If variance(Ans
Then
∟X(1)-min(Ans
Text(0,0,min(∟Y),"n",sub("+-",(Ans<0)+1,1),abs(Ans
Else
"NAAP

```

To remedy TI-BASIC's lack of number-to-string conversion, this uses output on the graphscreen (`Text(`) if the progression is arithmetic, which automatically concatenates the arguments together.

This assumes that negative numbers are entered using TI-BASIC's high-minus character (which looks a little like ), not the binary minus sign. However, output uses the binary minus sign.
> 2 votes

# Answer
# Matlab, 103 bytes

```
x=str2num(input('','s'));y=diff(x);if range(y) disp('NAAP'),else fprintf('%gn%+g\n',y(1),x(1)-y(1)),end

```
> 1 votes

# Answer
# CJam, 38 bytes

```
{:T2ew::-):U-"NAAP"UW*"n%+d"T0=U+e%+?}

```

This is an anonymous function that takes an array on the stack as input, and leaves a string on the stack as output. Try it online with additional I/O code for testing.

Explanation:

```
:T      Save a copy of input in variable T for output generation.
2ew     Generate list of pairs of sequential elements.
::-     Reduce all pairs with subtraction operator.
)       Pop last value from list of differences.
:U      Save difference value in variable U for output generation.
-       Set difference. This will leave an empty list (falsy) if all values are the same.
"NAAP"  First value for ternary operator, for case where not all values are the same.
UW*     Start generating output for success case. Need to flip sign of difference saved
        in variable U, since it was 1st value minus 2nd, and we need the opposite.
"n%+d"  Push format string for printf operator. The + sign in the format specifies that
        the sign is always generated, saving us from needing different cases for the
        value being negative or positive.
T0=     Extract first value from original input saved in variable T.
U+      Add the difference (with the "wrong" sign) to it.
e%      "printf" operator.
+       Concatenate two parts of result.
?       Ternary operator for picking one of the two output cases.

```
> 1 votes

# Answer
# JavaScript (ES6), 91 bytes

```
x=>(s=x.split`,`,m=s[1]-s[0],a=s[0]-m,s.some((n,i)=>n!=m*i+m+a)?"NAAP":m+"n"+(a<0?a:"+"+a))

```

## Explanation

```
x=>(
  s=x.split`,`,       // s = array of input numbers
  m=s[1]-s[0],        // m = the multiplication part of the formula
  a=s[0]-m,           // a = the addition part of the formula
  s.some((n,i)=>      // check if the rest of the numbers follow this sequence
    n!=m*i+m+a
  )?"NAAP":
  m+"n"+(a<0?a:"+"+a) // output the formula
)

```

## Test

```
<input type="text" id="input" value="5,1,-3,-7,-11,-15" /><button onclick='result.innerHTML=(

x=>(s=x.split`,`,m=s[1]-s[0],a=s[0]-m,s.some((n,i)=>n!=m*i+m+a)?"NAAP":m+"n"+(a<0?a:"+"+a))

)(input.value)'>Go</button><pre id="result"></pre>
```
> 1 votes

# Answer
## Perl 6, ~~123~~ ~~102~~ 101 bytes

EDIT: Don't negate difference

EDIT: use anonymous sub, logical operators and string interpolation. Thanks Brad Gilbert b2gills

```
sub{my@b=@_.rotor(2=>-1).map({[-] $_}).squish;$_=@_[0]+@b[0];@b.end&&"NAAP"||"@b[0]n{'+'x($_>=0)}$_"}

```

Test program (reads from stdin):

```
my $f = <the code above>
$f(split(/<[;,]>/, slurp)).say

```

Explanation:

```
my @b =
  @_.rotor(2=>-1)  # sliding window of 2: (1,2,3,4) => ((1,2),(2,3),(3,4))
  .map({[-] $_})  # calculate difference (subtract all elements and negate)
  .squish;         # remove adjacent elements that are equal

@b.end        # @b.end is last index, @b.end = 0 means @b has only 1 element
&& "NAAP"     # true branch
|| "@b[0]n{'+'x($_>=0)}$_" # string for an+b,
        # {'+'x($_>=0)} inserts a plus sign using the repetition operator x

```
> 1 votes

# Answer
# Ruby, ~~95~~ ~~78~~ 76 bytes

```
->s{i,j=s;puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"}

```

**78 bytes**

```
->s{puts s.reduce(:+)==s.size*(s[-1]+i=s[0])/2?"%dn%+d"%[v=s[1]-i,i-v]:"NAAP"}

```

**95 bytes**

```
->s{puts s.reduce(:+)==s.size*(s[0]+s[-1])/2?"#{v=s[1]-s[0]}n#{"+"if (i=s[0]-v)>0}#{i}":"NAAP"}

```

**Ungolfed:**

```
-> s {
  i,j=s
  puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"
}

```

**Usage:**

```
->s{i,j=s;puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"}[[-6,8,22,36,50]]

=> 14n-20

```
> 1 votes

# Answer
**Python 3, 92 bytes**
Based on my answer from Find the Sequence

`def m(t):s=str;a=t[0];b=t[1];q=b-a;return((s(q)+'n'+'+'*(0<a-q)+s(a-q)),'NAAP')[t[2]/b==b/a]`
> 0 votes

---
Tags: code-golf, math, arithmetic, sequence
---


title: string length comparer

text:
# Question
Title: string length comparer
this program has to take two strings and compare their length, then tell you which one is longer (`string-a` or `string-b`) and by how much

## rules:

* no using `.length` or other built-in length checking methods (duh!)
* no using addition or subtraction, this includes improvised addition/subtraction, in case you find some sort of weird improvisation.
* no `>` / `<` (greater then/less then) inside `if` / `if-else` statements (you can use them in loops though), this obviously includes `>=` etc. and no cheating (`bool = a > b;if(bool)`)
* emphasis is on short rather then efficient code
* oh yeah almost forgot... good luck!

# Answer
## SED, 45 (43 + 2 for the -n flag)

```
s/./a/g
h
n
s/./b/g
G
:a
s/b\(.*\)a/\1/
ta

```

Expects input as two separate lines, outputs the difference in unary, using "a" or "b" to indicate the longer string. run with `sed -n`.
> 12 votes

# Answer
## Tcl 8.6, 90

```
lmap c [split $a {}] d [split $b {}] {puts [expr {{}eq$d?{A}:{}eq$c?{B}:[continue]}];exit}

```

If you run Tcl 8.5, use `foreach` instead `lmap`.

This shows a nice feature of Tcl's foreach/lmap: It can walk over several lists at once.
> 5 votes

# Answer
# Perl, ~~87~~ 78 - tells which is longer and by how much

alternative:

* 72 - tells which is longer and by how much, no special message if equal

---

Perl script expecting 2 strings as command line arguments. Tells which one is longer and by how much. This one I tried to make it readable and not short.

```
#!/usr/bin/perl
use warnings;
use strict;

my ($x,$y)=@ARGV;
$x=$x=~s/.//g;
$y=$y=~s/.//g;
my @z=($x..$y);
my @w=($y..$x);
if (@z) {
    if ($#z) { print "2nd longer than 1st by $#z" }
    else { print "Equal length" }
}
else {
    print "1st longer than 2nd by $#w"
}

```

Same code as a one liner, counting 78 characters (output now prints "a3" if a \> b by 3 characters, "0" if equal):

```
perl -E'($x,$y)=@ARGV;$_=s/.//g for$x,$y;@z=$x..$y;@w=$y..$x;say@z?$#z?"b$#z":0:"a$#w"'

```

Finally, since OP clarified that when they are equal it is not really important what it will print, we can save 6 more characters:

```
perl -E'($x,$y)=@ARGV;$_=s/.//g for$x,$y;@z=$x..$y;@w=$y..$x;say@z?"b$#z":"a$#w"'

```
> 5 votes

# Answer
# J 17

Since there is no output specification: the length difference is outputted at the location of the shortest string

```
    longest =: *&.^/"1@(=&' ')@,:
    'foobar' longest 'abc'
0 3 NB. Means abc is shorter by 3 chars.

```
> 4 votes

# Answer
# Javascript ~~96~~ 92

```
x=prompt;i=c=0;for(p=x();c=p[i=-~i];);q=x();for(j=0;c=q[i=~-i,j=-~j];);alert(0<i&&p+i||q+-i)

```

*Note `0<i&&` contains no if statement but a logical operator, which is not forbidden.*

Input asd,asdfg Output asdfg2

Means asdfg is 2 characters longer.
> 4 votes

# Answer
# Ruby, ~~66~~ 52 (shows only which one is longer)

```
f=->{gets.gsub(/./,?1)}
a=f[]
b=f[]
puts'sab'[a<=>b]

```

Prints `s` for same, `a` for string a, and `b` for string b.

# Ruby, ~~184~~ ~~173~~ ~~146~~ ~~143~~ ~~139~~ 140 (also shows how much longer it is)

```
f=->{gets.gsub(/./,?1)}
a=f[]
b=f[]
d=->e{Math.log10(e.to_i).floor.next.to_s}
puts(a==b ? ?s:(c=a.sub(b,''))!=a ? ?a+d[c]:?b+d[b.sub(a,'')])

```

Sample run:

```
c:\a\ruby>stringcmp
testing123
testing
a3

c:\a\ruby>stringcmp
codegolf.SE
code golf . stack exchange
b15

c:\a\ruby>stringcmp
test
test
s

c:\a\ruby>

```
> 3 votes

# Answer
Bringing up the rear as always with the verbose language. :)

# Java - 278

```
import java.util.*;class b{public static void main(String[]a){Stack z=new Stack(),y=new Stack();for(String q:a[0].split(""))z.push(q);for(String q:a[1].split(""))y.push(q);while(!z.empty()&&!y.empty()){z.pop();y.pop();}System.out.print(y.empty()?"1-"+z.size():"2-"+y.size());}}

```

**With line breaks and tabs**

```
import java.util.*;
class a{
    public static void main(String[]a){
        Stack z=new Stack(),y=new Stack();
        for(String q:a[0].split(""))z.push(q);
        for(String q:a[1].split(""))y.push(q);
        while(!z.empty()&&!y.empty()){
            z.pop();
            y.pop();
        }
        System.out.print(y.empty()?"1-"+z.size():"2-"+y.size());
    }
}

```
> 3 votes

# Answer
# Mathematica 40

```
f = #~Count~0 & /@ PadLeft[Characters /@ {##}] &

```

Output is similar to the J version.

**Example Usage:**

```
f["looooong", "short"]

```

> {0, 3}

```
f["short", "thisstringisveryverylong"]

```

> {19, 0}

```
f["equal", "equal"]

```

> {0, 0}
> 3 votes

# Answer
## PHP (44)

```
-r'list(,$a,$b)=$argv;echo strcmp($a^$a,$b^$b);'

```
* The `-r` argument and single quotes are not counted in the score.
* *string-a* and *string-b* are accepted as command-line arguments.
* The magnitude of the decimal number printed is the difference in length.
* The sign indicates which string is longer. A positive number means *string-a* is longer. A negative number means *string-b* is longer. Zero means the strings are the same length.

## PHP 5.4 (96)

Here, `strcmp` is avoided in favor of other string functions that are not so cheap.

```
-r'list(,$a,$b)=$argv;echo@strtr(explode(${"\3"^$c=trim(($a^=$a).b^($b^=$b).a)},$$c,2)[1],"\0",$c);'

```
* Scoring and input format remain the same.
* The difference in length is printed in unary.
* The symbol `a` is used if *string-a* is longer; `b` is used if *string-b* is longer.
* Nothing is printed if the strings are the same length (except in the commented version, which omits the error suppression operator `@` and thus may report PHP notices and warnings).

Commented code:

```
<?php

list(, $a, $b) = $argv;

// Replace all bytes in both $a and $b with null bytes
// (Anything XORed with itself is zero.)
$a ^= $a;
$b ^= $b;

// PHP's bitwise XOR truncates its output to the shorter string's length,
// so only the marker ('a' or 'b') appended to the shorter string will
// remain after the null bytes in common are trimmed off. If $a is shorter,
// 'b' remains; likewise, if $b is shorter, 'a' remains.
$longer = trim($a . 'b' ^ $b . 'a'); // $c in the golfed code

// Flip bits 0 and 1 to switch 'a' to 'b' (or 'b' to 'a')
// ('a' === chr(0b1100001); 'b' === chr(0b1100010); "\3" === chr(0b11))
$shorter = "\3" ^ $longer;

// Remove the shorter string from the longer string
// $$shorter refers to $a if $shorter === 'a' or $b if $shorter === 'b'.
// $$longer works the same way.
$difference = explode($$shorter, $$longer, 2)[1];

echo strtr($difference, "\0", $longer);

```
> 3 votes

# Answer
## JavaScript (prompt for input) - 128

I golfed it 2 more characters.

```
p=prompt,f=alert,i='lastIndexOf'
a=p().replace(/./g,'.')
b=p().replace(/./g,'.')
j=a[i](b),k=b[i](a)
~j&&f('a '+j)
~k&&f('b '+k)

```
> 2 votes

# Answer
# Python - 291 261 244 223 220 210 206

I got 206

```
import sys,itertools
q=sys.argv
h=[]
i=0
for k,g in itertools.groupby(map(lambda f,b:2 if f is None else 1 if b is None else 0,q[1],q[2])):h.append(list(g))
for i,a in enumerate(h[1],1):0
print q[h[1][0]],i

```

## Sample Run

```
C:\pjs\codegolf>python last.py bananas apples
bananas 1
C:\pjs\codegolf>python last.py bananas hazlenuts
hazlenuts 2

```
> 2 votes

# Answer
Bending the rules some...

## JavaScript (92)

```
p=prompt
~function f(a,b) {
   a && !b && alert(0)
  !a &&  b && alert(1)

  f(a.slice(1), b.slice(1))
}(p(),p())

```

(Minified: `p=prompt;~function f(a,b){a&&!b&&alert(0);!a&&b&&alert(1);f(a.slice(1),b.slice(1))}(p(),p())`)

Takes two strings via `prompt`s. Alerts the difference in unary (as with Hasturkun's solution), using `0`s if the first string is longer and `1`s if the second string is longer. Outputs each digit in a separate alert (ow), and terminates eventually when the call stack runs out (owww).

If we ignore the rule about no addition or subtraction, we could easily have the number be a nice (base 10) number whose sign denotes which string is longer:

```
p=prompt
alert(function f(a,b,n) {
  return a || b? f(a.slice(1), b.slice(1), n - !a + !b)
       :         n
}(p(),p(),0))

```

This version doesn't even wait for the call-stack to overflow!
> 2 votes

# Answer
**Perl, 69 characters**

```
sub l{l(map{substr$_,1}@_)if$_[0]&&$_[1];say pop()?2:1;die}l(<>,<>)

```

The gist is, recurse until one string is empty, then print the other. Run with `perl -e CODE 2> /dev/null`
> 2 votes

# Answer
# Python 3: 125 91 90

Finally beat the JavaScript solutions :)

Prints both which is longer, and by how much.

**Current (90 and Python 3):**

```
I=input
q=a,b=I(),I()
while a+b:s=q[b!=""];a=a[1:];b=b[1:];i=a and b and-1or-~i
print(s,i)

```

Example output:

```
rees@Rees-Ubuntu:~/Python/CodeGolf$ python3 StringComparer.py
hi <- input one
hello <- input two
hello 3 <- output

```

**Old (125 and Python 2):**

```
r=raw_input
q=a,b=r(),r()
while a and b:a=a[1:];b=b[1:]
s=(q[0],q[1])[a==""]
i=0
while a or b:a=a[1:];b=b[1:];i=-~i
print s,i

```
> 2 votes

# Answer
## Python, ~~708~~, ~~570~~, ~~566~~, ~~462~~, ~~492~~, ~~481~~, ~~480~~, ~~475~~, ~~363~~, ~~357~~, ~~354~~, ~~346~~, ~~343~~, ~~341~~, ~~340~~, ~~327~~, 315 (with whitespace)

My first CG, be gentle:

```
import sys
c=[1,2]
a=o=[]
l=d=e=v=0
s=sys.argv
r=range(0,99)
a=[zip(list(s[x]),r[1:]) for x in c]
a.insert(0,0)
for x in c:
    for p in a[x]:
        try:
            v=a[x==2 and 1 or 2][p[1]]
        except:
            l=s[x]
            o.append(1)
            e=1
    if e:break
o=zip(o,r)
print[l,o.pop()[1]]

```

**Sample run:**

```
me@home:~$ python diff.py bananas apples
['bananas', 1]
me@home:~$ python diff.py bananas hazlenuts
['hazlenuts', 2]

```
> 1 votes

# Answer
**C, 230 200 193 characters**

**EDIT: Shortened it from 230 to 193 characters.**

My first golf attempt. Maybe not a hole-in-one, but it works. Not being allowed to use strlen for this forces it to be fairly verbose in C. Maybe it can be shortened a bit?

```
a,b,w,i,l;
int main(int c,char **v){
    for(;a<256||b<256;i++){
        if(!v[1][i])a|=256;
        if(!v[2][i])b|=256;
        if(!(a&256))a++;
        if(!(b&256))b++;
    }
    a&=255;b&=255;
    w=a>b?0:1;
    l=w?b-a:a-b;
    printf("%s %i\n",v[w+1],l);
}

```

Or the uglier version:

```
a,b,w,i,l;int main(int c,char **v){for(;a<256||b<256;i++){if(!v[1][i])a|=256;if(!v[2][i])b|=256;if(!(a&256))a++;if(!(b&256))b++;}a&=255;b&=255;w=a>b?0:1;l=w?b-a:a-b;printf("%s %i\n",v[w+1],l);}

```

Example output:

```
N:\>golf.exe everything works
everything 5

```
> 1 votes

# Answer
**Powershell 140** *(assumes a max difference of 999)*

```
$c=@(compare($args[0]-split'.')($args[1]-split'.'))
$n=[collections.stack]@(999..1)
$c|%{$n.pop()}
if($c){$args[$c[0].sideindicator-eq'=>']}

```

Outputs nothing if the string lengths are equal. If the string lengths are not equal, the longer string is displayed; the last number is the difference.
> 1 votes

# Answer
# C (gcc), 89 bytes

```
i;c;q;j;f(a,b)char*a,*b;{for(i=j=c=0;a[i]||b[j];a[i]&&++i,b[j]&&++j)a[i]&&b[j]?:++c;a=c;}

```

Try it online! I think this has room for improvement, but I'm not sure where. Abuses undefined behaviour, but it it Works On TIO™. Simply starts increment `c` when one of `a[i]` or `b[j]` is the null byte (the end of the string); `i` and `j` are incremented until they hit this null byte.
> 1 votes

# Answer
**Clojure - 206**

```
(defn is-longer [first second first-left second-left]
  (defn remaining [current count]
    (if (empty? current)
      (/ (Math/log count) (Math/log 2))
      (remaining (rest current) (bit-shift-left count 1))))
  (cond
   (empty? first-left) [2 (remaining second-left 1)]
   (empty? second-left) [1 (remaining first-left 1)]
   :else (is-longer first second (rest first-left) (rest second-left))))

```

Or minified:

```
(defn y [a b al bl] (defn x [u t] (if (empty? u) (/ (Math/log t) (Math/log 2)) (x (rest u) (bit-shift-left t 1)))) (cond (empty? al) [2 (x bl 1)] (empty? bl) [1 (x al 1)] :else (y a b (rest al) (rest bl))))

```

Or in prettierific:

Returns: \[1|2 count\]

Getting around not using + was a fun challenge.
> 0 votes

# Answer
**Python, 194**

```
import sys,itertools as T
A=sys.argv
B=[]
N,i=None,0
for k,g in T.groupby(map(lambda f,b:[[0,1][b is N],2][f is N],A[1],A[2])):B.append(list(g))
for i,j in enumerate(B[1],1):0
print A[B[1][0]],i

```
> 0 votes

# Answer
## R - 120/114

Shows difference:

```
a=strsplit(scan(what='c'),"")
c=0
for(i in 1:2){for(y in a[[i]]){if(i-1)c=c+1 else c=c-1}}
d=abs(c)
cat(a[[(c==d)+1]],d)

```

Shows just the longer:

```
a=strsplit(scan(what='c'),"")
c=0
for(i in 1:2){for(y in a[[i]]){if(i-1)c=c+1 else c=c-1}}
cat(a[[(c==abs(c))+1]])

```
> 0 votes

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


# Question
Title: Return the highest possible placement value based on the input
## Introduction

The challenge itself was something I came across and had to try and figure out for a personal of project of mine. I ended up branching out and asking family members if they could provide an equation to meet the requirements.

**Note:** I have (with the help of others) found a solution for this but now I'm just trying to see how others would approach this.

## Challenge

Take the following scenario where the left hand side number is N (the input):

```
N    Output
0 -> 9
1 -> 99
2 -> 999
3 -> 9999
4 -> 99,999
5 -> 999,999
...
15 -> 9,999,999,999,999,999

```

So, essentially, for an input number **N**, your program must provide the highest integer with **N + 1** decimal places.

**Note:** Commas are not required to separate the numbers, I placed them above purely for readability.

## Criteria of Success

The criteria of success is based on the following:

* Shortest in terms of code size

# Answer
# Neim, 3 bytes

```
>9

```

Explanation:

```
>      Increment input
 9    Repeat 9

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 3 bytes

### Code:

```
>°<

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
>      # Increment the implicit input
 °     # Compute 10 ** (input + 1)
  <    # Decrement the result

```
> 5 votes

# Answer
# Proton, 11 bytes

```
(1+)+("9"*)

```

Try it online!

This is a function.

# Explanation

```
(1+)+("9"*)  Function
 1+          Anonymous function; add the input to 1
      "9"*   Anonymous function; multiply "9" by the input
    +        Function Composition; add the input to 1 then multiply "9" by this number
(  ) (    )  Brackets for order of operations

```

:o proton beats python with its function composition for once :D
> 4 votes

# Answer
# APL+WIN, ~~9~~ 5 bytes

Thanks to ngn for -3 bytes and Adám for -1 byte

Prompts for integer input:

```
1⎕/⍕9

```
> 4 votes

# Answer
# , 7 bytes

Anonymous tacit prefix function

```
9^&.>:]

```

Try it online!

`9^``]` nine raised to the power of the argument

`&.`… while both nine and the argument are under the influence of

`>:` increment

I.e. increment nine and the argument, then power, then un-increment, i.e. decrement. Effectively `((9+1)^(n+1))-1`.
> 4 votes

# Answer
# 99, 90 bytes

```
 999
9999 9 9
99999 99 9 9999 9
999 999 9999 9

99999
999 999 9
 999999 999
 9 9999

```

Try it online!

Possibly not optimal, but it was fun to write.

EDIT: looks like I was right, as Jo King outgolfed me by not incrementing the input and being smarter about the gotos.

```
 999			assign input to tri-nine
9999 9 9		assign 0 to quad-nine
99999 99 9 9999 9	assign 81 to quint-nine for printing
999 999 9999 9		increment tri-nine

99999			print 81/nine (the numeral nine)
999 999 9		decrement tri-nine
 999999 999		if tri-nine is zero exit program (goto outside program)
 9 9999			else goto line nine

```
> 4 votes

# Answer
# *99*, 69 bytes

```
9999 9 9
99999 99 9 9999 9
 999

99999
 99 999
999 999 9
 9 9999

```

Try it online!

Appropriate (but it's a pity that this didn't end up at 99 bytes)

### Explanation

```
9999 9 9           9999 = 9-9
99999 99 9 9999 9  99999 = 99-9+(9-9)-9 = 9*9
 999               999 = input*9

Filler to get up to line 9

99999      Print (9*9)/9 as a number
 99 999    Jump to line 99 if 999 is 9-9
999 999 9  999 = 999 - 9
 9 9999    Jump unconditionally to line 9

```
> 4 votes

# Answer
# Actually, 3 bytes

```
u╤D

```

Explanation:

```
u    Increment input
 ╤   10 ** x
  D  Decrement

```

Try it online!
> 3 votes

# Answer
# Haskell, ~~14~~ 13 bytes

```
f n=10*10^n-1

```

Or for string output 15 bytes, `f n='9'<$[0..n]`

Thanks to @EsolangingFruit for a byte.

Try it online!
> 3 votes

# Answer
# MATL, 6 bytes

```
Q10w^q

```

Try it online!

### Explanation:

```
Q       % Grab input and increment by 1
 10     % Push 10
   w    % Swap stack
    ^   % Raise 10 to the power of input+1
     q  % Decrement by 1

```
> 3 votes

# Answer
# Pyth, 4

```
*\9h

```

Online test.

### Explanation

```
    Q  # Implicit input
   h   # Increment
*\9    # Repeat string "9" n+1 times

```
> 3 votes

# Answer
# dc, 8

```
A?1+^1-p

```

Try it online!

### Explanation

```
A         # Push 10
 ?        # Push input
  1+      # Increment input
    ^     # Raise 10 to the (input + 1)th power
     1-   # Decrement
       p  # Print

```
> 3 votes

# Answer
# Zsh, 19 bytes

Zsh does a better job than Bash (needs eval):

```
printf 9%.s {0..$1}

```

Try it online!

### Alternative, 20 bytes

This works for both Zsh and Bash (due to Digital Trauma):

```
echo $[10**($1+1)-1]

```

Try it online!
> 3 votes

# Answer
# Python 3, 16 bytes

```
lambda a:"9"*-~a

```

Try it online!

Just a simple anonymous function.
> 2 votes

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

```
x=>"9".repeat(x+1)

```

Try it online!
> 2 votes

# Answer
# Jelly, 4 bytes

```
‘⁵*’

```

Try it online!

```
‘⁵*’ - Main link. Argument: n (integer)
‘    - n+1
 ⁵*  - 10 ** (n+1)
   ’ - (10 ** (n+1)) - 1

```
> 2 votes

# Answer
# Husk, 4 bytes

```
R'9→

```

Try it online!

```
R'9→  -- example input: 3
   →  -- increment: 4
R'9   -- replicate the character '9': ['9','9','9','9']
      -- implicitly print "9999"

```
> 2 votes

# Answer
# Japt, ~~5~~ 4 bytes

```
°Uî9

```

Try it online!

Shaved off that one byte thanks to Shaggy's clever eyes. You can see the edit history for a number of 5-byte solutions.
> 2 votes

# Answer
# Canvas, 3 bytes

```
╵9×

```

Try it here!

```
╵    increment the input
 9   push "9"
  ×  repeat the "9" input+1 times

```
> 2 votes

# Answer
# Brain-Flak, 48 bytes

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

```

Try it online!

This uses the `-A` to enable ASCII output. Bonus round: A version without `-A`.

# Brain-Flak, 50 bytes

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

```

Try it online!
> 2 votes

# Answer
# Momema, 21 bytes

```
a00+1*0-8 9a=+*0-+1_A

```

Try it online! Requires the `-i` interpreter flag.

## Explanation

A brief rundown of Momema's features:

* Its only data type is the unbounded integer. It has a double-ended tape (indexed by unbounded integers) where every number is initialized to zero.
* Strings of digits are integer literals which evaluate to themselves. Leading zeroes are parsed as their own integers.
* `+ab` evaluates to the sum of `a` and `b`.
* `-a` evaluates to the negation of `a`.
* `*a` evaluates to the value of cell `a` on the tape.
* `=a` evaluates to 0 if `a` evaluates to 0, and `=` otherwise.
* At the top level, `ab` stores `b` at cell `a` on the tape. Attempting to write a number to `-8` writes its decimal representation to STDOUT instead.
* At the top level, `[w]a` (where `[w]` is any string of lowercase letters) acts like "relative jump forward by `a` jump instructions that share the label `[w]`."
* The Momema reference implementation accepts a flag `-i`, which activates interactive mode. In interactive mode, `_[W]` (where `[W]` is any string of uppercase letters) is called a *hole* and evaluates to a number read from STDIN. However, it caches the number with its label, so if a hole with the same label is ever evaluated again it will be reused.

Knowing this, here's how you expand this program:

```
a   0                                                                                # do {
0   (+ 1 (* 0))                                                                             #   n = n + 1
-8  9                                                                                #   print 9
a   (= (+ (* 0) (- (+ 1 _A))))                                                              # while (n != input)

```

(This still parses, by the way; the Momema parser treats parentheses the same way as whitespace.)

---

```
a   0

```

Jumps forward by 0 `a` instructions (i.e. does nothing). This is only here to serve as a jump target later.

```
0   (+ 1 (* 0))

```

Increments the value of cell 0 (initially 0) and stores it back in cell 0.

```
-8  9

```

`-8` is memory-mapped for numeric I/O, so this outputs `9` to STDOUT.

```
a   (= (+ (* 0) (- (+ 1 _A))))

```

Compute `tape[0] - (input + 1)`. If it is zero (i.e. both sides were equal), then `=` maps the result to 0, making it a no-op. Control runs off of the end of the program. However, if it is nonzero, this is a `1`. Since there are no `a` instructions after here, it wraps around to the beginning of the program.
> 2 votes

# Answer
# brainfuck, ~~24~~ 23 bytes

thanks to Jo King for -1 byte

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

```

Try it online! Takes input as ASCII
> 2 votes

# Answer
# Whitespace, 79 bytes

```
[S S S T    S T S N
_Push_10][S N
S _Duplicate_10][S N
S _Duplicate_10][S N
S _Duplicate_10][T  N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][N
S S N
_Create_Label_LOOP][S S S T N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][N
T   T   S N
_If_negative_Jump_to_Label_EXIT][S N
T   _Swap][S T  S S T   S N
_Copy_2st][T    S S N
_Multiply][S N
T   _Swap][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_EXIT][T   S S S _Add][T   N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer i = STDIN as integer
Integer j = 10
Start LOOP:
  i = i - 1
  If i is negative (-1): Go to function PRINT_AND_EXIT
  j = j * 10
  Go to next iteration of LOOP

function PRINT_AND_EXIT:
  j = j + i (Since i=-1 at this point, this is basically j = j - 1)
  Print j as integer
  Exit with error

```

**Example run (`n=4`):**

```
Command   Explanation                   Stack              HEAP    STDIN   STDOUT  STDERR

SSSTSTSN  Push 10                       [10]
SNS       Duplicate top (10)            [10,10]
SNS       Duplicate top (10)            [10,10,10]
SNS       Duplicate top (10)            [10,10,10,10]
TNTT      Read STDIN as integer         [10,10,10]         {10:4}  4
TTT       Retrieve                      [10,10,4]          {10:4}
NSSN      Create Label_LOOP             [10,10,4]          {10:4}
 SSSTN     Push 1                       [10,10,4,1]        {10:4}
 TSST      Subtract (4-1)               [10,10,3]          {10:4}
 SNS       Duplicate top (3)            [10,10,3,3]        {10:4}
 NTTSN     If neg.: Jump to Label_EXIT  [10,10,3]          {10:4}
 SNT       Swap top two                 [10,3,10]          {10:4}
 STSSTSN   Copy 2nd                     [10,3,10,10]       {10:4}
 TSSN      Multiply (10*10)             [10,3,100]         {10:4}
 SNT       Swap top two                 [10,100,3]         {10:4}
 NSNN      Jump to Label_LOOP           [10,100,3]         {10:4}

 SSSTN     Push 1                       [10,100,3,1]       {10:4}
 TSST      Subtract (3-1)               [10,100,2]         {10:4}
 SNS       Duplicate top (2)            [10,100,2,2]       {10:4}
 NTTSN     If neg.: Jump to Label_EXIT  [10,100,2]         {10:4}
 SNT       Swap top two                 [10,2,100]         {10:4}
 STSSTSN   Copy 2nd                     [10,2,100,10]      {10:4}
 TSSN      Multiply (100*10)            [10,2,1000]        {10:4}
 SNT       Swap top two                 [10,1000,2]        {10:4}
 NSNN      Jump to Label_LOOP           [10,1000,2]        {10:4}

 SSSTN     Push 1                       [10,1000,2,1]      {10:4}
 TSST      Subtract (2-1)               [10,1000,1]        {10:4}
 SNS       Duplicate top (1)            [10,1000,1,1]      {10:4}
 NTTSN     If neg.: Jump to Label_EXIT  [10,1000,1]        {10:4}
 SNT       Swap top two                 [10,1,1000]        {10:4}
 STSSTSN   Copy 2nd                     [10,1,1000,10]     {10:4}
 TSSN      Multiply (1000*10)           [10,1,10000]       {10:4}
 SNT       Swap top two                 [10,10000,1]       {10:4}
 NSNN      Jump to Label_LOOP           [10,10000,1]       {10:4}

 SSSTN     Push 1                       [10,10000,1,1]     {10:4}
 TSST      Subtract (1-1)               [10,10000,0]       {10:4}
 SNS       Duplicate top (0)            [10,10000,0,0]     {10:4}
 NTTSN     If neg.: Jump to Label_EXIT  [10,10000,0]       {10:4}
 SNT       Swap top two                 [10,0,10000]       {10:4}
 STSSTSN   Copy 2nd                     [10,0,10000,10]    {10:4}
 TSSN      Multiply (10000*10)          [10,0,100000]      {10:4}
 SNT       Swap top two                 [10,100000,0]      {10:4}
 NSNN      Jump to Label_LOOP           [10,100000,0]      {10:4}

 SSSTN     Push 1                       [10,100000,0,1]    {10:4}
 TSST      Subtract (0-1)               [10,100000,-1]     {10:4}
 SNS       Duplicate top (-1)           [10,100000,-1,-1]  {10:4}
 NTTSN     If neg.: Jump to Label_EXIT  [10,100000,-1]     {10:4}
NSSSN      Create Label_EXIT            [10,100000,-1]     {10:4}
TSSS       Add (10000+-1)               [10,99999]         {10:4}
TNST       Print as integer             [10]               {10:4}          99999
                                                                                error

```

Stops program with error: No exit defined.
> 2 votes

# Answer
# Perl 5, 7 bytes

```
$_=9x$_

```

Try it online!
> 1 votes

# Answer
# AWK, 26 bytes

```
{for(;a++<$1;){printf"9"}}

```

Try it online!
> 1 votes

# Answer
# Julia, 14 bytes

`f(n)="9"^(n+1)`

That's if the result can be a string.
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 30 bytes

```
	OUTPUT =DUPL(9,INPUT + 1)
END

```

Try it online!
> 1 votes

# Answer
# Gol\>\<\>, 5 bytes

```
PR`9H

```

Try it online!

This is a Gol\>\<\> function which takes the stack content as input.

### Example full program & How it works

```
1AG9G
PR`9H

1AG    Register row 1 as function G
   9G  Call G with stack [9]

P      Increment
 R`9   Push char '9' that many times
    H  Print the stack content as chars and halt

```
> 1 votes

# Answer
# TI-Basic, 7 bytes

```
10^(Ans+1)-1

```

Fairly straightforward...
> 1 votes

# Answer
# CJam, 6 bytes

```
qi)'9*

```

Try it online!
> 1 votes

# Answer
# Befunge-98 (FBBI), ~~13~~ 12 bytes

-1 byte thanks to Jo King

```
&#9':_@#\-1,

```

Try it online!
> 1 votes

# Answer
# IBM/Lotus Notes Formula, 16 bytes

```
@Power(10;i+1)-1

```

Simple port of my Python answer. One of the nice things about formula is that if you pass it a list it will apply the same function to each list member.
> 1 votes

# Answer
# Symbolic Python, ~~40~~ 37 bytes

```
__=-~(_==_)
_=(__+__**-~__)**-~_+~_+_

```

Try it online!

---

### Ungolfed

```
# implicit input stored in _
__  = -~(_==_)             # __ = -~True = 1 + True = 1 + 1 = 2
_=(__+__**-~__)**-~_+~_+_  # _  = (2 + 2 ** -~2) ** -~_ + ~_ + _
                                = (2 + 2**3) ** (_ + 1) - -~_ + _
                                = 10 ** (_ + 1) - (_ + 1) + _
                                = 10 ** (_ + 1) - 1
# implicit output of _

```

---

### other 37 byte solutions

```
__=_==_
_=(-~__*-~-~-~-~__)**-~_+~_+_

```

Try it online!

```
_=(-~(_==_)*-~-~-~-~(_==_))**-~_+~_+_

```

Try it online!

---

# Symbolic Python, 29 bytes

multiplies the string `'9'` by `_ + 1`

```
_=`-~-~(_==_)*-~-~(_==_)`*-~_

```

Try it online!
> 1 votes

# Answer
# Charcoal, ~~5~~ 4 bytes

```
×9⊕Ｎ

```

Try it online!

### Explanation

```
×9     Repeat "9"
  ⊕Ｎ ++(next number as input) times

```
> 1 votes

# Answer
# Tcl, 26 bytes

```
puts [expr 10*10**$argv-1]

```

Try it online!
> 1 votes

# Answer
# Common Lisp, 30 bytes

```
(lambda(n)(1-(expt 10(1+ n))))

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 18 bytes

Just throwing out a recursive solution to the problem:

```
f=n=>n?9+f(n-1):''

```

Evaluates the expression `''+9+9+9+9...` (depending on `n`).

Because the first operand is a string, all the `+` operators are treated as concatenation instead of addition.

In my Chrome, works up to `f(11424)` before hitting a stack overflow.

```
f=n=>n?9+f(n-1):''

for(i = 0; i < 100; i += 10) {
  console.log(f(i));
}
```
> 1 votes

# Answer
## PHP, 25 bytes

Try it online

**Code**

(Passing `$arguments` to the script)

```
<?=str_repeat(9,$argv+1);

```

**Or a recursive function, 42 Bytes**

Try it online!

```
function f($u){echo($u<0)?"":"9".f($u-1);}

```
> 1 votes

# Answer
# Phooey, 11 bytes

```
&.+1[$i9-1]

```

Try it online!

## Explanation

```
&.+1[$i9-1]
&.              take numeric input
  +1            add 1
    [   -1]     until that is zero:
     $i9        output 9s

```
> 0 votes

# Answer
# Attache, 9 bytes

```
{N!-~_&9}

```

Try it online!

## Alternatives

**10 bytes:** `{"9"*t-~_}`

**13 bytes:** (pointfree) `9&Resize@1&`+`

## Explanation

```
{N!-~_&9}
{       }     anonymous lambda taking input `_`
   -~_        input + 1
      &9      9s repeated that much (array of 9s)
 N!           cast to integer

```
> 0 votes

# Answer
# Red, 24 bytes

```
func[n][loop n[prin"9"]]

```

Outputs a string

Try it online!
> 0 votes

# Answer
# Python 2, ~~20~~ 18 bytes

```
lambda i:10**-~i-1

```

Try it online!

Don't think it needs an explanation.

-2 with thanks to @ovs
> 0 votes

# Answer
# Triangularity, 31 bytes

```
...)...
..IE@..
.)10^).
@_+....

```

Try it online!

### Also 31 bytes

```
...)...
..IE)..
.@_rM..
"9"}""J

```

Try it online!
> 0 votes

# Answer
# Java 8, ~~27~~ 25 bytes

```
n->n+=Math.pow(10,n+1)+~n

```

Try it online.

This is basically a shorter version of `n->(long)Math.pow(10,n+1)-1`, because `n+=...-n` saves a byte in comparison to `(long)...`. (And combining `-n-1` to `+~n` saves a second byte in this case.)
> 0 votes

# Answer
# Swift 4, ~~47~~ ~~34~~ 32 bytes

~~-13~~ -15 bytes thanks to @Mr. Xcoder

```
{(0...$0).map{_ in"9"}.joined()}

```

Try it online!
> 0 votes

# Answer
# Prolog (SWI), ~~34~~ ~~23~~ 20 bytes

```
X+Y:-Y is 10*10^X-1.

```

Try it online!

Call as `<input>+<result variable>`.
> 0 votes

# Answer
# Excel, 12 bytes

```
=10^(A1+1)-1

```

Or alternatively, to better handle larger values (`>10`) for `13 bytes`

```
=REPT(9,A1+1)

```
> 0 votes

# Answer
# Ruby, 11 bytes

```
->n{?9*-~n}

```

Try it online!
> 0 votes

# Answer
# C (gcc) (`-lm`), 22 bytes

```
f(n){n=pow(10,-~n)-1;}

```

Try it online!

Saved 4 bytes thanks to Kevin Cruijssen.
> 0 votes

# Answer
# Cubix, 15 bytes

```
Iu9)^>Os(?@.>sW

```

Try it online!

Expands to the following cube:

```
    I u
    9 )
^ > O s ( ? @ .
> s W . . . . .
    . .
    . .

```
> 0 votes

# Answer
# Japt `-P`, 3 bytes

```
ò@9

```

Try it

---

## Explanation

```
ò       :Range [0,input]
 @      :Pass each through a function
  9     :  Return 9
        :Implicitly join and output

```
> 0 votes

# Answer
# GolfScript, 6 bytes

```
~)'9'*

```

Try it online!

Explanation:

```
~)'9'* Full program, implicit input
       Stack: '5'
~      Evaluate
       Stack: 5
 )     Increment
       Stack: 6
  '9'  Push '9'
       Stack: 6 '9'
     * Repeat
       Stack: '999999'
       Implicit output

```

## GolfScript, 7 bytes

```
~)10\?(

```

Try this one!

Explanation:

```
~)10\?( Full program, implicit input
        Stack: '5'
~)      Evaluate and increment (as above)
        Stack: 6
  10\?  Raise 10 to that power
        Stack: 1000000
      ( Decrement
        Stack: 999999
        Implicit output

```
> 0 votes

# Answer
# Stax, 4 bytes

```
^|Av

```

Run and debug it

Packed would not be any shorter.

Explanation:

```
^|Av Full program, implicit input
^    Increment
 |A  Raise ten to that power
   v Decrement
     Implicit output

```

## Stax, 4 bytes

```
^'9*

```

Run and debug it

```
^'9* Full program, implicit input
^    Increment
 '9* Repeat "9"
     Implicit output

```
> 0 votes

---
Tags: code-golf, math, number
---


title: Ascending integer pyramid

text:
# Question
Title: Ascending integer pyramid
Output either the text below, or a list of lists of integers (more details below).

```
 0
10  1
20 11  2
30 21 12  3
40 31 22 13  4
50 41 32 23 14  5
60 51 42 33 24 15  6
70 61 52 43 34 25 16  7
80 71 62 53 44 35 26 17  8
90 81 72 63 54 45 36 27 18  9
91 82 73 64 55 46 37 28 19
92 83 74 65 56 47 38 29
93 84 75 66 57 48 39
94 85 76 67 58 49
95 86 77 68 59
96 87 78 69
97 88 79
98 89
99

```

## Rules

* If you wish, you may "one index" and replace each `n` with `n+1`. In this case the output will contain the numbers 1 to 100 inclusive.

### If output is text

* The single digits are right aligned in each column in the text provided, but it is fine if you wish to left align. Additionally, alignment is not required to be consistent between columns.
* Leading/trailing whitespace is permitted. Trailing spaces on each line are also permitted.
* Returning a list of lines is acceptable.

### If output is numerical

* Output can be a list of lists of integers (or 2D array): `[[1], [11, 2], [21...`
* Floats are fine.
* If it is not possible to have nonrectangular array in the language used, then the elements in the array that aren't within the triangle can take any value and will be ignored.

If you prefer another format, feel free to ask.

Shortest code wins.

# Answer
# Jelly,  ~~13 12 10~~  6 bytes

-4 thanks to Dennis, yes FOUR! (use of group indices and Cartesian product)

```
⁵pḅ1ĠU

```

Uses 1-indexing and the list option for output.

**Try it online!** (The footer formats the output in Python representation)
...or see a 0-indexed, formatted version.

### How?

```
⁵pḅ1ĠU - Main link: no arguments
⁵      - literal 10
 p     - Cartesian product (with the leading constant of 10 and implicit ranges)
       -       = [[1,1],[1,2],[1,3],...,[10,8],[10,9],[10,10]]
  ḅ1   - to base one (proxy for sum each without the monad)
       -       = [2,3,4,5,6,7,8,9,10,11,3,4,5,6,7,8,9,10,11,12,4,...,18,19,20]
    Ġ  - group indices by value
       -       = [[1],[2,11],[3,12,21],...,[90,99],[100]]
     U - upend = [[1],[11,2],[21,12,3],...,[99,90],[100]]

```
> 10 votes

# Answer
# Python 2, 54 bytes

```
k=1
exec"print range(k,0,-9)[:101-k];k+=10-k/91*9;"*19

```

Try it online!

(1-indexed, because `range(k,0,-9)` is shorter than `range(k,-1,-9)`.)
> 5 votes

# Answer
# Charcoal, ~~29~~ 20 bytes

```
Ｅ¹⁹⪫Ｉ⮌Φ¹⁰⁰⁼ι⁺÷λχ﹪λχ

```

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

```
 ¹⁹                     Literal 19
Ｅ                       Map over implicit range
       ¹⁰⁰              Literal 100
      Φ                 Filter over implicit range
              λ  λ      Inner index
               χ  χ     Predefined variable 10
                ﹪       Modulo
             ÷          Integer divide
            ⁺           Sum
           ι            Outer index
          ⁼             Equals
     ⮌                  Reverse
    Ｉ                   Cast to string
   ⪫                    Join with spaces
                        Implicitly print each string on its own line

```
> 4 votes

# Answer
# JavaScript (ES6), 61 bytes

0-based. Returns a string.

```
f=(k=n=0)=>k>98?k:k+((k-=9)%10>0?' '+f(k):`
`+f(n+=n>89||10))

```

Try it online!

### How?

We start with **k = n = 0** and stop when **k = 99**. We subtract **9** from **k** at each iteration.

End of rows are detected with `k % 10 <= 0`. This condition is fulfilled if:

* **k** is negative (upper part of the pyramid) because the sign of the modulo in JS is that of the dividend.

```
 0 (-9)
10  1 (-8)
20 11  2 (-7)

```
* *or* **k % 10 == 0** (lower part of the pyramid)

```
90 81 72 63 54 45 36 27 18  9 (0)
91 82 73 64 55 46 37 28 19 (10)
92 83 74 65 56 47 38 29 (20)

```

At the beginning of the next row, we add either **1** or **10** to **n** and restart from there.
> 4 votes

# Answer
# Python 2, 66 bytes

```
r=range
for a in r(0,90,10)+r(90,100):print r(a,a/10+a%10*10-1,-9)

```

Try it online!
> 3 votes

# Answer
# , 14 bytes

```
,.<@|./.i.,~10

```

Try it online!

## Note:

This solution uses boxed output - I'm not sure if it's allowed (I hope it is, because lists of integers are also allowed)

## Alternative:

# , 10 bytes

```
|./.i.,~10

```

In this solution the numbers outside the triangular area are displayed as `0`

Try it online!

## Explanation:

`i.,~10` creates a matrix 10x10 of the numbers 0..99 `,~10` is short for `10 10`

```
   i.,~10
 0  1  2  3  4  5  6  7  8  9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99

```

`/.` finds the oblique diagonals (antidiagonals) of the matrix

```
   ]/.i.,~10
 0  0  0  0  0  0  0  0  0  0
 1 10  0  0  0  0  0  0  0  0
 2 11 20  0  0  0  0  0  0  0
 3 12 21 30  0  0  0  0  0  0
 4 13 22 31 40  0  0  0  0  0
 5 14 23 32 41 50  0  0  0  0
 6 15 24 33 42 51 60  0  0  0
 7 16 25 34 43 52 61 70  0  0
 8 17 26 35 44 53 62 71 80  0
 9 18 27 36 45 54 63 72 81 90
19 28 37 46 55 64 73 82 91  0
29 38 47 56 65 74 83 92  0  0
39 48 57 66 75 84 93  0  0  0
49 58 67 76 85 94  0  0  0  0
59 68 77 86 95  0  0  0  0  0
69 78 87 96  0  0  0  0  0  0
79 88 97  0  0  0  0  0  0  0
89 98  0  0  0  0  0  0  0  0
99  0  0  0  0  0  0  0  0  0

```

Using `]` (same) pads all lines with `0`s. Each line is reversed. In order to get rid of the zeroes I box the lines `<` after they are reversed `|.`

```
   <@|./.i.,~10
┌─┬────┬───────┬──────────┬─────────────┬────────────────┬
│0│10 1│20 11 2│30 21 12 3│40 31 22 13 4│50 41 32 23 14 5│. . .
└─┴────┴───────┴──────────┴─────────────┴────────────────┴

```

Boxing makes the list of lists to be flatten. I finally ravel `,.` the list so that the lines are ordered in a column.

```
  ,.<@|./.i.,~10
┌────────────────────────────┐
│0                           │
├────────────────────────────┤
│10 1                        │
├────────────────────────────┤
│20 11 2                     │
├────────────────────────────┤
│30 21 12 3                  │
├────────────────────────────┤
│40 31 22 13 4               │
├────────────────────────────┤
│50 41 32 23 14 5            │
├────────────────────────────┤
│60 51 42 33 24 15 6         │
├────────────────────────────┤
│70 61 52 43 34 25 16 7      │
├────────────────────────────┤
│80 71 62 53 44 35 26 17 8   │
├────────────────────────────┤
│90 81 72 63 54 45 36 27 18 9│
├────────────────────────────┤
│91 82 73 64 55 46 37 28 19  │
├────────────────────────────┤
│92 83 74 65 56 47 38 29     │
├────────────────────────────┤
│93 84 75 66 57 48 39        │
├────────────────────────────┤
│94 85 76 67 58 49           │
├────────────────────────────┤
│95 86 77 68 59              │
├────────────────────────────┤
│96 87 78 69                 │
├────────────────────────────┤
│97 88 79                    │
├────────────────────────────┤
│98 89                       │
├────────────────────────────┤
│99                          │
└────────────────────────────┘

```
> 3 votes

# Answer
# Pure Bash (no external utilities), 66

```
eval a={{9..1},}\;b={9..0}';c[a+b]+=$a$b\ '
printf %s\\n "${c[@]}"

```

Try it online!
> 2 votes

# Answer
# , ~~137 86 73~~ 69 bytes

```
for(u in 0:18)cat("if"(u>9,seq(81+u,10*u-81,-9),seq(10*u,u,-9)),"\n")

```

Try it online!

Previous golfed version, %100 credits to Giuseppe.

```
S=sapply
c(S(1:10,function(u)1:u-1+10*(u-1:u)),S(9:1,function(y)1:y+9-y+10*(y:1+9-y)))

```

Try it online!

Below my first attempt at Codegolf keeping it just for the record.

```
x<-c(1:10)
z<- c(9:1)
c(sapply(x,function(u) seq_len(u)-1+10*(u-seq_len(u))),sapply(z,function(y) seq_len(y)+9-y+10*rev(seq_len(y)+9-y)))

```

Try it online!
> 2 votes

# Answer
# Pyth, 16 bytes

```
V19fqssM`TN_U100

```

Try it online!
> 2 votes

# Answer
# Gol\>\<\>, 24 bytes

```
0D9FlF{a+|lD|9F~lF{P|D|;

```

Try it online!

The output looks like this:

```
[0]
[10 1]
[20 11 2]
[30 21 12 3]
[40 31 22 13 4]
[50 41 32 23 14 5]
[60 51 42 33 24 15 6]
[70 61 52 43 34 25 16 7]
[80 71 62 53 44 35 26 17 8]
[90 81 72 63 54 45 36 27 18 9]
[91 82 73 64 55 46 37 28 19]
[92 83 74 65 56 47 38 29]
[93 84 75 66 57 48 39]
[94 85 76 67 58 49]
[95 86 77 68 59]
[96 87 78 69]
[97 88 79]
[98 89]
[99]

```

### How it works

```
0D9FlF{a+|lD|9F~lF{P|D|;

0D                       Push 0 and print stack
  9F        |            Repeat 9 times...
    lF{a+|                 Add 10 to all numbers on the stack
          l                Push stack length (the last one-digit number)
           D               Print stack
             9F       |  Repeat 9 times...
               ~           Discard the top
                lF{P|      Increment all numbers on the stack
                     D     Print stack
                       ; Halt

```
> 2 votes

# Answer
# , ~~50~~ 48 bytes

```
split(y<-rev(order(x<-outer(0:9,0:9,"+"))),x[y])

```

Try it online!

1-indexed. Follows the same logic as Jonathan Allan's Jelly answer, so make sure to upvote him.

As a bonus, here is also an implementation of standard looping approach (0-indexed). Here, I at least tried to make the output prettier (thus, didn't even save bytes for `print` instead of `cat(...,"\n")` to get rid of annoying `[1]`s in the console.

# , ~~66~~ 59 bytes

```
for(i in c(0:8*10,90:99))cat(seq(i,i/10+i%%10*10-1,-9),"
")

```

Try it online!

Edit: -2 and -7 both thanks to Giuseppe.
> 2 votes

# Answer
# Octave, ~~67~~ ~~66~~ ~~65~~ 64 bytes

```
for i=0:8disp(10*i:-9:0)end,for i=0:9disp(90+i:-9:11*i+(i<1))end

```

Try it online!

Those missing semicolons hurt my eyes!
> 1 votes

# Answer
# 05AB1E, 22 bytes

```
TLûvTLD>T*«NèyGD9+})R,

```

Try it online!

---

Super Naive Approach: Try it online! may be a better solution but I can't figure out how to get from A to B.
> 1 votes

# Answer
# PowerShell, 77 bytes

```
(0..90|?{!($_%10)})+91..99|%{"$(for($i=$_;$i-gt$_/10+$_%10*10-1;$i-=9){$i})"}

```

Try it online!

Outputs as ASCII-art with the single-digits left-aligned. Exploits the fact that stringifying an array inserts spaces between elements by default.

Very similar to Rod's Python answer, apparently, but developed independently.
> 0 votes

# Answer
# JavaScript, 69 bytes

```
f=(i=e=[])=>e[i<19&&(e[+i]=[]),i/10+i%10|0].unshift(+i)*i++-99?f(i):e

```

Try it online!

# JavaScript REPL, 77 bytes

```
[...Array(100)].map((_,i)=>e[i<19&&(e[i]=[]),i/10+i%10|0].unshift(i),e=[])&&e

```
> 0 votes

# Answer
# Perl 6, ~~43~~ 40 bytes

```
{map {[R,] grep :k,$_,(^10 X+ ^10)},^19}

```

Try it online!

-3 bytes thanks to Brad Gilbert b2gills.
> 0 votes

# Answer
# Perl 5, 62 bytes

```
$,=$";say@,=map$_+=10,@,,$_ for-9..0;say map++$_,@,while pop@,

```

Try it online!

1-indexed to save a couple bytes
> 0 votes

# Answer
# Red, 105, 95 91 bytes

```
v: make vector! 0
loop 10[alter v + 10 length? v print v]loop 9[alter v last v print 1 + v]

```

Try it online!

## Explanation:

```
v: make vector!   0                           ; start with a vector with one element: -10
loop 10[alter v + 10 length? v print v]       ; Ten times print the vector after adding 10
                                              ; to its elements and appending the length
loop 9[alter v last v print 1 + v]            ; Nine times print the vector after adding 1
                                              ; to its elements and removing the last one
                                              ; `alter` appends the item if it's not
                                              ; in the list, otherwise removes it

```
> 0 votes

# Answer
# Ruby, 58 bytes

```
0.step(180,10){|x|p x.step(0,-9).select{|y|y<100&&y>x-90}}

```

Try it online!
> 0 votes

# Answer
# JavaScript, 112 bytes

Not that optimal, but I wanted to try a different approach.

```
[...Array(19)].map((x,y)=>y>9?81+y:y?y+'0':y).map(x=>(f=(n,a=[n])=>!n|a[n+='']|n[1]>8?a:f(n-=9,a.concat(n)))(x))

```

Try it online!

Old Solution:

```
[...Array(19)].map((x,y)=>y>9?y-9+'9':y).map((x,y)=>(f=(n,a=[n])=>a[n/10]|!n?a.reverse():a.push(n+=9)&&f(n,a))(x*1).slice(y-19))

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 16 bytes

```
тL<ΣTLãOsè}TLû£í

```

Try it online!

**Explanation**

```
тL<Σ      }       # sort the values in [0 ... 99] by
        sè        # the value at that index in
       O          # the sum of
      ã           # the cartesian product of
    TL            # the range [1 ... 10]
              £   # split the result into pieces of sizes
           TLû    # [1,2,...,9,10,9,...2,1]
               í  # and reverse each

```
> 0 votes

---
Tags: code-golf
---