title: Inverse-quotes-quine

text:
# Question
Title: Inverse-quotes-quine
The prospect of this challenge is:

* If your program is run normally, all of the code in the speech marks (`"` \- double quotes) should be printed.
* If your program is wrapped in double quotes (in turn inverting the speech marks), the code that is normally not in quotes should be printed.

E.g:

Let's say you have the following code:

```
fancyStuff("myCode"); "I like".isGreat();

```

If I run it, I would expect an output of:

```
myCode
I like

```

However, if I wrapped it in quotes, I would get:

```
"fancyStuff("myCode"); "I like".isGreat();"

```

When this code is run, the expected output would be:

```
fancyStuff(
);
.isGreat();

```

Obviously, the above example is not a functional response in any language. Your job is to write the code that performs in this way.

# Rules

* Standard loopholes apply.
* The printed values, in both quoted and unquoted forms, must be non-empty, or consist solely of whitespace. This also means that all programs must include at least one set of quotes.
* However, trailing/preceeding whitespace is allowed.
* No looking at your own code, required file names, etc.
* Unmatched quotes are disallowed
* If there are multiple strings, they can either be printed as newlines (as in the example), or in some other *human-readable* way - no arrays or objects
* This is , so shortest answer in bytes wins.

# Answer
# Python 2, 20 bytes

```
print";print'print'"

```

-7 bytes thanks to tsh

Try it online!

---

# Old answer:

# Python 2, 27 bytes

```
'';print";print 2*"'';print

```

Try it online!

### Train of thought behind this answer:

Begin with a simple print, because we need to print *something*.

```
print"a"

```

We also need to print something in the inverted case, ie. have a print inside quotes.

```
print"print"

```

The non-inverted case is pretty good at this point. Let's focus on the inverted case. We now start with the string `print`, which can't be followed immediately by a print statement. Let's fix this with a semicolon.

```
print";print"

```

Good stuff. Except, the inverted code doesn't actually print anything. We'll need to print the `print` at the start, because it ends up in quotes, but also print whatever comes after the second quote, because it ends up in quotes too. The obvious way around this is to append `print` and multiply the last string by 2.

```
print";print 2*"print

```

Now the inverted code works fine, though we have to be wary of the fact that the section before the first quote and the section after the second quote need to be kept the same throughout future changes. As for the non-inverted code, it throws a syntax error - once again, we need to introduce a semicolon to separate expressions.

```
;print";print 2*";print

```

Python doesn't really like the look of that lone semicolon, so we must satisfy the snake's hunger with two of the same no-op expression, inserted before the first semicolon and the last semicolon. Most expressions will work fine in the first case, but in the second case it must follow `print";print 2*"` in the non-inverted code without breaking anything. We can use `''`, which simply gets concatenated with the prior string.

```
'';print";print 2*"'';print

```
> 28 votes

# Answer
# CSS, 66 bytes

```
body:after{content:"{}body:after{content:'body:after{content:}'}"}
```

```
"body:after{content:"{}body:after{content:'body:after{content:}'}"}"
```

Not so much questions may be solved by CSS...
> 19 votes

# Answer
# HQ9+<sup>\[see notes below\]</sup>, 1016 bytes

```
"Hello World"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""Hello World
```

Use the implementation on https://esolangs.org/w/index.php?title=HQ9%2B&oldid=59995 and compile the interpreter with MinGW GCC 5.3.0 on Windows. I'm not sure if it works with other version of compiler, since an undefined behavior of C is required to terminate the program. The buffer is 1000 bytes long. And source code greater than 1000 bytes do the trick. I'm not sure how these happened.
> 10 votes

# Answer
# 05AB1E, 4 bytes

```
"A"§

```

Outputs concatenated without separator.

Try it online or try it online with surrounding quotes.

**Explanation:**

```
        # Program without surrounding quotes will output string "A"
"A"     # Push "A" to the stack
   §    # Cast it to a string
        # (output the top of the stack implicitly as result)

        # Program with surrounding quotes will output string "§"
""      # Push an empty string to the stack
  A     # Push the alphabet to the stack: "abcdefghijklmnopqrstuvwxyz"
   "§"  # Push "§" to the stack
        # (output the top of the stack implicitly as result)

```
> 9 votes

# Answer
# Japt, 4 bytes

```
"P"s

```

Try it unquoted or quoted

`P` is the Japt variable for the empty string and the `s` method slices a string - without any arguments, it does nothing.

---

Or, ever so slightly less trivial:

```
"+"u

```

Try it unquoted or quoted

The first one uppercases `+` and the second one appends `u` to an empty string.
> 6 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~113~~ ~~112~~ ~~107~~ ~~70~~ 64 bytes

```
Write(".f();static void f(this string s){Write(s+')'+';');}//");

```

*Saved 5 bytes thanks to @negative seven*

Unquoted and Quoted

After a while, I realized that my solution was too complicated. The newest program shown here simply hides the rest of the program in a comment to avoid errors when wrapped in quotes.

When wrapped in quotes, `Write(` is passed onto an extension method, which prints it along with `);`.
> 5 votes

# Answer
# Perl 6, 11 bytes

```
say ".say~"

```

Try it online!

Prints `.say~` with a trailing newline. Seems too easy. Am I missing something?

When wrapped in quotes, produces `say` with a space and trailing newline.
> 4 votes

# Answer
# Foo, 4 bytes

```
"P"s

```

Try it online! Also works in Japt.

### 5 bytes (UTF-8)

```
"A"§

```

Try it online! Also works in 05AB1E.

### 9 bytes

```
"!""$;"$;

```

Try it online! Also works in Runic Enchantments.

### 11 bytes

```
say ".say~"

```

Try it online! Also works in Perl 6.

### 20 bytes

```
print";print'print'"

```

Try it online! Also works in Python 2.

### 69 bytes

```
body::after{content:"{}body::after{content:'body::after{content:}'}"}

```

Try it online! Also works in CSS.

Hmm... Foo is a highly adaptable language.
> 4 votes

# Answer
## \>\<\>, ~~18~~ 9 bytes

```
"|o<"r>o|

```

*-9 bytes thanks to Jo King*

Try it online! (quoted)

### Explanation

```
"|o<"r>o|
"|o<"     Pushes the quoted characters onto the stack
     r    Reverses the stack
      >o| Outputs all characters on stack & errors

```

```
""|o<"r>o|"
""          No-op
  |         Reverses the IP direction
     "r>o|" Pushes the quoted characters onto the stack (backwards)
  |o<       Outputs all characters on stack & errors

```
> 4 votes

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

```
<@,k4"<@,k4"

```

Unquoted Quoted

Both cases print `<@,k4`. Either (or both) of the `@`s can be replaced with `q` instead.
> 3 votes

# Answer
# Runic Enchantments, 9 bytes

```
"!""$;"$;

```

Try it online! and `""!""$;"$;"`

From Kevin Cruijssen, who essentially fixed my first attempt utilizing what I did in my second.

Going down the "fungoids never have unmatched quotes" rule-bending "there's something about this that shouldn't be OK" route, alluded to in my own comment:

## 7 bytes

```
0".""$;

```

Try it online! and `"0".""$;"`

Under normal circumstances, this program executes as `0".""$;0".""$;` pushing an integer `0`, then the string `.`, concatenates `$;0`, NOP, concatenates an empty string, prints top-of-stack (the string `.$;0`) and terminates. Wrapping it in quotes produces `"0".""$;"` which pushes a string-`0`, NOPs, concatenates an empty string, prints top-of-stack, and terminates (rendering the previously un-printed integer `0` in string form). The last `"` is left unexecuted (and not part of the *original* program anyway).

Fungoids don't have string literals, they have a command that toggles "read own source as a string" mode and some form of "instruction pointer has reached the source boundary" rule (usually edge-wrap), so the same source-code-positional-byte acts as both "begin string" and "end string" instruction, creating a string literal of that entire row/column (excluding the `"` itself).
> 2 votes

# Answer
## Haskell, 31 bytes

```
putStr"#1;(#)=const<$>putStr--"

```

Try it online! Or enclosed in quotes: Try it online!
> 2 votes

# Answer
# MathGolf, 4 bytes

```
";"q

```

Try it online!

The `;` and `q` can be exchanged for a lot of different commands, including no-ops.
> 1 votes

# Answer
# Ruby, 8 bytes

```
p";p'p'"

```

Try it online!

Wraps output in quotes, which may be illegal.

# Ruby, 17 bytes

```
puts";puts'puts'"

```

Try it online!
> 1 votes

# Answer
# JavaScript (SpiderMonkey), 25 bytes

```
print("-print`print()`-")

```

Try it online!

```
"print("-print`print()`-")"

```

Try it online!

Trivial but functional.
> 0 votes

# Answer
# Japt, 4 bytes

```
"P"u

```

Unquoted, it converts the string `P` to uppercase. Quoted, it prints `u`.

Try it

# Japt, 4 bytes

```
"P"w

```

Unquoted, it reverses the string `P`. Quoted, it prints `w`.

Try it
> 0 votes

# Answer
# R, 16 bytes

```
 ";print(";");"

```

Note that the above code is not wrapped in the additional quotation marks and has both leading and trailing spaces.

Try it (non-wrapped version)
> 0 votes

# Answer
# AppleScript, 9 bytes

```
return"&"

```

### Explained:

```
return"&"    -- returns "&"

```

Quoted:

```
"return"&""  -- implied return of the string "return" concatenated with ""

```
> 0 votes

---
Tags: code-golf, restricted-source, quine
---


title: Who is the sleepiest of them all?

text:
# Question
Title: Who is the sleepiest of them all?
Write a program or function that takes in a string of the characters `-=o.` where the `-=o`'s and `.`'s always alternate, character to character. The string will have an odd length greater than one and always start and end in one of `-=o`.

Basically, the input will look like a line of emoticon faces that share eyes in various states of sleepiness, e.g.

```
o.=.=.-.-.o.o

```

Your goal is to print or return the face that is either the sleepiest or the most awake (it's up to you which you choose). If there are multiple choices for who is sleepiest/most awake then any one of them may be output.

There are nine distinct faces and five levels of sleepiness:

```
-.- is 100% sleepy
-.= is 75% sleepy
-.o is 50% sleepy
=.- is 75% sleepy
=.= is 50% sleepy
=.o is 25% sleepy
o.- is 50% sleepy
o.= is 25% sleepy
o.o is 0% sleepy

```

In case it's not clear, the sleepiness percentage is computed by assigning `1` to `-` for fully asleep, `0.5` to `=` for half asleep, and `0` to `o` for awake. Then the sum of the two eye values divided by two is the percentage.

**The shortest code in bytes wins.**

# Test Cases

**Sleepiest**

```
-.- GIVES -.-
=.- GIVES =.-
o.o GIVES o.o
o.-.= GIVES -.=
=.-.= GIVES =.- OR -.=
o.-.= GIVES -.=
-.-.= GIVES -.-
o.o.- GIVES o.-
=.=.=.o GIVES =.=
-.=.=.= GIVES -.=
=.o.-.= GIVES -.=
o.-.o.=.= GIVES o.- OR -.o OR =.=
-.o.-.=.= GIVES -.=
o.o.o.o.o GIVES o.o
-.-.-.-.- GIVES -.-
o.=.=.-.-.o.o GIVES -.-
-.=.-.o.o.=.o.-.o.=.-.o.=.o.- GIVES -.= OR =.-
```

**Most Awake**

```
-.- GIVES -.-
=.- GIVES =.-
o.o GIVES o.o
o.-.= GIVES o.-
=.-.= GIVES =.- OR -.=
o.-.= GIVES o.-
-.-.= GIVES -.=
o.o.- GIVES o.o
=.=.=.o GIVES =.o
-.=.=.= GIVES =.=
=.o.-.= GIVES =.o
o.-.o.=.= GIVES o.=
-.o.-.=.= GIVES -.o OR o.- OR =.=
o.o.o.o.o GIVES o.o
-.-.-.-.- GIVES -.-
o.=.=.-.-.o.o GIVES o.o
-.=.-.o.o.=.o.-.o.=.-.o.=.o.- GIVES o.o
```

# Answer
# Pyth, ~~12~~ 10 bytes

```
hoSN%2.:z3

```

This prints the sleepiest emoticon. Verify all test cases at once in the Pyth Compiler.

*Credit goes to @Sp3000 for the idea to use sorting.*

### How it works

```
hoSN%2.:z3
              (implicit) Save the in z.
      .:z3    Compute all substrings of length 3.
    %2        Keep every seconds substring. This discards non-emoticons.
 o            Sort the emoticons by the following key:
  SN            Sort the characters of the emoticon.
                This works since '-' < '=' < 'o'.
h             Retrieve the first, minimal element.

```
> 27 votes

# Answer
# Python 2, ~~54~~ 53 bytes

```
f=lambda s:s and max((s+' ')[:3],f(s[2:]),key=sorted)

```

This is a function that returns the face that is most awake.

Many thanks to xnor for providing many tactical tricks to shorten my original algorithm.
> 9 votes

# Answer
# CJam, 12 bytes

```
q3ew2%{$}$0=

```

This prints the sleepiest emoticon. Try this fiddle or this test suite in the CJam interpreter.

*Credit goes to @Sp3000 for the idea to use sorting.*

### How it works

```
q            e# Read all input from STDIN.
 3ew         e# Push all overlapping slices of length 3.
    2%       e# Keep every seconds slice. This discards non-emoticons.
      {$}$   e# Sort the slices by their sorted characters.
             e# This works since '-' < '=' < 'o'.
          0= e# Retrieve the first, minimal slice.

```
> 5 votes

# Answer
## Dyalog APL, ~~35~~ 28 bytes

```
{⊃{⍵[⍒{+/'.??o='⍳⍵}¨⍵]}3,/⍵}

```

This is a monadic function that takes the string on the right and outputs the sleepiest face.

```
    {⊃{⍵[⍒{+/'.??o='⍳⍵}¨⍵]}3,/⍵}'o.=.=.-.-.o.o'
-.-

```
> 4 votes

# Answer
# Prolog, ~~205~~ 189 bytes

**Code**

```
r([X|T],[N|B],M):-N=M,write(X);r(T,B,M).
p(X):-findall(S,sub_atom(X,_,3,_,S),L),findall(E,(nth1(I,L,E),I mod 2=\=0),R),maplist(atom_codes,R,Q),maplist(sum_list,Q,S),min_list(S,M),r(R,S,M).

```

**Explanation**

```
r([X|T],[N|B],M):-N=M,write(X);r(T,B,M).
p(X):-findall(S,sub_atom(X,_,3,_,S),L),              % L = all sublists of length 3
      findall(E,(nth1(I,L,E),I mod 2=\=0),R),        % R = every other element of L
      maplist(atom_codes,R,Q),                       % Q = list of decimal ascii codes
                                                           created from R

      maplist(sum_list,Q,S),                         % S = list of sums of R's lists
      min_list(S,M),                                 % M = minimum sum
      r(R,S,M).                                      % Prints first element in R with sum M

```

**Example**

```
>p('-.=.-.o.o.=.o.-.o.=.-.o.=.o.-').
-.=

```

**Edit:** Saved 16 bytes by unifying r-clauses with OR.
> 4 votes

# Answer
**Clojure, 82 bytes**

```
(fn[x](println(apply str(apply min-key #(reduce +(map int %))(partition 3 2 x)))))

```

Bonus: the following smaller function prints the same face, but with more style!

```
(fn[x](println(apply min-key #(reduce +(map int %))(partition 3 2 x))))

```

Test here.
> 1 votes

# Answer
## Minkolang 0.12, 119 bytes

At first, I tried doing this short and really golfy. I gave up and went for something a bit more "fun", but still relatively golfy.

```
>2@fv$oI2:[9[i$z3[iciz1+q=]++3=tt"^"3zpt]$x$x]IX3140w
o.o1F
o.=1$
=.o1+
=.=12
o.-1:
-.o11
=.-1+
-.=13
-.-1[
/c0i<
\qO].

```

Try it here!

### Explanation

But really, click on the link above and click `Slow`! Anyway...

```
>2@fv

```

This skips over the `fv`, which will be important later.

```
$o                                                  Read in whole input as characters
  I2:                                               Half the stack length
     [                                              Open for loop (for each face)
      9[                                            Open another for loop - 9 repeats
        i$z                                         Stores loop counter in register
           3[                                       Open another for loop - 3 repeats
             ic                                     Copy char 1/2/3
               iz1+q                                Retrieve char from lookup table
                    =                               1 if equal, 0 otherwise
                     ]                              Close for loop
                      ++                            Add twice
                        3=                          1 if equal to 3, 0 otherwise
                          tt      t                 Ternary - executes first part when 0,
                                                    second part otherwise
                            "^"3zp                  Put a ^ next to the face that matched
                                   ]                Close lookup for loop
                                    $x$x            Dump first two characters
                                        ]           Close for loop
                                         IX         Dump the whole stack
                                           31       Push a 3, then a 1
                                             40w    Wormhole to (4,0) in the code

```

What all that did was put a `^` next to the faces that matched. So now the codebox might look like this:

```
>2@fv$oI2:[9[i$z3[iciz1+q=]++3=tt"^"3zpt]$x$x]IX3140w
o.o1F
o.=1$
=.o1+
=.=^2   <-- caret
o.-^:   <-- caret
-.o11
=.-1+
-.=^3   <-- caret
-.-1[
/c0i<
\qO].

```

Without the comments, of course. Now, the `40w` wormhole sent the instruction pointer to `v`, which immediately redirects it onto `F`. Now, `F` is a "gosub" command. It's like a goto, but you can return to where you called it. At the time `F` is encountered, the stack is `[3,1]`, so it jumps to the `1` (maybe) on the second row. As the program counter was heading downwards, it continues, pushing `1`s onto the stack along the way. That is...until it hits a `^`, at which point it's redirected back up, where it pushes each `1` again. The instruction pointer then hits `f`, which restores its position and direction (when `F` was encountered earlier). For convenience, I will take the following code and change its layout. (The `</\` serve to redirect the instruction pointer as needed.)

```
$+                 Sum up the whole stack
  2:               Divide by 2 (because each 1 was pushed twice)
    1+             Add 1 (shift down one row)
      3[           Open for loop - 3 repeats
        i          Push loop counter
         0c        Copy top of stack
           q       Retrieve face character
            O      Output as character
             ].    Close for loop and stop when it's done.

```

I'm actually kinda proud of how I used multiple features unique to Minkolang that I haven't often used before. Mainly the ternary and the gosub. Anyway, there you have it!
> 1 votes

# Answer
## Ruby, 59 bytes

Function returns sleepiest face, using the sorting trick.

```
f=->(s){s.split(?.).each_cons(2).min_by{|e|e.sort}.join(?.)}

```

Called like this:

```
f.call("o.=.=.-.-.o.o")
# => "-.-"

```

Works on awkward eye order due to internal sort of eyes:

```
f.call("=.-.o")
# => "=.-"

```
> 1 votes

# Answer
# Python 2/3, 54 ~~56~~ bytes

```
lambda x:".".join(max(zip(x[::2],x[2::2]),key=sorted))

```

Just wanted to take an alternative tack to xsot's recursive answer.

This takes the best (or worst?) tuple of adjacent pairs of eyes and joins them together.

Replace max with min to return the most sleepy (as is this returns the most awake)

Seems to work, using the following test:

```
for line in """-.- GIVES -.-
    =.- GIVES =.-
    o.o GIVES o.o
    o.-.= GIVES o.-
    =.-.= GIVES =.- OR -.=
    o.-.= GIVES o.-
    -.-.= GIVES -.=
    o.o.- GIVES o.o
    =.=.=.o GIVES =.o
    -.=.=.= GIVES =.=
    =.o.-.= GIVES =.o
    o.-.o.=.= GIVES o.=
    -.o.-.=.= GIVES -.o OR o.- OR =.=
    o.o.o.o.o GIVES o.o
    -.-.-.-.- GIVES -.-
    o.=.=.-.-.o.o GIVES o.o
    -.=.-.o.o.=.o.-.o.=.-.o.=.o.- GIVES o.o""".splitlines():
    inp, _, opts = line.partition(" GIVES ")
    optst = opts.split(" OR ")
    act = f(inp)
    print(inp, "expected", opts, "got", act, "equal?", act in optst)

```

Which gives the following result:

```
-.- expected -.- got -.- equal? True
=.- expected =.- got =.- equal? True
o.o expected o.o got o.o equal? True
o.-.= expected o.- got o.- equal? True
=.-.= expected =.- OR -.= got =.- equal? True
o.-.= expected o.- got o.- equal? True
-.-.= expected -.= got -.= equal? True
o.o.- expected o.o got o.o equal? True
=.=.=.o expected =.o got =.o equal? True
-.=.=.= expected =.= got =.= equal? True
=.o.-.= expected =.o got =.o equal? True
o.-.o.=.= expected o.= got o.= equal? True
-.o.-.=.= expected -.o OR o.- OR =.= got =.= equal? True
o.o.o.o.o expected o.o got o.o equal? True
-.-.-.-.- expected -.- got -.- equal? True
o.=.=.-.-.o.o expected o.o got o.o equal? True
-.=.-.o.o.=.o.-.o.=.-.o.=.o.- expected o.o got o.o equal? True

```
> 1 votes

# Answer
# C, 70 bytes

```
char*f(char*s){char*p=s[3]?f(s+2):s;return*s+s[2]>*p+p[2]?s[3]=0,s:p;}

```

The function returns the most awake face. It modifies the input string in place, so as to return a null-terminated string.
> 1 votes

# Answer
# Brachylog, 10 bytes

```
s₃ᶠġ₂hᵐoᵒh

```

Try it online!

Translated from Dennis' Pyth answer.
> 1 votes

# Answer
# Mathematica, 61 bytes

```
"."
Sort[Partition[#~StringSplit~%,2,1]][[1]]~StringRiffle~%&

```

Goes for the sleepiest one.
> 0 votes

# Answer
# F# 60

```
fun s->Seq.max[for n in 0..2..String.length s-2->s.[n..n+2]]

```

Returns the most awake face (change `max` by `min` for the sleepest)
> 0 votes

# Answer
## ES6, ~~81~~ 72 bytes

```
a=>"-.-,-.=,=.-,-.o,=.=,o.-,=.o,o.=,o.o".split`,`.find(b=>a.includes(b))

```

Probably requires Chrome 45 or Firefox 41.

Thanks to @ETHproductions for saving 9 bytes.
> 0 votes

# Answer
## Perl 5, 127 bytes

```
%h=qw[- 2 = 1];sub r{$b=0;$b+=$h{$_}for split'',pop;$b}($_)=<>;@a='o.o';while(/.../g){push@a,$& if(r$&)>r$a[-1];--pos}say$a[-1]

```

(I'm sure it's doable more briefly.) How it works:

1. Grab each three-character string from the string, with overlap by one (that's what the `--pos` does).
2. Append that three-character string to an array if its value exceeds that of the last element of the array; here, "value" is just the sum of its characters' values in sleepiness.
3. Print the last element of the array.
> 0 votes

# Answer
# \>\<\>, 55 bytes

try it here!

```
<v~i:i&0"."0
 >i:@+:&:@)?v&~i0(?v
 ^?)0i:r~r&~<;ooo$r<

```

Outputs most awake face.

Since the ASCII values for -, =, and o increase respectively, I could use that to my advantage. Basically it adds the values of the current and previous eye part, check if it's a higher value than before, if it is it saves the new value and updates what face that represents, then loops until the end of the input. Then outputs the face that remains. (I'm very pleased at how nicely all the code fits in place)
> 0 votes

# Answer
# Perl 5 `-MList::Util=max -p`, 68 bytes

```
s|..(?=(.))|$t=max$t,ord($&)%15%4+ord($1)%15%4 .$&.$1|eg;$_=$t;s/.//

```

Try it online!

Grabs each set of three characters, ignores the `.` in the middle, maps the addition of the other two to an integer in the range 0-4, concatenates that to the front of the emoticon face, then sorts by that. Grabs the last entry (most awake), removes the number from the front, and outputs it.
> 0 votes

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


title: Is it a wordinian?

text:
# Question
Title: Is it a wordinian?
What is the shortest way to see if an input is a wordinian using any programming language?

A wordinian is a word that contains words of length 1 to the original word's length. For example,

> ## bin
>
> 'I' is a word
> 'in' is a word
> 'bin' is a word

Or,

> ## stage
>
> 'a' is a word
> 'ta' is a word (yes it is)
> 'age' is a word
> 'stag' is a word
> 'stage' is a word

# Input

Your code should take a word and a dictionary as inputs, in any reasonable format.

# Output

The output should be a value to indicate true or false, to tell us if the word is a wordinian.

For more info on wordinians click here.

Here is a list of words that I will be using as inputs and subwords. Also, in response to @xnor, it has to contain subwords of each length, not a chain of subwords. Note that only one word will be used as an input.

# Answer
> 4 votes
# Pyth, ~~20~~ ~~16~~ ~~15~~ ~~13~~ 11 bytes

Thanks to Leaky Nun for saving 4 bytes! Unfortunately, I changed the entire method afterwards, but it still helped.

```
gl{lM}#zQlz

```

Expects input as dictionary followed by word. Outputs True or False.

Try it here!

Explanation:

```
        lz   Collects the length of the word  input
g             and compares it to:
 l             The length of the following:
     # Q        Select all words from the dictionary that
    } z         are contained within the input word.
  lM            Map them to their respective lengths, and
 {              then remove any duplicates.

```

This does not function if the empty string `""` is a valid word.

# Answer
> 11 votes
## Python, 52 bytes

```
lambda w,d:len({len(x)for x in d if x in w})==len(w)

```

An anonymous function that takes a word `w` and dictionary `d`. It takes the words in `d` that are substrings of `w`, makes a set of their lengths, and then checks that there as many distinct lengths as there are letters in `w`.

# Answer
> 4 votes
# Python 3, 108 bytes

```
lambda w,d,r=range:all(any(i in d for i in j)for j in[[w[i:i+s]for i in r(len(w)+1-s)]for s in r(1,len(w))])

```

An anonymous function that takes input, via argument, of a word `w` as a string and a dictionary `d` as a list of strings and returns `True` or `False`.

**How it works**

The first step is a list comprehension that generates a list of lists of all substrings of `w` excluding `w`, grouped by length. For example, for `'stage'`, the list `[['s', 't', 'a', 'g', 'e'], ['st', 'ta', 'ag', 'ge'], ['sta', 'tag', 'age'], ['stag', 'tage']]` is generated. This is achieved by looping over all valid start indices `i` for each substring length `s`, and slicing every `s`-length substring using `w[i:i+s]`. For each list in this list, the presence of each substring in the dictionary is checked; calling `any` returns a hit if at least one match for a given length is found. Finally, calling `all` checks if a match has been found for all substring lengths, and the result of this is returned.

Try it on Ideone

# Answer
> 4 votes
# Ruby, 44 bytes

* 7 Bytes off thanks to @NotThatCharles and his set operator tricks!
* 2 bytes off thanks to @Jordan with the Ruby 2.3 safe navigation operator trick `w[x]&.size` :)

```
->w,d{[*1..w.size]-d.map{|x|w[x]&.size}==[]}

```

It's an anonymous functions which takes a word `w` and a dictionary (array of words) `d`. Creates two arrays: The first containing the numbers 1 up to and including the length of `w`; The second array is `d` with each word mapped to their size if they are a substring of `w`, otherwise `nil`. Then it does set substraction to check whether the second array contains all element of the first array.

# Answer
> 3 votes
## PowerShell ~~v3+~~ v2+, ~~127~~ ~~110~~ ~~70~~ 65 bytes

```
param($a,$d)($d|?{$a-match$_}|select length -U).count-eq$a.length

```

*(I see now that my approach is similar to @xnor's, though I developed it independently)*

Takes input word `$a` and dictionary `$d`, expecting `$d` as an array (see examples below). Loops through the entirety of `$d` and performs a `Where-Object` to pull out the entries where the current word `$_` is a regex `-match` against the input word `$a` (i.e., is the current word a substring of the input word).

We collect all of those substring words and pipe them to `Select-Object` on the `length` parameter and the `-U`nique constraint. That will pull out the unique lengths of each substring. For example, for input word `comb`, this will be an array of `(4,2)` for `('comb','om')`.

We take the `.count` of that resultant array and compare it against the input word's `.length`. If it's equal to, that means that every substring length is in the dictionary, so `$TRUE`, otherwise we're missing at least one, so `$FALSE`. That Boolean value is left on the pipeline and output is implicit.

NB - This *should* work in v2+, since the `-in` operator is no longer present, but I've not tested that version.

### Examples

```
PS C:\Tools\Scripts\golfing> .\is-it-a-wordinian.ps1 'stage' (gc .\words.txt)
True

PS C:\Tools\Scripts\golfing> .\is-it-a-wordinian.ps1 'metal' (gc .\words.txt)
True

PS C:\Tools\Scripts\golfing> .\is-it-a-wordinian.ps1 'comb' (gc .\words.txt)
False

```

# Answer
> 2 votes
## Perl, 86 bytes

Requires `-E` at no extra cost.

```
chop(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x

```

Accepts all input via STDIN. First input is target word, rest of input is dictionary. Prints `1` on success, empty string on failure.

### Usage

```
perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'stage
a
ta
age
stag
stage'
1
perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'stage
a
at
age
stag
stage'

perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'bin
i
in
bin'
1

```

# Answer
> 2 votes
# Mathematica, 90 bytes

```
Sort[MemberQ[DictionaryWordQ/@StringPartition[#,t,1],True]~Table~{t,StringLength@#}][[1]]&

```

Uses *Mathematica's* builtin `DictionaryWordQ`.

Taking input `d` as dictionary is 5 bytes shorter, but much slower for long lists:

```
m=MemberQ;Sort[m[d~m~#&/@StringPartition[#,t,1],True]~Table~{t,StringLength@#}][[1]]&

```

# Answer
> 2 votes
# MATL, 15 bytes

*1 byte saved using an idea from @xnor's answer.*

```
XXgc32>!suz1Gn=

```

Outputs `1` or `0` for truthy or falsy.

**Try it online!**

```
XX      % Take the two inputs implicitly. Apply the second as a regex into the
        % first. Since the second input is a cell array, each of its contents is
        % applied separately as a regex. So for each dictionary word ("sub-word")
        % this outputs the sub-word if found in the original word, or else an
        % empty array. Gives a cell array of cells of strings
g       % Remove one level of nestedness
c       % Convert to char. This concatenates all found sub-words as rows of a 2D
        % char array, padding with spaces as needed
32>!s   % For each row, count how many non-space characters there are. This is
        % the length of each sub-word
uz      % Number of distinct non-zero elements
1Gn     % Push length of the original word
=       % Are they equal? Implicitly display

```

# Answer
> 1 votes
## JavaScript (Firefox 30-57), 68 bytes

```
(w,a)=>new Set((for(x of a)if(~w.search(x))x.length)).size==w.length

```

Using a generator comprehension avoids creating an intermediate array. 73 byte ES6 version:

```
(w,a)=>new Set(a.filter(x=>~w.search(x)).map(x=>x.length)).size==w.length

```

# Answer
> 1 votes
# Perl, ~~42~~ 41 bytes

Includes +2 for `-p0`

Give word followed by the dictionary on STDIN:

```
(echo stage; cat dictionary.txt) | ./wordinian.pl

```

(When testing on unix make sure dictionary.txt uses `\n` as line terminator, not `\r\n`)

`wordinian.pl`:

```
#!/usr/bin/perl -p0
s%\G.%!/^.*(.{$+[0]})\H*
\1
/%eg;$_=!//

```

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
ŒÃ€gZLåP

```

Word as first input, dictionary-list as second input.

Try it online or verify a few more test cases.

**Explanation:**

```
Œ         # Get all possible substrings of the (implicit) input-string
 Ã        # Only keep the ones which are also in the (implicit) dictionary-list
  €g      # Get the length of each remaining string
    Z     # Push the maximum length (without popping the list)
     L    # Pop and push a list in the range [1, maximum-length]
      å   # Check for each value if it's in the list of lengths
       P  # And check if this is truthy for all
          # (then output the result implicitly as result)

```

# Answer
> 1 votes
# Kotlin, 51 bytes

```
{w,d->w.indices.all{w.windowed(it+1).any{it in d}}}

```

Try it online!

# Answer
> 0 votes
# SQF, 147 bytes

Using the function-as-a-file format:

```
params["w","d"];a=[];c=count w;for"i"from 1 to c do{a=a+[""];for"j"from 0 to c-i do{q=w select[j,i];if(q in d)then{a set[i-1,q]}}};c==count(a-[""])

```

Call as: `["WORD", DICTIONARY] call NAME_OF_COMPILED_FUNCTION`

Ungolfed:

```
//name parameters
params["w", "d"];
a = []; c = count w;
//for each length of subword
for "i" from 1 to c do {
    //add entry to the `a`
    a = a + [""];
    //for each starting position for that length
    for "j" from 0 to c - i do {
        //get subword
        q = w select [j, i];
        //check if in dictionary
        if(q in d) then {
            //set the entry to the wubword
            a set [i - 1, q]
        }
    }
};
//check if length of word is equal to number of subwords
c == count (a - [""])

```

---
Tags: code-golf, subsequence, word-search
---


title: Squares in the Squares

text:
# Question
Title: Squares in the Squares
Given input of a positive integer `n`, write a program that completes the following process.

* Find the smallest positive integer greater than `n` that is a perfect square and is the concatenation of `n` and some other number. The order of the digits of `n` may not be changed. The number concatenated onto `n` to produce a perfect square may be called `r_1`.
* If `r_1` is not a perfect square, repeat the above process with `r_1` as the new input to the process. Repeat until `r_k` is a perfect square, denoted `s`.
* Print the value of `sqrt(s)`.

Input can be taken in any format. You can assume that `n` is a positive integer. If any `r_k` has a leading zero (and `r_k`≠0), the zero can be ignored.

---

**Test cases**

Here are some test cases. The process demonstrates the above steps.

```
Input:   23
Process: 23, 2304, 4
Output:  2

Input:   10
Process: 10, 100, 0
Output:  0

Input:   1
Process: 1, 16, 6, 64, 4
Output:  2

Input:   5
Process: 5, 529, 29, 2916, 16
Output:  4

Input:   145
Process: 145, 145161, 161, 16129, 29, 2916, 16
Output:  4

Input:   1337
Process: 1337, 13373649, 3649, 36493681, 3681, 368102596, 2596, 25969216, 9216
Output:  96

```

---

This is code golf. Standard rules apply. The shortest answer (in bytes) wins.

# Answer
> 2 votes
# MATL, 35 ~~44.0~~ bytes

```
XK``x@2^tVKVXf1=a~]VKVnQ0h)UXKX^t1\

```

**Try it online!**

```
XK        % implicit input: n. Copy to clipboard K
`         % do...while. Each iteration applies the algorithm
  `       %   do...while. Each iteration tests a candidate number
    x     %     delete top of stack
    @2^   %     iteration index squared
    t     %     duplicate
    V     %     convert to string
    K     %     paste from clipboard K: n or r_k
    V     %     convert to string
    Xf    %     find one string within another. Gives indices of starting matches, if any
    1=a~  %     test if some of those indices is 1. If not: next iteration
  ]       %   end. We finish with a perfect square that begins with digits of n or r_k
  V       %   convert to string
  K       %   paste from clipboard K: n or r_k
  VnQ0h   %   index of rightmost characters, as determined by r_k
  )       %   keep those figures only
  U       %   convert to number. This is the new r_k
  XK      %   copy to clipboard K, to be used as input to algorithm again, if needed
  X^      %   square root
  1\      %   fractional part. If not zero: apply algorithm again
          % implitic do...while loop end
          % implicit display

```

# Answer
> 2 votes
# Pyth, 26 bytes

```
LsI@b2 fy=sh.fys+QZ1\0)@Q2

```

Test suite

Output is as a float. If output as an int is desired, it would be 1 extra byte.

Explanation:

```
LsI@b2 fy=sh.fys+QZ1\0)s@Q2
                               Q = eval(input())
L                              def y(b): return
   @b2                         Square root of b
 sI                            Is an integer.
       f              )        Find the first positive integer T that satisfies
           h.f     1\0         Find the first digit string Z that satisfies
                +QZ            Concatenation of Q and Z
               s               Converted to an integer
              y                Is a pergect square.
          s                    Convert the string to an integer
         =                     Assign result to the next variable in the code, Q
        y                      Repeat until result is a perfect square
                               (The space) Discard return value
                        @Q2    Take square root of Q and print.

```

# Answer
> 2 votes
## Python 2, 98

```
i=input();d=o=9
while~-d:
 n=i;d=o+1;o=i=0
 while(n*d+i)**.5%1:i=-~i%d;d+=9*d*0**i
print'%d'%n**.5

```

Try it online.

# Answer
> 1 votes
# Python, 200 198 178 bytes

```
import math
def r(i):
 j=int(i**.5)+1
 while str(j*j)[:len(str(i))]!=str(i):j+=1
 return int(str(j*j)[len(str(i)):])
q=r(int(input()))
while math.sqrt(q)%1!=0:q=r(q)
print(q**.5)

```

# Answer
> 1 votes
# Brachylog, 26 bytes

```
{~a₀X√ℕ∧YcX∧Yh?∧Ybcℕ≜!}ⁱ√ℕ

```

Try it online!

The last test case was omitted in the TIO link because it alone takes more than a minute to execute. I ran it on my laptop and the correct result was achieved in no more than two hours.

```
{                             The input
 ~a₀                          is a prefix of
    X√                        X, the square root of which
      ℕ                       is a whole number.
       ∧YcX                   Y concatenated is X.
           ∧Yh?               The input is the first element of Y.
               ∧Yb            The rest of Y,
                  c           concatenated,
                      }       is the output
                   ℕ          which is a whole number.
                    ≜         Make sure that it actually has a value,
                     !        and discard all choice points.
{                     }ⁱ      Keep feeding that predicate its own output until
                        √     its output's square root
                         ℕ    is a whole number
                              which is the output.

```

The second-to-last  is necessary for when the initial input is already a perfect square, so the first perfect square which has it as a prefix is itself, and `!` is necessary to make sure that backtracking iterates instead of finding a larger concatenated square, but I don't really know why  is necessary, I just know that 5 produces a wrong answer without it.

# Answer
> 0 votes
# Perl 6, 101 bytes

```
my&q={$^k;$_=({++($||=$k.sqrt.Int)**2}.../^$k/)[*-1];+S/$k//}
put (q(get),&q...!(*.sqrt%1))[*-1].sqrt

```

```
my &q = {
  $^k; # declare placeholder parameter
  # set default scalar to:
  $_ = ( # a list
    # code block that generates every perfect square
    # larger than the input
    { ++( $ ||= $k.sqrt.Int )**2 }
    ...   # produce a sequence
    /^$k/ # ending when it finds one starting with the argument
  )[*-1]; # last value in sequence

  # take the last value and remove the argument
  # and turn it into a number to remove leading zeros
  +S/$k//
}

put (     # print the result of:
  q(get),     # find the first candidate
  &q          # find the rest of them
  ...         # produce a sequence
  !(*.sqrt%1) # ending with a perfect square
)[*-1]        # last value in sequence
.sqrt         # find the sqrt

```

# Answer
> 0 votes
## ES7, 116 bytes

```
n=>{do{for(i=n;!(r=(''+Math.ceil((i*=10)**0.5)**2)).startsWith(+n););n=r.replace(+n,'');r=n**0.5}while(r%1);return r}

```

Yes, I could probably save a byte by using `eval`.

---
Tags: code-golf, number, sequence
---


# Question
Title: Print the total length of all "quoted" characters
# Rules

In this challenge, I'm going to redefine the definition of "quotes" a bit.

* **Quotation marks** (AKA **quotes**) are *any identical characters* used in pairs in various writing systems to set off direct speech, a quotation, or a phrase. The pair consists of an opening quotation mark and a closing quotation mark, *which is the same character(case-sensitive).*
* If there are quote-pairs overlapping each other,

+ If a pair nesting another, both pairs are still valid.
    + If a pair not nesting another, the first starting pair remains valid. The other is no longer considered as a pair.
* When counting quoted characters(length of a pair of quotes),

+ The quotes themselves don't count.
    + Each pair's length is counted independently. Overlapping doesn't affect another.

# Goal

Your goal is to print the total length of all valid quotes. This is code golf, therefore the code with the fewest bytes wins.

# Examples

```
Legend:
    <foo>: Valid quotes
    ^    : Cannot be paired character

Input   : ABCDDCBA
`A`  (6): <BCDDCB>
`B`  (4):  <CDDC>
`C`  (2):   <DD>
`D`  (0):    <>
Output  : 12

Input   : ABCDABCD
`A`  (3): <BCD>
`B`  (0):  ^   ^
`C`  (0):   ^   ^
`D`  (0):    ^   ^
Output  : 3

Input   : AABBBBAAAABA
`A`  (0): <>    <><> ^
`B`  (0):   <><>    ^
Output  : 0

Input   : ABCDE
Output  : 0

Input   : Print the total length of all "quoted" characters
`r` (40):  <int the total length of all "quoted" cha>
`n` (14):    <t the total le>
`t` (15):     < >   <o>       <h of all "quo>
` `  (7):      ^   <total>      <of>   ^        ^
`h`  (0):        ^             ^                  ^
`e`  (8):         < total l>                 ^          ^
`o`  (0):            ^           ^         ^
`a`  (0):              ^            ^              ^ ^
`l`  (0):               ^ ^          <>
`"`  (0):                               ^      ^
`c`  (0):                                        ^    ^
Output  : 84

Input   : Peter Piper picked a peck of pickled peppers
`P`  (5): <eter >
`e`  (9):  <t>     ^      <d a p>           <d p>  ^
`r`  (0):     ^     ^
` `  (3):      ^     ^      <a>    <of>       ^
`i`  (5):        <per p>
`p`  (3):         <er >        ^       ^       ^ <>
`c`  (8):               <ked a pe>       ^
`k`  (7):                ^        < of pic>
`d`  (0):                  ^                 ^
Output  : 40

Input   : https://www.youtube.com/watch?v=dQw4w9WgXcQ
`h` (27): <ttps://www.youtube.com/watc>
`t`  (0):  <>            ^          ^
`/`  (0):       <>               ^
`w` (14):         <><.youtube.com/>         <4>
`.`  (7):            <youtube>
`o`  (0):              ^       ^
`u`  (1):               <t>
`c`  (0):                     ^      ^             ^
`Q`  (8):                                  <w4w9WgXc>
Output  : 57

```

# Answer
> 1 votes
# Jelly, 12 bytes

```
œṡ¹¡ḢṖẈ;ß€ƲS

```

Try it online!

# Answer
> 4 votes
# APL (Dyalog Unicode), 36 bytesSBCS

Full program. Prompts for input from stdin.

```
≢∊t⊣{t,←'(.)(.*?)\1'⎕S'\2'⊢⍵}⍣≡⍞⊣t←⍬

```

Try it online!

`t←⍬` set up an accumulator `t` (for **t**otal)

`⍞⊣` discard that in favour of string input from stdin (symbol: quote in console)

`{``}⍣≡` apply the following anonymous lambda until stable (fix-point; previous ≡ next)

`⊢⍵` on the argument

…`⎕S'\2'` PCRE **S**earch for the following, returning group 2 for each match:

`(.)` any character (we'll call this group 1)
`(.*?)` as few characters as possible (we'll call this group 2)
`\1` the group 1 character

`t,←` update `t` by append that to `t`'s current value

`t⊣` discard that (the final list of no matches) in favour of `t`

count the number of characters in that

# Answer
> 2 votes
# JavaScript (ES6), 64 bytes

```
f=([c,...a],i=a.indexOf(c))=>c?(~i&&i+f(a.splice(0,i+1)))+f(a):0

```

Try it online!

### Commented

```
f = (                       // f is a recursive function taking either the input string
                            // or an array of characters, split into
  [c, ...a],                // c = next character and a[] = all remaining characters
  i = a.indexOf(c)          // i = index of the 1st occurrence of c in a[] (-1 if not found)
) =>                        //
  c ?                       // if c is defined:
    ( ~i &&                 //   if i is not equal to -1:
      i +                   //     add i to the final result
      f(a.splice(0, i + 1)) //     remove the left part of a[] up to i (included) and
    )                       //     do a recursive call on it
    + f(a)                  //   add the result of a recursive call on a[]
  :                         // else:
    0                       //   stop recursion

```

# Answer
> 2 votes
# Brain-Flak, 100 bytes

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

```

Try it online!

### Commented

```
# Loop over each character in input and sum iterations:
({{

  # Evaluate matching quote search as zero
  <

    # Move opening "quote" to right stack
    ({}<>)<>

    # Until match or end of search string found:
    # Note that the character to search for is stored as the sum of the top two entries in the right stack.
    (

      ({

        <>((

          # Character to search for
          {}({})

          # Subtract and move next character
          <>[({}<>)]

        # Push difference twice
        ))

        # Add 1 to evaluation of this loop
        ()

        # If no match, cancel out both 1 and pushed difference to evaluate iteration as zero (keep one copy of difference for next iteration)
        # (compare to the standard "not" snippet, ((){[()](<{}>)}{}) )
        # Then move to other stack
        {[{}()](<>)}{}

        # If a match was found, this will instead pop a single zero and leave a zero to terminate the loop, evaluating this iteration as 0+1=1.

      # Push 1 if match found, 0 otherwise
      }{})

      # If match found, move to left stack and push 0 denote end of "quoted" area.
      {(<>)}

    # Push the same 1 or 0 as before
    )

    # Remove representation of opening "quote" searched for
    # The closing quote is *not* removed if there is a match, but this is not a problem because it will never match anything.
    <>{}

  >

  # Move searched text back to left stack, evaluating each iteration as either the 1 or 0 from before.
  # This counts characters enclosed in "quotes" if a match is found, and evaluates as 0 otherwise.
  {<>({}<<>({}<>)>)<>}

  # Remove 0/1 from stack; if 1, cancel out the 1 added by the closing "quote"
  <>[{}]

# Repeat until two consecutive zeroes show up, denoting the end of the stack.
# (Because closing quotes are not removed, it can be shown that all other zeroes are isolated on the stack.)
}{}})

```

# Answer
> 2 votes
# Ruby, 49 bytes

Recursive solution. Find quote groups, count their lengths, and then recursively look for sub-group lengths and sum everything together.

```
f=->s{s.scan(/(.)(.*?)\1/).sum{|a,b|b.size+f[b]}}

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), ~~65~~ ~~64~~ 62 bytes

```
f=s=>(s=/(.)(.*?)\1(.*)/.exec(s))?f(s[3])+f(s=s[2])+s.length:0

```

Try it online!

Original approach (64 bytes):

```
f=(s,r=/(.)(.*?)\1/g,t=r.exec(s))=>t?f(t=t[2])+t.length+f(s,r):0

```

Try it online!

```
f=s=>                              // Main function:
 (s=/(.)(.*?)\1(.*)/.exec(s))?     //  If a "quoted" segment can be found:
  f(s[3])                          //   Return the recursive result outside this segment,
  +f(s=s[2])                       //   plus the recursive result of this segment,
  +s.length                        //   plus the length of this segment
 :0                                //  If not: no quoted segment, return 0.

```

# Answer
> 1 votes
# Jelly, 17 bytes

```
œṡḢẈṖ$Ḣ+ɼṛƲ)Ẏ$F¿®

```

Try it online!

A full program that takes a single argument, the input string wrapped in a list, and returns the number of quotes characters as an integer.

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


# Question
Title: Letter Boxed, part 2: this time, solve it
This challenge is a sequel to Letter Boxed Validator.

The New York Times has a daily online game called Letter Boxed (the link is behind a paywall; the game is also described here), presented on a square as follows:

You are given 4 groups of 3 letters (each group corresponds to one side on the picture); no letter appears twice. The aim of the game is to find words made of those 12 letters (and those letters only) such that:

* Each word is at least 3 letters long;
* Consecutive letters cannot be from the same side;
* The last letter of a word becomes the first letter of the next word;
* All letters are used at least once (letters can be reused).

In this challenge, you are given the letters, and a dictionary. The goal is to output a valid solution, which minimizes the number of words used. If there is no solution, any consistent output is acceptable.

For the input `{{I,C,O}, {M,R,E}, {G,N,S}, {A,P,L}}`, a valid solution is PILGRIMAGE, ENCLOSE. Another valid solution is SOMNOLENCE, EPIGRAM. The following are not valid:

* PILGRIMAGE, ECONOMIES (can't have CO since they are on the same side)
* GRIMACES, SOPRANO (L has not been used)
* PILGRIMAGE, ENCLOSURE (U is not one of the 12 letters)
* ENCLOSE, PILGRIMAGE (last letter of 1st word is not first letter of 2nd word)
* CROPS, SAIL, LEAN, NOPE, ENIGMA (number of words is not minimal)

## Input

Input consists of a dictionary, and of 4 groups of 3 letters. It can be in any suitable format.

## Output

A list of words giving a solution to the challenge. There may be several acceptable solutions: you should output at least one, but may output several if you want.

## Test cases

The test cases use this dictionary. If using a large dictionary is too difficult on TIO, you may use instead the dictionary `{PILGRIMAGE, ENCLOSE, SOMNOLENCE, EPIGRAM, ECONOMIES, GRIMACES, SOPRANO, ENCLOSURE, CROPS, SAIL, LEAN, NOPE, ENIGMA, OVERFLOWS, STACK, QUESTIONABLY, QUARTZ, ZIGZAG, GHERKIN, CODE, GOLF, NO, I, DO, NOT, IN}`, but your code should in principle work on a larger dictionary.

Note that the solution is not necessarily unique; these are possible solutions.

Input=`{{I,C,O}, {M,R,E}, {G,N,S}, {A,P,L}}`. Solution: PILGRIMAGE, ENCLOSE

Input:`{{OSA}, {FVK}, {WEL}, {CTR}}`. Solution: OVERFLOWS, STACK.

Input: `{{BCD}, {FGH}, {JKL}, {MNP}}`. No solution.

Input: `{{AQT}, {LUI}, {BOE}, {NSY}}`. Solution: QUESTIONABLY

Input: `{{QGN}, {ZUR}, {AHK}, {ITE}}`. Solution: QUARTZ, ZIGZAG, GHERKIN.

## Scoring:

This , lowest score in bytes wins!

# Answer
> 2 votes
# Jelly, 38 bytes

```
iⱮⱮL>2ƊƇẠƇ’:3IẠƲƇŒPU=ḢɗƝẠ$ƇFQL=ʋƇ12ịḷḢ

```

Try it online!

A dyadic link taking the flattened letters as left argument and the dictionary as right. Returns a list of strings of one of the shortest solutions, or a zero if there is no solution.

Full explanation to follow once it’s a bit better golfed.

---
Tags: code-golf, game
---


title: Decode a 7-segment display

text:
# Question
Title: Decode a 7-segment display
You probably all know the 7-segment display which can display among other things all digits from \\$0\dots 9\\$:

# Challenge

We only consider the segments \\$\texttt{A}\dots\texttt{G}\\$, your task is to decode a single digit given which segments are turned on.

This can be encoded as an 8-bit integer, here's a table of each digit with their binary representation and the corresponding little-endian and big-endian values:

$$ \begin{array}{c|c|rr|rr} \text{Digit} & \texttt{.ABCDEFG} & \text{Little-endian} && \text{Big-endian} & \\ \hline 0 & \texttt{01111110} & 126 & \texttt{0x7E} & 126 & \texttt{0x7E} \\ 1 & \texttt{00110000} & 48 & \texttt{0x30} & 12 & \texttt{0x0C} \\ 2 & \texttt{01101101} & 109 & \texttt{0x6D} & 182 & \texttt{0xB6} \\ 3 & \texttt{01111001} & 121 & \texttt{0x79} & 158 & \texttt{0x9E} \\ 4 & \texttt{00110011} & 51 & \texttt{0x33} & 204 & \texttt{0xCC} \\ 5 & \texttt{01011011} & 91 & \texttt{0x5B} & 218 & \texttt{0xDA} \\ 6 & \texttt{01011111} & 95 & \texttt{0x5F} & 250 & \texttt{0xFA} \\ 7 & \texttt{01110000} & 112 & \texttt{0x70} & 14 & \texttt{0x0E} \\ 8 & \texttt{01111111} & 127 & \texttt{0x7F} & 254 & \texttt{0xFE} \\ 9 & \texttt{01111011} & 123 & \texttt{0x7B} & 222 & \texttt{0xDE} \end{array} $$

# Rules & I/O

* Input will be one of
    + single integer (like in the table above one of the two given orders)
    + a list/array/.. of bits
    + a string consisting of characters `ABCDEFG` (you may assume it's sorted, as an example `ABC` encodes \\$7\\$), their case is your choice (not mixed-case)
* Output will be the digit it encodes
* You may assume no invalid inputs (invalid means that there is no corresponding digit)

# Tests

Since this challenge allows multiple representations, please refer to the table.

# Answer
> 10 votes
# JavaScript (ES6), 26 bytes

Takes input in little Endian.

```
n=>'0958634172'[n*3%77%10]

```

Try it online!

# Answer
> 8 votes
# Python 3, 18 bytes

```
b'~0my3[_p{'.find

```

Try it online!

Uses little-endian inputs. Contains a raw `\x7F` byte.

# Python 2, 27 bytes

```
map(ord,'~0my3[_p{').index

```

Try it online!

# Answer
> 7 votes
# Wolfram Language (Mathematica), 41 bytes

```
9[,6,0,8,2,3,1,7,5,4][[#~Mod~41~Mod~11]]&

```

Try it online!

Uses the little-endian column of integers as input. Ignore the syntax warning.

For an input X, we first take X mod 41 and then take the result mod 11. The results are distinct mod 11, so we can extract them from a table. For example, 126 mod 41 mod 11 is 3, so if we make position 3 equal to 0, then we get the correct answer for an input of 126.

The table is `9[,6,0,8,2,3,1,7,5,4]`. Part 0 is the head, which is `9`. Part 1 is missing, so it's `Null`, to save a byte: we never need to take part 1. Then part 2 is `6`, part 3 is `0`, and so on, as usual.

---

Jonathan Allan's answer gives us `1[4,9,8,6,2,0,5,3,7][[384~Mod~#~Mod~13]]&`. This isn't any shorter, but it does avoid the syntax warning!

---

# Wolfram Language (Mathematica), ~~27~~ 25 bytes

```
Mod[Hash[")dD}"#]+2,11]&

```

(There's some character here that doesn't quite show up, sorry. Click on the link below and you'll see it.)

Try it online!

This is all about brute-forcing some string to go inside `Hash` so that the hashes end up having the right values mod 11. More brute forcing can probably get us to an even shorter solution.

# Answer
> 4 votes
# Jelly, 12 bytes

```
“0my3[_p¶{‘i

```

Accepts a little-endian integer.

**Try it online!**

This is the naive implementation, there *might* be a way to get a terser code.

# Answer
> 4 votes
# Java (JDK), 32 bytes

```
n->"99608231754".charAt(n%41%11)

```

Try it online!

## Credits

# Answer
> 4 votes
# Python 2, 31 bytes

```
lambda n:'99608231754'[n%41%11]

```

Try it online! takes input as little-endian.

# Answer
> 4 votes
# JavaScript (Node.js), 25 bytes

```
n=>'1498620537'[384%n%13]

```

Accepts a little-endian integer.

**Try it online!**

---

Ports for 31 bytes in Python with `lambda n:'1498620537'[384%n%13]`

# Answer
> 3 votes
# Whitespace, 152 bytes

Obligatory "the S's, T's, and L's aren't really there, they're just visible representations of the commands".

```
S S S T	S S L
S S S T	S T	L
S S S T	T	T	L
S S S T	L
S S S T	T	L
S S S T	S L
S S S T	S S S L
S S S L
S S S T	T	S L
S S S L
S S S T	S S T	L
S S S L
S L
S T	L
T	T	T	T	T	S S S T	S T	S S T	L
T	S T	T	S S S T	S T	T	L
T	S T	T	L
S S L
S L
S L
T	S S L
S T	L
S T	L
S S S T	L
T	S S T	L
S L
L
L
S S S L
S L
L
T	L
S T

```

Try it online!

Ends in an error.

Equivalent assembly-like syntax:

```
	push 4
	push 5
	push 7
	push 1
	push 3
	push 2
	push 8
	push 0
	push 6
	push 0
	push 9
	push 0
	dup
	readi
	retrieve
	push 41
	mod
	push 11
	mod
slideLoop:
	dup
	jz .slideLoop
	slide 1
	push 1
	sub
	jmp slideLoop
.slideLoop:
	drop
	printi

```

# Answer
> 3 votes
# brainfuck, ~~474~~ ~~176~~ ~~154~~ ~~151~~ ~~149~~ 137 bytes

Takes an input string of **eight** `0` and `1` including the first `0` for decimal point.

*(like in the second column of the table in the post)*

Outputs digit from 0 to 9.

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

```

Try it online!

### Algorithm

By observing state of a particular segment we can split a set of possible digits into smaller subsets. Below is the static binary search tree used in my code. Left subtree corresponds to segment ON state, right corresponds to segment OFF state.

```
                                         0,1,2,3,4,5,6,7,8,9
                                                  |
                                         /-------[A]-------------------------\
                                 0,2,3,5,6,7,8,9                             1,4
                                        |                                     |
                         /-------------[B]----------------\             /----[G]----\
                   0,2,3,7,8,9                            5,6          4             1
                        |                                  |
              /--------[E]--------\                  /----[E]----\
            0,2,8                3,7,9              6             5
              |                    |
        /----[F]----\        /----[F]----\
      0,8            2      9            3,7
       |                                  |
 /----[G]----\                      /----[G]----\
8             0                    3             7

```

### Some observations useful for golfing

1. Bits C and D are redundant and can be ignored.
2. Leading zero (bit for decimal point) can be (ab)used as value 48, important both for parsing input and preparing output.
3. When leaf is reached and digit is printed, we just need to skip all further conditions. It can be done by moving data pointer far enough to the area of zeros so that it cannot come back.
4. For the compatibility it is better to use zeros on the right, because some BF implementations doesn't support negative data pointers.
5. Hence it is better to store output value in the rightmost cell, so we can easily reach area of zeros to the right.
6. Hence it is better to check bits from left to right: A,B,E,F,G so we can reach output cell easier.
7. Different digits may share output code. For example, 5 and 6 are in the same subtree. We may do `+++++` for both values and then `+` for six only.
8. We may decrease number of `+` commands if we add 2 to output value in advance. In that case we need to decrease it for `0` and `1` only and get advantage for other digits.

# Answer
> 2 votes
# Retina, 96 bytes

```
^(A)?(B)?C?(D|())(E|())(F)?(G)?
$.($.5*$.8*$(6*$7$2$2)$#6*$.3*$($.2*$(___$7)5*$7)$#4*$(6*$1_3*$8

```

Try it online! May not be the best way, but it's an interesting way of programming in Retina. Explanation:

```
^(A)?(B)?C?(D|())(E|())(F)?(G)?

```

Tries to capture the interesting cases. The positive captures simply capture the letter if it's present. The length of the capture is therefore 1 if it's present and 0 if it's absent. The special cases are captures 4 and 6 which exist only if D or E are absent respectively. These can only be expressed in decimal as `$#4` and `$#6` but that's all we need here. The captures are then built up into a string whose length is the desired number. For instance, if we write `6*$1` then this string has length 6 if A is present and 0 if it is absent. In order to choose between different expressions we use either `$.` (for the positive captures) or `$#` (for the negative captures) which evaluate to either 0 or 1 and this can then be multiplied by the string so far.

```
$.5*$.8*$(6*$7$2$2)

```

`F` is repeated 6 times and `B` twice (by concatenation as it's golfier). However, the result is ignored unless both `E` and `G` are present. This handles the cases of `2`, `6` and `8`.

```
$#6*$.3*$($.2*$(___$7)5*$7)

```

`F` is repeated 5 times, and if `B` is present, it is added a sixth time plus an extra 3 (represented by a constant string of length 3). However, the result is ignored unless `D` is present and `E` is absent. This handles the cases of `3`, `5` and `9`.

```
$#4*$(6*$1_3*$8

```

`A` is repeated 6 times, and `G` is repeated 3 times, and an extra `1` added (represented by a constant character between the two because it's golfier). However the result is ignored unless `D` is absent. This handles the cases of `1`, `4` and `7`.

```
$.(

```

The above strings are then concatenated and the length taken. if none of the above apply, no string is generated, and its length is therefore `0`.

The resulting strings (before the length is taken) are as follows:

```
1   _
2   BB
3   ___
4   _GGG
5   FFFFF
6   FFFFFF
7   AAAAAA_
8   FFFFFFBB
9   ___FFFFFF

```

# Answer
> 2 votes
# MATL, 14 bytes

```
'/lx2Z^o~z'Q&m

```

Input is a number representing the segments in little-endian format.

Try it online!

### Explanation

```
'/lx2Z^o~z'  % Push this string
Q            % Add 1 to the codepoint of each char. This gives the array
             % [48 109 ... 123], corresponding to numbers 1 2 ... 9. Note that
             % 0 is missing
&m           % Implicit input. Call ismember function with second output. This
             % gives the 1-based index in the array for the input, or 0 if the
             % input is not present in the array.
             % Implicit display

```

# Answer
> 2 votes
# Perl 5 -pl, 24 bytes

```
$_=index'~0my3[_p{',chr

```

Try it online!

Takes little-endian integers.

# Answer
> 2 votes
# Ruby, 29 bytes

```
->n{"0083416243795"[n%23-10]}

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~17~~ ~~16~~ ~~15~~ 12 bytes

```
•NŽyf¯•I41%è

```

-1 byte thanks to *@ErikTheOutgolfer*.
-1 byte by creating a port of *@MishaLavrov*'s Mathematica answer.
-3 bytes thanks to *@Grimy*.

Try it online or verify all test cases.

**Explanation:**

```
•NŽyf¯•       # Push compressed integer 99608231754
       I41%   # Push the input modulo-41
           è  # Index this into the integer (with automatic wraparound)
              # (and output the result implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•NŽyf¯•` is `99608231754`.

# Answer
> 1 votes
# Japt, 15 bytes

Takes the big-endian value as input.

```
"~¶ÌÚúþÞ"bUd

```

Try it

---

## Explanation

The string contains the characters at each of the codepoints of the big-endian values; `Ud` gets the character at the input's codepoint and `b` finds the index of that in the string.

# Answer
> 1 votes
# Neim, 15 bytes

```
&bᚫJOℤ£ᛖ)

```

Explanation:

```
&bᚫJOℤ£ᛖ)      create list [126 48 109 121 51 91 95 112 127 123]
                      index of

```

Try it online!

# Answer
> 1 votes
# Stax, 12 bytes

```
å╬JÄk☺é[£¿⌐→

```

Run and debug it

Input is little endian integer.

It uses the same string constant as Luis' MATL solution.

# Answer
> 1 votes
# TI-BASIC (TI-83+/84+ series), 15 bytes

```
int(10fPart(194909642ln(Ans

```

Uses little-endian input. Hashes are fairly common in TI-BASIC, so I wrote a hash function brute-forcer for cases like this.

We get a bit lucky here, as the multiplier is 9 digits long rather than the expected 10.

```
      fPart(194909642ln(Ans   hash function mapping onto [0,1)
int(10                        take first digit after decimal point

```

# Answer
> 0 votes
# Charcoal, 17 bytes

```
Ｉ⌕”y~¶ÌÚúþÞ”℅Ｎ

```

Try it!

Port of the Japt answer.

---
Tags: code-golf, encoding
---


title: Inverse-quotes-quine, inverted (pt. 2)

text:
# Question
Title: Inverse-quotes-quine, inverted (pt. 2)
Based on a comment by Jo King on my previous question (called 'Inverse-quotes-quine'), I present this new question. The rules are similar, but just, the opposite:

* If your program is run normally, all of the code **not** in the speech marks (`"` \- double quotes) should be printed.
* If your program is wrapped in double quotes (in turn inverting the speech marks), the code that is normally n̶o̶t̶ in quotes should be printed.

E.g:

Let's say you have the following code:

```
fancyStuff("myCode"); "I like".isGreat();

```

If I run it, I would expect an output of:

```
fancyStuff(
);
.isGreat();

```

However, if I wrapped it in quotes, I would get:

```
"fancyStuff("myCode"); "I like".isGreat();"

```

When this code is run, the expected output would be:

```
myCode
I like

```

Obviously, the above example is not a functional response in any language. Your job is to write the code that performs in this way.

# Rules

* Standard loopholes apply.
* The printed values, in both quoted and unquoted forms, must be non-empty, or consist solely of whitespace. This also means that all programs must include at least one set of quotes.
* However, trailing/preceeding whitespace is allowed.
* The quoted and unquoted strings *must* print different results.
* No looking at your own code, required file names, etc.
* Unmatched quotes are disallowed
* If there are multiple strings, they can either be printed as newlines (as in the example), or in some other *human-readable* way - no arrays or objects
* This is , so shortest answer in bytes wins.

# Answer
# Python 2, 32 bytes

```
''*2;print"''*2;print"''*2;print

```

Try it online!

Based on my initial solution for the other variant of this puzzle.
> 4 votes

# Answer
## \>\<\>, ~~39~~ 16 bytes

```
"l2*0.|or|["090.

```

Try it online! (quoted)

### Explanation

```
        BA
"l2*0.|or|["090.
"l2*0.|or|["     Pushes the quoted characters onto the stack
            0    Pushes 0
             90. Goes to A
          [      Wipes the stack (requires the 0)
"          "090. Pushes the quoted characters onto the stack
 l2*0.           Length is 4; goes to B
      |or|       Reverses & prints the stack

```

```
A        B
""l2*0.|or|["090."
""                 No-op
  l2*0.            Length is 0; goes to A
 "l2*0.|or|["      Pushes the quoted characters onto the stack
             0     Pushes 0
              90.  Goes to B
       |or|        Reverses & prints the stack

```

## Old answer, 39 bytes

```
"!~l?!<r&[orl&"0[c2*&d0.>o<~~.!?@@0+1fl

```

Try it online! (quoted)

Whew, this took a while. Can probably be golfed further.

```
             A
"!~l?!<r&[orl&"0[c2*&d0.>o<~~.!?@@0+1fl
"!~l?!<r&[orl&"                         Pushes the quoted characters onto the stack
               0[                       Wipes the stack
                 c2*&                   Puts 24 into the register (&)
                     d0.                Goes to A
"             "0[c2*&d0.>o<~~.!?@@0+1fl Pushes the quoted characters onto the stack
 !~l?!<                                 No-op (in this case)
       r                                Reverses the stack
        &[                              Wipes the stack, preserving the top &
          o                             Outputs the top character on the stack
           r                            Reverses the stack
            l&                          Puts the current length of the stack into the register
                                        Repeats until &=0, then errors

```

```
                B
""!~l?!<r&[orl&"0[c2*&d0.>o<~~.!?@@0+1fl"
""!~                                      No-op
    l?!<                                  Reverses the IP direction
""!~l?!                                 " No-op
                            ~~.!?@@0+1fl  If the length is 0, go to B
""!~l?!<r&[orl&"                        " Pushes the quoted characters onto the stack (backwards)
                            ~~.!>@@0+1fl  No-op (length != 0)
                         >o<              Outputs all the characters on the stack, then errors

```

*(Note: when I "wipe" the stack, it really creates a new stack; the old stack is still there and accessible)*
> 3 votes

# Answer
# 05AB1E (legacy), 5 bytes

```
·"·"·

```

Outputs concatenated without separator.

Try it online or try it online with surrounding quotes.

**Explanation:**

```
         # Program without surrounding quotes will output string "··"
·        # Double the top of the stack, which is empty, so an empty string is pushed
 "·"     # Push string "·" to the stack
    ·    # Double it (2*). Since the legacy version is built in Python, the string is
         # concatenated with itself: "··"
         # (output the top of the stack implicitly as result)

         # Program with surrounding quotes will output string "·"
"·"      # Push string "·" to the stack
   ·     # Double it to string "··"
    "·"  # Push string "·" to the stack
         # (output the top of the stack implicitly as result)

```
> 3 votes

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

```
 `H"H` "H

```

Try it online! Quoted version.
> 1 votes

# Answer
# \>\<\>, 17 bytes

```
"af0.|o<"i!.1!0<9

```

Try it unquoted! Quoted!
> 1 votes

# Answer
# Runic Enchantments, 11 bytes

```
!"!""!$;"$;

```

Try it online! and `"!"!""!$;"$;"`

Just a one-byte 'inversion' of the prior answer (and 1 byte for having to include the inverting-byte as part of a string literal as well).

### Explanation

Note that `.` is a NOP command and used as a spacer where other commands are not executed or otherwise removed for explanatory purposes.

`!"` is effectively NOP, resulting in the execution of only `...."!$;"$;` which prints the contents of the code not contained between quote-pairs (`!........$;`)

Wrapping everything in quotes causes the first `!"` to be string literal, resulting in `"!".."!$;"$;.` and which prints the parts of the program contained within quote-pairs (`"!"` and `"!$;"`).
> 1 votes

---
Tags: code-golf, restricted-source, quine
---


# Question
Title: Write the shortest O(n^2) sorting algorithm
Write a sorting algorithm for a list of integers that has an average performance of O(n^2).

This is , so the shortest code in bytes wins.

**RULES:**

* The characters wasted for the declaration of the list are not counted

(e.g. `var c = new List<int>() { 4, 2, 1, 3 };` is not counted)
* Builtins to sort a list are not allowed.

The best I did in C# is **82** ('c' is the list to be sorted):

```
var n=c.ToList();for(int i=0;i<n.Count;i++){int x=c.Min();c.Remove(x);n[i]=x;}c=n;

```

# Answer
# Jelly, 5 bytes

```
ṭ@Ṣ¥/

```

Try it online!

Jelly's sort builtin  is too fast, so we had to slow it down a bit, via using it as part of a slower sorting algorithm rather than using it directly. (This algorithm doesn't sort the original list with a builtin, which is what the question banned at the time this answer was written.)

## Explanation

```
ṭ@Ṣ¥/
    /  One element at a time,
ṭ@     append that element to the list so far
   ¥   and
  Ṣ    sort the resulting list

```

Jelly's sort algorithm (which, behind the scenes, is Python's sort algorithm) is O(*n*) on lists that have only one element out of place, thus this implements an O(n²) sorting algorithm (specifically insertion sort).
> 4 votes

---
Tags: code-golf, sorting, restricted-complexity
---


title: Number conversion

text:
# Question
Title: Number conversion
Assume that there is a number `a`. In every conversion of that number, the number can either convert itself to its value plus the value of one of its digits, or convert itself to its value minus the value of one of its digits.

In this situation, find the minimum number of conversions one has to make in order to get to the number `b`. If b cannot be reached, output `-1`.

## Input

Input one line containing the integers a and b (where 1 \<= a, and b \<= 10^6).

## Output

Output a line containing one integer, which represents the minimum amount that one has to convert the number.

## Example input and output (s)

```
Input:  1 10
Output: 5

```

Why?

```
   1
-> 1+1=2
-> 2+2=4
-> 4+4=8
-> 8+8=16
-> 16-6=10
=> 10

```

The shortest program wins, as this is a code golf question.

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

Takes input as `(a)(b)`. Can be very slow if there's no solution, but it should eventually return \\$-1\\$ (at least in theory).

```
a=>h=(b,k=0)=>(g=(v,n)=>n--?[...v+''].some(x=>g(+x+v,n)|g(v-x,n)):v==b)(a,k)?k:k<a+[b]?h(b,k+1):-1

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~38~~ 37 bytes

```
3Ýo*Êß8LIå*i®ë¹¸[DIå#¼Ùvy©v®y+®y-}})}¾

```

Can definitely be golfed a bit more..

Thanks to *@tsh* for the condition of the first if-statement.

Try it online or verify a few more test cases.

**Explanation:**

```
3Ý             # Push the list [0,1,2,3]
  o            # For each value, take 2 to the power that value: [1,2,4,8]
   *           # Multiply each by the first (implicit) input
    Êß         # Check that the second (implicit) input is NOT in this list
8L             # Push the list [1,2,3,4,5,6,7,8]
  Iå           # Check that the second input is in this list
*i             # If both are truthy:
  ®            #  Push -1
 ë             # Else:
  ¹¸           #  Push the first input again, and wrap it into a list
    [          #  Start an infinite loop:
     D         #  Duplicate the list at the top of the stack
      Iå       #  If the second input is in this list:
        #      #   Stop the infinite loop
      ¼        #  Increase the counter variable by 1
      v        #  Loop over each number `y` in the list:
       y©      #   Store the current number `y` in variable `®` (without popping)
         v     #   Inner loop over each digit `y2` of `y`
          ®y+  #    Add digit `y2` to integer `®`
          ®y-  #    Subtract digit `y2` from integer `®`
      }}       #  After the nested loop:
        )      #  Wrap all values on the stack into a list for the next iteration
    }¾         # After the infinite loop: push the counter variable
               # (and output the top of the stack implicitly as result)

```

# Answer
> 2 votes
# Jelly, ~~33~~ 29 bytes

```
0ịD;N$+Ɗ;@€)ẎL<¥Ƈȷ7Ʋ=⁴¬ȦƊ¿ẈṪ’

```

Try it online!

A full program that takes `[[a]]` as the left argument and `b` as the right argument.

More efficient version (36 bytes)

# Answer
> 2 votes
# Python 2, ~~104~~ ~~99~~ ~~96~~ ~~93~~ 95 bytes

```
f=lambda a,b,i=0:i*(b in a)-(0<b<9<i)or f({x+int(c+d)for x in a for d in`x`for c in' -'},b,i+1)

```

Try it online!

This function takes `a` as a list (or set, or any other collection really), which is not ideal, but the Jelly answer does something similar it seems. My original approach with varargs couldn't be used because I needed the `i` parameter, with a default value, to return -1 if no answer can be found.

@tsh's prerequisites for there not being an answer are partially used. However, instead of the expensive and highly unpractical (for golfing) second part of that condition, we simply let the recursion run for a little while to see if an answer is found anyway.

# Explanation

```
f=lambda a,b,                       # a and b are as defined in the
         i=0:                       #  challenge; i is a counter
i*(b in a)                          # Return the counter if b is found
-(0<b<9<i)                          # This is the only code needed for the
                                    #  existence problem
or f(                               # Recursively call the function
 {x+int(c+d)                        # All possible numbers in the next step
  for x in a                        # All numbers in this step
  for d in`x`                       # All digits of those numbers
  for c in' -'},                    # Either positive or negative (making
                                    #  good use of the fact that int()
                                    #  ignores leading whitespace)
 b,i+1)                             # Increase the counter

```

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 217 bytes

Correctly returns -1 now if b can't be reached, thanks to @tsh for the formula

```
(a,b)=>{var l=new List<int>(){a};int r=-1,z;if(!(b<9&!(b==a|b==2*a|b==4*a|b==8*a)))for(r=0;!l.Any(x=>x==b);r++)l.ToList().ForEach(x=>(x+"").ToList().ForEach(y=>{z=y-'0';l.Remove(x);l.Add(x+z);l.Add(x-z);}));return r;}

```

Try it online!

---
Tags: code-golf
---


title: Repdigit Base Finding

text:
# Question
Title: Repdigit Base Finding
A repdigit is a natural number that can be written solely by repeating the same digit. For example, `777` is a repdigit, since it's solely composed of the digit `7` repeated three times.

This isn't limited to simply decimal (base 10) numbers, however:

* Every Mersenne number (of the form *Mn = 2n-1*) is a repdigit when written in binary (base 2).
* Every number is trivially a repdigit when written in unary (base 1).
* Every number `n` can also trivially be written as the repdigit `11` in base `n-1` (for example, `17` when written in hexadecimal (base 16) is `11`, and `3` when written in binary (base 2) is also `11`).

The challenge here is to find *other* bases where the input number may be a repdigit.

### Input

A positive integer `x > 3`, in any convenient format.

### Output

A positive integer `b` with `(x-1) > b > 1` where the representation of `x` in base `b` is a repdigit.

* If no such `b` exists, output `0` or some falsey value.
* If multiple such `b` exist, you can output any or all of them.

### Rules

* The `(x-1) > b > 1` restriction is to prevent the trivial conversions to unary or the "subtract one" base. The *output* number can be written in unary or any convenient base, but the *base itself* must not be one of the trivial conversions.
* Input/output can be via any suitable method.
* Standard loophole restrictions apply.

### Examples

```
In --> Out
11 --> 0            (or other falsey value)
23 --> 0            (or other falsey value)
55 --> 10           (since 55 is 55 in base 10)
90 --> 14           (since 90 is 66 in base 14 ... 17, 29, 44 also allowed)
91 --> 9            (since 91 is 111 in base 9 ... 12 also allowed)

```

# Answer
> 11 votes
# Jelly, ~~11~~ 9 bytes

```
bRI¬P€TḊṖ

```

Returns a list of bases, which is empty (falsy) if there is none. Try it online!

### How it works

```
bRI¬P€TḊṖ  Main link. Argument: x (number)

 R         Range; yield [1, ..., x].
b          Base; convert x to base n, for each n in the range.
  I        Compute the increment (differences of successive values) of each array
           of base-n digits. This yields only 0's for a repdigit.
   ¬       Apply logical NOT to each increment.
    P€     Compute the product of all lists of increments.
      T    Get the indices of all truthy products.
       Ḋ   Discard the first index (1).
        Ṗ  Discard the last index (x - 1).

```

# Answer
> 9 votes
# Pyth, ~~11~~ 10

```
fqjQT)r2tQ

```

Apparently Pyth's unary `q` checks for a list that has all unique values as of about 10 days ago. Apparently investigating Pyth bugs improves golf scores.

Filters the list `[2..input-1)` on if the unique set of digits of the input in that base is length 1.

Test Suite

### Explanation:

```
r2tQ     ##  generate the python range from 2 to the input (Q) - 1
         ##  python range meaning inclusive lower and exclusive upper bounds
f        ##  filter that list with lambda T:
  jQT    ##  convert the input to base T
 q    )  ##  true if the resulting list digits has all equal elements

```

# Answer
> 5 votes
## Ruby, ~~87~~ ~~69~~ 63 bytes

```
->x{(2..x-2).find{|b|y=x;a=y%b;a=0if a!=y%b while(y/=b)>0;a>0}}

```

I had to implement base conversion by hand, since Ruby's builtins only go up to base 36...

Returns `nil` for not found.

```
->x{      # anonymous lambda that takes one argument
(2..x-2)  # range of the possible bases to search over
.find{    # return the first element that satisfies the block, or nil if none
|b|       # b represents the base currently being tested
y=x;      # a temporary value to avoid mutating the original value of x
a=y%b;    # the first (well, last) digit in base b, which will be compared to

                   y/=b      # divide the number by the base
   if a!=y%b                 # if this digit does not match (is different)...
a=0                          # set a to a value representing "failure"
             while(    )>0;  # keep doing this until we get zero (no digits left)

a>0       # return whether a has maintained its original value (no digit change)
}}        # find then returns the first element for which this is true (or nil)

```

# Answer
> 5 votes
## Python, 71 72 78 bytes

```
lambda x:{b for b in range(2,x-1)for d in range(x)if x*~-b==x%b*~-b**d}

```

No recursion, just tries all bases and outputs a set of those that work.

It's tempting to encode `b` and `d` in a single number, but it takes too many parenthesized expressions to extract them. 77 bytes:

```
lambda x:{k/x for k in range(2*x,x*x-x))if x*~-(k/x)==x%(k/x)*~-(k/x)**(k%x)}

```

---

**72 bytes:**

```
f=lambda x,b=2:b*any(x*~-b==x%b*~-b**d for d in range(x))or f(x,b+1)%~-x

```

Outputs the first `b` that works, or `0` if none do.

A rep-unit `x` of `d` digits of `c` in base `b` has value `x==c*(b**d-1)/(b-1)`. Equivalently, `x*(b-1)==c*(b**d-1)`.

The value `c` must be `x%b`, the last digit. I don't see a way though to determine `d` arithmetically, so the code tries all possibilities to see if any of them work.

Saved 5 bytes by copying Dennis's trick of giving a falsey output when `b` reaches `x-1` by taking the output modulo `x-1`. Another byte saved from Dennis reminding me that exponentiation inexplicably has higher precedence that `~`.

An equal-length solution with `in` instead of `any`.

```
f=lambda x,b=2:b*(x*~-b in[x%b*~-b**d for d in range(x)])or f(x,b+1)%~-x

```

# Answer
> 4 votes
# Ruby, 50 bytes

```
->n{(2..n-2).find{|b,i=n|i%b==(i/=b)%b ?redo:i<1}}

```

I would really like to remove that annoying space but as a newcomer to ruby, I'm still quite unfamiliar with its syntactic quirks.

# Answer
> 4 votes
# Python 2, 79 bytes

```
f=lambda x,b=2:~-b*x in[i%b*~-b**(i/b)for i in range(b*x)]and b or f(x,-~b)%~-x

```

Try it on Ideone.

### Idea

Any repdigit **x** of base **b \> 1** and digit **d \< b** satisfies the following.

Since **d \ 1**, we have **c \< x**, so **cb + d \< cb + b = (c + 1)b ≤ xb**.

This means that, to find suitable values for **c** and **d** for a given base **b**, we can iterate through all **i** in **\[0, …, bx)** and check whether **(b - 1)x == (i % b)(bi / b \- 1)**.

### Code

The named lambda **f** test whether **(b - 1)x** is in the set **{(i % b)(bi / b \- 1) | 0 ≤ i \< bx}**, beginning with the value **b = 2**.

* If the test was successful, we return **b**.
* Else, we call **f** again, with the same **x** and **b** incremented by **1**.

Since **b** may eventually reach **x - 1**, we take the final result modulo **x - 1** to return **0** in this case. Note that this will not happen if **b = 2** satisfies the condition, since it is returned without recursing. However, the question guarantees that **b = 2 \< x - 1** in this case.

# Answer
> 4 votes
# Emojicode, 214 bytes

(77 characters):

```
➡bi 2n 0◀i➖b 1vb i▶vv 0 1vn iin 90

```

Prints results in base 9.

I've been meaning to do a code golf with emojicode for a couple weeks now, but the language has only recently become stable enough to actually work with . As a bonus, this question makes use of the one piece of functionality emojicode is actually really good at: representing integers in other bases.

Ungolfed ( is a line comment in emojicode)

```
          define main class ""
  ➡   define main method

     read an integer from stdin, store it in frozen variable "b"
     b

     i 2   i = 2
     n 0   n = 0

    ◀i➖b 1      while i < b - 1
       v b i   v = the string representation of b in base i

       Split v on every instance of the first character of v.
       If the length of that list is greater than the actual length of v,
       n = i
      ▶vv 0 1v
         n i

       i   increment i

      n 9   represent n in base 9 instead of 10, to save a byte
     0           return error code 0

```

# Answer
> 3 votes
# Dyalog APL, 28 bytes

```
 {b/⍨⍵{1=≢∪⍵⊥⍣¯1⊢⍺}¨b←1+⍳⍵-3}

```

`{``}` anonymous function to be applied to `x` (represented by )
`b←1+⍳⍵-3` integers from 2 – ⍵-2 stored as `b`
`⍵{` for each element in b (), apply the function `{``}` with x as left argument
`⍵⊥⍣¯1⊢⍺` convert x to that base
`1=≢∪` is 1 equal to the tally of unique digit?
`b/⍨` elements of b where true (that there is only one unique digit).

Example cases

If no base exists, the output is empty (which is falsey), as can be demonstrated by this program:

```
 WhatIsEmpty
 →''/TRUE ⍝ goto (→) TRUE: if (/) emptystring ('')
 'False'
 →END
TRUE:
 'True'
END:

```

This prints 'False'

# Answer
> 3 votes
# Perl 6, ~~45~~ ~~43~~ 42 bytes

```
{grep 2..$^x-2: {[==] $x.polymod($_ xx*)}}

```

**Explained (sort of)**

For reference, a variable `$^x` in `{ ... }` is the same as doing `-> $x { ... }`

```
{grep 2..$^x-2: {[==] $x.polymod($_ xx*)}}
{                                          # Anonymous function taking $x
 grep                                      # Return the all values in
      2..$^x-2: {                          # Range from 2 to $x - 2 satisfying:
                 [==]                      #     Reduce with ==:
                      $x.polymod(          #         (See below for polymod)
                                 $_ xx*    #         An infinite list containing
                                           #         the current value
                                       )}}

```

Polymod (TL;DR): `$n.polymod($b xx *)` gives you a reversed list of digits/'digits' for `$n` in base `$b`

Polymod (For real): The polymod method is almost like a more powerful version of python's `divmod` function. `$n.polymod(*@args)` divides $n by each value in \*@args, adding the remainder (`$n mod $x`) to the list it returns, and using the quotient for the next division. I feel I explained it poorly so here's some examples (written in perl 6, but clean enough to be understood by most I hope):

```
12.polymod(7)    # returns (5, 1)
# Roughly equivalent to:
(12 mod 7, 12 div 7)

86400.polymod(60,60,24) # returns (0, 0, 0, 1)
# Roughly equivalent to (this will give you an array rather than a list):
my $n = 86400;
my @remainders; # Here lies the end result
for (60, 60, 24) -> $divisor {
    @remainders.push( $n mod $divisor );
    $n div= $divisor;
}
@remainders.push($n)

# This is essentially the base conversion algorithm everyone
# knows and loves rolled into a method.
# Given an infinite list of divisors, polymod keeps going until
# the remainder given is 0.
0xDEADBEEF.polymod(16 xx *) # returns (15 14 14 11 13 10 14 13)
# Roughly equivalent to (but gives an array rather than a list):
my $n = 0xDEADBEEF;
my @remainders; # Here lies the end result
while $n > 0 {
    @remainders.push( $n mod 16 );
    $n div= 16;
}

```

# Answer
> 2 votes
# MATL, ~~15~~ 14 bytes

```
3-:Q"G@:YAd~?@

```

This works with current version (14.0.0) of the language/compiler.

If no base exists, the output is empty (which is falsey).

**Try it online!**

```
3-:Q    % take input x implicitly. Generate range of possible bases: [2,3,...,x-2]
"       % for each base b
  G     %   push input again
  @:    %   generate vector of (1-based) digits in base b: [1,2,...,b]
  YA    %   convert to that base
  d~    %   differences between consecutive digits; negate
  ?     %   if all values are true (that is, if all digits were equal)
    @   %     push that base
        %   end if implicitly
        % end for each implicitly
        % display implicitly

```

# Answer
> 2 votes
# Pyth, ~~26~~ 19 bytes

```
hMfql{eT1m,djQdr2tQ

```

Try it here!

~~Will add an explanation after I golfed this.~~ Look at this answer for a shorter implementation and explanation.

# Answer
> 2 votes
# Mathematica, 55 bytes

```
Cases[4~Range~#-2,a_/;Equal@@#~IntegerDigits~a]/.{}->0&

```

Anonymous function, not too complicated. Just filters out bases based on repdigit-ness.

# Answer
> 2 votes
# Python 2, 75 bytes

```
n=input()
b=1
while b<n-2:
 i=n;b+=1
 while i%b==i/b%b:i/=b
 if i<b:print b

```

A port of my ruby answer. Prints all valid bases if any exists.

# Answer
> 2 votes
# Julia, 45 bytes

```
n->filter(b->endof(∪(digits(n,b)))<2,2:n-2)

```

This is an anonymous function that accepts an integer and returns an integer array. To call it, assign it to a variable. It will return all applicable bases or an empty array. There are no issues with large bases.

First we generate the inclusive range \[2, *n* \- 2\], where *n* is the input. We then `filter` the list to only integers *b* for which *n* in base *b* has fewer than 2 unique digits. To do this, for each integer *b* in the range, we get the digits of *n* in base *b* as an array using `digits`, get unique items using , and get the index of the last element (i.e. the length) using `endof`.

# Answer
> 1 votes
# Brachylog, 12 bytes

```
>>.ℕ₂≜&ḃ↙.=∧

```

Try it online! (as a generator!)

Takes input through the input variable and outputs a base through the output variable in the case that this is possible, failing otherwise. At the same time, it also works as a generator which outputs a list of all bases, where that list can be empty.

Ideally this could look something like `ḃ↙.=&>>`, possibly sacrificing generator functionality in that form or a similar one (since it would eventually hit unary), but as of now 12 bytes is the shortest I know how to get it.

```
     ≜          Assign an integer value to
  .             the output variable
   ℕ₂           which is greater than or equal to 2
 >              and less than a number
>               which is less than the input.
      &         The input
       ḃ↙.      in base-(the output)
          =     is a repdigit.
           ∧    (which is not necessarily the output)

```

# Answer
> 1 votes
# Ruby, ~~46~~ 43 bytes

Uses the Integer#digits function introduced in Ruby 2.4 to avoid needing to manually divide.

-3 bytes thanks to @Jordan.

```
->n{(2..n-2).find{|i|!n.digits(i).uniq[1]}}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 7 bytes

```
ÍL¦ʒвÙg

```

Outputs all possible values, or an empty list as falsey value (although technically valid outputs are falsey as well, since only `1` is truthy in 05AB1E, and everything else is falsey).

Try it online or verify all test cases.

**Explanation:**

```
Í        # Decrease the (implicit) input-integer by 2
 L       # Create a list in the range [1, input-2]
  ¦      # Remove the first value to make the range [2, input-2]
   ʒ     # Filter this list by:
    в    #  Convert the (implicit) input to the base of the number we're filtering
     Ù   #  Uniquify it, leaving only distinct digits
      g  #  Get the length of this, which is truthy (1) if all digits were the same
         # (and then output the filtered list implicitly as result)

```

# Answer
> 0 votes
# Perl 5 `-Minteger -na`, 63 bytes

```
map{$r=$,=($c="@F")%$_;$r*=$c%$_==$,while$c/=$_;$r&&say}2..$_-2

```

Try it online!

Outputs all possible answers or nothing if no solution exists.

---
Tags: code-golf, base-conversion
---