title: Quoted rational numbers

text:
# Question
Title: Quoted rational numbers
Quote notation is a way of expressing rational numbers based on the concept of \\$p\\$-adic numbers, written in the form \\$x'y\\$.

The quote indicates that the number to it's left (\\$x\\$) is "repeated" infinitely to the left, then prefixed to the number on the right (\\$y\\$). For example \\$3' = \\: ...3333\\$ and \\$764'31 = \\: ...76476431\\$. We can then consider the geometric series:

$$\cdots + 10^{3k} + 10^{2k} + 10^{k} + 10^{0} = \frac 1 {1 - 10^k}$$

By setting \\$k\\$ to be equal to the number of digits of \\$x\\$, we can transform this "infinite" number into a value which converges:

$$\begin{align} 3' & = \\: ...333 & 764'31 & = \\: ...76476431 \\ & & & = 31 + 764'00 \\ & = \cdots + 3\cdot10^3 + 3\cdot10^2 + 3\cdot10^1 + 3\cdot10^0 & & = 31 + 100 \times 764'\\ & = 3(\cdots + 10^3 + 10^2 + 10^1 + 10^0) & & = 31 + 100 \times 764(\cdots + 10^9 + 10^6 + 10^3 + 10^0)\\ & = 3\left( \frac 1 {1 - 10} \right) & & = 31 + 76400\left( \frac 1 {1 - 10^3} \right) \\ & = \frac {3} {-9} & & = 31 - \frac {76400} {999}\\ & = - \frac 1 3 & & = - \frac {45431} {999} \end{align}$$

Note that \\$9'0 \ne 9'\\$ as the first equals \\$-10\\$ and the second \\$-1\\$. Additionally, note that leading zeros on \\$y\\$ do affect the output: \\$81'09 = -\frac {801} {11} \ne \frac {9} {11} = 81'9\\$ Therefore, a value after the \\$'\\$ (\\$y\\$) may be omitted in the input.

You are to take, in any reasonable format, up to 2 non-negative integers \\$x\\$ and \\$y\\$, and output the fraction \\$\frac a b\\$ represented by \\$x'y\\$. Reasonable formats include:

* A string, delimited by a non-digit character, such as `'`, e.g. `9'` or `9'0`. The string will always begin with a digit; if there is no \\$x\\$ value, it will be a \\$0\\$ (e.g. `0'3`)
* A list of either 1 or 2 non-negative integers, represented as strings or lists of digits. If there is only 1, it represents \\$x'\\$. 2 integers represent \\$x'y\\$.
* A list of 2 elements. The last element may be either a non-negative integer (as a string or digit list), or a consistent value that is not a non-negative integer (e.g. `null` or `None` or `-1` etc.) that indicates that there is no \\$y\\$ value. The first value will always be a non-negative integer.

This is not an exhaustive list, if you have another method, feel free to ask.

You may output the two integers \\$a\\$ and \\$b\\$ instead of the fraction \\$\frac a b\\$. The fraction must be exact, and fully simplified (i.e. \\$a\\$ and \\$b\\$ are coprime). If \\$b\\$ is 1, outputting just \\$a\\$ is acceptable. For negative outputs, if outputting \\$a\\$ and \\$b\\$ separately, either may have the negative sign, but not both.

You may input and output in any convenient method. This is so the shortest code in bytes wins.

---

Modified from the linked Wikipedia page:

> Let \\$x\\$ and \\$y\\$ be sequences of digits, as in \\$x'y\\$
>
> Let \\$z\\$ be the digit \\$1\\$ followed by a sequence of zeros of the same length as \\$y\\$.
>
> Let \\$w\\$ be a sequence of \\$9\\$s of the same length as \\$x\\$.
>
> Then the number represented by \\$x'y\\$ is given by \\$y-\frac{xz}w\\$

## Test cases

```
x'y    = a / b
31'491 = 17609 / 99
844'80 = -4480 / 999
4'128  = -2848 / 9
247'0  = -2470 / 999
0'716  = 716 / 1
592'   = -16 / 27
3'45   = 35 / 3
9'7    = -3 / 1
9'     = -1 / 1
3'0    = -10 / 3
764'31 = -45431 / 999
81'09  = -801 / 11
81'9   = 9 / 11
123456' = -41152 / 333333

```

# Answer
> 14 votes
# , 25 bytes

```
(%-.)~/@(10^#&>)#.10#.&>]

```

Try it online!

Takes a boxed 2-item vector containing the digit vectors of \\$x\\$ and \\$y\\$, and returns a rational number. The digits must be given in extended precision. \\$y\\$ may be an empty vector. I guess it's pretty well golfed when Jelly is at 20 bytes :)

### How it works

Uses the formula at the end of the challenge. If we define \\$\\#x\\$ as the number of digits of \\$x\\$,

$$ z = 10^{\\#y}, \quad w=10^{\\#x}-1, \quad x'y = -\frac{z}{w}x+y, $$

and observe that the result is the same as the 2-vector \\$\[x,y\]\\$ evaluated in base \\$-\frac{z}{w}\\$.

```
(%-.)~/@(10^#&>)#.10#.&>]    NB. Monadic train; input = (digits of x;digits of y)
                  10#.&>]    NB. Evaluate each in base 10 to get [x,y]
                #.           NB. Evaluate in base...
        (10^#&>)    NB. 10 raised to the power of length of each; [10^#x, 10^#y]
(%-.)~/@            NB. (10^#y) / (1 - 10^#x) = -z/w

```

---

# , 23 bytes

```
(%-.)~&(10x^#)#.,&{.&".

```

Try it online!

Modification of Jonah's solution to use the same base trick. This one is a dyadic function accepting plain strings as its two args. One caveat is that eval(`".`) of an empty string is an empty vector, so we need to make it a 0 explicitly using `{.`.

# Answer
> 10 votes
# Wolfram Language (Mathematica), ~~37~~ 33 bytes

```
d[#/d[0#-9]]~d~#2&
d=Fold[9#+##&]

```

Try it online!

Input two lists of digits.

`Fold[9#+##&]` is longer than `FromDigits`, but has more flexibility with its input.

# Answer
> 8 votes
# Vyxal v2.6.0pre1, ~~15~~ 11 bytes

```
vL↵‡⌐/R?⌊$β

```

Haha rationals go brrr. Obligatory port of Jelly, M and Bubbler.

## Explained

```
vL↵‡⌐/R?⌊$β  # Full program, takes ["x", "y"]
vL           # vectorise length over each
  ↵          # and raise 10 to the power of each
   ‡⌐/       # lambda x, y: x / 1 - y
      R      # reduce the above list by that
       ?⌊    # cast each string in input to it
         $β  # and convert to the result of reducing the lambda

```

## History

I spent roughly an hour on this, trying to arrange it to work properly. Took me a few re-reads of the specs, but I got there in the end.

Input taken as:

```
y
x

```

where `y` and `x` are strings (done by surrounding them with `""`s), and if `y` isn't provided, `[]` is used.

## Explained

```
L↵⁰I*⁰L↵‹/¹I$-ƒ
L↵               # 10 ** length(y)
  ⁰I             # int(x)
    *            # ↑ * ↑↑ (we'll call this W)
     ⁰L↵         # 10 ** length(x)
        ‹        # ↑ - 1
         /       #  W / ↑
          ¹I     # int(y) # on an empty list, this will return 0
            $-   # ↑↑ - ↑
              ƒ  # fractionify(↑) # this built-in has been around for a long time before this challenge --> it turns a decimal into the most simple fraction

```

# Answer
> 7 votes
# , ~~118~~ ~~116~~ ~~108~~ ~~103~~ ~~98~~ 92 bytes

```
function(x,y,`+`=nchar,B=10^+x-1,A=el(max(y,0):0)*B-x*10^+y,q=1:x)c(A,B)/max(q[!A%%q&!B%%q])

```

Try it online!

Takes first input as integer and second as string (empty if no \\$y\\$).

GCD implementation borrowed from here: https://codegolf.stackexchange.com/a/48845/55372

*-8 bytes thanks to @Kirill & @Dominic;
-5 and another -6 bytes thanks to @Giuseppe*

# Answer
> 7 votes
# , ~~114~~ ~~110~~ ~~109~~ ~~107~~ 104 bytes

*Edit: -4 and then -2 more bytes thanks to Giuseppe's comments on pajonk's answer, and then -3 bytes after copying a trick from Robin Ryder's answer here*

```
function(s,z=10^nchar(s)-1:0,n=scan(t=pmax(s,0)),a=c(diff(n*z[2:1]),z[1]),c=1:z)a/max(c[!a%%c&!a[2]%%c])

```

Try it online!

Input is a vector of two strings representing `x` and `y`.

I tried to answer this without peeking at the other  answers, but now I realise that pajonk's answer is ~~probably~~ golfier... Bah!

# Answer
> 7 votes
# JavaScript (Node.js), 61 bytes

```
x=>y=>(G=(a,b)=>b?G(b,a%b):[x/a,z/a])(z=-1+x-~x,x-=y+x-(x+y))

```

Try it online!

Take input as two strings, output an array with two numbers.

JavaScript use `+` for both number plus and string concatenation. When any operand is string, it works as string concatenation.

# Answer
> 6 votes
# , 39 32 30 27 bytes

```
{.@".@]-".@[*(%<:)~&(10x^#)

```

Try it online!

-5 thanks to Bubbler. Also go upvote his j answer, which is more creative and has delightful application of base `#.`

The wikipedia formula translated into J. The only part that might be of some interest is the calculation of `z/w`:

* `(%&x:<:)~&(10^#)`
    + `&(1>.10^#)` Convert each string input by raising 10 to the power of its length `10^#` (which will be 1 when length is 0).
    + `(%&x:<:)~` Next swap the argument order `~` and subtract 1 `<:` from the new right arg, to get a number whose digits are all nines. Divide the left argument by that `%`.

# Answer
> 6 votes
# JavaScript (ES7),  ~~80~~  76 bytes

Expects `(x)(y)` as strings (`y` may be an empty string) and returns `[numerator, denominator]`.

```
x=>y=>(G=(a,b)=>b?G(b,a%b):[p/a,q/a])(q=1-10**x.length,p=y*q+x*10**y.length)

```

Try it online!

### Commented

```
x =>                       // outer function taking x
y =>                       // inner function taking y
  ( G = (a, b) =>          // G is a helper function which takes 2 integers,
      b ? G(b, a % b)      // computes their GCD a
        : [ p / a, q / a ] // and eventually returns [ p / a, q / a ]
  )(                       // we invoke G with (q, p) defined as follows:
    q =                    //   q =
      1 -                  //   1 - 10 ** len(x)
      10 ** x.length,      //
    p =                    //   p =
      y * q +              //   y * q + x * 10 ** len(y)
      x * 10 ** y.length   //
  )                        //

```

# Answer
> 6 votes
# Haskell, 58 bytes

```
x#y=f y-f x*0!y/1!x
c!s=10^length s-c
f x=read$'0':x++"%1"

```

Try it online!

The relevant function is `(#)`, which takes `x` and `y` as strings, with `y` possibly empty. Returns a `Rational`.

**DISCLAIMER:** the compiler is unable to correctly deduce the type of `(#)`, unless it is specified by some other part of the program, either explicitly (i.e. `::Rational`) or implicitly (i.e. by using the return value as if it were a `Rational`). Based on this Meta answer I believe this should be allowed, but since I'm quite inexperienced I'm not sure. If that's not the case, then the best I can do is:

## Haskell, 63 bytes

```
x#y=f y-f x*0!y/1!x
c!s=10^length s-c
f x=toRational.read$'0':x

```

Try it online!

# Answer
> 6 votes
# `+ MASS`, ~~99~~ 91 bytes

```
function(x,y,`[`=gsub)MASS::fractions(eval(parse(t=paste0(y,"-",x,"."[0,y],"/","."[9,x]))))

```

Try it online!

Takes input as two strings (`y` possibly empty), outputs a rational fraction or an integer.

# Answer
> 5 votes
# Jelly (fork), 11 bytes

```
ḌḅẈ⁵*C÷@¥/Ʋ

```

Try it online!, or rather, don't

As of last week, my fork now includes symbolic math support! Unfortunately,  (Jelly's version with symbolic math) only implements this in the `İ` atom, not in the `÷` division atom. My fork does both.

Again, implements Bubbler's strategy to evaluate \\$\[x, y\]\\$ in base \\$-\frac z w\\$.

## How it works

```
ḌḅẈ⁵*C÷@¥/Ʋ - Main link. Takes [x, y] as lists of digits on the left
Ḍ           - Convert [x, y] to integers
          Ʋ - Do the following to [x, y]:
  Ẉ         -   Lengths of each
   ⁵*       -   Raise 10 to the power of each length
        ¥/  -   Reduce by the following:
     C      -     Complement; 1 - a
      ÷@    -     Divide b by that; b / (1 - a)

```

# Answer
> 4 votes
# Jelly, 20 bytes

```
9ṁḌ+Ø.µ×³ḌU¤_/,Ḣ:g/$

```

Try it online!

Seems very bad ¯\\\_(ツ)\_/¯

# Answer
> 4 votes
# Retina, ~~96~~ 92 bytes

```
(.+)'(.*)
$($($.1*9)*$2*)-$($1$.2*0)*_/$($.1*9)*
+`_-_
-
-/
/
(_+)(\1)*/(\1)*$
$.(_$#2*)/$#3

```

Try it online! Link includes faster test cases. Explanation:

```
(.+)'(.*)
$($($.1*9)*$2*)-$($1$.2*0)*_/$($.1*9)*

```

Write out `yw-xz/w`. (Edit: I don't actually multiply `x` by `z`, I just suffix the appropriate number of `0`s to it, which saves on a `1` amongst other things.)

```
+`_-_
-
-/
/

```

Perform the subtraction, slowly.

```
(_+)(\1)*/(\1)*$
$.(_$#2*)/$#3

```

Slowly divide by the GCD and convert to decimal.

Just for completeness, optimising for speed results in code that readily dispatches all of the test cases. Try it online!

# Answer
> 4 votes
# APL (Dyalog Extended), 70 bytes

Not great, but I felt like submitting it anyway

```
{⍺←⍬⋄{⍵÷⊃⌽⊃∩⍥(⍸0=⊢|⍨⍳)/|⍵}((W×⍎'0',⍺)-(⍎⍵)×⍎'1','0'\⍨⍴,⍺),W←⍎'9'\⍨⍴,⍵}

```

Not sure why, but my code to handle single arguments works in TryAPL.org but not in tio.run

Also, because of how APL handles default arguments, I had to swap the order on input...like I said, not the best solution :|

```
⍺←⍬⋄ ⍝ assign Empty Set to the default value for the left argument (Y from the problem statement)
 ⍵÷⊃⌽ ⍝ divide the 2-tuple (a and b from the problem statement) by their gcd
  ⊃ ⍝ pick (removes one layer of nesting)
   ∩ ⍝ intersection
    ⍥ ⍝ function composition operator (Over)
     (⍸0=⊢|⍨⍳)/ ⍝ fold/reduce by finding divisors
      |⍵ ⍝ absolute value of 2-tuple (a and b from the problem statement)
       W×⍎'0',⍺ ⍝ W (from problem statement) times the integer representation of the left argument (Y from the problem statement) or zero if alpha is the empty set
        -(⍎⍵) ⍝ subtract the integer representation of the right argument (X from the problem statement)
         ×⍎ ⍝ decode then multiply
          '1', ⍝ concatenate the character 1
           '0'\⍨⍴ ⍝ expand the character 0 by the number of characters in Y
             ,⍺ ⍝ ravel Y (effectively making single characters into singleton arrays)
              , ⍝ concatenate
                W←⍎'9'\⍨⍴ ⍝ assign the integer representation of the expansion of the character 9 by the number of characters in X
                 ,⍵ ⍝ ravel X

```

Try it online!

# Answer
> 3 votes
# Charcoal, 55 bytes

```
Ｆ⪪Ｓ'«≔ζη≔ιζ»≔Ｉ⭆η⁹δ≔⁻×ＩζδＩ⁺η⭆ζ⁰ε⊞υε⊞υδＷ﹪εδ«≔δε≔ιδ»⪫÷υ↔δ/

```

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

```
Ｆ⪪Ｓ'«≔ζη≔ιζ»

```

Split the input string on `'` and save the parts into separate variables.

```
≔Ｉ⭆η⁹δ

```

Change the digits of the first part to `9`s and save the result as an integer.

```
≔⁻×ＩζδＩ⁺η⭆ζ⁰ε

```

Multiply that by the second part as an integer, then change the digits of the second part to `0`s, append that to the first part, and subtract the integer value.

```
⊞υε⊞υδ

```

Save the fraction to the predefined empty list.

```
Ｗ﹪εδ«≔δε≔ιδ»

```

Find the GCD.

```
⪫÷υ↔δ/

```

Reduce the fraction to its lowest terms and output it with a `/` separator.

# Answer
> 3 votes
# Clojure, 92 bytes

```
#(let[b biginteger p(fn[x](.pow(b 10)(count x)))](-(b(or %2 0))(/(*(b %)(p %2))(dec(p %)))))

```

Try it online!

Relies on the formula from Wikipedia. Takes input as two strings (`nil` when there is no `y`), outputs a rational fraction, or a bigint when denominator is 1.

# Answer
> 3 votes
# , 13 bytes

```
Cİ×
L€⁵*ç/ḅ@Ḍ

```

Try it online!

Implements Bubbler's method

## How it works

```
Cİ× - Helper link. Takes a on the left and b on the right
C   - Yield 1-a
 İ  - Inverse; Yield 1 / (1-a)
  × - Times; Yield b / (1-a)

L€⁵*ç/ḅ@Ḍ - Main link. Takes [x, y] as lists of digits
L€        - Length of each
  ⁵*      - Raise 10 to the power of the lengths
    ç/    - Run the helper link with the powers of 10 as a and b
        Ḍ - Convert [x, y] into integers
      ḅ@  - Evaluate [x, y] as base b / (1-a)

```

# Answer
> 2 votes
# Perl 5 `-apl`, 99 bytes

```
($w,$z)=map s/./9/gr,@F;@e=($F[1]*$w-$F[0]*($z+1),$w);$w--while grep$_%$w,@e;$_=join"/",map$_/$w,@e

```

Takes two space separated strings from `stdin`, outputs a fraction.

Try it online!

# Answer
> 1 votes
# 05AB1E (legacy), 18 bytes

```
ÂI‚JÆ-нID®ì+н>‚D¿÷

```

Despite 05AB1E's name (when `05AB1E` converted to hexadecimal is interpret as base64 it spells `Base`), it can't do base conversion from decimal values, so *@Bubbler*'s approach won't work for it.
Instead, this is a port of *@tsh*'s JavaScript answer, so make sure to upvote that answer as well!

This uses the legacy version of 05AB1E, because the GCD builtin `¿` will always result in a positive integer in the new version of 05AB1E (the `D¿÷` should be `Ð.±s¿*ß÷` as workaround in that case).

Try it online or verify all test cases.

**Explanation:**

Uses the formula:

$$(x,y) = \[x-(y\mathbin\Vert x-x\mathbin\Vert y), \text{-1}\mathbin\Vert x + x + 1\]$$

integer-divided by their \\$\gcd\\$ afterwards; where \\$\mathbin\Vert\\$ is concatenation, taking precedence over the other operators.

```
Â        # Reverse the (implicit) input-pair (without popping)
 I‚      # Pair it with the input-pair
   J     # Join both inner pairs together
    Æ    # Reduce this pair by subtracting
     -   # Subtract this integer from both values of the input-pair
      н  # Pop and only keep the first one
ID       # Push the input-pair twice again
  ®ì     # Prepend both integers in the top pair with "-1"
    +    # Add both to the input-pair at the same positions
     н   # Pop and only keep the first one
      >  # Increase it by 1
‚        # Pair the two values together
 D       # Duplicate this pair
  ¿      # Get the GCD (Greatest Common Divisor)
   ÷     # Integer-divide the values in the pair by this GCD
         # (after which the pair is output implicitly as result)

```

---
Tags: code-golf, math, rational-numbers
---


title: Make a Scrabble Word Finder

text:
# Question
Title: Make a Scrabble Word Finder
> Yes, I know there is a similar question, but this one specifically concerns any possible words, even with letters left over, while the linked one restricts to a permutation of the input

## Objective

Have you ever had those moments in a Scrabble game where you're staring at your letters, trying to find a good word, and your mind is just blank? Some of us feel cheaty and turn to word unscrambling software like this one to help us. This challenge is to build your own word unscrambler.

Given a list of possible words and a string of characters conforming to the regex `([A-Z]|[a-z])+`, your program has to find all the words whose letters are all found in the scrambled string.

Sample inputs:

```
asto, [as, so, to, oats] -> [as, so, to, oats]
asto, [as, to] -> [as, to]
ast, [as, so, to] -> [as]
zzyzx, [as, to, so] -> []
trom, [as, to, too, or] -> [to, or]
roomt, [as, to, too, or] -> [to, too, or]

```

## Scoring

This is , shortest answer wins.

# Answer
# Vyxal 2.6pre1, ~~5~~ 3 bytes

```
Þ×↔

```

Don't Try it Online! (the site runs a few commits 2.4.1)

Haha builtin go brr.

-2 thanks to Lyxal.

```
  ↔ # The elements in common between
Þ×  # All combinations of the letters
    # And the input.

```
> 7 votes

# Answer
# Jelly, 4 bytes

```
œ&ƑƇ

```

Try it online!

## How it works

```
œ&ƑƇ - Main link. Takes a list of words L on the left, a word W on the right
   Ƈ - Keep those words from L such that:
  Ƒ  -   They are unchanged after taking:
œ&   -     The multiset intersection with W

```
> 8 votes

# Answer
# Python 2, 66 bytes

```
lambda s,l:[w for w in l if all(w.count(c)<=s.count(c)for c in w)]

```

Try it online!
> 6 votes

# Answer
# Python 3.10, 74 bytes

```
lambda w,l:[x for x in l if C(x)<=C(w)]
from collections import*
C=Counter
```

Attempt This Online!

In versions before 3.10 `C(x)<=C(w)` would have been `not C(x)-C(w)` instead.
> 5 votes

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

```
s=>l=>l.filter(w=>w.map(g=c=>g|=w[c]=s.indexOf(c,w[c]+1))|~g)

```

Try it online!

Input / output words as list of characters.
> 4 votes

# Answer
# Ruby, 46 bytes

```
->b,a{a.select{|w|d=b*1;w.all?{|c|d[c]&&=''}}}

```

Try it online!

Takes the list of tiles as a string; words are input and output as lists of characters. The inconsistent formats can be avoided at a cost of a few extra bytes: 47 bytes to use lists of characters exclusively and 52 bytes for strings.

All variants work the same way. For each letter of a word, remove the first occurrence of that letter from the list of tiles or return `nil` (falsy) if there is no such tile. The word can be formed if this procedure succeeds for all its letters.
> 3 votes

# Answer
# Factor \+ `math.combinatorics math.unicode`, 53 bytes

```
[ <permutations> '[ _ [ subseq? ] with ∃ ] filter ]

```

Try it online!

In plain English, select all words from the dictionary that appear in any permutation of the scrabble letters.
> 3 votes

# Answer
# Charcoal, 12 bytes

```
Φη⬤ι¬›№ιλ№θλ

```

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

```
 η              Word list
Φ               Filtered where
   ι            Current word
  ⬤             All letters satisfy
      №ιλ       Count of letter
    ¬›          Does not exceed
         №θλ    Count available
                Implicitly print

```
> 3 votes

# Answer
# , 24 bytes

```
(1 e.[E.e.~#])&(/:~@>)#[

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~7~~ 5 bytes

```
æ€œ˜Ã

```

-2 bytes thanks to *@ovs*.

Inputs in the order `letters, words-list`.

Try it online or verify all test cases.

**Explanation:**

```
æ      # Get the powerset of the (implicit) first input-string of letters
 €œ    # Get the permutations of each string in this list
   ˜   # Flatten this nested list to a single list of strings
    Ã  # Keep the words from the second (implicit) input-list that are also in this list
       # (after which the result is output implicitly)

```
> 3 votes

# Answer
# Retina, 49 bytes

```
A`^|(.)(.*\1)*(?<!^.*(?(2)^)(?<-2>.*\1)*\1(.|¶)+)

```

Try it online! Takes newline-separated input but link is to test suite that splits on commas for convenience. Explanation:

```
A`^|

```

Delete the first line, plus...

```
(.)(.*\1)*

```

... any lines that have more of a particular letter...

```
(?<!^.*(?(2)^)(?<-2>.*\1)*\1(.|¶)+)

```

... than the first line does.
> 3 votes

# Answer
# ayr, ~~10~~ 9 bytes

```
[#*/&,:/:

```

Takes the words on the left and the letters on the right

# Explained

```
       /:  Each left
     ,:    Membership
  */&      And then reduce with multiplication
[#         Filter words with this mask

```

`*/ 1 0 0 1 0` is the same as `^./ 1 0 0 1 0` but shorter.
> 3 votes

# Answer
# Vyxal, 5 bytes

```
ṖvKf↔

```

Try it Online!

This has to be the first time I've found a use for `K` on strings lol

## Explained

```
ṖvKf↔
Ṗ      # All permutations of the input word
 vK    # and get the divisors (substrings that split the string into more than once piece - idk how this actually makes this work)
   f   # flatten that
    ↔  # remove words from the input list that aren't in ^

```
> 2 votes

# Answer
# Python, 88 bytes

```
lambda a,w:filter(" ".join(map("".join,permutations(a))).count,w)
from itertools import*
```

Attempt This Online!

Assumes the words don't contain spaces, but the `" "` can be changed to any other character that the words won't contain.

Unusually for Python, this declarative approach (map+filter) is shorter than a list comprehension.
> 2 votes

# Answer
# Perl 5, ~~52~~ 47 bytes

```
sub{$c=pop;grep{$C=$c;!grep{$C!~s/$_//}/./g}@_}

```

Try it online!

(shaved 5 extra bytes from Dom Hastings' suggestions)
> 2 votes

# Answer
# Perl 5 \+ `-F -M5.10.0`, 38 bytes

```
say grep{$t=$_;$t=~s/$_// for@F;!$t}<>

```

Try it online!

## Explanation

The letters (first line of input) are implicitly stored in `@F` via the `-F` flag.

We `grep` through the word list (`<>`), temporarily storing the word (`$_`) in `$t`, then `for` each letter in `@F`, `s///`ubstitute it (`$_`) for the empty string, returning a truthy value (which includes the word in the set to be printed by `say`) if `$t` is now empty (all letters of the word were removed because they exist in the input letters).
> 2 votes

# Answer
# K4, 28 bytes

**Solution:**

```
{y@&x{&/1>(#:'=y)-#:'=x}/:y}

```

**Examples:**

Count letter occurrences, subtract and spit out words that match...

```
q)k){y@&x{&/1>(#:'=y)-#:'=x}/:y}["trom";("as";"to";"too";"or")]
"to"
"or"
q)k){y@&x{&/1>(#:'=y)-#:'=x}/:y}["asto";("as";"so";"to";"oats")]
"as"
"so"
"to"
"oats"
q)k)()~{y@&x{&/1>(#:'=y)-#:'=x}/:y}["zzyzx";("as";"to";"so")]
1b

```

**Explanation:**

```
{y@&x{&/1>(#:'=y)-#:'=x}/:y} / the solution
{                          } / lambda taking implicit x and y args
    x{                 }/:y  / apply inner lambda to x and each y
                     =x      / group x
                  #:'        / count length of each group
                 -           / subtract from
          (     )            / do this together
              =y             / group y
           #:'               / count length of each group
        1>                   / 1 greater than subtraction result?
      &/                     / all
   &                         / indices where true
 y@                          / index into y with these indices

```

**Alternatives:**

* `{y@&&/'1>(#:''=:'y)-\:#:'=x}`, also 28 bytes
> 2 votes

# Answer
# Pyth, 9 bytes

```
@E{.nyM.p

```

Try it online!

```
@E{.nyM.p
     yM.P   // Collect all subsets of all permutations of the input
  {.n       //     -> Flatten and de-duplicate the list
 E          // Read the word list
@           // Get the intersections of the two lists.

```
> 1 votes

# Answer
# Japt `-f`, ~~6~~ 5 bytes

```
øVáUl

```

Try it

```
-f flag to output the elements of first input
   that return a truthy value when passed through

ø       - true if word contains any of:
  Vá    - permutations of alphabet
   Ul   - of same length of word hence equal

```

Or try that
> 1 votes

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


title: Generate net puzzles

text:
# Question
Title: Generate net puzzles
An *acyclical grid* is a mapping of an acyclical graph (that is, a tree) where each node has no more than four edges onto a toroidal rectangular grid such that each cell of the grid is occupied by a node. Here is an example of an acyclical grid:

```
┴─┐╵╵│└┘└╴╶┴┬
╴╷╵┌┐│╷┌┬┐╶┐├
╷│╷╵│├┘│╵└╴│╵
┘└┴┐│└┬┤┌─┬┴─
╷╶─┤│╷╵├┤╶┘╶┐
│╶┐└┤└┬┤╵╷╶─┤
┤╷└─┴┬┤└┐└┬┬┴
│├──┐│├╴├─┤├╴
┘└┐┌┴┤└┐├╴╵╵┌
┌┬┘╵┌┴┐╵└─┐╶┘
┤└─┐│╷│┌┬╴╵╷╶

```

Some browser fonts have trouble rendering this in a properly monospaced way. If the grid looks off, please copy-paste it into a text editor of your choice.

Notice that this grid is toroidal: the left and right, as well as the top and bottom are connected preserving the axis you are moving along. For example, if you move left in the third row you eventually end up on the right of the third row and vice versa.

This grid is composed of box-drawing characters which fall into four classes:

1. The characters  , , , and  denote leaves (nodes with one edge)
2. The characters  and  denote nodes with two edges in a collinear arrangement
3. The characters , , , and  denote nodes with three edges
4. The characters , , , and  denote nodes with two edges in a perpendicular arrangement

The *characteristic matrix* of an acyclical grid is a matrix comprising for each cell in the acyclical grid the class of the node positioned there. For instance, the characteristic matrix of the aforementioned grid is this:

```
3241124441133
1114424232123
1211234214121
4434243342332
1123211331414
2144343311123
3142333444333
2322423131331
4444334431114
4341434142414
3424212431111

```

A *net puzzle* is an *n* × *m* matrix of integers in the range from 1 to 4 such that it is the characteristic matrix of exactly one acyclical grid.

If you want to gain an intuitive understanding about net puzzles, you can play net from Simon Tatham's puzzle collection. Make sure that “wrapping” and “ensure unique solution” are both checked and that “barrier probability” is set to 0.

## The challenge

Write a function or program that given two integers *n* and *m* in the range from 3 to 1023 generates a net puzzle of dimension *n* × *m.* You may optionally receive a third integer *p* in the range from 1 to 1023.

If you implement the variant with two arguments (the non-deterministic variant), then your submission shall with great probability return a different puzzle each time it is called. If you implement the variant with three arguments (the deterministic variant), then the set of puzzles generated for all *p* for a given pair (*n, m*) shall contain at least four different puzzles for each pair (*n, m*).

There are no further restrictions with respect to input and output.

## Scoring

This challenge is code golf. The solution with the least number of octets wins.

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

```
{((x,y)#&(0;y;y*x-2;y-2;2))z|:/x!z+!x}

```

Try it online!

I can't believe that it went unanswered for, like, six and a half years?

Implements the three-argument version. It is a function that takes `n m p` as three separate parameters and builds a valid net puzzle deterministically.

Basically what it does is to build one asymmetric and easily constructible net puzzle of size `n m`, and then permute its rows based on `p`.

### What it builds & Why it is valid for this challenge

The result for `f[5;6;0]` is this:

```
1 1 1 1 1 1
2 2 2 2 2 2
2 2 2 2 2 2
2 2 2 2 2 2
3 3 3 3 4 4

```

In box drawing chars:

```
1 1 1 1 1 1 : ╷╷╷╷╷╷
2 2 2 2 2 2 : ││││││
2 2 2 2 2 2 : ││││││
2 2 2 2 2 2 : ││││││
3 3 3 3 4 4 : ┴┴┴┴┘└

```

And it has a unique solution, as well as its reflections and rotations (as in APL sense; cyclically moving rows and columns).

Why unique solution? First, the solution is an unrooted tree (in graph-theoretical sense); if a configuration has a cycle, then it is not a solution because it necessarily has two or more disjoint parts. Then, the 2's must be all aligned either horizontally or vertically, but if they're horizontal then they form one or more cycles of their own. So they must be vertical. Then the orientation of 1's are fixed (downwards), and then the 3's (disconnected to the lower side). Finally the orientations for 4's are fixed in order to connect everything.

The code is easy:

```
&(0;y;y*x-2;y-2;2)    Create an array of:
                      m copies of 1's, m*(n-2) copies of 2's,
                      (m-2) copies of 3's, and 2 copies of 4's
(x,y)#                Reshape into n-row, m-col matrix

```

For "at least four distinct puzzles" part, I had to use two different permuting methods because of the 3x3 grid (single reflection gives at most 2; stepwise rotation gives at most either `n` or `m`). I went for pure row permutation because applying two separate transforms was too long.

For code, `!x` creates the identity permutation vector `0 1 2 ... (n-1)`, `x!z+` rotates it by `p` steps, and `z|:/` reverses it `p` times. This creates `lcm(2, n)` unique grids, which is always at least 4.

I know, it's likely against the original intent of the challenge, but this is not the first time I exploited "generate at least x distinct grids" :P
> 11 votes

---
Tags: code-golf
---


# Question
Title: Min-Max GHC command line error bytes to bytes of source code
GHC command line errors can be horrible, lets make them as bad as possible. To disincentivize very long programs use the following formula to calculate your "score".

```
(# of bytes of GHC output) / 2^(8 + # of bytes of code)

```

Template Haskell is banned as there is probably a TH configuration where you can replicate an error f(n) times where f is an arbitrary fast growing computable function. CPP and GHC options are banned for similar reasons.

GHC output should be computed using this release of GHC 8.6.3.

To calculate the bytes of GHC output run:

```
ghc -hide-all-packages -package base Main.hs |& wc -c

```

The following is an example submission:

```
main = print (1 + True)

```

Error:

```
[1 of 1] Compiling Main             ( Main.hs, Main.o )

Main.hs:1:15: error:
    • No instance for (Num Bool) arising from a use of ‘+’
    • In the first argument of ‘print’, namely ‘(1 + True)’
      In the expression: print (1 + True)
      In an equation for ‘main’: main = print (1 + True)
  |
1 | main = print (1 + True)
  |               ^^^^^^^^

```

Score:

```
375 / 2^(8 + 24) = 0.0000000873114914

```

Submissions must contain the code and the score. Highest score wins.

# Answer
# Score diverges to \\$\infty\\$

```
f=(:).(:)
g=f.f.f.f.f.f.f.f -- adding ".f" always results in better score
main=g+main g

```

Based on ASCII-only's construction, it is pretty easy to get ever-increasing score with longer and longer programs. Just posting to knock the challenge out of the unanswered list.

Given the following program form

```
f=(:).(:).(:) -- n copies of (:) composed
main=f+main f

```

the sizes of error messages are:

```
2 copies -> 2328
3 copies -> 8121 (x3.488)
4 copies -> 27121 (x3.339)
5 copies -> 103385 (x3.812)
6 copies -> 432486 (x4.183)
7 copies -> 1898125 (x4.388)
8 copies -> 8495224 (x4.475)
9 copies -> 39395094 (x4.637)
10 copies -> 198171503 (x5.030)

```

We can't know the exact formula of this because Haskell's error message pretty-printing is complicated, but we can at least know that adding one copy of `.(:)` consistently increases the error size by a factor of 4 or higher. In the top submission, adding two characters `.f` adds two copies of `(:)`, multiplying the error size by at least 16 and therefore the score by \\$16 \div 4 = 4\\$.

To roughly see what is going on, here's the full error for 1-copy `(:)` program: (those `��`s are pretty quotes, which got somehow broken in my editor)

```
[1 of 1] Compiling Main             ( Main.hs, Main.o )

Main.hs:2:1: error:
    ? Couldn't match expected type ��IO t0��
                  with actual type ��(a0 -> [a0] -> [a0])
                                    -> (a0 -> [a0] -> [a0])
                                    -> [a0 -> [a0] -> [a0]]
                                    -> [a0 -> [a0] -> [a0]]��
    ? Probable cause: ��main�� is applied to too few arguments
      In the expression: main
      When checking the type of the IO action ��main��
  |
2 | main=f+main f
  | ^

Main.hs:2:6: error:
    ? Couldn't match type ��[a -> [a] -> [a]]�� with ��a -> [a] -> [a]��
      Expected type: (a -> [a] -> [a])
                     -> (a -> [a] -> [a]) -> [a -> [a] -> [a]] -> [a -> [a] -> [a]]
        Actual type: (a -> [a] -> [a])
                     -> [a -> [a] -> [a]] -> [a -> [a] -> [a]]
    ? Possible cause: ��(+)�� is applied to too many arguments
      In the expression: f + main f
      In an equation for ��main��: main = f + main f
    ? Relevant bindings include
        main :: (a -> [a] -> [a])
                -> (a -> [a] -> [a]) -> [a -> [a] -> [a]] -> [a -> [a] -> [a]]
          (bound at Main.hs:2:1)
  |
2 | main=f+main f
  |      ^^^^^^^^

```

and for 2-copy `(:)` program:

```
[1 of 1] Compiling Main             ( Main.hs, Main.o )

Main.hs:2:1: error:
    ? Couldn't match expected type ��IO t0��
                  with actual type ��(a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]])
                                    -> (a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]])
                                    -> [[a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]]]
                                        -> [a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]]]]
                                    -> [[a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]]]
                                        -> [a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]]]]��
    ? Probable cause: ��main�� is applied to too few arguments
      In the expression: main
      When checking the type of the IO action ��main��
  |
2 | main=f+main f
  | ^

Main.hs:2:6: error:
    ? Couldn't match type ��[[a -> [[a] -> [a]] -> [[a] -> [a]]]
                            -> [a -> [[a] -> [a]] -> [[a] -> [a]]]]��
                     with ��a -> [[a] -> [a]] -> [[a] -> [a]]��
      Expected type: (a -> [[a] -> [a]] -> [[a] -> [a]])
                     -> (a -> [[a] -> [a]] -> [[a] -> [a]])
                     -> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
                         -> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
                     -> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
                         -> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
        Actual type: (a -> [[a] -> [a]] -> [[a] -> [a]])
                     -> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
                         -> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
                     -> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
                         -> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
    ? Possible cause: ��(+)�� is applied to too many arguments
      In the expression: f + main f
      In an equation for ��main��: main = f + main f
    ? Relevant bindings include
        main :: (a -> [[a] -> [a]] -> [[a] -> [a]])
                -> (a -> [[a] -> [a]] -> [[a] -> [a]])
                -> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
                    -> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
                -> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
                    -> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
          (bound at Main.hs:2:1)
  |
2 | main=f+main f
  |      ^^^^^^^^

```

Basically the inferred type signature of `main` is blowing up by factor of \>4. The type has the format of `x -> y -> z -> w`, where each of `x, y, z, w` contains the sub-structure `p -> q -> r`. When a copy of `(:)` is added, `q` and `r` parts are doubled and `z` and `w` are quadrupled.
> 4 votes

---
Tags: code-challenge, haskell
---


title: Compute matrix blockiness

text:
# Question
Title: Compute matrix blockiness
Consider a non-empty binary matrix **M** and a natural number *n*. For the purposes of this challenge, **M** is said to have blockiness *n* if it can be built using adjacent square blocks of size *n*, where each block has equal entries; and it cannot be formed using square blocks of any larger size. Intuitively, *n* can be thought of as the "pixel size" of the matrix.

**Example 1**: let the values of the matrix be represented as `+` and `o` for clarity.

```
++oo++++
++oo++++
oo++++++
oo++++++

```

has blockiness `2`. Although some entries can be considered to belong to larger blocks, `2` is the maximum block size that is valid for all entries. To be specific, the blocks are shown below, using `·` as separator:

```
++·oo·++·++
++·oo·++·++
···········
oo·++·++·++
oo·++·++·++

```

**Example 2**:

```
+++oo+++
+++oo+++

```

has blockiness `1`. Even if any entry can be seen as belonging to some "sliding" block of size `2`, it is not possible to form the matrix using adjacent blocks of that size.

# The challenge

Given a non-empty binary matrix, output its blockiness.

# Rules

* Any two consistent values can be chosen to define the matrix. Input format is flexible as usual (2D array, list of lists of numbers, flattened array and one or two numbers defining its shape, list of strings, ...).
* Input and output means are flexible as usual. Programs or functions are allowed. Standard loopholes are forbidden.
* Code golf, shortest wins.

# Test cases

See also "inputs in common formats" at the end.

* Blockiness `1`:

```
+

ooo

+o
++

+++oo+++
+++oo+++

ooo+++
ooo+++
++++++
++oooo

ooooo
ooooo
ooooo
ooooo

```
* Blockiness `2`:

```
oo
oo

++++
++++

++oo++++
++oo++++

++oo++++
++oo++++
oo++++++
oo++++++

```
* Blockiness `3`:

```
++++++ooo
++++++ooo
++++++ooo

ooo+++ooo
ooo+++ooo
ooo+++ooo
+++ooo+++
+++ooo+++
+++ooo+++

```
* Blockiness `4`:

```
++++++++
++++++++
++++++++
++++++++

++++++++oooo
++++++++oooo
++++++++oooo
++++++++oooo
++++++++oooo
++++++++oooo
++++++++oooo
++++++++oooo

```

**Inputs in common formats**:

# Answer
> 3 votes
# 05AB1E, 6 bytes

```
xø«Åγ¿

```

Try it online!

Port of my Mathematica answer.

Take a list of lists of 2's and 3's as input.

```
x       # Pop a and push a, 2a
 ø      # Transpose
  «     # Concatenate
   Åγ   # Run-length encode
     ¿  # GCD

```

# Answer
> 10 votes
# Wolfram Language (Mathematica), 33 bytes

```
GCD@@Length/@Split@Join[2#,#]&

```

Try it online!

Take a 2d array of 2's and 3's, or any two values \\$a\\$, \\$b\\$ such that \\$\\{a,b\\}\cap\\{2a,2b\\}=\\{\\}\\$.

Split the array into runs of identical rows and columns, and take the GCD of the lengths of these runs.

Here  is the postfix operator for matrix transpose.

# Answer
> 7 votes
# , 24 bytes

```
+./@,&I.&(1#.0&,~:,&0)|:

```

Try it online!

Port of alephalpha's Mathematica answer.

```
+./@,&I.&(1#.0&,~:,&0)|:    NB. Input: matrix M
     &                |:    NB. For M and its transpose:
             0&,            NB. M with a zero row prepended
                  ,&0       NB. M with a zero row appended
                ~:          NB. Elementwise unequal of the two
          1#.   NB. Row-wise sum
      I.&       NB. Indices; x[i] copies of i
+./@,           NB. Concatenate the two results and GCD reduce

```

---

# , 39 bytes

```
1 i:~0,(2 2$#)\(];.3*/@,@e.0 1+[$1:)"2]

```

Try it online!

The input format is a matrix of 1's and 2's.

### How it works

```
1 i:~0,(2 2$#)\(];.3*/@,@e.0 1+[$1:)"2]    NB. input: matrix M having n rows

(2 2$#)\    NB. 3D block, each layer is 2x2 matrix of i where i <- 1..n
(...)"2]    NB. For each layer of above and the entirety of matrix M...
 ];.3       NB.  A: Extract ixi blocks of M, padding with zeros
            NB.  (when some padding exists, the test always fails)
 0 1+[$1:   NB.  B: 3D block having two layers: ixi of 1's and ixi of 2's
 */@,@e.    NB.  Test if every 2D cell of A exists as a cell in B
            NB.  i.e. Test if all ixi blocks of M are valid
1 i:~0,     NB. Extract the last 1-based index of 1

```

# Answer
> 5 votes
# Charcoal, ~~52~~ 42 bytes

```
ＷＳ⊞υιＩ⊟Φ⊕Ｌυ∧ι›⬤υ⬤λ⁼ν§§υ⁻μ﹪μι⁻ξ﹪ξι∨﹪Ｌυι﹪Ｌθι

```

Try it online! Link is to verbose version of code. Takes input as a newline-terminated list of strings. Explanation:

```
ＷＳ⊞υι

```

Input the matrix.

```
Ｉ⊟Φ⊕Ｌυ∧ι

```

Output the largest number from `1` to the height of the matrix...

```
›⬤υ⬤λ⁼ν§§υ⁻μ﹪μι⁻ξ﹪ξ

```

... for which each character equals that at the top left corner of its aligned submatrix ...

```
ι∨﹪Ｌυι﹪Ｌθι

```

... and which divides both its height and width.

# Answer
> 5 votes
# , 57 51 50 48 44 43 39 bytes

```
<:@]^:(0 e.[:,[:="1[,;.3~2 2$])^:_<./@$

```

Try it online!

*-4 thanks to Bubbler's idea of using 1-2 encoding to capitalize on automatic 0-padding*

Input is 1-2 matrix.

* `<./@$` \- Starting with the smaller dimension of the input (call it `d`)...
* `<:@]` \- Decrement `d` while...
* `^:...^:_` \- Stuff (elaborated below) that checks if, when we tile the input with `d x d` tiles, any one of them is non-homogeneous:
    + `0 e.` Is 0 an element of...
    + `[:,` The flatten of...
    + `[:="1` The catalog of... (the catalog of a list is all ones only for a homogeneous list)
    + `[,;.3~2 2$]` Each `d x d` tile flattened. Partial tiles are 0 padded, and thus guaranteed to be non-homogeneous.

# Answer
> 5 votes
# Python 3 with numpy, 92 bytes

```
from numpy import*
f=lambda m,k=1:k<len(m)and f(m,k+1)or all(m==kron(m[::k,::k],eye(k)<2))*k

```

Try it online!

Takes a numpy `ndarray`.

`m[::k,::k]` takes every `k`th element of `m` in both dimensions; `eye(k)<2` is a short way to make a `k`-by-`k` matrix with every entry `True` (which is equivalent to 1 here). With these arguments, `kron` expands each element from `m[::k,::k]` to a `k`-by-`k` block. Next, the equality check with `m` produces a matrix of individual Boolean results if the sizes are the same, or `False` if the sizes are different (deprecated); `all` turns this into a single Boolean representing whether the matrices are the same.

# Answer
> 4 votes
# , ~~104~~ ~~97~~ ~~90~~ 85 bytes

*Edit: -3 bytes thanks to pajonk*

```
f=function(m,b=nrow(m))`if`(identical(m[i<-1:b<2,i,drop=F]%x%diag(b)^0,m),b,f(m,b-1))

```

Try it online!

Recursive function: tests blockiness `b` starting with number of rows of matrix `m`, and recurses decreasing `b` until it finds one that fits.
Blockiness test consists of calculating the kronecker product (`%x%` function in ) of each `b`-th element of `m`, and a `bxb` matrix of `1`s: the result should be identical to `m` if `b` is the correct blockiness.

# Answer
> 3 votes
# JavaScript (ES6),  ~~101 92 90~~  89 bytes

*Saved 4 bytes thanks to @Neil, and  ~~7~~  8 more bytes from there*

```
m=>m.reduce(o=>++w*m.some(r=>r.some(v=>v-m[y-y%w][x-x++%w],x=0)*++y|x%w,y=0)|y%w?o:w,w=0)

```

Try it online!

### Commented

```
m =>                 // m[] = input matrix
m.reduce(o =>        // for each row in m[], using o as an accumulator:
  ++w *              //   increment w
  m.some(r =>        //   for each row r[] in m[]:
    r.some(v =>      //     for each value v in r[]:
      v -            //       compare v with
      m[y - y % w]   //       the top-left corner of the submatrix of
      [x - x++ % w], //       width w in which we're currently located
                     //       increment x afterwards
      x = 0          //       start with x = 0
    )                //     end of inner some()
    * ++y            //     increment y
    | x % w,         //     force to fail if w does not divide x
    y = 0            //     start with y = 0
  )                  //   end of outer some()
  | y % w            //   force to fail if w does not divide y
  ?                  //   if failed:
    o                //     leave o unchanged
  :                  //   else:
    w,               //     update it to w
  w = 0              //   start with o = w = 0
)                    // end of reduce()

```

# Answer
> 3 votes
# , ~~143~~ ~~139~~ 132 bytes

Or **\>=4.1, 118 bytes** by replacing two `function` occurences with `\`s.

```
function(M,k=dim(M))for(n in k:1)if(!any(k%%n,tapply(M,(row(M)-1)%/%n*max(k)+(col(M)-1)%/%n,function(x)sum(table(x)|1)-1)))return(n)

```

Try it online!

Bases heavily on the `split` idea from my answer to *Square chunk my matrix* (although here we have rectangular matices, which are a little trickier).

# Answer
> 3 votes
# Ruby, 118 bytes

```
f=->m,z=$.=m.size{x=[]
(0...$.).step(z){|r|y=[]
(0...m[0].size).step(z){|c|y+=[m[r][c]]*z}
x+=[y]*z}
x==m ?z:f[m,z-1]}

```

Try it online!

* Recursively (starting from one dimension length) try block sizes, return first valid value.
* Reconstructs the matrix by taking a value at each block, repeating it z times to form each block. Finally compare with original input.

Tried a different approach by slicing each block but ended at 125B

```
->m{(1..m.size).select{|z|x=[]
m.each_slice(z){|s|x+=s.transpose.each_slice(z).map(&:flatten)}
x.all?{|b|b==[b[0]]*z*z}}.max}

```

# Answer
> 3 votes
# Python 3, 108, 104, 97 bytes

-7 by borowing @m90's better control flow

```
f=lambda M,n=1:n<len(M)and f(M,n+1)or all(X==[*sum(zip(*n*[X[::n]]),())]for X in[M,[*zip(*M)]])*n

```

Try it online!

Old version

Straight-forward approach; tries successively smaller block sizes until a working one is found.

Old, longer but more readable version:

```
f=lambda M,n=0:n and all(X[i::n]==X[::n]for i in range(n)for X in[M,[*zip(*M)]])and n or f(M,~-n%-~len(M))

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 27 bytes

```
SgLR.Δδôøy©δô€`εSDËsgt®Q*}P

```

Inputs as list of strings.

Try it online or verify all test cases.

**Explanation:**

```
S                # Convert the (implicit) input-list of strings to a flattened list of
                 # characters
 g               # Pop and push its length
  L              # Pop and push a list in the range [1,length]
   R             # Reverse it to [length,1]
    .Δ           # Find the first block-size `y` which is truthy for:
      δ          #  Map over each string in the (implicit) input-list:
       ô         #   Split it into substrings of size `y`
        ø        #  Zip/transpose; swapping rows/columns
           δ     #  Map over each inner list again:
         y  ô    #   And split it into blocks of size `y` again
          ©      #  Also store block-size `y` in variable `®` (without popping)
             €`  #  Flatten this list of lists of blocks one level down
      ε          #  Map over each `y` by `y` sized block (or smaller, if we couldn't
                 #  divide a row or column into size `y` with builtin `ô`)
       S         #   Convert the current block to a flattened list of characters
        D        #   Duplicate it
         Ë       #   Check if all characters are the same
          s      #   Swap so the list of characters is at the top again
           g     #   Push its length
            t    #   Take the square-root of that
             ®Q  #   Check if this is equal to block-size `®`
               * #   Check if both are truthy
      }P         #  After the map: check if all were truthy
                 # (after which the found result is output implicitly)

```

# Answer
> 1 votes
# Core Maude, ~~319~~ 317 bytes

```
mod M is pr LIST{Nat}*(op size to z). ops b n : Nat Nat ~> Nat . var A B M N
W X Y Z :[Nat]. eq b(M,W)= n(M,W s W). ceq n(M,W s N)= n(M,W N)if X A Y B Z :=
M /\ W rem N + z(M)quo W rem N =/= 0 or A + B == 1 and z(X)quo W quo N(z(X)rem W
quo N)== z(X A Y)quo W quo N(z(X A Y)rem W quo N). eq n(M,W s N)= N[owise]. endm

```

To obtain the result, reduce the `b` function with the matrix as a flattened list, and the row length. (Maude has a matrix type, but we're not using it.)

### Example Session

```
Maude> --- Blockiness 1
>
> red b(
>     0,
>     1
> ) .
result NzNat: 1
Maude>
> red b(
>     1 1 1,
>     3
> ) .
result NzNat: 1
Maude>
> red b(
>     0 1
>     0 0,
>     2
> ) .
result NzNat: 1
Maude>
> red b(
>     0 0 0 1 1 0 0 0
>     0 0 0 1 1 0 0 0,
>     8
> ) .
result NzNat: 1
Maude>
> red b(
>     1 1 1 0 0 0
>     1 1 1 0 0 0
>     0 0 0 0 0 0
>     0 0 1 1 1 1,
>     6
> ) .
result NzNat: 1
Maude>
> red b(
>     1 1 1 1 1
>     1 1 1 1 1
>     1 1 1 1 1
>     1 1 1 1 1,
>     5
> ) .
result NzNat: 1
Maude>
>
> --- Blockiness 2
>
> red b(
>     1 1
>     1 1,
>     2
> ) .
result NzNat: 2
Maude>
> red b(
>     0 0 0 0
>     0 0 0 0,
>     4
> ) .
result NzNat: 2
Maude>
> red b(
>     0 0 1 1 0 0 0 0
>     0 0 1 1 0 0 0 0,
>     8
> ) .
result NzNat: 2
Maude>
> red b(
>     0 0 1 1 0 0 0 0
>     0 0 1 1 0 0 0 0
>     1 1 0 0 0 0 0 0
>     1 1 0 0 0 0 0 0,
>     8
> ) .
result NzNat: 2
Maude>
>
> --- Blockiness 3
>
> red b(
>     0 0 0 0 0 0 1 1 1
>     0 0 0 0 0 0 1 1 1
>     0 0 0 0 0 0 1 1 1,
>     9
> ) .
result NzNat: 3
Maude>
> red b(
>     1 1 1 0 0 0 1 1 1
>     1 1 1 0 0 0 1 1 1
>     1 1 1 0 0 0 1 1 1
>     0 0 0 1 1 1 0 0 0
>     0 0 0 1 1 1 0 0 0
>     0 0 0 1 1 1 0 0 0,
>     9
> ) .
result NzNat: 3
Maude>
>
> --- Blockiness 4
>
> red b(
>     0 0 0 0 0 0 0 0
>     0 0 0 0 0 0 0 0
>     0 0 0 0 0 0 0 0
>     0 0 0 0 0 0 0 0,
>     8
> ) .
result NzNat: 4
Maude>
> red b(
>     0 0 0 0 0 0 0 0 1 1 1 1
>     0 0 0 0 0 0 0 0 1 1 1 1
>     0 0 0 0 0 0 0 0 1 1 1 1
>     0 0 0 0 0 0 0 0 1 1 1 1
>     0 0 0 0 0 0 0 0 1 1 1 1
>     0 0 0 0 0 0 0 0 1 1 1 1
>     0 0 0 0 0 0 0 0 1 1 1 1
>     0 0 0 0 0 0 0 0 1 1 1 1,
>     12
> ) .
result NzNat: 4

```

### Ungolfed

```
mod M is
    pr LIST{Nat} * (op size to z) .

    ops b n : Nat Nat ~> Nat .

    var A B M N W X Y Z : [Nat] .

    eq b(M, W) = n(M, W s W) .

    ceq n(M, W s N) = n(M, W N)
        if X A Y B Z := M
        /\ W rem N + z(M) quo W rem N =/= 0
        or A + B == 1
        and z(X) quo W quo N (z(X) rem W quo N)
            == z(X A Y) quo W quo N (z(X A Y) rem W quo N) .
    eq n(M, W s N) = N [owise] .
endm

```

For a given `N`, we essentially test *every* partition of the input list into five sublists (including ones where `A` and `B` aren't single elements). Then we verify if that partition corresponds to an actual counter-example for `N`. This is very slow — the last case for blockiness 4 takes several minutes to run. But it terminates!

---

Saved 2 bytes by removing two pairs of parentheses. Parentheses don't often cost bytes in Maude because they can often replace a space due to tokenization weirdness, but in this case there were two pairs of parentheses next to each other.

---
Tags: code-golf, array, matrix, binary-matrix
---


title: Euler's numerus idoneus

text:
# Question
Title: Euler's numerus idoneus
Euler's numerus idoneus, or idoneal numbers, are a finite set of numbers whose exact number is unknown, as it depends on whether or not the Generalized Riemann hypothesis holds or not. If it does, there are exactly 65 idoneal numbers. If not, there are either 66 or 67. For the purposes of this challenge, we'll revolutionise mathematics and say that the Generalised Riemann hypothesis is true (I'd prove it, but I'm trying to golf the challenge body).

Under this assumption, the idoneal numbers are

```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 16, 18, 21, 22, 24, 25, 28, 30, 33, 37, 40, 42, 45, 48, 57, 58, 60, 70, 72, 78, 85, 88, 93, 102, 105, 112, 120, 130, 133, 165, 168, 177, 190, 210, 232, 240, 253, 273, 280, 312, 330, 345, 357, 385, 408, 462, 520, 760, 840, 1320, 1365, 1848

```

This is A000926, and many different ways to describe this sequence can be found there. However, we'll include two of the most standard ones here:

* A positive integer \\$D\\$ is idoneal if, for any integer expressible in the form \\$x^2 \pm Dy^2\\$ in exactly one way (where \\$x^2\\$ and \\$Dy^2\\$ are co-prime), that integer is either a prime power, or twice a prime power.

For example, let \\$D = 3\\$. \\$3\\$ is idoneal, meaning that all integers that can be expressed as \\$x^2 \pm 3y^2\\$ for exactly one co-prime pair \\$(x, y)\\$ are either primes \\$p\\$, powers of primes \\$p^n\\$ or twice a prime power \\$2p^n\\$. As an example, \\$(x, y) = (2, 3)\\$ yields \\$29\\$ as \\$x^2 + 3y^2\\$. \\$29\\$ is a prime, and cannot be expressed in the form \\$x^2 \pm 3y^2\\$ for any other co-prime pair \\$(x, y)\\$.
* Alternatively (and rather more simply), a positive integer \\$n\\$ is idoneal iff it cannot be written in the form \\$ab + ac + bc\\$ for distinct positive integers \\$a, b, c\\$

For example, \\$11 = 1\times2 + 1\times3 + 2\times3\\$, therefore, \\$11\\$ is not idoneal.

This is a standard challenge, you may choose one of the following three options:

* Take an integer \\$n\\$ (either \\$0 \le n \< 65\\$ or \\$0 \< n \le 65\\$, your choice) as input, and output the \\$n\\$th (either 0 or 1 indexed, also your choice) idoneal number. **You may choose how to order the idoneal numbers**, so long as its consistent.
* Take a positive integer \\$1 \le n \le 65\\$ and output the first \\$n\\$ idoneal numbers. Again, you may choose how to order the idoneal numbers.
* Output all 65 idoneal numbers, in any order, with no duplicates.

This is , so the shortest code in bytes wins

# Answer
# Wolfram Language (Mathematica), 53 bytes

```
Range[7!]/.<|Array[+##(3#+#2)-#3#->Set@$&,49+0{,,}]|>

```

Try it online!

Outputs all(?) 65 idoneal numbers. Filters out numbers of the form \\$a(a+b)+(a+b)(a+b+c)+(a+b+c)a\\$ with \\$a,b,c\\$ positive integers.
> 5 votes

# Answer
# Jelly, 13 bytes

```
2ȷœc3ṙ€1ḋƊḟ@R

```

Try it online!

First Jelly answer! Prints all ideonal numbers.

Gosh this was painful. This *should* work given several terabytes of RAM and a couple of hours. To see, replace (2000) with 20 or something.

-10 thanks to Dude coinheringaahing.

```
2ȷœc3          # Combinations of 1..2000 of length 3
     ṙ€1ḋ      # Calculate ab+ac+bc for each
         Ɗḟ@   # Remove these from
2ȷ          R  # 1...2000

```
> 5 votes

# Answer
# , ~~72~~ ~~65~~ 62 bytes

```
r=i=1:2e3
for(a in r)for(b in a+r)i[(b+r)*(a+b)+a*b]=F;r[i[r]]

```

Try it online!

Outputs all idoneal numbers in ascending order.

The TIO link will time-out, since `r` is needlessly set to `1...2000` to save bytes; here is a link to a version with `r` initialized to `1...99` instead, which doesn't time-out (and still gives the right output).
> 4 votes

# Answer
# Charcoal, 30 bytes

```
Ｆ⁹⁹ＦιＦκ⊞υ⁺×⊕ι⁺⊕κ⊕λ×⊕κ⊕λＩ⁻…¹⊗φυ

```

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

```
Ｆ⁹⁹ＦιＦκ

```

Loop over distinct `100 > a > b > c > 0`. (Replacing `⁹⁹` with `φ` would save a byte but make the code too slow for TIO.)

```
⊞υ⁺×⊕ι⁺⊕κ⊕λ×⊕κ⊕λ

```

Calculate `ab + ac + bc`.

```
Ｉ⁻…¹⊗φυ

```

Take the range from `1` to `1999` and remove all values that resulted from the above calculation.
> 4 votes

# Answer
# JavaScript (V8),  ~~87~~  85 bytes

*Saved 2 bytes thanks to @tsh*

A full program printing the sequence in reverse order.

```
for(i=2e3;--i;)for(a=99;--a?b=~a&&a:print(i);)while(c=--b)while(--c)a*=a*b+a*c+b*c!=i

```

Try it online!

### Commented

```
for(                 // 1st loop
  i = 2e3;           // going from i = 1999 to i = 1
  --i;               //
)                    //
  for(               //   2nd loop
    a = 99;          //   starting with a = 99
    --a ?            //   decrement a; if it's not zero:
      b = ~a && a    //     stop if a = -1, otherwise set b to a
    :                //   else:
      print(i);      //     we've reached a = 0: print i
  )                  //
    while(c = --b)   //     3rd loop going from b = a - 1 to b = 1
      while(--c)     //       4th loop going from c = b - 1 to c = 1
        a *=         //         clear a if ab + ac + bc is equal to i,
          a * b +    //         which will turn it into -1 on the next
          a * c +    //         iteration of the 2nd loop
          b * c != i //         (otherwise, leave it unchanged)

```
> 4 votes

# Answer
# Vyxal, 17 bytes

```
∞'£ɾ3ḋ'Ǔ*∑¥=;ḃ;?i

```

Try it Online!

Warning: This will *not work* for n ≥ 7. It's just too slow.

```
∞'            ;?i # Get the nth number where...
             ḃ    # None of
   ɾ3ḋ'     ;     # The ways you can choose 3 numbers less than n
       Ǔ*∑        # Have ab+ac+bc...
  £       ¥=      # Equal n

```
> 4 votes

# Answer
# Python 3, ~~93~~ 82 bytes

```
R=range(1,2000)
print({*R}-{a*b+c*(a+b)for a in R for b in R for c in R if a<b<c})

```

Try it online!

Outputs all the idoneal numbers (works but times out on TIO).

This version works on TIO:

# Python 3, ~~103~~ 92 bytes

```
R=range(1,99)
print({*range(1,2000)}-{a*b+c*(a+b)for a in R for b in R for c in R if a<b<c})

```

Try it online!

*Saved 11 bytes thanks to FryAmTheEggman!!!*
> 3 votes

# Answer
# Ruby, 75 bytes

```
p [*1..2e3]-(r=*1..56).product(r,r).map{|i|a,b,c=i;a<b&&b<c ?a*b+b*c+c*a:0}

```

Try it online!

A full program printing an array.

An array of the numbers `1..2000` is created and all non-ideonal numbers deleted from it. The smallest value of range `r` that works is `1..56`. Reducing the number below 56 fails to delete `1012` corresponding to `a,b,c = 5,12,56`.
> 3 votes

# Answer
# APL(Dyalog Unicode), 23 bytes SBCS

```
(⍳!7)~(1⊥2×/4⍴+\)¨⍳3⍴50

```

Try it on APLgolf!

A full program that prints all 65 terms. Essentially the same strategy as att's Mathematica answer. All attempts to factor out `⍳!7` failed, so here goes an efficient solution.

### How it works

```
(⍳!7)~(1⊥2×/4⍴+\)¨⍳3⍴50    Full program; no input
                  ⍳3⍴50    50x50x50 cube containing coordinates of each cell
      (         )¨         For each item...
              +\             Cumulative sum
       1⊥2×/4⍴               From a, b, c compute ab+bc+ca
(⍳!7)~                     Remove all numbers appearing in ^ from 1..5040

```
> 3 votes

# Answer
# jq, 76 bytes

```
[range(2e3)+1]-[[range(56)+1]|.[]as$a|[.[]+$a][]as$b|$a*$b+($a+$b)*(.[]+$b)]

```

Try it online!

I don't really know why `[.[]+$a][]` and `.[]+$a` have different behavior.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 58 bytes

```
Select[Range[7!],!Reduce[a(b+c)+b*c-#==0<a<b<c,Integers]&]

```

Try it online! (here are values \<100 because TIO times out)

-1 byte from Dude coinheringaahing
-8 bytes from @att
> 2 votes

# Answer
# Jelly, 13 bytes

```
⁹œc3P-Ƥ€§ṬCTḣ

```

Try it online!

Monadic link that returns the first n terms. The leading  (constant 256) is necessary to get the correct output for n = 1 and 2 (otherwise the output is empty for those two inputs). The linked code has  replaced by `20` for demonstration purposes.

### How it works

```
⁹œc3P-Ƥ€§ṬCTḣ    Monadic link. Left arg = n, the number of terms
⁹œc3             3-combinations of 1..256
    P-Ƥ€§        ab+bc+ca for each row
         ṬCT     List of numbers in 1..max(above) that do not appear
                 in the above list
            ḣ    Take first n

```

In order to filter out all `ab+bc+ca` numbers before 1848, the input numbers should be at least:

* 56 if you use "3-combinations of 1..(some fixed number)"
* 44 if you use "cumulative sums of 3rd cartesian power of 1..(some fixed number)"

In both cases, the hardest one to filter out is `(5, 12, 56) → 1012`. The next hardest is `(8, 17, 51) → 1411`.

---

# Jelly, 14 bytes

```
³œc3P-Ƥ€§2ȷR¤ḟ

```

Try it online!

Full program that prints all 65 terms. This one finishes within a few seconds without modification.

### How it works

```
³œc3P-Ƥ€§2ȷR¤ḟ    Niladic chain.
³œc3              3-combinations of 1..100
    P-Ƥ€§         Compute ab+bc+ca for each row
         2ȷR¤ḟ    Filter out the above from 1..2000

```
> 2 votes

# Answer
# 05AB1E, 14 bytes

```
₄·LD3.ÆεĆü*O}K

```

Outputs all 65 values.

Try it online (with `≤2000` replaced with `≤50`).

**Explanation:**

```
₄            # Push 1000
 ·           # Double it to 2000
  L          # Pop and push a list in the range [1,2000]
   D         # Duplicate this list
    3.Æ      # Get all triplets with unique integers
       ε     # Map each triplet to:
        Ć    #  Enclose; append its own head: [a,b,c] to [a,b,c,a]
         ü   #  For each overlapping pair:
          *  #   Multiply them together: [a*b,b*c,c*a]
           O #  Sum this list: ab+bc+ca
       }K    # After the map: remove all those non-idoneal numbers from the [1,2000] list
             # (after which the result is output implicitly)

```
> 2 votes

# Answer
# Husk, 17 bytes

```
Ṡ-omoΣSz*ṙ1Ṗ3ḣ□43

```

Try it online!

Returns all idoneal numbers in ascending order, but too inefficiently to run in \<1min on TIO.
Instead, try idoneal numbers less than 100 without timing-out

```
             ḣ□43   # 1..1849 (square of 43)
Ṡ-                  # return those that aren't
  omoΣ              # sums of
      Sz*           # zipping together by multiplying
           Ṗ3       # all combinations of picking 3 numbers
         ṙ1         # with that combination rotated by 1

```
> 1 votes

# Answer
# Pari/GP, 52 bytes

```
f()=[n|n<-[1..7!],![c-2|c<-quadclassunit(-4*n).cyc]]

```

Try it online!
> 1 votes

---
Tags: code-golf, sequence, kolmogorov-complexity, number-theory
---


title: Verb arities in J trains

text:
# Question
Title: Verb arities in J trains
## Background

J has trains similar to APL's. Given a sequence of verbs (functions), three rightmost verbs are grouped to form a derived verb (a *fork*) recursively, until one or two verbs remain. If the sequence has odd length, the entire train is a chain of forks. Otherwise, two verbs remain at the end, forming a *hook*.

```
    (F G H J K) x             5-train called monadically
->  (F G (H J K)) x
->  (F x) G ((H x) J (K x))   Function arities: 1, 2, 1, 2, 1

    x (F G H J K) y                 5-train called dyadically
->  x (F G (H J K)) y
->  (x F y) G ((x H y) J (x K y))   Function arities: 2, 2, 2, 2, 2

    (F G H J K L) x                 6-train called monadically
->  (F (G H (J K L))) x
->  x F ((G x) H ((J x) K (L x)))   Function arities: 2, 1, 2, 1, 2, 1

    x (F G H J K L) y               6-train called dyadically
->  x (F (G H (J K L))) y
->  x F ((G y) H ((J y) K (L y)))   Function arities: 2, 1, 2, 1, 2, 1

```

You don't need to fully understand J trains to solve this challenge. The pattern is pretty simple:

* If the train length is even, the pattern is `[2, 1, 2, 1, ..., 2, 1]` regardless of the train's arity.
* Otherwise (length is odd), if the train is called monadically, the pattern is `[1, 2, 1, 2, ..., 2, 1]`; if called dyadically, the pattern is all 2's.

## Challenge

Given a train's length and arity (monadic is 1, dyadic is 2), output the arities of each function in the train.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
length, arity -> answer
1,      1     -> [1]
1,      2     -> [2]
2,      1     -> [2, 1]
2,      2     -> [2, 1]
3,      1     -> [1, 2, 1]
3,      2     -> [2, 2, 2]
4,      1     -> [2, 1, 2, 1]
4,      2     -> [2, 1, 2, 1]
9,      1     -> [1, 2, 1, 2, 1, 2, 1, 2, 1]
9,      2     -> [2, 2, 2, 2, 2, 2, 2, 2, 2]
10,     1     -> [2, 1, 2, 1, 2, 1, 2, 1, 2, 1]
10,     2     -> [2, 1, 2, 1, 2, 1, 2, 1, 2, 1]

```

# Answer
# Python 2, 28 bytes

```
lambda l,a:(l*[2,l%a+1])[l:]

```

Try it online!

### Python 2, 27 bytes

It saves one byte to output as a string.

```
lambda l,a:(l*`21+l%a`)[l:]

```

Try it online!
> 12 votes

# Answer
# HBL 0.1, 10 bytes

```
<(0.(*(1(+(%.,))2?).

```

Try it at HBL Online!

HBL uses a half-byte codepage. Each character above represents one hex digit, two characters per byte. Here's a hexdump of the raw binary file:

```
00000000: 3c0a c5c1 c4c8 abdd 29da                 <.......).

```

### Explanation

If we reverse the desired output, we can see some patterns emerge:

```
3 1  (1 2 1)
3 2  (2 2 2)
4 1  (1 2 1 2)
4 2  (1 2 1 2)
5 1  (1 2 1 2 1)
5 2  (2 2 2 2 2)

```
* The output is some two-element list repeated a number of times and trimmed to a length equal to the first argument.
* The second element of that list is always 2.
* The first element of that list is 2 if the arguments are, respectively, an odd number and 2; otherwise, the first element is 1.

This leads to our initial solution, given here in Thimble, HBL's "ungolfed mode":

```
'(reverse           ; Reverse of
  (take arg1        ; The first (arg1) elements of
   (repeat          ; Repeat the following list...
    (cons           ;  Construct a list from the values...
     (cond          ;   If...
      (mul          ;    Multiply
       (odd? arg1)  ;    parity of arg1
       (dec arg2))  ;    by (arg2 - 1)
      2             ;   ... is nonzero, then 2
      1)            ;   else 1
     2              ;  ... and 2
     nil)           ;  prepended to the empty list
    arg1)))         ; ... (arg1) times

```

Translating this solution into HBL gives `<(0.(*(1(?(*(%.)(-,))21)2?).` (14 bytes). To get to our 10-byte solution, observe that there's a nice relationship between our two arguments and the number we want in our list:

```
 arg1 % 2 | arg2 | num | arg1 % arg2
----------|------|-----|-------------
 0        | 1    | 1   | 0
 0        | 2    | 1   | 0
 1        | 1    | 1   | 0
 1        | 2    | 2   | 1

```

So instead of the conditional, all we need is `(inc (mod arg1 arg2))`.

```
'(reverse
  (take arg1
   (repeat
    (cons
     (inc
      (mod arg1 arg2))
     2
     nil)
    arg1)))

```

Replacing the builtins with their HBL equivalents and removing the opening and closing parentheses (implicit in HBL), this solution maps directly onto the HBL solution given above.
> 10 votes

# Answer
# Jelly, 7 bytes

```
%‘;2ṁḷU

```

Try it online!

Thanks to Unrelated String for making this work! Port of dingledooper's answer.

```
%‘ṭ2ṁḷU # Dyadic link taking two arguments
    ṁ   # Mold...
  ;2    # 2 appended to...
%       # The modulo of the two inputs
 ‘      # Plus 1
    ṁ   # To length...
     ḷ  # Left argument (length input)
      U # Reversed

```
> 4 votes

# Answer
# 05AB1E, 10 bytes

```
%21+sиJs.$

```

Try it online!
> 3 votes

# Answer
# Factor \+ `sequences.repeating`, 50 bytes

```
[ dupd mod 1 + '[ 2 _ ] over 2 * cycle swap tail ]

```

Try it online!

This is a port of @dingledooper's excellent Python 2 answer.

There is a locals version that is the same length:

```
[| l a | 2 l a mod 1 + 2array l 2 * cycle l tail ]

```

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes the length and the arity (in that order) from the data stack as input and leaves a sequence on the data stack as output. Assuming `9 1` is on the data stack when this quotation is called...

| Snippet | Comment | Data stack (the bottom is the top) |
| --- | --- | --- |
|  |  | ``` 9   <--- NOS (next on stack)<br>1   <--- TOS (top of stack) ``` |
| ``` dupd ``` | Duplicate NOS | ``` 9<br>9<br>1 ``` |
| ``` mod ``` | NOS % TOS | ``` 9<br>0 ``` |
| ``` 1 ``` | Push 1 | ``` 9<br>0<br>1 ``` |
| ``` + ``` | NOS + TOS | ``` 9<br>1 ``` |
| ``` '[ 2 _ ] ``` | Slot TOS into the _ | ``` 9<br>[ 2 1 ] ``` |
| ``` over ``` | Copy NOS to TOS | ``` 9<br>[ 2 1 ]<br>9 ``` |
| ``` 2 ``` | Push 2 | ``` 9<br>[ 2 1 ]<br>9<br>2 ``` |
| ``` * ``` | NOS * TOS | ``` 9<br>[ 2 1 ]<br>18 ``` |
| ``` cycle ``` | Repeat NOS until length of TOS | ``` 9<br>[ 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 ] ``` |
| ``` swap ``` | Swap NOS and TOS | ``` [ 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 ]<br>9 ``` |
| ``` tail ``` | Take NOS from index at TOS | ``` [ 1 2 1 2 1 2 1 2 1 ] ``` |
> 3 votes

# Answer
# Retina 0.8.2, 32 bytes

```
\d+
$*
r`11
21
T`1`2`21,1.*
.+,

```

Try it online! Link includes test cases. Takes input in the order arity, length. Explanation:

```
\d+
$*

```

Convert the length to unary, conveniently using `1`s.

```
r`11
21

```

Working right-to-left, change every other `1` to a `2`.

```
T`1`2`21,1.*

```

If the arity is two and the length is odd, change all the `1`s to `2`s.

```
.+,

```

Delete the arity.
> 3 votes

# Answer
# Vyxal, 8 bytes

```
%21+S⁰*∷

```

Try it Online!

*-1 thanks to emanresuA*

Haha 05ab1e porting goes brrrr. When v2.6.0pre2 drops later this week, this'll be 7 bytes:

```
%21+⁰ẋ∷

```

## Explained (old)

```
%21+S⁰*⁰ȯ # Full program, takes arity, length
%         # Push length mod arity,
 21+      # add 21 to that,
    S     # and cast to string. (This value will be called x)
     ⁰    # Push the length,
      *   # and repeat x that many times. (This value will be called y)
       ⁰  # Push the length again,
        ȯ # and push y[length:]

```
> 2 votes

# Answer
# Ruby, 25 bytes

```
->l,a{([2,l%a+1]*l)[l,l]}

```

Try it online!

Another port of @dingledooper's Python answer.
> 2 votes

# Answer
# , 47 bytes

```
(".@,'~'''''}.~2&|)~'(',')',~,&'1&, :(,2&,)'&''

```

Try it online!

I would call this one a conscious un-golf, because ofc I could port dingledooper's Python answer to J for fewer bytes...

But it just didn't feel right for a J answer not to use J's train parsing code to compute the answer.

## the idea

First, we construct a verb `1&, :(,2&,)` that prepends 1 to its argument (say `a b c`) when called with 1 argument:

```
1 a b c

```

but plops 2 in the middle when called with 2 args:

```
a b c 2 a b c

```

Next we duplicate that verb `length` times to form a train, and then invoke the train on the empty list `''`. More precisely, we call:

```
train ''

```

if our arity is 1, and:

```
'' train ''

```

if our arity is 2.

With that setup, J's train execution will do the required computation for us.
> 2 votes

# Answer
# Jelly, 6 bytes

```
ḶU|%Ḃ‘

```

Try it online!

Like Dingledooper's answer, but a bit different.

```
ḶU       range [L-1..0]
  |%     bitwise OR by L%A
            (if L%A=0, this does nothing;
             if L%A=1, it makes the whole range odd)
    Ḃ‘   mod 2, add 1

```
> 2 votes

# Answer
# , 38 bytes

Or **\>=4.1, 31 bytes** by replacing the word `function` with `\`.

```
function(l,a)tail(rep(2:(l%%a+1),l),l)

```

Try it online!

Based od @dingledooper's idea.
> 1 votes

# Answer
# C (gcc), 46 bytes (44 using puts)

```
i;f(l,a){for(i=l;i--;)printf(L"122"+i%2+l%a);}

```

Try it online!

* Based on @dingledooper answer
> 1 votes

# Answer
# MathGolf, 9 bytes

```
\%J+░*h½≥

```

Port of *@dingledooper*'s Python answer.

Try it online.

**Explanation:**

```
\          # Swap the two (implicit) input-integers
 %         # Modulo
  J+       # Add 21
    ░      # Convert it to a string
     *     # Repeat it the first (implicit) input-integer amount of times
      h    # Push the length of this string (without popping)
       ½   # Halve it
        ≥  # Remove that many leading digits from the string
           # (after which the entire stack is output implicitly as result)

```
> 1 votes

# Answer
# Charcoal, 12 bytes

```
Ｎθ↓Ｉ……⊕﹪θＮ³θ

```

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

```
Ｎθ              Input the length as an integer
     …          Range from
        θ       Input length
       ﹪        Reduced modulo
         Ｎ      Arity as an integer
      ⊕         Incremented
          ³     Until 3 (exclusive)
    …           Cycled to length
           θ    Input length
   Ｉ            Cast to string
  ↓             Output right-to-left

```

Instead of , either  or  can be used for vertical output.
> 1 votes

# Answer
# Rust, 61 bytes

```
|l,a|->Vec<_>{(0..l).rev().map(move|x|(x|l%a)%2+1).collect()}

```

Try it online!

Port of @Lynn's Jelly answer.

Generates range `l-1 .. 0`, bitwise ORs each item with `l modulo a`, then modulos the result with `2` and adds `1`

`Range` in rust (`(start..stop)`) must be ascending, as it returns an empty iterator if `start >= stop`, so we have to `.rev()` the range to reverse it before mapping. Thankfully though the `stop` of a range is exclusive, so `(0..l)` generates range `0` to `l-1` inclusive.
> 1 votes

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