title: Tex Quotes(UVa 272)

text:
# Question
Title: Tex Quotes(UVa 272)
Given a string, replace all left-double-quotes into two backticks and all right-double-quotes into two single-quotes.

Left-quotes means the quotes that starts a quote. Right-quotes means the quotes that ends a quote. Quotes cannot be nested. You may assume that there are an even number of double-quotes in the string.

# Examples

Input:

```
"To be or not to be," quoth the Bard, "that
is the question".
The programming contestant replied: "I must disagree.
To `C' or not to `C', that is The Question!"

```

Output:

```
``To be or not to be,'' quoth the Bard, ``that
is the question''.
The programming contestant replied: ``I must disagree.
To `C' or not to `C', that is The Question!''

```

# Answer
> 21 votes
# Unreadable, ~~789~~ 777 bytes

-12 bytes by using variable X34 rather than X6.

> '""""""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""'""""""'""'""'""'""'"""'""'""'""'""'""'"""""""'""'"""'"""""'""'""""""'"""'""""""""""'""""'""""""'""'""'""'"""'"""""""'""'"""'""""'""""""'""'""'"""'"""""""'"""'""""'"""""'"""""""'""'""'""'"""'""""'""""""'""'""'""'"""'""""""""'"""""""'""'""'""'"""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'"""""""""'"""""""'""'""'"""'"'"""""""'"""'"'"""""""""'"""""""'"""""""'""'"""'""""'""""""'"""""""'""'"""'""""""""'"""'"'"""""""'""'""'""'""'"""'""""'""""""'"""""""'""'"""'"""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'""'""'""'""'"""

Try it online!

Displayed in variable-width font, per the traditional tribute to the language name.

I learnt Unreadable for this challenge, because it is obviously the best tool for the job. The only characters allowed in Unreadable are `'` and `"`, so surely it is perfectly suited to a challenge which involves changing `"` into `''`. Isn't it?

Explanation:

```
'""""""'""'""" assign to X2
'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""" 34 (double quote sign)
'""""""'""'""'""'""'""" assign to X5
'""'""'""'""'""'"""""""'""'""" X2+5 (apostrophe sign)
'"""""'""'""""""'"""'"""""""""" while (1+ (assign to X1 a value read from stdin, or -1 if stdin is empty) != 0)
 '"""" do 2 things
 '""""""'""'""'""'""" assign to X4
 '"""""""'""'""" the value of X2
 AND
 '"""" do 2 things
 '""""""'""'""'""" assign to X3
 '"""""""'""" the value of X1
 AND
 '"""" do 2 things
 '"""""'"""""""'""'""'""'""" while(X4 != 0)
  '"""" do 2 things
  '""""""'""'""'""'""" assign to X4
  '""""""""'"""""""'""'""'""'""" X4-1
  AND
  '""""""'""'""'""" assign to X3
  '""""""""'"""""""'""'""'""" X3-1
 end while
 AND
 '"""""""""'"""""""'""'""'""" if(X3 != 0)
  '"'"""""""'""" print X1
 else
  '" print the output of
  '"""""""""'"""""""'"""""""'""'""" if(X34 !=0)
   '"""" do 2 things
   '""""""'"""""""'""'"""'""""""""'""" assign X34=0
   AND
   '"'"""""""'""'""'""'""'""" print X5
  else
   '"""" do 2 things
   '""""""'"""""""'""'"""'""" assign X34=1
   AND
   '"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'""'""'""'""'""" print X5+57
 end if
end while

```

(Calls to X34 are actually calls to X(X5), since X5=34.)

# Answer
> 6 votes
# TeX, ~~54~~ 32 bytes

For a TeX quotes replacement challenge we also need a TeX version of course!

```
\catcode`"13\def"#1"{``#1''}...\bye

```

`...` is the input string, so it doesn't add to the byte count.

# Answer
> 5 votes
# JavaScript (ES9), 34 bytes

Working on quoted blocks:

```
s=>s.replace(/"(.*?)"/gs,"``$1''")

```

Try it online!

---

# JavaScript (ES6), 38 bytes

Working on each double-quote separately:

```
s=>s.replace(/"/g,_=>(c="'`"[s^=1])+c)

```

Try it online!

# Answer
> 5 votes
# Retina, 13 bytes

Learning Retina quickly because for some reason I don't like Japt winning and feel like a C# solution would use regular expressions anyway. I know there is a Retina answer, but I haven't used it when creating this, and I found it (exactly) too anyway.

```
#2$`"
``
"
''

```

Try it online!

# Answer
> 4 votes
# Jelly, ~~15~~ 13 bytes

```
⁾``⁾''2ƭ”"Ƒ¡€

```

Try it online!

Full program.

# Answer
> 4 votes
# Japt, 12 bytes

Would be 11 only for a limitation of (or maybe it's a bug in) Japt.

```
r'"È²îT°g"`'

```

Try it

```
r'"È²îT°g"`'     :Implicit input of string
r'"              :Replace double quotes
   È             :Pass each match through a function
    ²            :  Duplicate
     î           :  Replace each character with
      T°         :    Postfix increment T (initially 0)
        g"`'     :    Index into "`'" with wrapping

```

# Answer
> 4 votes
# Python 3, 65 bytes

```
f=lambda s:s and(s[0],"`'"[s.count('"')%2]*2)[s[0]=='"']+f(s[1:])

```

Try it online!

*-8 bytes thanks to Erik the Outgolfer*

# Answer
> 3 votes
# !@#$%^&\*()\_+, ~~22~~ 21 bytes

```
`'("_*("+@"_*)+$!!@@)

```

Try it online!

Terminates with an error. 21 looks like an impressive score, beating quite a few languages including Charcoal. Inspired by this.

# Answer
> 2 votes
# , 40 bytes

```
cat(scan(,"",,,'"',""),sep=c("``","''"))

```

Try it online!

Reads string input, separating at each `"`, giving a vector of strings. Then pastes those strings, alternating between the double backticks and the double apostrophes as separators, recycling them as needed.

Someone will probably post a shorter R answer based on a regex... Still, this answer is more typical of R, I think.

Explanation of the `scan(,"",,,'"',"")` part:

```
scan(, # empty first parameter: read from STDIN
  "",  # type of input is a string
  ,    # default 3rd parameter nmax
  ,    # default 4th parameter n
  '"', # separate on character "
  "")  # do not treat any characters as quotations marks (necessary to handle ' in the input)

```

# Answer
> 2 votes
# Charcoal, 23 bytes

```
ＷＳ⊞υι⭆⪪⪫υ¶¦"⎇κ⁺×²§'`κιι

```

Try it online! Link is to verbose version of code. Includes 8 bytes to avoid a cumbersome input format. Explanation:

```
ＷＳ⊞υι

```

Collect input lines until an empty line is reached.

```
⪫υ¶¦

```

Join the lines on newline characters.

```
⪪..."

```

Split the input on quotes.

```
⭆...

```

Map over each part and concatenate the results for implicit print.

```
⎇κ...ι

```

Leave the first part unchanged.

```
⁺×²§'`κι

```

Prefix the appropriate quote, doubled.

# Answer
> 2 votes
# Jelly, 13 bytes

```
ṣ”"µJḊ⁾`'ṁḤż@

```

A full program.

**Try it online!**

### How?

```
ṣ”"µJḊ⁾`'ṁḤż@ - Main Link: list of characters, T   e.g. ..."hi" - she "said"...
 ”"           - character '"'                           '"'
ṣ             - split (T) at ('"')                      ["...","hi"," - she ","said","..."]
   µ          - (call that X) start a new monadic chain
    J         - range of length (of X)                  [1,2,3,4,5]
     Ḋ        - dequeue                                 [2,3,4,5]
      ⁾`'     - list of characters                      ["`","'"]
         ṁ    - mould like                              ["`","'","`","'"]
          Ḥ   - double                                  ["``","''","``","''"]
           ż@ - (with reversed @rguments) zip (with X)  [["...","``"],["hi","''"],[" - she ","``"],["said","''"],["..."]]
              - implicit (smashing) print               ...``hi'' - she ``said''...

```

# Answer
> 2 votes
# Perl 6, 23 bytes

```
{S:g/\"(.*?)\"/``$0''/}

```

Try it online!

Darn, the obvious solution is shorter. Replaces each quoted portion with a version with the appropriate quotes.

# Perl 6, 24 bytes

```
{S:g{\"}=<`` ''>[$++%2]}

```

Try it online!

Replaces each double quote, alternating between the two sets of characters.

# Answer
> 2 votes
# Labyrinth, (43?) 53 bytes

```
396"
 } "",)@
  ~"  (
 "~ 3_:
""" 4
" .;-
=   ;
..::;

```

**Try it online!**

A golfed version of this, much simpler, 92 byte program:

```
3 """
9 " ",)@
}96 " (
    " :_34-;;
    "     ; :
   """"""". :
   "        .
   """"""""=.

```

If we don't need to handle input containing the zero byte **then 43 bytes**:

```
39}9
@  6
`,""
`  "
: ."=..
_ ;   "
34-;;::

```

# Answer
> 1 votes
# Red, 79 bytes

```
func[s][q:"^""parse s[any[to change[q copy t to q q](rejoin["``"t"''"])skip]]s]

```

Try it online!

# Answer
> 1 votes
# Retina, 15 bytes

```
"
""
Y`"`\`\`''

```

Try it online! Edges out the boring Retina 0.8.2 answer by 1 byte. Explanation:

```
"
""

```

Duplicate all of the quotes.

```
Y`"`\`\`''

```

Cyclically replace the quotes with pairs of backticks and single quotes.

Boring 16-byte Retina 0.8.2 answer for completeness:

```
s`"(.*?)"
``$1''

```

Try it online!

# Answer
> 1 votes
# PHP, 62 bytes

Non-RegEx solution:

```
for(;''<$l=$argv[1][$i++];)echo$l=='"'?["''","``"][++$j%2]:$l;

```

Try it online!

---

# PHP, 48 bytes

Port of Arnauld's RegEx solution:

```
<?=preg_replace('/"(.*?)"/s',"``$1''",$argv[1]);

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~69~~ 68 bytes

```
t=39,z;f(char*s){z=*s-34?*s:257*(t^=71);printf("%s",&z);*++s&&f(s);}

```

Try it online!

One byte shaved off by @ceilingcat!

# Answer
> 1 votes
# Haskell, ~~67~~ ~~60~~ 58 bytes

```
(#0)
('"':x)#n=["``","''"]!!n++x#(1-n)
(a:b)#n=a:b#n
x#n=x

```

Try it online!

The relevant function is `(#0)`.

Since I originally thought the question also required us to convert single quotes here is a version that handles both:

# Haskell, 125 bytes

```
(#(1<0,1<0))
('"':x)#(m,n)=last("``":["\""|m])++x#(not m,n)
('\'':x)#(m,n)=last('`':['\''|n]):x#(m,not n)
(a:x)#n=a:x#n
x#n=x

```

Try it online!

# Answer
> 1 votes
# Python 2, 57 bytes

```
lambda s:re.sub('"(.*?)"',r"``\1''",s,flags=16)
import re

```

Try it online!

Although I really like Jitse's answer.

# Answer
> 1 votes
# (GNU) sed, ~~38 33~~ 30 bytes

***-4** by removing the `-n` flag and implicitly printing on `n`, **-1** by reusing previous `/expression/`, thanks @Cowsquack. **-3** by using implicit branch-to-end.*

```
:a
s/"/``/;T
:b
s//''/;ta
n;bb

```

~~Try it online! Try it online!~~ Try it online!

Some pretty basic label jumping. ~~This can probably be golfed by a byte or two.~~

```
:a          # label a
s/"/``/;T   # replace " -> ``. If unsuccessful, move to next line
:b          # label b
s//''/;ta   # replace " (implicit) -> ''. If successful, jump to a (w/o reading new line)
n;bb        # read in the next line, but jump to label b.

```

# Answer
> 1 votes
# Stax, 11 bytes

```
û╩↕H£ñ╟Uzay

```

Run and debug it

### Procedure:

1. Take all input, newlines and all.
2. Regex replace `'"'` with a block that produces alternating outputs of pairs of backticks and foreticks(?)

# Answer
> 1 votes
# 05AB1E, 15 bytes

```
'"¡ā¨„'`sè2×.ιJ

```

Try it online!

No regexes in 05AB1E, so we split on `"`, make a list of alternating ```` and `''`, then interleave the two.

# Answer
> 1 votes
# QuadR, 14 bytes

```
"(.*?)"
``\1''

```

Try it online!

Simple find/replace using @Adám's wrapper for Dyalog APL's `⎕R`eplace function.

### How:

```
"(.*?)" ⍝ PCRE, finding anything between two double quotes and assigning it to group 1
``\1''  ⍝ Transformation string, replacing the match with ``group_1''.

```

# Answer
> 1 votes
# GolfScript, ~~35~~ 34 bytes

```
1:c;{.34={;c)2%:c'""'"``"if}""if}%

```

Try it online!

# Explanation

```
1:c;                                # Set 1 to the current item counter

    {                            }% # Map for every character in the input:
     .34=                      if   #     If the character isn't the quote,
                             ""     #         Just leave it alone
         {                  }       #     Otherwise:
          ;                         #         Remove the copy of the input
           c):c                     #         Increment the counter
                2%        if        #         If the counter isn't divisible by 2,
                  '""'              #             Output the double-quote
                      "``"          #         Otherwise: Output the double backtick

```

# Answer
> 1 votes
# Vyxal `Ṡs`, 18 bytes

```
\"Ẇƛ\"=[&›¥₂[\'|\`

```

Try it Online!

```
\"Ẇ                # Split on ", keeping delimiter
   ƛ               # Map...
    \"=[           # If a "
        &›         # Increment the register
          ¥₂[      # If even...
             \'    # Single quote,
               |\` # Else backtick.

```

# Answer
> 0 votes
# Lua, 36 bytes

```
print((...):gsub('"(.-)"',"``%1''"))

```

Try it online!

Wow, only two chars longer than js solution.

# Answer
> 0 votes
# Perl 5 `-p0`, 19 bytes

```
s/"(.*?)"/``$1''/gs

```

Try it online!

# Answer
> 0 votes
# Java 8, 40 bytes

```
s->s.replaceAll("\"([^\"]+)\"","``$1''")

```

Try it online.

**Explanation:**

```
s->                             // Method with String as both parameter and return-type
  s.replaceAll("\"([^\"]+)\"",  //  Replace all these matches,
               "``$1''")        //  with this replacement

```

*Regex explanation:*

```
 "([^"]+)"                      // MATCH:
 "                             "//  A literal "
   [^"]+                       "//  Followed by 1 or more non-" characters
  (     )                       //  (captured in capture group 1)
         "                     "//  Followed by a literal " again

``$1''                          // REPLACEMENT:
``                              //  Literal ``
  $1                            //  Followed by the match of capture group 1
    ''                          //  Followed by a literal ''

```

# Answer
> 0 votes
# Wren, 91 bytes

```
Fn.new{|n|
var c=1
for(i in n.split("\"")[1..-1])System.write(((c=-~c)%2==0?"``":"''")+i)
}

```

Try it online!

## Explanation

```
Fn.new{|n| // New anonymous function
var c=1    // Set the index counter as 1
for(i in n.split("\"")                                                 // For each over n splitted with quotes
                      [1..-1])                                         // Get rid of the first quote
                              System.write(                          ) // Output this to the console
                                           (
                                            (c=-~c)                    // Increment the counter
                                                   %2==0?"``"          // If that's divisible by 2, output a backquote
                                                             :"''"     // Otherwise, output a frontquote
                                                                  )+i  // Join the result with i
}

```

---
Tags: code-golf
---


title: Build a Mastermind engine

text:
# Question
Title: Build a Mastermind engine
For reference to the game of Mastermind: Solving Mastermind in 6 or less moves

In the version of Mastermind used in this problem, the operating string is a 4-digit number, from 0000 to 9999, represented as either numbers from `0` to `9999` or strings of consecutive digits `"0000"` to `"9999"` in input.

Your task is to build a function that will take two numbers/strings `secret` and `guess` as input, and return two numbers `A` and `B`, the number of red and white pegs respectively.

The shortest code in any language to do this wins.

# Answer
> 5 votes
# J: 40 26 29 22

```
=,&(+/)(~:#[)e.&~.~:#]

```
* *change*: don't laminate, but work truly dyadically, eliminating need for explicit ranks ("1), lamination(,:) and between (/)
* *change*: don't count duplicate characters twice
* *change*: Strings are more efficient as they don't need parsing

This verb takes a left and right argument a string from '0000' to '9999'. It takes care of doubles and excludes exact matches from checking correct numbers but wrong place.

Test cases:

```
NB. Give the beast a name
mm=: =,&(+/)(~:#[)e.&~.~:#]
NB. make 6 by 4 arrays of the inputs
secret =: (, ;. _2) '1254 1234 5441 5441 5441 5441 '
guess  =: (, ;. _2) '1342 1111 1234 4531 4441 5441 '

NB. Apply the verb on each pair of secret/guess
'1111' mm '1231'
2 0

NB. A whole bunch of test cases with formatting and printing of the inputs:
secret ([,' ',(":@mm),' ',])"1 guess

NB. output:
1254 1 2 1342
1234 1 0 1111
5441 0 2 1234
5441 1 2 4531
5441 3 0 4441
5441 4 0 5441

```

A little bit of explanation, reading from right to left:

```
NB.   ExactMatch: checks where digits correspond:
ExactMatch =: =

NB.   GoodDigitWrongPlace: Copies non-matched numbers from both arguments (left and right
NB.   pairs of parentheses, and checks them for same elements(e.), after eliminating
NB.   doubles in both (&~.)
GoodDigitWrongPlace =: (~: # [) (e.&~.) (~: # ])

NB.   Piecing the conditions together, after summing the booleans:
mm =: ExactMatch ,&(+/) GoodDigitWrongPlace

```

# Answer
> 4 votes
# K, ~~41~~ 36

```
{+/'(b;(in).(?x;y)@\:(!#x)@&~b:x=y)}

```

.

```
k)c1:("1254";"1234";"5441";"5441";"5441";"5441")
k)c2:("1342";"1111";"1234";"4531";"4441";"5441")
k){+/'(b;(in).(?x;y)@\:(!#x)@&~b:x=y)}'[c1;c2]
1 2
1 0
0 2
1 2
3 0
4 0

```

# Answer
> 2 votes
## Ruby 2.0, 71 characters

```
f=->s,g{[x=(0..3).count{|n|s[n]==g[n]},g.chars.count{|e|s.sub!e,''}-x]}

```

This function actually modifies the first parameter, which is obviously a bit dodgy. Would be easy enough to fix if it's actually against the rules.

I'm sure there's something sneaky you could do with `String#count` but I couldn't think of a nice way to handle duplicates.

Example usage:

```
p f['1254', '1342'] #=> [1, 2]
p f['1234', '1111'] #=> [1, 0]
p f['5441', '1234'] #=> [0, 2]
p f['5441', '4531'] #=> [1, 2]
p f['5441', '4441'] #=> [3, 0]
p f['5441', '5441'] #=> [4, 0]

```

# Answer
> 1 votes
### GolfScript, 50 characters

```
{[[\].zip{1/~=},,\{$}/{1$?.)!!{)>0}*)},,\;1$-]}:M;

```

A similar solution to chron's answer written in GolfScript. Input must be provided as two strings on the stack, the result will be the array `[A B]`.

Examples:

```
"1254" "1342" M p    # => [1 2]
"1234" "1111" M p    # => [1 0]
"5441" "1234" M p    # => [0 2]
"5441" "4531" M p    # => [1 2]
"5441" "4441" M p    # => [3 0]
"5441" "5441" M p    # => [4 0]

```

# Answer
> 1 votes
## GolfScript (48 chars)

```
{[\]:&zip{1/~=},,.~)10,{{''+-,~5+}+&%.~>=+}/}:E;

```

`E` here stands for `eval`. I take a similar approach to Knuth's definition of the number of white pegs by calculating `sum_{i=0}^{9} min(count(secret, i), count(guess, i))`.

Online demo

# Answer
> 1 votes
# MATL, 17 bytes

```
=s,4Y2@G!=s]Xlsy-

```

Try it online (Tested multiple inputs with this)

**Explanation**:

(For white pegs, Knuth's definition as mentioned by Peter Taylor is used: `sum_{i=0}^{9} min(count(secret, i), count(guess, i))`)

```
=         % check which digits are equal
s         % sum of 1s is the number of red pegs
,         % do twice
  4Y2     % predefined literal: '0':'9'
  @G      % get the next input
  !=      % broadcast equality check
  s       % sum to get the count of each digit in the input
]         % end
Xl        % elementwise minimum
s         % sum
y-        % subtract the number of red pegs
          % (implicit) convert to string and display

```

# Answer
> 0 votes
# Python - 93

I'm pretty sure this is right. But a few example input/outputs in the question would help.

```
def m(S,G):
 R = [(s,g) for s,g in zip(S,G) if s!=g];S,G=zip(*R);W=set(S)&set(G);return 4-len(R),len(W)

```

And calling it gives:

```
print m('1234','1231')
>>> (3, 0)
print m('1234','1230')
>>> (3, 0)
print m('1234','1243')
>>> (2, 2)
print m('1234','4312')
>>> (0, 4)
print m("0123","0131")
>>> (2, 1)
print m("0123","0132")
>>> (2, 2)
print m("0123","0123")
>>> (4, 0)
print m("0123","4131")
>>> (1, 1)

```

# Answer
> 0 votes
Here's a first draft in PowerShell: `168` characters.

```
function Test-Mastermind{param([char[]]$s,[char[]]$g)
4-($p=0..3|?{$s[$_]-ne$g[$_]}).Count
($p|%{$i=$_;$p|?{$s[$i]-eq$g[$_]-and0-ne$s[$i]}|%{($s[$i]=$g[$_]=0)}}).Count}

```

For the sake of illumination:

```
function Test-Mastermind {
    param([char[]]$s,[char[]]$g)
    4 - ($p = 0..3|?{ $s[$_] -ne $g[$_] }).count # count same  characters
    ( $p | % { $i = $_                           # ForEach $i in $p (char in secret)
        $p | ? {                                 # ForEach $_ in $p (char in guess)
            $s[$i] -eq $g[$_] -and 0 -ne $s[$i]  # If they match and aren't 0
         } | % { ($s[$i]=$g[$_]=0) }             # 0 them out, output something we can count
    } ).Count
}

```

---
Tags: code-golf
---


# Question
Title: Biggest katlani noun dictionary in 400 bytes
Katlani is a constructed language being designed in chat. In this challenge, your goal is to print the largest dictionary of katlani nouns possible in 400 bytes or less.

## Task

In 400 bytes or less, your program should print a list of katlani nouns. You can choose to output them as a list/array in your language, or as a string with any (not necessarily consistent) non-alphabetical separator, such as newlines or commas. The capitalization and sorting of the words does not matter. Words not in the list are not allowed in the output, but duplicates are.

**The list of nouns you may choose from are:**

```
abail
abikis
ak
akniton
alfabit
atirsin
atom
ats
aypal
baka
baklait
banl
bgil
bianto
bit
bo
boraky
borsh
bot
br
brbrno
byt
daosik
diga
digiz
dogo
dolmuk
dongso
douv
drarkak
fa
fafasok
fasmao
fidr
floria
fridka
friv
fully
fylo
fyrus
gilmaf
gogu
gogzo
gongul
gorlb
gosio
gratbt
gutka
hisi
horrib
hurigo
inglish
iomshuksor
isa
ispikar
isplo
ita
iushb
izlash
kaikina
kat
katisas
katlani
kfaso
khalling
kisongso
kivsk
klingt
kod
koik
kolbat
komy
konma
korova
koss
kotsh
kris
kromir
ksik
ksuz
ktaf
ktomish
ktomizo
la
lan
lgra
loshad
lyly
mak
makanto
makav
makina
marinolus
marta
matiks
mim
mimhis
mingso
mitsh
molo
mosdob
motif
motkop
movogal
muratsh
mutka
naita
ngoirfo
nidriok
nilo
nin
nini
ninibr
nirus
noguna
nolif
nors
o
ogig
omkop
onion
opru
orilha
orni
ozon
papin
paslo
pasrus
pirishy
pluban
polr
posodo
pouk
produty
rak
raznitsa
rigiks
rilifior
riomr
rno
ronta
rus
ryby
sabbia
sai
sakar
saman
sandvitsh
sasa
sfiny
shatris
shidoso
shilan
shimshoom
shor
shotiya
shuan
shubhu
shuksor
shuriok
shutis
shutrak
shyba
sibas
sibin
simriomr
sod
sokit
spamra
spamt
srirad
sutka
taika
tipstor
tizingso
tksu
tobl
tokvod
tomp
tonfa
toto
totobr
tshans
tshimiso
tshomp
tura
tuvung
uboiak
umub
vaf
vintz
voda
vodl
vontark
y
yntsh
zimdo
zivod
zombit
zorliplak

```

## Scoring

The winner (per language) is the answer that can print the largest number of unique words from the dictionary. Ties are broken by byte count, so if two answers manage to print all 200, the shorter of the two will win.

# Answer
# JavaScript (ES6), 400 bytes, 104 words

```
_=>`oï�ño�÷�
��¯�¯�¯9�:�@¯p_�O��S_ÀOÅoË��?
hñ���WñÓÖÛò9?F4ôhïF�ôÃ�I4÷Ü�~~øgoSvõ5?VÉöÓßlSüáï��ù&Ï¤�úa¦¦ú¼�¸±ð�7ñl�ýlqýi6ýº@ó¹!ôe�ôj�ø� ø:�øº@õ� õ<¹öSeü6�üe ù��ù��ù+�ù.�ù1    ù15ùd:ùº@ú�@þZ�ð�C���¦ñl�ï��VýeÛÜ
�òlÃ�+ÃÖôs]¯Fq
ôÆ�Ï�CPø
4���9ø5ÙoSS�õmµ�l7 ü=4���0ù#p_�±+ù+£�¦¦�ú���±c�ðE:eð£É5ñ�p:ó]s�`.replace(r=/./g,x=>x.charCodeAt().toString(16).padStart(2,0)).replace(r,y=>"abhiknolmsturgy,"[+("0x"+y)])

```

Almost certainly going to get mangled due to all the weird Unicode, but this uses a string of bytes, which if represented with an extended ASCII code page (like the one HTML defaults to) would be exactly 290 bytes. The other 110 are a decoder, which split each byte into 4-bit nibbles, and map them to one of 15 letters or a comma.

The problem is, this is exactly 400 bytes, leaving no room for backslashes in the string. JS is pretty good at ignoring control characters and stuff in strings, so all I need to worry about is `\0` (NUL), `\r` (which is mangled by newline conversion), ```, and `\`.

I could sacrifice a few words, and escape these with `\`, but that seemed like a bit of a waste. The solution I came up with was figuring out the representation of these four characters as nibbles (`00`, `0d`, `5c`, and `60`), and all of the pairs of letters in the words that never appeared beside each other. Then, I could map those letter pairs to the bytes I didn't want to appear. I ended up with `a` for `0`, `g` for `d`, `n` for `5`, `r` for `c`, and `o` for `a`. since `aa`, `ag`, `nr`, and `oa` never appear in the list of 104 words I chose.
> 6 votes

# Answer
# JavaScript (Node.js), 399 bytes, 96 words

Simple zlib compression with base-64 encoding. Returns a single string of words separated with `_`.

```
_=>require('zlib').inflateRawSync(Buffer("HY+BCgQhCEQ/dTBiOylz0TrY/fqbDppnipYjHbLciESRLsQcKE0JXSjOE/khmQTKs1C1Cao3J2bLE/YXl+DSGrhCK59hYG2P8eB6hhOxE83bPnidjFHIVN734sjHI7RAU6ibM7oEXRa6V0o7YQ8xjXUP/56QSSxu2EN5zdOW+0VfcmEIz8RoITDpVPBNU6POjDm/MV/db9h/iamsTJ1H+gddTx96kZFweNMGtzPiU33C79jwYLu/TG8fQeyO4I+hboGYjuM/RakuQRoXS6HZpHFil89meAorWoTNtJ23GHc/YWHRGJaXQdhNLP+DG9KMzMS2XfD1KgcDD1616iTTHw","base64"))+''

```

Try it online!

### How?

This is the result of a random search where each iteration keeps a word \\$W\\$ of length \\$L\\$ if a random value \\$k\in\[0\dots1\]\\$ satisfies:

$$ k\>\frac{(L-1)^2}{30} $$

This is really just a guesstimate that keeps all one-letter words, discards all words of more than 6 characters and uses probabilities between 17% and 97% in between.
> 5 votes

# Answer
# Bubblegum, ~~147~~ ~~148~~ 149 words, 400 bytes

```
00000000: 15cc 810a c520 0885 e157 3dc6 5893 4a87  ..... ...W=.X.J.
00000010: d685 f6f4 f704 f9fd cd41 b25f e990 227a  .........A._.."z
00000020: d4a6 0999 3e08 2f0d 459a 10eb 2855 898a  ....>./.E...(U..
00000030: 4d67 260a e321 6d9f e443 b9db 9ce0 2961  Mg&..!m..C....)a
00000040: 8e4b ab7e 47c1 e5d5 89d5 3c59 3fdc c293  .K.~G.....<Y?...
00000050: 431c 77e8 d5e4 845b bd02 f7ea 7de3 dedd  C.w....[....}...
00000060: 49ac 44f5 ba0e 9f53 abab 33d1 0b4d e56a  I.D....S..3..M.j
00000070: cd26 7834 158f 4768 814e 81e6 99b7 3b74  .&x4..Gh.N....;t
00000080: e5c3 ddd7 251f 3499 685d ad32 7e71 b491  ....%.4.h].2~q..
00000090: b149 2f32 99f0 9f30 368e 331f 9a89 163e  .I/2...06.3....>
000000a0: 3418 e53d b591 f5a1 4db9 d185 c7d0 6bf0  4..=....M.....k.
000000b0: b2fb c690 7646 7e47 3561 6252 1d8f e609  ....vF~G5abR....
000000c0: c76a 3a73 de1f de9d e4e5 8599 cddf 13bd  .j:s............
000000d0: 31d6 6c02 139d 54bb 133b a338 9460 6225  1.l...T..;.8.`b%
000000e0: cceb 3261 bade 3412 0eaf 5ae1 e3bc e5a6  ..2a..4...Z.....
000000f0: 6ef0 3716 3cb4 3fc2 98c2 3f6e 5f79 f598  n.7.<.?...?n_y..
00000100: e79d b7af 22fc f2f4 cb99 1e64 3584 70b4  ...."......d5.p.
00000110: 6a4b c647 20cc 116e 5310 8bbb 5d36 524a  jK.G ..nS...]6RJ
00000120: 5161 94d3 24e8 10a3 c9e5 adb6 918f 7631  Qa..$.........v1
00000130: c683 2cb1 6379 d6c9 d464 7611 a416 c9a3  ..,.cy...dv.....
00000140: 1ad2 9b4e 7a21 5f19 2138 e122 3484 bb35  ...Nz!_.!8."4..5
00000150: 9b60 8a1e 5b2e 4c2f 9db4 9f5f cc78 89dd  .`..[.L/..._.x..
00000160: 42a7 e350 0233 1fb1 3cf1 f37f 8590 dfb2  B..P.3..<.......
00000170: 8a55 5ca5 618d 55f0 931b 3fb5 f981 4fc9  .U\.a.U...?...O.
00000180: a163 63db cc07 9f8e cb29 97f8 7c14 9d7f  .cc......)..|...

```

Try it online!

General compression algorithm baseline. Prints all words of length up to 4, most of length 5 and some of length 6. The words are separated by ```.

The actual words of length 5 and 6 are found with a very basic random search, but the quantities of each length are just guesses. The order of the words is mostly alphabetic, but I moved some words around by hand. I can't really tell why moving some words yields an improvement, but I was able to save 1 or 2 bytes by experimentation. I'm sure a better result could be achieved by a more systematic and automatic search.

The list is compressed with `zopfli -c --deflate --i300000 words.txt`.
> 4 votes

# Answer
# Charcoal, 400 bytes, 139 words

Try it online! Link is to verbose version of code. Just a compressed string based on @ovs's Bubblegum word list, except deciding which nine words to drop was interesting to say the least, as deleting some words actually increases the byte count!
> 4 votes

# Answer
# Nibbles, 161 words, 400 bytes.

```
.=\`\<159\`D 6+~"o y"`D 21*"sh"`%!|;@`#$4+~:`/@5`<+$~;@=" "$$45f31d2e733373ab092b79e7b544370bc7a0e362d8beeb825fe11e496df679b92e76991f03d6bc7f4389125c5b3648e326c221e31340945b6a79d28e6cbafaf177dccffd45c3e0e544365a8c973aed312eb485f57c8d861d18c62044842f41b7db23a106ede98d24c314c9d979ba388abeed82b04e848d8a9b6e44aafbb4bc0a7eae60687b13ecba3c0c240b05f7a0b2910a1843ca0af8f46849d9a565d695255ae19b2c954869ba9662723e903f422af11ef182dc00343885921657571bd40757f46ba10eda6a60e78c37ba913f26c93db1c2e1b9714d6c2601f504eba9cb0fff65d060cf08156986b079ae1046cd3dc1415a1daad9d57a79d13a271c9bc788631440d1ee118a40099517ce55c1389854cf0afa17ad73765d017de916abb93abfa49ff8d2d77382ab8f89db95a4ff8ce929bccd1435a1c98f9af7e67fe1847e6cdb348fad50d8c2c7ed5efd26bf7b838a985bc0bffe0a5168fcad28060f974b40c7dcf00b562ed1cbc3937ce387e71f

```

That's 64 nibbles of code and 736 hex digits of data at half a byte for each.

Nibbles isn't on TIO yet, but run it like this:

```
nibbles words.nbl < /dev/null

```

Ungolfed version:

```
  .=\
      `\ <159 \`D 6 +
           ~"o y" `D 21 \c unused dat
     *"sh"`%!
            |fstLine `# $ 4 #" abdfghiklmnoprstuvyz"
            +~:`/c 5 sets m `<+m~ dat sets w
            =
           " "
      w
    $

```

(hex data is the same)

The method is essentially to encode each letter in base 21 data, but with 1 key trick.

Notice these two inefficiencies with that trivial encoding.

* If the list is sorted then the next first letter is the same or 1 more.
* Spaces are by far the most common

With the trick, a space and the next first letter combined can be encoded with a single base 6 digit! That's a savings of 125 bytes of data.

First sort the words alphabetically by first character and length as the tie breaker. Now compute difference in length of words, with 6 added if they differ in starting letter. These numbers now encode what the next words length and starting letters are.

So if the last word was "ats" and the digit is 2, it means the next word also starts with 'a' but has length 5. Now if the next digit is 2, it means the next word starts with 'b' and is length 3. That is because there are no 7+ letter words and no 1 letter words encoded (o and y are handled specially for this reason).

One problem I ran into is there are only 160 words \< 7 in length. But if we handle even one 7 letter word the above method would need base 7 digits which would add about 5 bytes of data. To get around this I encode all "sh" as spaces, which effectively makes words with sh in them shorter. That's the most common letter combo (used 23 times in the words used), but this trick doesn't really save much because it increases the base that the letters are encoded as and requires code to convert back. Each use saves one base 21 digit (-12.5 bytes), but requires base 21 instead of 20 (+5 bytes), and the decoding code is `*"sh"`% WORD_GOES_HERE " "` which is 5 bytes. The next most common combo (15ish occurrences) isn't common enough to save anything unless the decoding process becomes more efficient.

The way the base 21 list and base 6 list are encoded is using nibbles data feature which lets you encode a single number after your program with no terminators possible (normal numbers would use 1 bit of every 4 to terminate or not). This is a pure number not a list, but can be extracted to a desired base using ``D <base>`. But since the data needs to be used for both lists, we reverse it for one of them and truncate it. The non truncated list will have garbage data at the end, but this will never be consumed the way the program is written.

There's another useful trick that saves about 8 bytes which is how the alphabet is encoded which is: " abdfghiklmnoprstuvyz"

Rather than encode this directly, we use luck. The Nibbles hash function ``#` also uses data as salt, so if we have enough degrees of freedom in our encoding then we can create a hash that will deterministically map:

```
" abcdefghijklmnopqrstuvwxyz" to
"111010111101111110111110011" so that after filtering it, it becomes
" ab d fghi klmnop rstuv  yz" (without the spaces)

```

The probability that this mapping occurs is `(1/4)**7*(3/4)**20` if we take the hash value mod 4 and use 0 as false and 1 2 3 as true. This is about 1 in 5 million. Notice that we can permute sets of words that have the same starting letter and length. This will change the encoded data, but will still give a correct output. There are also multiple 6 letter words that aren't used (now that sh is 1 letter), so that is another degree of freedom.

Luckily this only takes about 1 hour to find with brute force search on random permutations of the starting words.

Here's the code to find it:

```
  # removed o y
  let uwords |.%"abail abikis ak akniton alfabit atirsin atom ats aypal baka baklait banl bgil bianto bit bo boraky borsh bot br brbrno byt daosik diga digiz dogo dolmuk dongso douv drarkak fa fafasok fasmao fidr floria fridka friv fully fylo fyrus gilmaf gogu gogzo gongul gorlb gosio gratbt gutka hisi horrib hurigo inglish iomshuksor isa ispikar isplo ita iushb izlash kaikina kat katisas katlani kfaso khalling kisongso kivsk klingt kod koik kolbat komy konma korova koss kotsh kris kromir ksik ksuz ktaf ktomish ktomizo la lan lgra loshad lyly mak makanto makav makina marinolus marta matiks mim mimhis mingso mitsh molo mosdob motif motkop movogal muratsh mutka naita ngoirfo nidriok nilo nin nini ninibr nirus noguna nolif nors ogig omkop onion opru orilha orni ozon papin paslo pasrus pirishy pluban polr posodo pouk produty rak raznitsa rigiks rilifior riomr rno ronta rus ryby sabbia sai sakar saman sandvitsh sasa sfiny shatris shidoso shilan shimshoom shor shotiya shuan shubhu shuksor shuriok shutis shutrak shyba sibas sibin simriomr sod sokit spamra spamt srirad sutka taika tipstor tizingso tksu tobl tokvod tomp tonfa toto totobr tshans tshimiso tshomp tura tuvung uboiak umub vaf vintz voda vodl vontark yntsh zimdo zivod zombit zorliplak"~
     \w
        ?==w "yntsh" w *" "`%w"sh" # don't convert this word because the jump to zimdo would be 6 then
     - 7 ,$

  hex / |.,~ \i
  let words +=~ uwords \w `# :w i 4273 # this essentially permutes the words randomly
  # permuting randomly is more efficient than searching through permutations in order as small changes will actually likely map to the same encoding (i.e. if you swap words of different lengths that will get undone during the encode process).

  let takewords 159
  let bestchars -" abdfghiklmnoprstuvyz" ""
  let selectedwords | | words ~ \w | w ~ \l  ? bestchars l - 7,$
  let nc ,bestchars

  let bestwords < takewords +=~ selectedwords ,$
  let sortedwords +=~ +=~ bestwords ,$ =1$
  let tailed .sortedwords>>$

  let lens \:1 ! sortedwords >>sortedwords ~ \w1 w2
        let lengthdiff -,w2,w1
        let chardiff - ?bestchars =1w2 ?bestchars=1w1
        +lengthdiff *5 chardiff

  let data . sortedwords \word
     let wd ! bestchars word ?
        >>. wd
           \c1 -c1~

  let d1 `@ nc +data
  let d2 `@ 6 lens
  let d1p *d1 ^nc ,`@ nc d2
  +d1p % -d2   `@ 6 \<,lens \`@ 6 d1p   ^6 takewords

  \fd
  * ==| " abcdefghijklmnopqrstuvwxyz" \c `#~ :o c `@ 256 fd 4
        " abdfghiklmnoprstuvyz"
    - 737 ,hex fd # max size 736 (sometimes it is 737 for unknown reasons)

  $

```

Other ideas: Remove z, this was a complete wash because z is in some short words.

I considered using something like huffman encoding since some letters are common and others rare. It would save about 30 bytes of data, but now you have to encode at least the order of commonness of the alphabet (and then assume some function of probability on it, it is actually pretty linear though). That would take at least 10 bytes. I don't think that leaves enough to decode and save anything.

I'm kind of surprised this method did so well without really finding any other patterns in the data. But it doesn't seem like there are any other obvious patterns that are so strong to be worth the extraction code.
> 3 votes

# Answer
# Vyxal, 399 bytes, 85 words

```
`ab₴⁋
ak
ƈ¶
₴ǒ
ay₃⁺
b√ṫ
b□×
b£ṫ
Ǎ₂ǎǏ
°ẋ
bo
b⋎≈h
ǍĊ
br
Ǎ∩
d⋏ė
d⋏ḟz
d꘍τ
›¢£ǎ
∩ḟv
fa
⊍½…ƈk
⊍†Ǐẏ
f⋏ø
⊍¾≥‹
fȦ‹ka
ß≠v
↔¥
fƒİ
fy≥₃
£ṫǏ⟨
g꘍ȧ
£₆zo
£§£Ḣ
g⋎Ċb
go∪ḋ
gr₴↵t
£Ȧka
¥₈≥ḟ
¥Ġ⋏ġ
ḋ₌l⋏÷
₍₴
i∪…kar
isɖ„
↲₍
iꜝ⁺b
izl⁋‛
Ṅ⋎k⋏£
kat
kµ₴Ẇ≠
k₴≬…„
kf…ƈ
k€Ḟḋ₌
ki↔Ṡo
kivsk
klḋ₌t
kod
koik
kolḂṙ
k꘍¼
koǏṗ
k⋎§va
koss
k⋎Ṡh
k≥τ
kroǏḂ
ksik
ksuz
k≠ʁ
k¢‹⋏÷
kt꘍⁽zo
la
ȯ¡
l£Ẇ
†ṫλ‡
lƒṖ
mak
m√ṫv
s¥₈
shꜝø
∪Ǐǎ⌐
∪Ǐ≠ḣ
shƒ≠
siǍḟ
si½ǔ`

```

Try it Online!
> 1 votes

# Answer
# 05AB1E, 126 words, 399 bytes

```
.•2Z₃LSι#@#«Σ±ñÿ˜¸‚÷ý…qÄнβŠŒäãΣαÑz@W|RÈÚ<¸´_£]ºRùƒl®нJë2k‘ƶ9žΔÍ2s`0õÙ{óžM¨àWhà
—'ïš<G¾¯×c†}À|Òé´8N/§j::&βxΓ"oÑ.ðË¡ÄΛ™ζÒ₅¬]õ2b?ç9.d€γβвΣ;$θǝØ,ó=-ž4ó§¸™₃λ¬ÍÕ~Oì&^uÜ≠¥ƒvé©^Ûïæ(7I†=^;L½ÃÜ-+ÙXe‡¯ÚŒ†zÏZ₁≠pxÎUθè±t&∊s†è-ÚÎîÓEd£¤Áà³à^]I>ûr\ú±ÉþÏ˜2ƒv´g¸>[—üéÃ≠JQG0(*ŠØ²DƵδтÕây/Y*.¤\4hVÌè¯ʒ<ÊvßëĀиðθH₆÷aΔθåŸнā₅·…˜l’ƶ8¥þ“Àöë₄æ*b₁¤—εÒ¥QëQÒeн≠Càz”9†Í=<Xóγ¯mpð]BIÅтîƒ6ƒ°ĆAćγΣß”/8#Dv:‡‘{zƒ$ƒF?¼[v¡bËδvÍ¸špîÈfa÷ÆðÛн‹

```

Try it online!
> 1 votes

# Answer
# Python, 46 words (397 bytes)

```
import base64;print(base64.b85decode(b'VPauvY#?D`X=`b7AYp56X>@OHAYp7~VPa`?AYpWAa&u{JAYpWGZ6INEb0A@PaA9m9Vqt4xAYx%_Y+-41AYx%|Y#?H1X>1^3X<=@3Zy;i6bRc4Ha$#$EAYyNFb7&x9Z*(AHav)-IVsdV8AYyrRAY@^0b7^ZJWNBw%AY^H0X?h@JZ)a~HWN&P3b!#AGZ*FIEZy;oEb#@?Ra$$07VQU~}VP;`-Z)+fCVRLO^Zy;uAWO5*8Y;SUDVIXF5X=H0*AZBuDb|7YTY;1WTW_fIHAZB@Tb#owRX>4s_W*}#8XLTTFZ)bXMAZKrGXLW2KXK!+BVjyR4b7^lNXL4b5Vss#9b#!ZCAZTfGX&`8Ca&l>6'))

```

The base85 encoded text, for testing:

```
VPauvY#?D`X=`b7AYp56X>@OHAYp7~VPa`?AYpWAa&u{JAYpWGZ6INEb0A@PaA9m9Vqt4xAYx%_Y+-41AYx%|Y#?H1X>1^3X<=@3Zy;i6bRc4Ha$#$EAYyNFb7&x9Z*(AHav)-IVsdV8AYyrRAY@^0b7^ZJWNBw%AY^H0X?h@JZ)a~HWN&P3b!#AGZ*FIEZy;oEb#@?Ra$$07VQU~}VP;`-Z)+fCVRLO^Zy;uAWO5*8Y;SUDVIXF5X=H0*AZBuDb|7YTY;1WTW_fIHAZB@Tb#owRX>4s_W*}#8XLTTFZ)bXMAZKrGXLW2KXK!+BVjyR4b7^lNXL4b5Vss#9b#!ZCAZTfGX&`8Ca&l>6

```

Try it online
> 1 votes

---
Tags: code-challenge, kolmogorov-complexity, restricted-source, natural-language, open-ended-function
---


title: Is it a possible Hearts result?

text:
# Question
Title: Is it a possible Hearts result?
Hearts is a 4-player game that uses the following scoring rules:

1. Everyone starts with *score* 0.
2. Each round every player gets a non-negative amount of *points*. The sum of the points is 26, and at least one player gets 13 or more points.1
3. The points are then added to the players' score except if a player gets 26 points. If that happens, everyone else adds 26 to their score, and the player who got 26 points adds none.
4. The game ends when someone gets a score of 100 or more. Until then, steps 2 and 3 are repeated.

Your task is to take 4 non-negative integers representing the scores of the players at the end of the game and decide if it's a valid game. That is, are those scores possible to achieve by following the rules until the game ends.

# Samples

```
[26,26,26,26]  -> False (The game has not ended since no one has a score of 100 or more)
[1,1,2,100]    -> True  ([1,0,0,25]+[0,1,0,25]+[0,0,1,25]+[0,0,1,25])
[1,1,2,108]    -> False (Sum not divisible by 26)
[26,26,26,260] -> False (Game should have ended before a score of 260 is reached. In fact, 125 is the maximum score a player can have)
[104,104,104,0]-> True  ([26,26,26,0]+[26,26,26,0]+[26,26,26,0]+[26,26,26,0])
[0,0,0,104]    -> False (One can't just add 26 points to his score. That would add 26 to the 3 other players)
[13,13,104,104]-> True  ([0,0,13,13]+[0,0,13,13]+[0,0,13,13]+[0,0,13,13]+[0,0,13,13]+[0,0,13,13]+[13,0,13,0]+[0,13,0,13]+[0,0,13,13])
[10,10,120,120]-> False (The last turn must be [26,26,26,0] for two players to reach 120, but two players also have <26 score)
[0,0,5,125]    -> False (The last turn can't be [0,0,0,26], suggested by Neil
[117,117,117,117]-> False (Last turn get >26 point and is not a [0,26,26,26])
[104,104,104,104]-> False (Even if last round is [13,5,4,4], it was [91,99,100,100] which is impossible)
[101,101,101,113]-> True  ([7,7,6,6]+[26,26,26,0]+[26,26,0,26]+[26,0,26,26]+[0,26,26,26]+[13,13,0,0]+[0,0,13,13]+[3,3,4,16] thank AnttiP for the example)
[15,125,125,125] -> True  ([5,13,4,4]+[5,4,13,4]+[5,4,4,13]+[0,26,26,26]+[0,26,26,26]+[0,26,26,26]+[0,26,26,26] as Nitrodon suggest)

```

This is so the shortest code in each language wins.

# Note

* All true cases can be seen here. You can also see here for possibilities of score for a given amount of rounds and state(ended/not)

1 `non-negative amount of points` is the game part. 13 is the Queen of spades

# Answer
# Charcoal, 69 bytes

```
∧‹﹪Σθ²⁶‹³⁻Σθ⌈θ⎇‹⁹⁹⌊θ›³¹¹⁻Σθ⌈θ¬÷⎇‹²ΣＥθ‹²⁵ι⁻⌈θ¹⁰⁰∨±‹¹²⁴⌈θ⊖ΣＥθ⌈⟦⁰⁻ι⁹⁹⟧²⁶

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if possible, nothing if not. Explanation: A final score is valid if it satisfies the following:

* The sum of all the scores is a multiple of 26.
* The three players excluding the highest score have scored at least 4 between them.
* If all four players have scored at least 100, then the three players excluding the highest score have scored at most 310 between them.
* Otherwise if at least three players have scored 26, then the highest score is between 100 and 125 inclusive.
* Otherwise, the highest score is less than 125 but the sum of the amounts by which the relevant players have scored over 99 is between 1 and 26 inclusive.

In order to verify the assertions above I devised an alternative approach which unfortunately is still 7 bytes longer than the fixed version after it discovered a bug in my original approach.

```
Ｆ³⁸⁴¹⁶Ｆ⁴⊞υＥ⁴⁺﹪÷ιＸ¹⁴λ¹⁴×¹³⁼κλ›∧‹⁹⁹⌈θ‹³⁻Σθ⌈θ∨﹪Σθ²⁶⬤υ∨⁻²⁶Σι⊙⎇№ι²⁶⁻²⁶ιι÷⁻§θμλ¹⁰⁰

```

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

```
Ｆ³⁸⁴¹⁶Ｆ⁴⊞υＥ⁴⁺﹪÷ιＸ¹⁴λ¹⁴×¹³⁼κλ

```

Generate all valid captures for a single round (plus some invalid ones as well, but they'll be filtered out later). The idea is to generate all lists of four non-negative integers that sum to 13, then take each of those and add 13 in turn to each integer.

```
›∧‹⁹⁹⌈θ‹³⁻Σθ⌈θ∨﹪Σθ²⁶

```

Check at at least one score is at least 100, at least one other score is at least 4, and the sum of the scores is a multiple of 26.

```
⬤υ∨⁻²⁶Σι⊙⎇№ι²⁶⁻²⁶ιι÷⁻§θμλ¹⁰⁰

```

Check that there's at least one valid capture arrangement where subtracting the scores of that arrangement (adjusting for the case where one player captured all of the penalty cards) from the input results in a set of four scores between 0 and 99 inclusive.
> 2 votes

# Answer
# Jelly, 40 bytes

```
®ṗ4’S⁼®ƊƇṀ>12ƊƇ
4⁻þ`×26©;¢ṗ⁴+\Ṁ>99ƊƇḢƊ€ċ

```

A monadic Link accepting a list of integers that yield `0` (falsey) if not a possible Hearts result or a positive integer (truthy) if it is.

**Don't Try it online!** ...it won't finish (Maybe I'll golf one that will too...).

### How?

```
®ṗ4’S⁼®ƊƇṀ>12ƊƇ - Helper link: no arguments
®               - recall 26 from the register
 ṗ4             - All length 4 lists of [1..26]
   ’            - decrement (vectorises)
    S⁼®ƊƇ       - keep those with sum 26
         Ṁ>12ƊƇ - keep those with a maximum value over 12

4⁻þ`×26©;¢ṗ⁴+\Ṁ>99ƊƇḢƊ€ċ - Link: list of four integers, X
4⁻þ`                     - table of not-equal between [1,2,3,4] and itself
     26©                 - place 26 in the register
    ×                    - multiply the table values by 26
        ;¢               - concatenate all the other scores by calling the helper Link
          ṗ⁴             - All length 16 lists with those lists as elements
                             note: games take at most 15 rounds (and ⁴ is shorter than 15)
                     Ɗ€  - for each, last three links as a monad:
            +\           -   cumulative reduce by addition (non-vectorising, unlike Ä)
                   Ƈ     -   keep those for which:
              Ṁ>99Ɗ      -     maximum is greater than 99
                    Ḣ    -   head (first reached winning score list)
                       ċ - count occurrences of X

```
> 1 votes

# Answer
# Python 3, 220 bytes

```
s={(0,)*4}
r=range(27)
f=lambda*a:[a]*(12<max(a)<sum(a)==26or sum(a)-min(a)*2==78)if len(a)>3 else sum([f(*a,i)for i in r],[])
for t in r:s={i*(max(i)>99)or tuple(map(sum,zip(i,j)))for j in f() for i in s}
s.__contains__

```

It should work in theory. But I had never tested it actually. No TIO links as it certainly timed out on TIO.
> 1 votes

# Answer
# 05AB1E, 48 bytes

An extremely slow brute-force approach..

```
30Åœ4ù<ć_₂*šʒà13@}€œ€`₂ã€η€`€øOʒàƵP‹}ʒ{¨OƵÓ‹}€Qà

```

No TIO since it's way too slow.

A port of *@Neil*'s Charcoal answer would be 52 bytes:

```
{¨OUт@PiXƵÓ‹ë₂@O3@iàтƵOŸsåë₂LIZƵO‹*99-DdÏOå]IO₂ÖX4@P

```

Try it online or verify all test cases.

**Explanation:**

```
30Åœ           # Get all lists of positive integers that sum to 30
    4ù         # Only keep all lists of length 4
      <        # Decrease each by 1
               # (we now have all non-negative integers that sum to 26)
       ć       # Extract head; pop and push remainder-list and first list
               # separated to the stack
               # (the first list is [0,0,0,26])
        _      # Check for each if it's 0: [1,1,1,0]
         ₂*    # Multiply that by 26: [26,26,26,0]
           š   # Prepend it back to the list
ʒ              # Filter these lists by:
 à13@          #  Check if the maximum is ≥13
}€             # After the filter: map over each remaining list:
  œ            #  Get all its permutations
   €`          # Flatten it one level down to a list of lists again
     ₂ã        # Take the cartesian product of 26
               # (at least 15 is required, and 26 is the smallest single byte
               # constant above this)
       €η      # Get the prefixes of each inner list of 26 lists
         €`    # Flatten it one level down to a list of list of lists
           €ø  # Zip/transpose each inner list of lists
             O # Sum each inner-most list
ʒ              # Filter these lists of sums:
 àƵP‹          #  Check if the maximum is smaller than 126
}ʒ             # Filter again:
  {            #  Sort the four values
   ¨           #  Remove the last/highest
    O          #  Sum the lowest three
     ƵÓ‹       #  Check if it's smaller than 311
 }€Q           # After the filter: check for each remaining list if it's equal to
               # the (implicit) input-list
    à          # Max: check if any is truthy
               # (which is output implicitly as result)

```

```
{                     # Sort the (implicit) input-list
 ¨                    # Remove the last/highest value
  O                   # Sum the remaining three
   U                  # Pop and store it in variable `X`
т@Pi                  # If all four values in the (implicit) input-list are ≥100:
    XƵÓ‹              #  Check if `X` is smaller than 311
   ë₂@O3@i            # Else-if at least three values are ≥26:
          àтƵOŸså     #  Check if the maximum is in the range [100,125]
         ë            # Else:
            IZƵO‹     #  Check if the maximum of the input is <125
                 *    #  Make everything 0 if this is falsey
             99-      #  Decrease each value in the input-list by 99
                DdÏ   #  Only keep the non-negative values
                   O  #  Sum those together
          ₂L        å #  Check if this sum is in a [1,26]-ranged list
]                     # Close all if-else statements
IO₂Ö                  # Check that the sum of the input-list is divisible by 26
X4@                   # Check that `X` is ≥4
P                     # Check if all four checks on the stack are truthy
                      # (after which this is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `ƵÓ` is `311` and `ƵO` is `125`.
> 0 votes

---
Tags: code-golf, decision-problem, card-games
---


# Question
Title: Make a sprite-sheet from all the Stack Exchange sites' favicons
Your goal in this code golf is to compile all the Stack Exchange sites' favicons.

---

## Getting the Domains

The domains you will be using will be:

* `*.stackexchange.com`
* `stackexchange.com`
* `stackoverflow.com`
* `superuser.com`
* `serverfault.com`
* `askubuntu.com`
* `mathoverflow.net`
* `stackapps.com`
* `stackauth.com`

Everything but `stackexchange.com` and `stackauth.com`, as of now, can be gathered from `/sites`.

All the meta counterparts will also be included. (just prepend `meta.` to the beginning of any of the domains to get the meta site)

The list above shows the order of the sites. Sites without their own domain (`*.stackexchange.com`, i.e. `codegolf.stackexchange.com`) are first in the stylesheet, and are sorted alphabetically. After you've sorted the subdomain sites, the rest of the domains are in the order listed above.

Then, you can append `/favicon.ico` to each one of the domains you dynamically compiled and get the 32 by 32 pixel image that results from it.

Here's another list for domains that redirect to `*.stackexchange.com` sites:

* `askdifferent.com``apple.stackexchange.com`
* `arqade.com``gaming.stackexchange.com`
* `seasonedadvice.com``cooking.stackexchange.com`

## Output the Images

As soon as you have all of the favicons from the sites and their meta counterparts, your code combines them. Optionally, convert them into .PNG files (you gathered .ICOs, and trying to get `favicon.png` doesn't work) After that, you can start combining the images into one rectangle.

There will be 10 columns, each 32 pixels in width, making a total of 320 pixels. The number of rows will match those needed to fit all the favicons, and they are 32 pixels in height.

Your code should output an image with all of the favicons you gathered as a transparent .PNG file, which is already , like seen below:

---

## Scoring

This is and so the least bytes wins!

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

```
var QUESTION_ID=86753;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```

# Answer
# JavaScript (ES6), ~~691~~ ~~687~~ ~~680~~ ~~663~~ ~~646~~ 657 bytes

```
fetch(new Request('//crossorigin.me/http://stackexchange.com/sites')).then(r=>r.text(t=(d=document).body.appendChild(c=d.createElement('canvas')).getContext('2d')).then(a=>(d=new DOMParser(c.width=320).parseFromString(a,'text/html'),s=[...d.querySelectorAll('.grid-view-container>a')].map(e=>!~(h=e.href[p='slice'](7))[o='indexOf']('met')?h:h[p](5)),c.height=-~(s.length/5)*32,s.sort((a,b)=>(e=a[o](k='.s'),g=b[o](k),~e&&~g?a[l='localeCompare'](b):!~e&&!~g?a[p](e)[l](b[p](g)):g-e)).concat(s.filter(u=>!~u[o]('ka')).map(u=>'meta.'+u))).map((u,i,x,y)=>(u=`http://${u}favicon.ico`,x=i%10,y=(i-x)/10,i=new Image,i.src=u,i.onload=_=>t.drawImage(i,x*32,y*32)))))
```

Oof. Hopefully I can trim down the byte count.

Basically:

* CORS request to `/sites`, parse DOM and scrape the site list from there using a query selector.
* Sort first by `*.stackexchange.com` sites alphabetically, then by independent domain sites alphabetically.
* Append the meta sites, filtering out `meta.stackexchange.com` and `stackapps.com` since they're both listed on `/sites` and are without their own `meta` site.
* Asynchronously load each `favicon.ico` without CORS since we don't care about tainting the `canvas`.
* Use each site's index `i` from the sorted array to place the loaded image in the correct position on the sprite-sheet.

You can right-click on the image and select "Save Image as", so I don't think I need to write more just to explicitly prompt the image for download, since it's already enough work just displaying it.

### Revisions

1. Inlining global declarations saved 2 bytes. Submission is now one loooong line.
2. Removing `()` from `new Image()` saved another 2 bytes.
3. Changing `Math.ceil(...)` to `-~(...)` saved 7 bytes. Doesn't apply now, but in the event that the amount of sites is a multiple of 10, it's still okay because *`"There are 10 columns, which is 320 pixels in width, and unlimited rows/height"`* regardless of the amount of sites.
4. Saved 17 bytes by moving a global declaration and refactoring an unneeded ternary operator in a `.map()` function.
5. Saved another 17 bytes by storing long repeated method names to variables.
6. Cost 11 bytes to factor in `stackexchange.com` and its meta... gross.
> 9 votes

# Answer
# Python 3.5, ~~591~~ ~~549~~ ~~541~~ ~~557~~ 570 bytes:

(*+16 bytes (`541 -> 557`) to add the ability for the final image to dynamically expand in height based on the number of favicons gathered.*)

(*+13 bytes (`557 -> 570`) since URL shorteners are apparently not allowed.*)

```
from urllib.request import*;from PIL import Image as I;from io import*;import re
H='http://';U=urlopen;u=y=0;V=sorted(re.findall('<h2><a href="%s((?!meta).+?.stackexchange.com)">'%H,U(H+'stackexchange.com/sites?view=list').read().decode()[7167:]))+['%s.com'%i for i in'stackexchange stackoverflow superuser serverfault askubuntu mathoverflow stackapps stackauth'.split()];i=I.new("RGBA",(320,-~(len(V)*2//10)*32))
for l in V+['meta.'+i for i in V]:
 try:
  i.paste(I.open(BytesIO(U(H+l+'/favicon.ico').read())),(u,y));u+=32
  if u>319:u=0;y+=32
 except:0
i.save('O.png')

```

Quite long, but hey, I beat Javascript! :D This imports the modules for the following uses:

* `urllib` to fetch website and image data.
* `io` module for the `BytesIO` function to decode the fetched image data for `PIL`.
* `re` for the use of regular expressions to parse the website data.
* `PIL` to create the final image from the fetched image data.

Creates and saves a `320 x 1024` PNG image named `O.png` in the current working directory, with all the favicons in the order specified. I will try to golf this down more over time as much as I can, but for now, I could not be happier. :)

**Final Output Image:**
> 3 votes

# Answer
# JavaScript, 563 bytes

```
a=[]
fetch`//api.stackexchange.com/sites?pagesize=999`.then(r=>r.json().then(j=>{p=j.items.forEach(i=>a.push(i.site_url+"/favicon.ico"))
s=a.sort()
g=s.filter(e=>/(?<!meta)\.stackexchange/.exec(e)).concat(["//stackexchange.com/favicon.ico"]).concat(s.filter(e=>!/meta|stackexchange/.exec(e))).concat(s.filter(e=>/meta/.exec(e)))
document.body.append(c=document.createElement`canvas`)
c.width=320
c.height=(g.length/10+0.9|0)*32
c=c.getContext`2d`
for(u in g){
var i=new Image()
i.src=g[u]
i.u=u
i.onload=(p)=>c.drawImage(b=p.target,b.u*32%320,((b.u/10)|0)*32)}}))
```

### Generated image (as of writing this)

```
<img src="https://i.stack.imgur.com/jy3Ct.png"/>
```

## Explanation (key points)

---

`fetch`//api.stackexchange.com/sites?pagesize=999``
▸ Fetch the list of all SE sites \[API docs\]
**-2 bytes**: Uses ES6's tagged template
**-3~4 bytes**: It also uses a trick `//` that takes advantage of Stack Snippets (otherwise, you'd have to replace `//` with `http:` or even `https:` because of CORS weirdness)
**Note:** It only list the first 999 sites. While as of writing this, theres "only" 355 sites, this could reach 1000. then you'll need to add one byte: `...``?pagesize="+2e9`, which can go up to 2000000000! (more than that makes an `invalid parameters` error)

---

`s=a.sort()`
▸ Sort the list of URLs in alphabetical order (meta and normal aren't separated yet)

---

`s.filter(e=>/(?<!meta)\.stackexchange/.exec(e))`
▸ Filter all of the urls that doesn't contain `meta` but contains `.stackexchange`

`.concat(["//stackexchange.com/favicon.ico"])`
▸ Add `stackexchange.com`'s favicon URL (Somehow stackexchange.com isn't on the list)

`.concat(s.filter(e=>!/meta|stackexchange/.exec(e))`
▸ Add all of the elements that doesn't contains `meta` or `stackexchange`
`.concat(s.filter(e=>/meta/.exec(e))`
▸ Add all of the elements that contains `meta`

---

`c.height=(g.length/10+0.9|0)*32`
▸ Set the height of the canvas to the number of urls(`g.length`) / 10(number of rows) approximately ceiled with `+0.9|0`

---

`i.u=u`
▸ Bind the URL id to the element so it can be drawn asynchronously after the `onload()`

---

`c.drawImage(b=p.target,b.u*32%320,((b.u/10)|0)*32)}}))`
`b.u*32%320` URL id(`g.u`) * 32(icon size) % 320(icon size\*10)
`((b.u/10)|0)*32` ((URL id(`g.u`) / 10(number of rows)) |0(floor)) * 32(icon size)
> 1 votes

---
Tags: code-golf, graphical-output
---


title: Solve Rubik's Clock

text:
# Question
Title: Solve Rubik's Clock
Rubik's Clock is a round(ish) puzzle with two flat sides. On each side, front and back, there are 9 clock faces, arranged on a 3x3 grid. In addition, there are 4 pegs (switches) in between the clock faces, and they can be set to protrude either from the front or the back. Lastly, there are 4 dials on the edge of the puzzle. You can rotate them to manipulate the 4 clocks in the corners, on the front and the back simultaneously. Here's a schematic.

The switches each have 4 clocks around them, and they act as a lock to those 4 clocks. If a switch is pressed in, any movement of any of the surrounding clocks is synchronised with the three others. If the switch is not pressed in, they move independently. However, in that case, it can be seen as pressed in from the other side. Therefore, the 4 clocks around the switch on the other side of the puzzle are synchronised. The switches thus always lock 4 clocks together, either on the front or the back.

For consistency in clockwiseness and switch settings, we define one side as the front and the other as the back. As seen from the front, the switches are set to 1 if they are pressed in, and 0 if they are not pressed in.

The four corner clocks are inversely synchronised between the front and the back. If you were to turn a dial clockwise, the clock on the backside in the same position would turn counter-clockwise. Therefore, there is a total of 14 independent clocks: 4 corners, 5 independent on the front and 5 independent on the back.

Consider an example where all clocks are set to 0 (or 12), switch 0 is set to 1 and the other switches are set to 0. If we turn dial 0 to position 2, the following happens:

* Front clocks 1, 3 and 4 are synchronised to clock 0 and all move to position 2
* Back clock 0 is inversly synchronised to clock 0 and moves to position 10 (= -2 mod 12)

Now consider the same example, but instead both switches 0 and 3 are set to 1, whereas switches 1 and 2 are set to 0. If we turn dial 0 to position 2 again, the following happens:

* Front clocks 1, 3 and 4 are synchronised to clock 0 and all move to position 2
* Front clocks 5, 7 and 8 are synchronised to clock 4 and all move to position 2
* Back clock 0 is inversely synchronised to clock 0 and moves to position 10 (= -2 mod 12)
* Back clock 8 is inversely synchronised to clock 8 and moves to position 10 (= -2 mod 12)

The aim of the puzzle, given a scrambled set of clocks, is to set all clocks to 0. You do this by flipping switches and turning dials appropriately. This is also the task of the challenge.

# The challenge

Given a valid setting for both the front and back clocks, output a sequence of switch settings and dial turns which set all clocks to 0.

# Rules

* Input and output are flexible to the extent permitted by the default rules, provided that they unambiguously describe the clock and the required sequence.
    + You can redefine the indexing.
    + If convenient, you can take only the 14 unique clock faces as input.
    + Clocks on the front must always respond directly (positively) to dial turns.
    + Clocks on the back must always respond inversely to dial turns.
* Consider all switches set to 0 at the start of the solve.
* The final switch settings can be nonzero, as long as all clocks are solved.
* Your program must finish in a reasonable amount of time: no brute-forcing.

# Examples

```
Example input: [9, 9, 0, 9, 9, 0, 9, 9, 0], [3, 0, 0, 0, 0, 0, 3, 0, 0]
Example output: [0, 2, (2, 3)]
                 |  |     +---- Dial turn
                 +--+---------- Switch flips
Step-by-step:

Current state
Switches: 0 0 0 0
Front:      Back:
 9  9  0  |  3  0  0
 9  9  0  |  0  0  0
 9  9  0  |  3  0  0

Flipping switch 0
Flipping switch 2
Turning dial 2; 3 times

Current state
Switches: 1 0 1 0
Front:      Back:
 0  0  0  |  0  0  0
 0  0  0  |  0  0  0
 0  0  0  |  0  0  0

```

```
Example input: [11, 0, 11, 8, 8, 8, 8, 8, 8], [1, 1, 1, 1, 1, 1, 4, 0, 4]
Example output: [2, 3, (2, 4), (1, 1)]

Step-by-step:

Current state
Switches: 0 0 0 0
Front:      Back:
11  0 11  |  1  1  1
 8  8  8  |  1  1  1
 8  8  8  |  4  0  4

Flipping switch 2
Flipping switch 3
Turning dial 2; 4 times

Current state
Switches: 0 0 1 1
Front:      Back:
11  0 11  |  1  1  1
 0  0  0  |  1  1  1
 0  0  0  |  0  0  0

Turning dial 1; 1 times

Current state
Switches: 0 0 1 1
Front:      Back:
 0  0  0  |  0  0  0
 0  0  0  |  0  0  0
 0  0  0  |  0  0  0

```

```
Example input: [3, 11, 0, 11, 11, 5, 2, 11, 1], [9, 8, 0, 8, 8, 4, 10, 8, 11]
Example output: [1, 3, (2, 9), (0, 7), 0, 1, 2, 3, (0, 6), 2, 3, (3, 7), 0, 1, 2, 3, (0, 4)]

Step-by-step:

Current state
Switches: 0 0 0 0
Front:      Back:
 3 11  0  |  9  8  0
11 11  5  |  8  8  4
 2 11  1  | 10  8 11

Flipping switch 1
Flipping switch 3
Turning dial 2; 9 times

Current state
Switches: 0 1 0 1
Front:      Back:
 0 11  0  |  0 11  0
11 11  5  | 11 11  4
11 11  1  |  1 11 11

Turning dial 0; 7 times

Current state
Switches: 0 1 0 1
Front:      Back:
 7 11  0  |  5  4  0
11 11  5  |  4  4  4
 6 11  1  |  6  4 11

Flipping switch 0
Flipping switch 1
Flipping switch 2
Flipping switch 3
Turning dial 0; 6 times

Current state
Switches: 1 0 1 0
Front:      Back:
 1  5  0  | 11  4  0
 5  5  5  |  4  4  4
 0  5  1  |  0  4 11

Flipping switch 2
Flipping switch 3
Turning dial 3; 7 times

Current state
Switches: 1 0 0 1
Front:      Back:
 8  0  0  |  4  4  0
 0  0  0  |  4  4  4
 0  0  8  |  0  4  4

Flipping switch 0
Flipping switch 1
Flipping switch 2
Flipping switch 3
Turning dial 0; 4 times

Current state
Switches: 0 1 1 0
Front:      Back:
 0  0  0  |  0  0  0
 0  0  0  |  0  0  0
 0  0  0  |  0  0  0

```

# Answer
# 05AB1E, ~~203~~ ~~202~~ ~~193~~ 192 bytes

```
•iN yÉ¯zoи!••)i‰â™â•S£vy,.µNUDX4-5ÖiX9÷©èDÅs12αÐV0s‚,+®ǝD®_èDŽ8SSDUèY-Xǝ®_ǝ12%ë[DX5@è4•EβQÑ´—•Xè‚èË#εD•3bž§j’λ¬Ā%úÍp₄ÞÞ5öćzz…õôty‘[z\Ä≠Îβ¥…uи•S•Eÿ>nºØ1Ç¦ƒÎÖ•S£2äNèXè©èN·<-12%®ǝ}¼}•I¤Ðcû®•Xè¾‚,

```

Input is similar as the example of the challenge. A pair of lists, with the first list being the front-clocks and the second being the back-clocks.

Every two lines of the output are a step. The first line indicates the 0-based indices of the four knobs that are upwards on the front; the first integer on the second line indicates the 0-based index of the wheel we're turning, and the second integer on the second line indicates how many times we turn it clockwise.
For example, this step:

```
01
[3,6]

```

means we have the top-left and top-right knobs up on the front, and we then turn the bottom-right 6 times clockwise.

It will also output no-op steps. If the second line of a step is `[x,0]` it means nothing has changed that step, since it was already correct. (And it might potentially output `[x,12]` in the three steps where it puts all relevant clocks on 12 o'clock when they were already on 12 o'clock. If this is not allowed, `12%` can be added after the `α` (+3 bytes).)

**Try it online or try it online with debug-lines or verify all test cases with debug-lines.**

### Explanation:

Let me start with a general explanation of the 15 steps I do to solve the Rubik's Clock.

In the pictures below:

* the orange knobs are the ones that are upward for that face;
* the purple stars indicate that any of those wheels can be turned for this step;
* the red circled clocks should all face the same direction after this step.

Step 1-4, done on the front:

In step 1 we have the bottom-left knob up and the other three knobs down. We then turn the bottom-left wheel until the direction of the center is facing the same way as the direction of the top-middle clock.
In step 2 we do the same with the top-left knob and wheel, until the direction of both the center AND top-middle clocks are facing the same way as the direction of the middle-right clock.
Etc.

Then in step 5, we put all four of the knobs upwards, and rotate until the five clocks that form a + are facing 12 o'clock.

For steps 6-10 we basically do the same for the backside, after we've turned the clock upside down. (In our code below we of course only use front knobs and wheel-turns, but during an irl solve you would turn the clock upside down to repeat these steps, and also finish it with the five steps below while still looking at the backside.)

After these 10 steps, the clocks that form a + on both the front and back should all face the same way, with the ones on the back facing 12 o'clock.

After that we do four more steps to fix the corners:

After these 14 steps, all clocks on the backside (you would still be looking at irl) are now facing the same direction; all clocks that form a + on the frontside are already at 12 o'clock; and the four corner-clocks on the frontside should also all be facing the same direction.
We can now put all the knobs up at the backside, and rotate any of the four wheels to put all clocks at 12 o'clock and finish the solve.

**As for the actual code:**

```
•iN yÉ¯zoи!•           # Push compressed integer 201010123012023123233210
 •)i‰â™â•              # Push compressed integer 111243332011110
  S                    # Convert it to a list of digits as well
   £                   # Convert the first into parts of the second:
                       #  [2,0,1,"01","0123","012","023",123,23,"",3,2,1,0,""]
                       # (these indicate the front-knobs that are up)
vy                     # Foreach over these:
  ,                    #  Pop and print it with trailing newline
 .µ                    #  Reset the counter variable to 0
 NU                    #  Save the 0-based loop-index in variable `X`
 D                     #  Duplicate the current clock-state
  X4-5Öi               #  If the loop-index is 4, 9, or 14 (index-4 is divisible by 5):
                       #  (these are the steps to put all relevant clocks to 12 o'clock)
   X9÷                 #   Integer-divide the loop-index by 9
                       #   (0 for index 4; 1 for indices 9 and 14)
      ©                #   Store this in variable `®` (without popping)
       è               #   Use it to index into the clock-state
        D              #   Duplicate this list
         Ås            #   Pop and push the center value
           12α         #   Pop and push its absolute difference with 12
              Ð        #   Triplicate this abs(center-12)
               V       #   Pop and store one copy in variable `Y`
                0s‚    #   Pair another one with leading 0
                       #   (since it doesn't matter which wheel we turn)
                   ,   #   Pop and print it with trailing newline
   +                   #   Add the remaining third one to each clock in the list
    ®ǝ                 #   Replace the list of clocks at X//9
   D                   #   Duplicate the new clock-state
    ®_è                #   Get the opposite face (using X//9==0)
       D               #   Duplicate this list
        Ž8S            #   Push compressed integer 2068
           S           #   Convert it to a list of digits
            DU         #   Store a copy in variable `X`
              è        #   Get the clocks at these indices (the corners)
               Y-      #   Decrease them by the abs(center-12)
                 Xǝ    #   Insert them back at the corners
                   ®_ǝ #   Replace the list of clocks at X//9==0
   12%                 #   Modulo-12
  ë                    #  Else (this is a regular step):
   [                   #   Loop indefinitely:
    D                  #    Duplicate the clock-state
     X5@               #    X>=5 check
        è              #    Use that to index into the clock-state
                       #    (the front face for the first 5 steps;
                       #    the back face for the remaining steps)
          •EβQÑ´—•     #    Push compressed integer 15370135708620
           Xè          #    Index the loop-index into that
         4   ‚         #    Pair it with 4 (center-index)
              è        #    Get the clock-values at those positions
               Ë       #    If they are the same clock-value
                #      #     Stop the infinite loop
    ε                  #    Map over both faces:
     D                 #     Duplicate the current clock-list
      •3bž§j’λ¬Ā%úÍp₄ÞÞ5öćzz…õôty‘[z\Ä≠Îβ¥…uи•
                       #     Push compressed integer 346701341245012345830020260280682686020245781245013401234501234567012345780134567812345678
         S             #     Convert it to a list of digits
          •Eÿ>nºØ1Ç¦ƒÎÖ•
                       #     Push compressed integer 4446011120333311120444608888
           S           #     Convert it to a list of digits as well
            £          #     Split the first into parts of the second:
             2ä        #     Split it into two equal-sized parts
                       #      [[[3,4,6,7],[0,1,3,4],[1,2,4,5],[0,1,2,3,4,5],[],[8],[3],[0],[0,2],[],[0,2,6],[0,2,8],[0,6,8],[2,6,8]],
                       #       [[6],[0],[2],[0,2],[],[4,5,7,8],[1,2,4,5],[0,1,3,4],[0,1,2,3,4,5],[],[0,1,2,3,4,5,6,7],[0,1,2,3,4,5,7,8],[0,1,3,4,5,6,7,8],[1,2,3,4,5,6,7,8]]]
               Nè      #     Index the map-index into it
                 Xè    #     Index loop-index `X` into it
                   ©   #     Store it in variable `®` (without popping)
                    è  #     Index it into the clock-list
        N              #     Push the map-index
         ·<            #     Double it, and decrease by 1
                       #     (-1 for index 0; 1 for index 1)
           -           #     Decrease the clock-values by that
                       #     (so it'll increase the front and decrease the back)
            12%        #     Modulo-12 each new clock value
               ®ǝ      #     Insert them back into the clock-list at positions `®`
    }                  #    Close the map
    ¼                  #    Increase the counter variable by 1
   }                   #   Close the infinite loop
    •I¤Ðcû®•           #   Push compressed integer 20100310100123
     Xè                #   Index the loop-index `X` into it
       ¾‚              #   Pair it with the counter variable
         ,             #   Pop and print it with trailing newline

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand how the compressed integers work.

In the time I wrote this program and answer I probably could have solved multiple hundreds of Rubik's Clocks irl, haha.. xD Solving a Rubik's Clock irl is easy, but translating that to a solver-program isn't as straight-forward as I hoped it would be when I started writing it.
> 18 votes

# Answer
# Charcoal, 117 bytes

```
§≔θ⁰⁺§θ⁰↨§θ⁴±¹Ｆ⁴«≔§θＩ§5731ιζ≔⁺§θＩ§2860ι↨ζ±¹εＦ²«ＩＥ⁴∧κ⁼¹﹪⁻λι⁴Ｉ⟦⟦ι﹪⎇κε±ε¹²⟧⟧Ｆ²«ＩＥ⁴⁼‹λ﹪⁻μι⁴κＩ⟦⟦ι﹪×∨κ±¹⎇λ§ζκ⁻∧¬ι§§θ⁴κ§ζκ¹²

```

Try it online! Link is to verbose version of code. Takes input as an array of nine clocks, with a single value for the corner clocks and an array of two values for the other clocks, and outputs lists of six integers: the first four are the peg states clockwise from top left, the fifth is the dial to rotate as an integer (counting clockwise with top left as `0`) and the sixth is the (clockwise) amount, from `0` (unnecessary moves are not removed) to `11`. Explanation:

```
§≔θ⁰⁺§θ⁰↨§θ⁴±¹

```

The first set of rotations will correct the centre clocks by rotating the top left clock, so correct its value here.

```
Ｆ⁴«

```

Loop over each dial.

```
≔§θＩ§5731ιζ

```

Get the pair of clocks three clocks clockwise from that dial.

```
≔⁺§θＩ§2860ι↨ζ±¹ε

```

The clock two clocks clockwise (i.e. the next dial's clock) will be rotated by the difference of those clocks so get the final value here.

```
Ｆ²«

```

Loop over a) rotating the other clocks to match the next corner or rotating all the clocks back to noon, or b) fixing the clock three clocks clockwise or its reverse.

```
ＩＥ⁴∧κ⁼¹﹪⁻λι⁴Ｉ⟦⟦ι﹪⎇κε±ε¹²⟧⟧

```

Enable either all the peg except the next corner or all the pegs, and then rotate the current dial appropriately. These two rotations fix that clock.

```
Ｆ²«

```

Loop over the clock three clocks clockwise and its reverse.

```
ＩＥ⁴⁼‹λ﹪⁻μι⁴κＩ⟦⟦ι﹪×∨κ±¹⎇λ§ζκ⁻∧¬ι§§θ⁴κ§ζκ¹²

```

Either enable only the dial's peg, or both the dial's peg and the next dial's peg, or for the reverse clock all the pegs except those pegs, then rotate the current dial appropriately, including adjusting for the centre dial on the first rotation.

The solution basically relies on two combinations:

* If you rotate a dial with just its peg toggled, and then inverse rotate the dial with its peg and the next peg toggled, you end up only rotating the second and third clocks clockwise from the dial. (For the very first rotation, take the opportunity to fix the centre clock as well, although this also rotates the top left clock.)
* If you rotate any dial with no pegs toggled, then inverse rotate any other dial while a dial has its peg toggled, you end up only rotating that dial's clock.

By accepting the clocks in a custom order it's possible to reduce the byte count to 105:

```
≔⊟θη⊞θ⁺⊟θ↨η±¹Ｆ⁴«≔§θ⊗ιζ≔⁺§θ⊕⊗ι↨ζ±¹εＦ²«ＩＥ⁴∧κ⁼¹﹪⁻λι⁴Ｉ⟦⟦ι﹪⎇κε±ε¹²⟧⟧Ｆ²«ＩＥ⁴⁼‹λ﹪⁻μι⁴κＩ⟦⟦ι﹪×∨κ±¹⎇λ§ζκ⁻∧¬ι§ηκ§ζκ¹²

```

Try it online! Link is to verbose version of code. Takes clocks in the order right, top right, bottom, bottom right, left, bottom left, top, top left, centre.
> 5 votes

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

```
(f,b,o=[],s=[])=>('012;301,13;103,01;007,2;005,13;00,3;311,31;113,10;017,2;015,13;01,012;008,31;202,10;300,02;106,2;00'.split`,`.map(S=>((n=>o.push(...[...n].map(i=>(s[i]=!s[i],i))))((T=S.split`;`)[0]),((d,w,z)=>{while((x=+w?b:f)[4]!=(z>=0?x[z]:0)){((d,q=new Set(),W=new Set())=>{[...'0268'].map((C,i,_,E=[...['0134','1254','3674','5784'][i]])=>{if(!s[d]&&!s[i]){W.add(C);E.map(j=>q.add(j))}else if(s[d]&&s[i]){q.add(C);E.map(j=>W.add(j))}});q.forEach(i=>f[i]=(f[i]+1)%12);W.forEach(i=>b[i]=(b[i]+11)%12);o.push(...(l=o.pop()).pop?(l[1]++,[l]):[l,[d,1]])})(d)}})(...T[1]))),o)

```

Try it online!

This answer adapts the "beginner" method of solving clock to code by walking through the same static steps. It is by no means efficient (since it often generates unnecessary switch toggles) but it is fast and simple.

Ungolfed:

```
const ungolfed = (f, b) => {
    // Output steps
    const o = [];
    // Switches
    const s = [0,0,0,0];
    // *t*oggle switch(es)
    // Called like t(0,1,2) with variadic argument count
    const t = (...n) => o.push(...n.map(i=>{
        console.log(`${s[i]?'Unp':'P'}ress ${i}`);
        s[i] = !s[i];
        return i;
    }));
    // const - corner clocks (for pressed switch dial turns)
    const c = [0,2,6,8];
    // const - corner/edge clocks (for unpressed switch dial turns)
    const e = [[0,1,3],[1,2,5],[3,6,7],[5,7,8]];
    // *r*otate a dial clockwise
    // Called like r(3)
    const r = d => {
        // Using sets for deduplication
        // Front clocks that will turn
        let q = new Set();
        // Back clocks that will turn
        let w = new Set();
        for (let i = 0; i < 4; i++) {
            if (!s[d]) {
                if (!s[i]) {
                    w.add(c[i]);
                    q.add(4);
                    e[i].map(j=>q.add(j));
                }
            } else {
                if (s[i]) {
                    q.add(c[i]);
                    w.add(4);
                    e[i].map(j=>w.add(j));
                }
            }
        }
        q.forEach(i=>f[i]=(f[i]+1)%12);
        w.forEach(i=>b[i]=(b[i]+11)%12);
        let l = o.pop();
        if (l.push) {
            l[1]++;
        } else {
            o.push(l);
            l = [d,1];
        }
        o.push(l);
    };
    // rotate a dial *u*ntil
    // d - Dial to rotate
    // W - truthy -> front, falsy -> back
    // y - First index to check (in golfed version, always 4)
    // z - Second index, or if -1, use 0 (pointing up) (in golfed version, use undefined in place of -1)
    const u = (d,W,y,z) => {
        x=W?b:f;
        while (x[y]!=(!~z?0:x[z])) {
            r(d);
            x=W?b:f;
            console.log(`Turn d${d} so c${W?'f':'b'}${y} ${!~z?"points up":`= c${W?'f':'b'}${z}`}`,f,b);
        }
    }

    // Actual steps to solve (starting from all unpressed switches)
    t(0,1,2);
    u(3,0,4,1);
    t(1,3);
    u(1,0,4,3);
    t(0,1);
    u(0,0,4,7);
    t(2);
    u(0,0,4,5);
    t(1,3);
    u(0,0,4,-1);
    t(3);
    u(3,1,4,1);
    t(3,1);
    u(1,1,4,3);
    t(1,0);
    u(0,1,4,7);
    t(2);
    u(0,1,4,5);
    t(1,3);
    u(0,1,4,-1);
    t(0,1,2);
    u(0,0,4,8);
    t(3,1);
    u(2,0,4,2);
    t(1,0);
    u(3,0,4,0);
    t(0,2);
    u(1,0,4,6);
    t(2);
    u(0,0,4,-1);

    return o;
};

```
> 2 votes

---
Tags: code-golf, array, game, puzzle-solver, restricted-time
---


title: Score a Scrabble Play

text:
# Question
Title: Score a Scrabble Play
## Background

In Scrabble, players take turns placing tiles on a grid so that each contiguous set of (more than one) tiles in every row and column makes a word. In one play, tiles can be placed anywhere in a single row or column as long as there is a contiguous set of tiles that includes all of the ones placed.1 A word is scored (without considering premium score spaces) by adding up the point value of each of its letters. The point values of the letters are as follows

```
1 point: E, A, I, O, N, R, T, L, S, U
2 points: D, G
3 points: B, C, M, P
4 points: F, H, V, W, Y
5 points: K
8 points: J, X
10 points: Q, Z

```

A play is scored by adding up the scores of each new word created in a play. For example, in the play below, N and W were played to form three new words, scoring 5 (PAN) + 6 (SEW) + 6 (NEW) = 17 points.

```
PAST      PAST
AXE   ->  AXE
 E        NEW

```

Apart from the starting play, each play must involve at least one already existing tile, so that it is connected to the rest of the board.

## The Challenge

Your challenge is to write a function which takes a play and returns the total points scored in that turn. **You do not have to consider the legality of the words formed by the play, or any premium score squares.** However, you should assume that the placement of the play will be valid (i.e. will connect to the board and be placed in a line) and that the board will be nonempty before the play. Unlike in Scrabble, a play can be more than 7 tiles, and the grid can be larger than 15x15.

Your function should take a mapping of the letters to their point values as a parameter. **In addition** to the letter point values, the function should take input in one of the following acceptable ways:

* Two grids representing the board, with one showing the board before the play and one showing the board after the play.
* A grid showing the board after the play and a list of the coordinates at which tiles were placed.
* A grid showing the board either before or after the play, and a map containing each letter of the play with the coordinate at which it was placed.

The grid can be exactly big enough to contain the relevant squares, or can be padded to any larger size. This is Code Golf so the fewest bytes wins.

## Examples

The examples use the first input method, with the board before and after the play separated with `|` and the expected output in bold along with the words formed above each example.

**17** (PAN, SEW, NEW)

```
PAST | PAST
AXE  | AXE
 E   | NEW

```

**18** (ST, OO, LO, IT, DE, TOOTED)

```
SOLID | SOLID
      | TOOTED

```

**9** (HOPE)

```
     |  H
ROLL | ROLL
     |  P
     |  E

```

**4** (DOT)

```
BAD | BAD
A   | A O
NOT | NOT

```

**6** (NEW)

```
PASTURE | PASTURE
AXE  Y  | AXE  Y
NEW  E  | NEW NEW

```

**13** (PROGRAMS)

```
GRAM | PROGRAMS

```

---

1 This set must be in a single row or column, but can include letters that were already on the board, i.e. `GRAM` -\> `PROGRAMS`

# Answer
# Python3, 387 bytes:

```
import re,itertools as I
lambda o,n:sum(sum(p[i]for i in j)for j in q(n)if all(j not in k for k in q(o))and len(j)>1)
q=lambda o:[j for k in[*map(list,I.zip_longest(*o,fillvalue=' '))]+o for j in re.findall('\w+',''.join(k))]
p={'E':1,'A':1,'I':1,'O':1,'N':1,'R':1,'T':1,'L':1,'S':1,'U':1,'D':2,'G':2,'B':3,'C':3,'M':3,'P':3,'F':4,'H':4,'V':4,'W':4,'Y':4,'K':5,'J':8,'X':8,'Q':10,'Z':10}

```

Try it online!
> 4 votes

# Answer
# Jelly, 20 bytes

```
,ZḲÇ€€$€€Ẏ)œ-"/ẎḊƇFS

```

A monadic Link that accepts a pair of boards (lists of lists of characters), the first being the board's state *after* the turn has been played, that yields the score. The boards must fully align, using spaces to pad as necessary.

**Try it online!** (The header is a Link that performs the lookup of the value of a tile by its character\*)
Or see the test-suite.

* Blank tiles can be incorporated by using a new character, e.g. `b`, too.

### How?

```
,ZḲÇ€€$€€Ẏ)œ-"/ẎḊƇFS - Link: pair of lists of equal-length lists of characters
          )          - for each grid in the pair:
 Z                   -   tranpose
,                    -   pair the grid and its transpose
      $€€            -   for each line in each of those:
  Ḳ                  -     split at spaces
    €€               -     for each tile character in each of those:
   Ç                 -       call our tile value finding function
         Ẏ           -   tighten
              /      - reduce by:
             "       -   zip with:
           œ-        -     multiset difference
               Ẏ     - tighten
                 Ƈ   - keep only those for which:
                Ḋ    -   dequeue -> falsey for length one words
                  F  - flatten
                   S - sum

```
> 2 votes

# Answer
# Charcoal, 59 bytes

```
ＳθＷＳ⊞υιＵＭυ⭆Ｓ⌈⟦λ↧§ιμ⟧ＩΣＥ⁺υＥ§υ⁰⭆υ§λκΣＥ⪪ι ∧∧‹¹Ｌλ№α⌊λΣＥ↥λ⊕§θ⌕αν

```

Try it online! Link is to verbose version of code. Takes as input:

1. A string of 26 digits representing the values of the letter tiles minus `1`.
2. The previous board state, as a rectangular list of strings
3. An empty line to delimit the two boards
4. The new board state, as a rectangular list of strings

The two boards must be the same size rectangle. Explanation:

```
Ｓθ

```

Input the decremented tile values.

```
ＷＳ⊞υι

```

Input the previous board state.

```
ＵＭυ⭆Ｓ⌈⟦λ↧§ιμ⟧

```

Input the new board state, but lowercase all letters that aren't new.

```
Ｅ⁺υＥ§υ⁰⭆υ§λκ

```

Loop over the new board and its transpose.

```
ΣＥ⪪ι

```

Map over each word and take the sum.

```
∧∧‹¹Ｌλ№α⌊λ

```

Only score words of at least two letters of which at least one is upper case.

```
ΣＥ↥λ⊕§θ⌕αν

```

Calculate the score of the word.

```
ＩΣ

```

Output the final total.
> 2 votes

# Answer
# Clojure, 180 bytes

```
#(let[s(fn[x](frequencies(for[y(concat x(apply map vector x))w(partition-by #{\ }y):when(second w)]w)))b(s %2)](apply +(for[[k v](merge-with -(merge b(s %3))b)n k](*(or(% n)0)v))))

```

Try it online!

Anonymous function, accepts the three arguments in the order of: scoring map, board before, board after.
> 0 votes

---
Tags: code-golf, grid, game, scrabble
---