title: Almost Lexicographical List Comparison

text:
# Question
Title: Almost Lexicographical List Comparison
# Input

Two lists `A` and `B` of nonnegative integers.

# Output

Either `1`, `0`, or `-1`, depending on whether `A` is larger than, equal to, or smaller than `B` with respect to the *twisted lexicographical ordering* as defined below. If you want, you can replace `1`, `0` and `-1` with any other three constant values.

The twisted lexicographical ordering is like the ordinary lexicographical ordering, in that you compare the lists element by element, and decide their order at the first differing index. However, in the twisted version we use a different ordering for nonnegative integers at each index. Namely, at every index `i` (indexing starts from `1`), the order of the first `i` nonnegative integers (from `0` to `i-1`) is reversed, and they are moved above all the other numbers. Moreover, the "missing element" that signifies one list being shorter than the other is moved directly below `i-1`. Visually, the order at index `i` is

```
i < i+1 < i+2 < i+3 < ... < [missing element] < i-1 < i-2 < i-3 < ... < 2 < 1 < 0

```

Note that the first `...` denotes infinitely many numbers. This means that the following lists are in ascending order with respect to the twisted lexicographical ordering:

```
[3,2,3,4]
[3,2,3,5]
[3,2,3,10]
[3,2,3,1341]
[3,2,3]
[3,2,3,3]
[3,2,3,2]
[3,2,3,1]
[3,2,3,0]

```

# Rules

You can give a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

# Test Cases

```
Output 1:
[0] []
[] [1]
[] [1,2,1,2]
[2,1] [1,1]
[0,1,2] [0,2,1]
[3,0] [3,1]
[3,1] [3]
[2] [2,2]
[2] [2,23]
[2,24] [2,23]
[2,1] [2,23]

Output 0:
[] []
[0] [0]
[1,1] [1,1]
[2,1,2] [2,1,2]

Output -1:
[1,2,1,1,2] [1,2,1,1,1]
[1,2,1,1,5] [1,2,1,1,4]
[1,2,1,1,5] [1,2,1,1]
[1,2,1] [1,2,1,1]
[1,2,1,1,5] [1,2,1,1,6]
[1,2,1,1,6] [1,2,1,1,7]

```

# Answer
> 1 votes
# CJam - 57

```
q:S~=0{S~]:A:,~e>{A{_,I>{I=_I>0{W*2}?}1?[\]}%}fI]z~>2*(}?

```

Yeah it's still very long...

Try it online

Brief explanation:
The code outputs 0 if the arrays are equal in the traditional sense, otherwise it converts each item of each array to a 2-element array: \[0 ai\] if ai\>i (0-based), \[1 whatever\] if ai is missing, and \[2 -ai\] if ai\<=i. In the process, the shorter array is also extended to the larger size. Then the transformed arrays are compared lexicographically and the result is adjusted to -1/1.

# Answer
> 4 votes
# Python 2, 76 bytes

```
c=lambda*a:cmp(*[[(max(i-x,-1),x)for i,x in enumerate(L)]+[(0,)]for L in a])

```

This replaces each integer in both lists with a 2-tuple to account for the twisted ordering. Python 2's `cmp` builtin does the rest.

Usage:

```
>>> c([1,2,1,1,6], [1,2,1,1,7])
-1

```

# Answer
> 1 votes
# Perl, 74

Without good array manipulation functions perl is not the optimal tool for the job, but it works.

```
#!perl -pa
$i=0,s/\d+,?/$s=sprintf"%9d",$&;$&>$i++?$s:~$s/ge for@F;$_=$F[0]cmp$F[1]

```

Test me.

# Answer
> 1 votes
# J, 95 bytes

(Not super-short but whatever. Definitely golfable.)

```
f=.4 :0
m=.>:>./x,y
t=.(|+(1+m)*0>:*)@(i.@#-~])@(],m$~>&#*-&#)
x(t~(*@-&((m+#x,y)&#.))t)y
)

```

Passing all the test cases. (Great test case set! Thanks!)

Method:

* Padding the shorter list with maxvalue+1 (`m=.>:>./x,y`). `(],m$~>&#*-&#`
* Transforming list elements so normal comparison could be used. `(|+(1+m)*0>:*)@(i.@#-~])`
* Calculating two baseX numbers from the two list with sufficient X. `((m+#x,y)&#.)`
* Returning the signum of the two numbers difference.`*@-&`

# Answer
> 1 votes
# Jelly, 9 bytes

```
J_»0;1ż)M

```

Try it online!

Direct port of grc's Python solution. Monadic link taking a pair of its arguments and returning `[1]` for `1`, `[1, 2]` for `0`, and `[2]` for `-1`.

```
       )     For each element of the input:
 _           Subtract each element from
J            its 1-index,
  »0         take the maximum of each of those and 0,
    ;1       append 1,
      ż      and zip those with the original elements.
        M    Return the list of maximal indices.

```

# Answer
> 0 votes
# Mathematica, 65

```
f=-Order@@MapIndexed[If[#>Last@#2,#,a-b#]&,PadRight[{##}+1],{2}]&

```

Usage:

```
f[{1, 2, 1, 1, 6}, {1, 2, 1, 1, 7}]

```

> -1

---
Tags: code-golf, array, sorting
---


title: How long till Halley's Comet returns?

text:
# Question
Title: How long till Halley's Comet returns?
Halley's Comet is the only comet that may appear (i.e. become visible to the naked eye on Earth) twice in a human lifetime. The orbital period of Halley's Comet is not constant: it has varied between 75 to 79 Earth years since the first definite apparition was recorded in 240 BCE. This variability is mainly driven by gravitational interactions between the comet and the planets of the Solar System. For the three millennia up to the year 3000, Halley's Comet appeared, or is projected to appear, in the following years:

66, 141, 218, 295, 374, 451, 530, 607, 684, 760, 837, 912, 989, 1066, 1145, 1222, 1301, 1378, 1456, 1531, 1607, 1682, 1758, 1835, 1910, 1986, 2061, 2134, 2209, 2284, 2358, 2430, 2504, 2579, 2653, 2726, 2795, 2863, 2931, 3000

Apparitions beyond 2134 predicted using this orbit simulator. The simulations account for gravitational perturbations due to the planets but not for other effects, such as changes in the comet's outgassing rate, that also affect its orbit. See here for further discussion.

### Task

Write a program or function that takes as input a positive integer up to 3000 (inclusive), representing a year, and outputs/returns the number of years until the next apparition of Halley's Comet. In other words, if the input year is \\$y\\$ and Halley's Comet next appears in year \\$y\_\text{H}\ge y\\$, find \\$y\_\text{H}-y\\$. The shortest code (in bytes) in each language wins.

### Test cases

```
   1 -> 65
1066 ->  0
1067 -> 78
1986 ->  0
1987 -> 74
2021 -> 40

```

# Answer
> 23 votes
# JavaScript (Node.js), 74 bytes

```
n=>Buffer("BKMMOMOMMLMKMMOMOMNKLKLMKLKIKKJHJKJIEDDE").every(c=>(n-=c)>0)-n

```

Try it online!

### Commented

```
n =>              // n = input year
  Buffer(         // build a buffer consisting of
    "BKMM...EDDE" // the year deltas encoded as ASCII codes
  )               // 'B' -> 66, + 'K' (75) -> 141, etc.
  .every(c =>     // for each value c in there:
    (n -= c)      //   subtract c from n
    > 0           //   and go on while the result is positive
  )               // end of every(), which yields false
  - n             // return -n

```

# Answer
> 12 votes
# 05AB1E, 35 bytes

Uses second-order differences to reconstruct the years, which is 1 byte shorter than first-order differences.

```
•6?É@fô]öÔMƵ4^-•7в4-.¥75+.¥66+I-.Δd

```

Try it online!

```
•6...-•                    # compressed integer
       7в                  # convert to base 7
         4-                # subtract 4 from each
           .¥              # un-delta: cumulative sum with a 0 prepended
             75+           # add 75 to each; this is now the list of years between appearances
                .¥         # un-delta
                  66+      # add 66 to each; this is now the list of years of appearances
                     I-    # subtract the input year
                       .Δd # find the first non-negative integer

```

Try it with step-by-step output!

The part `.¥75+.¥66+` can be written with a loop at the same length as `„KBÇv.¥y+}`.

# Answer
> 7 votes
# , ~~87~~ 81 bytes

```
(z=cumsum(utf8ToInt("BKMMOMOMMLMKMMOMOMNKLKLMKLKIKKJHJKJIEDDE"))-scan())[z>=0][1]

```

Try it online!

# Answer
> 6 votes
# MATL, ~~45~~ 44 bytes

```
66 75'#AeXj=*pq5 Oe>3-u'F7Za4-,hYs]i-t0<~)X<

```

Try it online! Or verify all test cases.

### Explanation

This uses the *second*-order consecutive differences to compress the list of years.

```
66                   % Push 66
75                   % Push 75
'#AeXj=*pq5 Oe>3-u'  % Push this string
F7Za                 % Uncompress from base94 (printable ASCII except quote) to base 7
4-                   % Subtract 4. This is the 2nd-order difference of the list of years
,                    % Do twice
  h                  %   Concatenate (first time with 75, second time with 66)
  Ys                 %   Cumulative sum
]                    % End
i-                   % Subtract input element-wise
t                    % Duplicate
0<~                  % Logical index of non-negative values
)                    % Apply index to keep only non-negative values
X<                   % Minimum. Implicitly display

```

# Answer
> 6 votes
# Perl 5 `-p`, 73 bytes

```
$,=EDDEIJKJHJKKIKLKMLKLKNMOMOMMKMLMMOMOMMKB;$_-=ord chop$,while$_>0;s/-//

```

Try it online!

Uses the popular ASCII encoding but puts the first appearance (year 66) at the right side.

# Answer
> 4 votes
# , 61 bytes

```
(3+/\@u:'BKMMOMOMMLMKMMOMOMNKLKLMKLKIKKJHJKJIEDDE')&(]-~I.{[)

```

Try it online!

Noticed I independently came up with the same long constant Arnauld used in his answer, which is 66 prepended to the differences of the years, converted to Unicode code points `u:`.

The J code then converts back to a list of numbers `3 u:`, and scan sums those numbers `+/\@` to recover the original list of comet years.

We then find the "insert before" index `I.` of the program input within the list of comet years, and subtract the program input `]-~` from the actual comet list value at that same index `I.{[`.

# Answer
> 3 votes
# Pyth, ~~85~~ ~~42~~ 41 bytes

```
-hg#Qt.u+NYCM+\B."BOÅ>+‘¸h`bÊ¹¹dtg"Z

```

Try it online!

---

Managed to shed 44 bytes by using Arnauld's delta string.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 80 bytes

```
-Fold[If[#>0,#-#2,#]&,#,36^^9cyu7y4a7m84jq6pihqeoy2jutbhh4~IntegerDigits~15+65]&

```

Try it online!

The comet should be visible near its periapsis. Unfortunately, `CometData` only includes the dates of the previous and next periapses (5 Feb 1986 and 31 May 2061).

# Answer
> 2 votes
# Charcoal, 42 bytes

```
Ｉ⌊Φ⁻ＥφΣＥ…”$↷↥CⅉＷＦ3⊖n↧JＮω∕υ³*Ｈ↨{Ｗ”⊕ι℅λＮ¬‹ι⁰

```

Try it online! Link is to verbose version of code. Also uses @Arnauld's string, although I didn't realise until I read @Jonah's answer. Explanation:

```
     φ                  Predefined variable 1000 (shorter than 40)
    Ｅ                   Map over implicit range
         ”...”          Compressed form of @Arnauld's string
        …               Truncate to length
               ι        Current index
              ⊕         Incremented
       Ｅ                Map over characters
                 λ      Current character
                ℅       Take the ordinal
      Σ                 Summed
   ⁻                    Vectorised subtract
                  Ｎ     Input year
  Φ                     Filter where
                     ι  Current value
                   ¬‹ ⁰ Is non-negative
 ⌊                      Take the minimum
Ｉ                       Cast to string
                        Implicitly print

```

# Answer
> 2 votes
# Husk, 47 bytes

```
-⁰ḟ≥⁰∫m+66ΘB14B95mo-30c"(p_45Ux2|!uvrA(C$TDL3W

```

Try it online!

No built-in numeric compression in Husk, so we encode the differences between Halley years as printable ASCII values.

Halley year differences are then reconstructed by subtracting 30 from the ASCII values, converting to base 95, getting base 14 digits and adding 66. The Halley years are the cumulative sum of this: altogether `∫m+66ΘB14B95mo-30c"(p_45Ux2|!uvrA(C$TDL3W`  (where `"(p_45Ux2|!uvrA(C$TDL3W "` is the encoding string).

We then just retrive the first element greater-or-equal to the input (`ḟ≥⁰`), and subtract the input from this (`-⁰`).

# Answer
> 2 votes
# Zsh, 78 bytes

```
for ((a=-$1;a<0;a+=##$s[++i]))s=BKMMOMOMMLMKMMOMOMNKLKLMKLKIKKJHJKJIEDDE;<<<$a

```

Try it online!

I've had this answer prepared since this question was in the sandbox and I'm annoyed I missed it being posted

Explanation:

```
for ((a=-$1;a<0;a+=##$s[++i]))s=...;<<<$a

for ((     ;   ;            ))     ;       # C-style for loop
      a=-$1;                               # initialise `a` to the input, negated
            a<0;                           # while `a` is less than 0
                              s=...;       # set `s` to the string
                        ++i                # increment `i` (starts at 0 implicitly)
                     $s[   ]               # get the `i`th character of `s`
                   ##                      # get the codepoint number of that character
                a+=                        # add that to `a`
                                   ;<<<$a  # then print `a`

```

**Note**: Initially I had `s=...;for ((...)):;<<<$r` \- setting s to the string beforehand, and the body of the loop being `:` (do nothing). But since the body of the loop is executed before the third clause of the loop (the "each iteration" part), and we only use `s` in that clause, we can put `s` in the body to save 2 bytes.

# Answer
> 2 votes
# Vyxal, 37 bytes

```
ɾ»«Ẏ⅛Ṁß)∞'₌›ṫh⁰ḟ†ṙ←⁰»12τ68+¦0p66+$Fhε

```

Try it Online!

# Answer
> 1 votes
# 05AB1E, 71 bytes

```
•1Ò}MKX…иv½ι„qā·&à©Dà|ãвìkPn…(l2ßrÏyO;¬VÕÏcw÷©ûëтÎBʒNdãA₄ΩΓ•3001вʒI@}αW

```

Try it online!

I know there's a shorter 05AB1E answer, but this uses a different method, so I thought it'd be interesting to see the comparison in byte lengths.

## Explained

```
•...•3001в          # Pushed compressed list of all years
          ʒI@}      # Keep only those >= the input year
              αW    # Push the smallest absolute difference amongst those values

```

# Answer
> 1 votes
# Jelly, 34 bytes

```
“¡AMzⱮ⁽ƑẸÑ[NṀtR“¦Ṛ’b8+"6FŻ+66ÄḟḶḢ_

```

**Try it online!**

### How?

```
“...“¦Ṛ’b8+"6FŻ+66ÄḟḶḢ_ - Link: year
“...“¦Ṛ’                - list of base 250 integers = [18853782274514630143915309466833, 1683]
        b8              - convert to base 8  = [[3, 5, 5, 7, ..., 2, 1], [3, 2, 2, 3]]
            6           - six
          +"            - zip (implicitly wrapped 6 = [6]) with addition
                                             = [[9,11,11,13, ..., 8, 7], [3, 2, 2, 3]]
             F          - flatten            = [ 9,11,11,13, ..., 8, 7,   3, 2, 2, 3]
              Ż         - prepend zero    = [ 0, 9,11,11,13, ..., 8, 7,   3, 2, 2, 3]
               +66      - add 66          = [66,75,77,77,79, ...,74,73,  69,68,68,69]
                  Ä     - cumulative sums = [66,141,218,295,374, ...,2653,2726,2795,2863,2931,3000]
                    Ḷ   - lowered range (year) = [0,1,2,...,year-1]
                   ḟ    - filter discard  - e.g. if year = 2860 then [2863,2931,3000]
                     Ḣ  - head                                        2863
                      _ - subtract (year)                                3

```

---

FWIW a port of ovs's 05AB1E answer using the second-difference (and also using the filter-out-lowered range technique above) is also 34:

```
“¬V>ƭṘḌƘH*O⁵i²Ọ’b7_4ÄŻ+75ÄŻ+66ḟḶḢ_

```

# Answer
> 1 votes
# Core Maude, ~~266~~ ~~263~~ ~~262~~ 204 bytes

```
mod H is pr LIST{Nat}. op n : Nat ~> Nat . vars A B C : Nat . eq n(A)= n(A 66
5710855311372188087909795024940117969860147607). eq n(A B C)= if A > B then
n(A(B +(C & 15)+ 68)(C >> 4))else sd(A,B)fi . endm

```

### Example Session

```
Maude> red n(1) .  --- Ex: 65
result NzNat: 65
Maude> red n(1066) .  --- Ex: 0
result Zero: 0
Maude> red n(1067) .  --- Ex: 78
result NzNat: 78
Maude> red n(1986) .  --- Ex: 0
result Zero: 0
Maude> red n(2021) .  --- Ex: 40
result NzNat: 40
Maude> red n(3000) .  --- Ex: 0
result Zero: 0

```

### Ungolfed

```
mod H is
    pr LIST{Nat} .

    op n : Nat ~> Nat .

    vars A B C : Nat .

    eq n(A) = n(A 66 5710855311372188087909795024940117969860147607) .
    eq n(A B C) =
        if A > B
            then n(A (B + (C & 15) + 68) (C >> 4))
            else sd(A, B)
        fi .
endm

```

The answer is obtained by reducing the function `n`, which takes the input year.

The large number encodes the differences between successive years (e.g., 141 - 66 = 75) *minus* 68, packed into a bitstring with 4 bits per value.

---

Shaved off 3 bytes by replacing two conditional equations with a single equation using `if_then_else_fi`.

Saved one more byte by deduplicating a long enough repeated sublist using a condition.

Saved 58 bytes by encoding the year differences as a bitstring (and a few other tweaks).

# Answer
> 1 votes
# Python 2, 83 bytes

```
f=lambda y,t=0x46ba1298ab6f2234037bc64abb247ba8e61402:f(y-t%14-66,t/14)if y>0else-y

```

Try it online!

Stores the differences between the years (minus 66) as digits in a base-14 number `t`. Repeatedly subtracts the differences from the given year `y` until we gets a non-positive number (overshoot), in which case the answer is `-y`.

---
Tags: code-golf, date, astronomy
---


title: Shift the letters, soldier?

text:
# Question
Title: Shift the letters, soldier?
## Context

We're at war! You need to transfer an important message to your general to inform them from an imminent assault. The thing is, your enemy knows a lot about cryptography : you will need to be more creative in order to encode your message...

## Task

Create a program that accepts an ascii message as input, and outputs the encoded message. The message should be encoded this way : each character should get its ascii value shifted by its position in the message.

For example, let's encode the message "Hello, world!"

```
H   e   l   l   o   ,       w   o   r   l   d   !     Original message

72  101 108 108 111 44  32  119 111 114 108 100 33    ASCII value

0   1   2   3   4   5   6   7   8   9   10  11  12    Place in the message

72  102 110 111 115 49  38  126 119 123 118 111 45    Encoded ascii (line 1 + line 2)

H   f   n   o   s   1   &   ~   w   {   v   o   -     Encoded message

```

The message `Hello, world!` should be encoded as `Hfnos1&~w{vo-`.

Sometimes the encoded ascii can go beyond printable character. In that case, the value loop back to 32 (read the rules for additionnal informations)

```
T   h   e       r   a   n   d   o   m       g   u   y      Original message

84  104 101 32  114 97  110 100 111 109 32  103 117 121    ASCII value

0   1   2   3   4   5   6   7   8   9   10  11  12  13     Place in the message

84  105 103 35  118 102 116 107 119 118 42  114 129 134    Encoded ascii (line 1 + line 2)

84  105 103 35  118 102 116 107 119 118 42  114 34  39    Corrected encoded ascii (looped back to 32)

T   i   g   #   v   f   t   k   w   v   *   r   "   '

```

`The random guy` is then converted into `Tig#vftkwv*r"'`

Using the same strat, `zzzzzzzzz` will be converted into `z{|}~ !"#` (ascii values converted into `122 - 123 - 124 - 125 - 126 - 32 - 33 - 34 - 35`)

## Rules

* The input message will be composed of printable ascii character (between 32 and 126)
* The message should be encoded as described before.
* The ascii values of the encoded message should be set between 32 and 126.
* The first character of the message should be at position **0**.
* If the new ascii value goes *beyond the limit*, it should loop back to **32**.
* **Every** character should be encoded. This includes punctuation, spaces etc.
* No standard loopholes allowed.
* This is codegolf, so the shortest code wins.

# Answer
# Python 3.8, ~~55~~ 54 bytes

Output is a list of characters.

```
lambda s,d=33:[chr((ord(c)-(d:=d-1))%95+32)for c in s]

```

Try it online!
> 7 votes

# Answer
# Charcoal, 9 bytes

```
⭆Ｓ§γ⁺κ⌕γι

```

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

```
 Ｓ          Input string
⭆           Map over characters and join
        ι   Current character
      ⌕     Find position in
       γ    Printable ASCII
    ⁺       Plus
     κ      Current index
  §         Cyclically indexed into
   γ        Printable ASCII
            Implicitly print

```
> 7 votes

# Answer
# , 22 bytes

```
(95|<:+#\)&.(_32+3&u:)

```

Try it online!

Almost word-to-word translation of my dzaima/APL solution.

### How it works

```
(95|<:+#\)&.(_32+3&u:)  NB. Input: string S
(   X    )&.(   Y    )  NB. The "Under" operator; do Y, do X and undo Y
             _32+3&u:   NB. Convert chars to codepoints and subtract 32
       #\               NB. One-based index
    <:+                 NB. Add to the codepoints minus 1
 95|                    NB. Modulo 95
             _32+3&u:   NB. Undo this: add 32 and convert to chars

```
> 5 votes

# Answer
# , ~~56~~ 57 bytes

```
function(s)intToUtf8((utf8ToInt(s)-33+1:nchar(s))%%95+32)

```

Try it online!

*Edit: thanks to Giuseppe for bug-spotting!*

I am beginning to despise string manipulations in R, and the `intToUtf8()` / `utf8ToInt()` function names in particular...
> 5 votes

# Answer
# APL (Dyalog Unicode), ~~28~~ ~~24~~ 22 bytes SBCS

-4 bytes thanks to @Adám; -2 bytes thanks to @ngn;

Monadic function expecting a string:

```
⎕ucs 32+95|⎕ucs-32-⍳∘≢

```

Try it online! Assumes `⎕IO←0`. How the 24-byter works:

```
32(⎕ucs⊣+95|⊢--∘⍳∘≢)⎕ucs  ⍝ monadic function taking a character vector on the right
                     ⎕ucs  ⍝ convert to unicode code points
32(                 )      ⍝ and then evaluate the expression with 32 as left argument and the code points as right arg
               -∘⍳∘≢        ⍝ do 32 minus (-) the range 0 1 ... [length of input string] (⍳∘≢)
            ⊢-            ⍝ take the right argument (⊢) [the codepoints] and subtract the previous calculation from those [effectively adding the positions and subtracting 32]
         95|               ⍝ and take those numbers modulu 95.
      ⊣+                  ⍝ Take the left (⊣) argument [32] and add it to the numbers we just did mod 95
  ⎕ucs                     ⍝ and convert the new code points to characters.

```

@Bubbler has a similar answer but making use of an operator that hasn't been implemented in Dyalog APL yet, check it out.
> 4 votes

# Answer
# 05AB1E, ~~16~~ ~~10~~ 9 bytes

```
žQDIkā<+è

```

-1 byte by porting *@Neil*'s Charcoal answer, so make sure to upvote him!

I/O as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
žQ          # Push the printible ASCII string builtin
  D         # Duplicate it
   I        # Push the input-list of characters
    k       # Get each index in the ASCII string
     ā      # Push the list [1, length] (without popping)
      <     # Decrease it by 1 to make it a 0-based range [0, length)
       +    # Add the values at the same positions in the lists together
        è   # Index each into the ASCII string (0-based and with automatic wraparound)
            # (after which the resulting list of characters is output implicitly)

```
> 4 votes

# Answer
# Perl 5 (`-p`), 32 bytes

-1 byte thanks to @Abigail

```
s/./chr 32+($x++-32+ord$&)%95/ge

```

Try it online!
> 4 votes

# Answer
# APL (dzaima/APL), 21 bytes

```
{95|⍵+⍳≢⍵}⍢(¯32+⎕UCS)

```

Try it online!

Just trying out the experimental Under operator  because the task is screaming for it.

### How it works

```
{95|⍵+⍳≢⍵}⍢(¯32+⎕UCS)  ⍝ Input: string S
          ⍢(¯32+⎕UCS)  ⍝ Convert S to Unicode codepoints and subtract 32
{   ⍵+⍳≢⍵}             ⍝ Add the index to each char
 95|                   ⍝ Modulo 95
          ⍢(¯32+⎕UCS)  ⍝ Undo the operation:
                       ⍝ Add 32 and convert back to Unicode chars

```
> 4 votes

# Answer
# C (gcc), ~~48~~ ~~47~~ 46 bytes

Saved a byte thanks to 640KB!!!

Saved a byte thanks to dingledooper!!!

```
i;f(char*s){for(i=32;*s;)*s++=(*s-i--)%95+32;}

```

Try it online!
> 4 votes

# Answer
# Retina 0.8.2, 19 bytes

```
{*\M!`^.
^.

T`~p`p

```

Try it online! Link includes test cases. Explanation:

```
{

```

Repeat until the input is empty.

```
*\M!`^.

```

Output the first character.

```
^.

```

Remove the first character.

```
T`~p`p

```

Cyclically increment the remaining characters.

12 bytes in Retina 1:

```
1,Tv`~p`p`.+

```

Try it online! Link includes test cases. Explanation:

```
v`.+

```

Create overlapping matches that start at each character and end at the end of the string.

```
1,

```

Ignore the match of the whole input.

```
T`~p`p`

```

Cyclically shift each character according to the number of times it was matched.
> 3 votes

# Answer
# K (oK), 19 bytes

```
{`c$32+95!x-32-!#x}

```

Try it online!
> 3 votes

# Answer
# x86-16 machine code, IBM PC DOS, ~~17~~ 16 bytes

**Binary:**

Build `STL.COM` using `xxd -r`:

```
00000000: b120 b408 cd21 2ac1 d45f 0420 cd29 e0f2  . ...!*.._. .)..

```

**Listing:**

```
B1 20       MOV  CL, 32         ; set up offset / position counter
        CLOOP:
B4 08       MOV  AH, 8          ; use DOS API get char from STDIN function
CD 21       INT  21H            ; read input char into AL
2A C1       SUB  AL, CL         ; subtract offset
D4 5F       AAM  95             ; AL = AL % 95
04 20       ADD  AL, 32         ; restore ASCII offset
CD 29       INT  29H            ; output AL to console
E0 F2       LOOPNZ CLOOP        ; keep looping until break, decrement CL

```

Standalone IBM PC DOS executable program. Input via `STDIN`, output to console.

**Runtime:**
> 3 votes

# Answer
# Java (OpenJDK 8), 80 60 bytes

```
s->{int i=0;for(char n:s)s[i]+=i-(n+i++>126?95:0);return s;}

```

Try it online!

Thanks for help from Kevin Cruijssen
> 3 votes

# Answer
# Haskell, 55 bytes

```
g '~'=' '
g c=succ c
i!c=iterate g c!!i
zipWith(!)[0..]

```

Try it online!

The TIO link has `f=`, but that doesn't contribute to the byte count because I defined it point-free. It's mostly there so that the code compiles.

I didn't play around much with using a point-free definition instead of `!`, so that might be a place where some bytes can be shaved off. I just figured that the parens and dots would add up. I also want to get rid of the call to `iterate`, but I'm not sure how. I want something like `mtimes`...

# Haskell \+ `-XParallelListComp`, 55 bytes

```
g '~'=' '
g c=succ c
f s=[iterate g c!!i|c<-s|i<-[0..]]

```

Try it online!

Unfortunately this isn't any shorter, but I thought it was a cool usage of a pragma. It seems most of the time that pragmas aren't too helpful in golfing.

# Explanation

```
-- g gives the successor of each character according to the specification
g :: Char -> Char
-- the successor of '~' is ' ' (wrap around)
g '~'=' '
-- all other characters have their normal successor
g c=succ c

-- (!) is an infix function that enciphers a character, given an int
(!) :: Int -> Char -> Char
-- iterate produces an infinite list of 'g' applied to 'c' repeatedly,
-- and '!!' indexes into that list at index 'i'. This has the effect
-- of applying 'g' to 'c' 'i' times.
i!c=iterate g c!!i

-- Point-free definition that applies '!' to each character of the input along with its index
zipWith(!)[0..]

```
> 3 votes

# Answer
# Haskell, ~~52~~ 51 bytes

```
zipWith(%)[-32..]
n%c=toEnum$32+mod(fromEnum c+n)95

```

Try it online!

---

# Haskell, 52 bytes

```
zipWith(%)[0..]
n%c=snd(span(<c)$cycle[' '..'~'])!!n

```

Try it online!

### Explanation

* `zipWith(%)[0..]` calls the infix function `%` on each character of the input string along with its index.
* `cycle[' '..'~']` builds a list where the ASCII chars are repeated infinitely.
* `span(<c)` partitions this list into a prefix of chars smaller than the current character `c` and a remainder.
* `snd` drops the prefix, so only the list of ASCII chars starting with `c` remains.
* `!!n` returns the `n`th element from that list.
> 3 votes

# Answer
# Ruby, 42 bytes

```
->s{i=33;s.map{((_1.ord-i-=1)%95+32).chr}}

```

Takes input and returns output as an array of characters.

### 44 byte version because TIO doesn't support ruby 2.7's `_1` syntax

```
->s{i=33;s.map{|c|((c.ord-i-=1)%95+32).chr}}

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Extended), 22 bytes (SBCS)

Full program. Requires `⎕IO←0`

```
⍞(⊢⊇⍨95|⍳⍨+~⍋⊣)' '…'~'

```

Try it online!

`' '…'~'` the printable ASCII range

`⍞(``)` with the input as left argument, apply the following tacit function to that:

the left argument (the input)

the sorting permutation to sort according to the following order:

`~` the input without any printable ASCII, i.e. an empty string (this means leave all in current positions)

`⍳⍨` the indices of the input characters in the printable ASCII

`95|` division remainder when divided by 95

`⊇⍨` use those indices to select from:

the printable ASCII
> 2 votes

# Answer
# T-SQL, 100 bytes

Added some line changes to make it readable

```
DECLARE @x INT=0
WHILE @x<len(@)
SELECT
@=substring(@,2,999)+char((ascii(@)+@x-32)%95+32),
@x+=1
PRINT @

```

**Try it online**
> 2 votes

# Answer
# Befunge-93, 25 bytes

```
:~:1+!#@_" "-+"_"%" "+,1+

```

Try it online!

Keeps the character count on the bottom of the stack. Then in a loop, reads a character at the time, subtracts 32 to the character, adds the character count, mods it with 95, adds 32 again, then prints the character. Finally, it adds 1 to the character count.
> 2 votes

# Answer
# Ly, 25 bytes

```
ir84*sp[l-l,sp(95)%84*+o]

```

Try it online!
> 2 votes

# Answer
# JavaScript, 77 bytes

Iterative!

```
s=>[...s].map((c,i)=>String.fromCharCode((c.charCodeAt()+i-32)%95+32)).join``

```

Try it online!

---

# JavaScript, 77 bytes

Outer recursive!

```
f=(s,i=0)=>s[i]?String.fromCharCode((s.charCodeAt(i)+i-32)%95+32)+f(s,i+1):''

```

Try it online!

---

# JavaScript, 77 bytes

Inner recursive!

```
s=>(F=i=>s[i]?String.fromCharCode((s.charCodeAt(i)+i-32)%95+32)+F(i+1):'')(0)

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~46 50~~ 48 bytes

```
x;f(char*s){*s?*s=(*s+x++-32)%95+32,x=f(s+1):0;}

```

Try it online!
> 1 votes

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

```
s=>Buffer(s).map((c,i)=>(c+i-32)%95+32)+''

```

Try it online!
> 1 votes

# Answer
# Jelly, 9 bytes

```
O+J_32ịØṖ

```

**Try it online!**

### How?

```
O+J_32ịØṖ - Link: list of characters, S  - e.g. "zzzzzzzzz"
O         - cast (S) to ordinal values          [122,122,122,122,122,122,122,122,122]
  J       - range of length (S)                 [  1,  2,  3,  4,  5,  6,  7,  8,  9]
 +        - add (vectorises)                    [123,124,125,126,127,128,129,130,131]
    32    - thirty-two                          32
   _      - subtract                            [ 91, 92, 93, 94, 95, 96, 97, 98, 99]
       ØṖ - printable ASCII characters          " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
      ị   - index into (1-based & modular)      "z{|}~ !"#"

```
> 1 votes

# Answer
# Erlang (escript), 68 bytes

```
f(I,[H|T])->[(H+I-32)rem 95+32]++f(I+1,T);f(_,[])->[].
f(I)->f(0,I).

```

Try it online!
> 1 votes

# Answer
# Stax, 9 bytes

```
éñÇöo♣j0♦

```

Run and debug it
> 1 votes

# Answer
# Wolfram Language, 68 bytes

```
FromCharacterCode@Mod[#&~Array~Length@#+#-1,95,32]&@*ToCharacterCode

```

Uses a little function composition to make it shorter, but other than that, does pretty much what it says on the tin. Converts the string to character codes, adds the proper offset to each, wraps around if needed using Mod (there's an optional argument for offset that I use here), then converts back to a string.
> 1 votes

# Answer
# Keg, 19 bytes

```
0&(⑻+:\~>[\~% +;],⑹

```

Try it online!

Woooo! I managed to beat APL somehow! This is a very literal interpretation of the challenge, except for the part where overflow values are decremented after modulusing.
> 0 votes

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

```
'!v
-1<,+ '%_'-\~@#:

```

Try it online!

Initially pushes `d=33` on the stack. On every iteration, `d` is reduced by one and `(input-d)%95+32` is printed.
> 0 votes

# Answer
# Pyth, 29 bytes

```
VlQ=+Y-C@QN32;s.eC+%+bk95 32Y

```

Try it online!
> 0 votes

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


title: Drawing one-liner

text:
# Question
Title: Drawing one-liner
# ~~Code~~Drawing one-liner

# Teaser

Behold this formidable drawing:

Can you draw this in a single stroke? Give it a try.

Can you do this one, now:

Give it a try.

# How it works

These "make this drawing with one pen stroke" problems are problems with a rather simple solution. For each vertex, compute its degree. If all vertices have an even degree or if only two vertices have an odd degree, this is possible. In any other case, it is impossible. This is the same as finding an Eulerian path in the graph. This is also related to the very famous seven bridges of Königsberg puzzle.

For the first drawing, the degrees are

```
   2
 /   \
4-----4
|\   /|
|  4  |
|/   \|
3-----3

```

so we are in the second possible case, as all numbers are even except for the two 3s in the bottom. What is more, when we have odd numbers, we have to start in one of them and finish in the other. When everything is even, we can start wherever we want but we will finish where we started.

For the second drawing it is impossible, as there are too many odd degrees:

```
     2
   /   \
  5-----5
 /|\   /|\
2 |  4  | 2
 \|/   \|/
  5-----5
   \   /
     2

```

# Task

Given the degrees of the edges as input, decide if a corresponding drawing could be done in a single pen stroke. Output Truthy if such a feat is possible and output Falsy otherwise.

# Input

The degrees of the vertices in any sensible format, such as

* an array of integers like `[2,4,4,4,3,3]` or `[2,5,5,2,4,2,5,5,2]`
* separate arguments to a function, like `f(2,4,4,4,3,3)` or `f(2,5,5,2,4,2,5,5,2)`

# Output

A Truthy value if all numbers are even or exactly two of them are odd, Falsy otherwise.

# Test cases

## Truthy

```
[2, 4, 4, 3, 3]
[2, 2]
[1, 2, 3, 4, 6, 8]
[2, 4, 2, 4, 2, 4, 2, 4]
[8, 6, 8, 2, 2, 3, 11]
[1, 3]
[8]

```

## Falsy

```
[1, 2, 3, 4, 5, 6]
[2, 3]
[9]
[7, 2, 2, 2]
[4, 2, 7]
[3, 3, 3, 3]
[1, 2, 3, 1, 1]
[1, 1, 4, 1, 1]
[7, 7, 7, 7, 7, 7, 7, 7]

```

---

This is so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

# Answer
> 13 votes
# Python, 31 bytes

```
lambda l:sum(n%2for n in l)|2<3

```

Try it online!

We use `k|2<3` to check that `k` is either 0 or 2. This works because the bit operation `|2` sets the bit for place-value 2, so to get a result that's 2 or less, there must be no other bits set.

# Answer
> 5 votes
# Wolfram Language (Mathematica), 25 bytes

```
(a=Tr@Mod[#,2])==0||a==2&

```

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~5~~ 4 bytes

Thanks to 05AB1E's weird boolification system, any number but 1 is falsy.

-1 Thanks to Jonathan Allan

```
ÉO1α

```

Try it online!

# Explanation

```
É     Vectorizing n % 2
 O    Sum the resulting list
  1α  |n - 1|

```

# Answer
> 4 votes
# Turing Machine But Way Worse, 1245 bytes

```
0 0 0 1 1 0 0
0 1 0 1 2 0 0
1 2 1 1 3 0 0
1 3 1 1 4 0 0
0 4 0 1 5 0 0
1 4 1 1 5 0 0
0 5 0 1 6 0 0
1 5 1 1 6 0 0
0 6 0 1 7 0 0
1 6 1 1 7 0 0
0 7 0 1 0 0 0
1 7 1 1 8 0 0
0 8 0 1 9 0 0
0 9 0 1 a 0 0
1 a 1 1 b 0 0
1 b 1 1 c 0 0
0 c 0 1 d 0 0
1 c 1 1 d 0 0
0 d 0 1 e 0 0
1 d 1 1 e 0 0
0 e 0 1 f 0 0
1 e 1 1 f 0 0
0 f 0 1 0 0 0
1 f 1 1 8 0 0
0 b 0 1 k 0 0
0 3 0 1 4 0 0
0 g 0 1 h 0 0
0 h 0 1 i 0 0
1 i 1 1 j 0 0
1 j 1 1 k 0 0
0 k 0 1 l 0 0
1 k 1 1 l 0 0
0 l 0 1 m 0 0
1 l 1 1 m 0 0
0 m 0 1 n 0 0
1 m 1 1 n 0 0
0 n 0 1 g 0 0
1 n 1 1 o 0 0
0 o 0 1 p 0 0
0 p 0 1 q 0 0
1 q 1 1 r 0 0
1 r 1 1 s 0 0
0 s 0 1 t 0 0
1 s 1 1 t 0 0
0 t 0 1 u 0 0
1 t 1 1 u 0 0
0 u 0 1 v 0 0
1 u 1 1 v 0 0
0 v 0 1 g 0 0
1 v 1 1 o 0 0
0 r 0 1 A 0 0
0 j 0 1 k 0 0
0 w 0 1 x 0 0
0 x 0 1 y 0 0
1 y 1 1 z 0 0
1 z 1 1 A 0 0
0 A 0 1 B 0 0
1 A 1 1 B 0 0
0 B 0 1 C 0 0
1 B 1 1 C 0 0
0 C 0 1 D 0 0
1 C 1 1 D 0 0
0 D 0 1 w 0 0
1 D 1 1 E 0 0
0 E 0 1 F 0 0
0 F 0 1 G 0 0
1 G 1 1 H 0 0
1 H 1 1 I 0 0
0 I 0 1 J 0 0
1 I 1 1 J 0 0
0 J 0 1 K 0 0
1 J 1 1 K 0 0
0 K 0 1 L 0 0
1 K 1 1 L 0 0
0 L 0 1 w 0 0
1 L 1 1 E 0 0
0 H 0 1 0 0 1
0 z 0 1 A 0 0
0 2 1 1 M 0 0
0 y 1 1 M 0 0
0 q 1 1 M 0 0
0 M 1 1 N 0 0
0 N 0 1 O 0 0
0 O 0 1 P 0 0
0 P 0 1 Q 0 0
0 Q 1 1 0 1 1
0 a 0 1 0 0 1
0 i 0 1 0 0 1
0 G 0 1 0 0 1

```

Try it online!

**Input:** A list like `n, n, n, n, ...`
**Output:** *(blank)* for falsy, `1` for truthy

# Answer
> 3 votes
# Charcoal, 8 bytes

```
⁼¹↔⊖Σ﹪Ａ²

```

Try it online! Link is to verbose version of code. Port of @ovs' 05AB1E answer. Explanation:

```
      Ａ     Input array
     ﹪ ²    Vectorised modulo literal 2
    Σ       Sum
   ⊖        Decremented
  ↔         Absolute
⁼¹          Equals literal 1

```

There are other ways to check for `0` or `2` for the same byte count, such as `Not(Decremented(Absolute(Decremented(...))))`, `Equals(2, BitwiseOr(2, ...))`, or `Count("02", Cast(...))` (careful not to use `"20"` of course).

# Answer
> 3 votes
# Retina 0.8.2, 18 bytes

```
M`[13579]\b
^[02]$

```

Try it online! Link includes test cases. Explanation:

```
M`[13579]\b

```

Count the number of odd numbers.

```
^[02]$

```

Compare to `0` or `2`.

# Answer
> 3 votes
# JavaScript (ES6), 29 bytes

```
a=>a.map(x=>m>>=x&1,m=5)&&m&1

```

Try it online!

### How?

We start with the bitmask \\$m=101\_2=5\_{10}\\$ and right-shift it by one position for each odd value in the input array. The final result is given by the parity of \\$m\\$.

# Answer
> 2 votes
# Python 3, 34 bytes

```
lambda a:sum(n%2for n in a)in(0,2)

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~6~~ 5 bytes

-1 byte thanks to a'\_'.

```
ÉO<ÄΘ

```

Try it online!

### Explanation

```
É       is the number odd (vectorizes over the input list)
 O      sum (number of odd values)
  <     decrement (number of odd values - 1)
   Ä    absolute value (|number of odd values - 1|)
    Θ   equal to 1 (|number of odd values - 1| == 1)

```

# Answer
> 2 votes
# Bash \+ Unix utilities, 28 bytes

```
dc<<<`grep -c [13579]$`d2-*p

```

Try it online!

Input is on stdin: one number per line.

Output is on stdout: 0 is truthy, any non-zero value is falsy.

How it works:

* grep counts the number *n* of lines ending with an odd digit;
* dc then computes and prints *n*\*(*n*-2), which is 0 iff *n* equals 0 or 2.

# Answer
> 2 votes
# C++ (gcc), 73 64 bytes

I don't know why I keep trying.

```
int f(int*a,int s){int o=1;for(;s;)o+=a[--s]%2;return o%2&&o<4;}

```

Commented :

```
int f(int*a,int s){ // function definition

  int o=1;      // odd counter starts at 1 because then parity of truthy inputs is one

  for(;s;)          // Use size arg as counter and iterate backwards (Thanks @MitchellSpector)
    o+=a[--s]%2;    // check for odd, add parity

  return o%2&&o<4;  // Valid values for odd are 0 and 2 (or rather 1 and 3)
                    // Solve with parity and range check
}

```

TIO-k6qqj7ln

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 26 bytes

```
p=>(p.Count(n=>n%2>0)|2)<3

```

Try it online!

Thanks to answer of @xnor -1B

# 27 bytes

```
p=>(p.Count(n=>n%2>0)&-3)<1

```

Try it online!

This one was my first attempt, but I made mistake at first so I'm publishing it now when I fixed it.

# Answer
> 2 votes
# Excel, 50 bytes

```
=ISNUMBER(FIND(SUMPRODUCT(--(MOD(A:A,2)=1)),"02"))

```

`MOD(A:A,2)=1` to find odd number `SUMPRODUCT()` to count them `FIND( ,"02")` to check if `0` or `2` `ISNUMBER()` to converts to TRUE/FALSE

Feels very clunky, hope to refine...

# Answer
> 2 votes
# MATL, 6 bytes

```
osq|1=

```

Try it online!

I herd we're portin 05AB1E solutions!

A port of Arnauld's JS solution while we're at it (8 bytes):
`osW5w/ko` Try it online!

And one of Gymhgy's Japt answer (6 bytes, 0 as Truthy, other numbers as Falsy):
`os3_Z&` Try it online! (though, `os2FZ:` is a more straightforward implementation of the idea in MATL Try it online!)

# Answer
> 2 votes
# Julia 1.0, 15 bytes

```
~v=sum(v.%2)&-3

```

Try it online!

A port of Gymhgy's Japt answer (0 as Truthy, other numbers as Falsy).

**17 bytes** porting Arnauld's JS solution :

`~v=5>>sum(v.%2)%2` Try it online!

And an obligatory port of the popular 05AB1E solution, at **19 bytes**:

`~v=abs(sum(v.%2)-1)` Try it online!

# Answer
> 1 votes
## `d`, ~~8~~ 7 bytes

```
♦æ╥└¬y÷

```

Uncompressed:

```
2mJ1-z1=

```

## Explanation

```
2m       % Modulo the list by 2, auto-vectorizes.
  J      % Sum the list.
   1-    % Decrement by 1.
     z   % Absolute value.
      1= % Is this 1?

```

# Answer
> 1 votes
# Stax, 8 bytes

This method is shorter in Stax.

```
ƒ╟⌡≡ù₧╬)

```

Run and debug it

# Explanation

```
{2%m       Map modulo 2 over the input
    |+     Sum the resulting list
      02\  In the list [0, 2]:
         # How many times does this number appear?

```

# Answer
> 1 votes
# Keg, 13 bytes

```
÷⑷2%⑸⅀:0=$2=+

```

Try it online!

Simply using everyone else's algorithm!

# Answer
> 1 votes
# Japt `-!`, 7 bytes

```
èu a1 É

```

Try it

# Answer
> 1 votes
# PHP, ~~39~~ 43 bytes

```
for(;$n=$argv[++$i];)$s+=$n%2;echo!($s&-3);

```

Try it online!

# Answer
> 1 votes
# Perl 5 `-pa`, 20 bytes

```
$_=(2|grep$_%2,@F)<3

```

Try it online!

Borrows the `|2<3` trick from @xnor's Python answer

# Answer
> 1 votes
# Japt `-!`, 6 bytes

```
èu &-3

```

Try it

```
èu &-3        Full program taking in array of degrees U
èu            Amount of odd numbers in array
   &          Bitwise AND
    -3        With -3; -3 has very bit set except of the second bit (1111...11101)
-!            Zero -> True, Other numbers -> False

```

# Answer
> 1 votes
# GolfScript, 11 bytes

```
{2%+}*(2?(!

```

Try it online!

My first go at it, may shrink it a bit. I made it so 1 is true, 0 is false, but if you're okay with the other way around, I can do different things :)

Short explanation; Convert all the elements to mod 2 and sum them. The only valid answers would be 0 or 2. Now, subtract 1 and square them. 0 is -1 is 1. 2 is 1 is 1. 0 and 2 both give you 1. Lastly, subtract 1 and perform a not operation to make all non-0, non-2 values to a 0 and the 0-2s to a 1.

Kind of roundabout, and I'm sure I can cut two characters somewhere.

# Answer
> 1 votes
# APL (Dyalog Unicode), 10 bytesSBCS

```
0 2∊⍨1⊥2∘|

```

Try it online!

Because a challenge needs an APL answer.

### How it works

```
0 2∊⍨1⊥2∘|
       2∘|  ⍝ Modulo 2
     1⊥     ⍝ Sum
0 2∊⍨       ⍝ Is member of [0 2]?

```

# Answer
> 1 votes
# Whitespace, 102 bytes

```
[S S S N
_Push_0][S N
S _Dupe_0][N
S S N
_Create_Label_LOOP][S N
S _Dupe][S N
S _Dupe][T  N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S N
S _Dupe_input][N
T   T   S N
_If_neg_Jump_to_Label_DONE][S S S T S N
_Push_2][T  S T T   _Modulo][T  S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_DONE][S N
N
_Discard][S N
S _Dupe][N
T   S T N
_If_0_Jump_to_Label_TRUTHY][S S S T S N
_Push_2][T  S S T   _Subtract][N
T   S T N
_If_0_Jump_to_Label_TRUTHY][T   N
S T _Print_as_integer][N
N
N
_Exit_program][N
S S T   N
_Create_Label_TRUTHY][S S S T   N
_Push_1][T  N
S T _Print_as_integer]

```

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

Since Whitespace inputs one integer at a time, the input should contain a trailing `-1` so it knows when to stop reading integers and the input is done.
Outputs `1`/`0` for truthy/falsey respectively.

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

**Explanation in pseudo-code:**

```
Integer n = 0
Start LOOP:
  Integer i = STDIN as input
  If(i < 0):
    Jump to Label DONE
  n = n + (i modulo-2)
  Go to next iteration of LOOP

Label DONE:
  If(n == 0): Jump to Label TRUTHY
  If(n-2 == 0): Jump to Label TRUTHY
  Print 0 as integer to STDOUT
  Exit program

Label TRUTHY:
  Print 1 as integer to STDOUT

```

# Answer
> 1 votes
# MathGolf, 6 bytes

```
¥Σ(±1=

```

Try it online.

**Explanation:**

```
¥       # Take modulo-2 on each integer of the (implicit) input-list
 Σ      # Sum those
  (     # Decrease it by 1
   ±    # Take the absolute value
    1=  # And check whether this is equal to 1
        # (after which the entire stack joined together is output implicitly)

```

# Answer
> 1 votes
# Java 8, 28 bytes

```
s->(s.map(i->i%2).sum()|2)<3

```

Port of *@xnor*'s Python answer

Try it online.

**Explanation:**

```
s->               // Method with IntStream parameter and boolean return-type
  (s.map(i->i%2)  //  Take modulo-2 for each value in the IntStream
    .sum()        //  And them sum those
    |2)           //  Take a bitwise-OR with 2
       <3         //  And check whether that is smaller than 3

```

# Answer
> 1 votes
# Chevron, ~~172~~ 147 bytes

```
^__>^n
>^n>^t
^t~s>>^s
0>>^o
0>>^i
^i+1>>^i
^t,^i~c>>^c
->+2??^c~^_i
->-3
^n^c>^n
^n~o>>^z
^o+^z>>^o
^__>^n
->+2?^i=^s
->-9
^o-2>>^p
^o*^p>>^o
>^o

```

Takes numbers from stdin in the form `2 4 4 3 3`.

Outputs `0` or `-0` for truthy, anything else falsy.

# Answer
> 1 votes
# Vyxal, 6 bytes

```
∺∑⨪Ȧ1=

```

Try it Online!

Just another port of the 05ab1e answer.

# Answer
> 1 votes
# , ~~30~~ 29 bytes

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

*Edit: -1 byte thanks to @Giuseppe.*

```
function(v)sum(v%%2/2)%in%0:1

```

Try it online!

Almost straightforward approach.

Less straightforward, but used by many other answers, approach results in the same byte-count:

```
function(v)(sum(v%%2)-1)^2==1

```

Try it online!

# Answer
> 1 votes
# , 28 bytes

```
function(v,w=sum(v%%2))w&w-2

```

Try it online!

Possibly an even-more-straightforward approach than pajonk's R answer: just check separately whether the sum of even elements `w` is non-zero (`w`) and also not 2 (`w-2`).

# Answer
> 1 votes
# Vyxal, 5 bytes

```
∷∑‹ȧċ

```

Try it Online!

05ab1e port. Outputs 0 for possible + 1 for impossible. The last character can be removed if we can output 1 for possible and anything for impossible.

---
Tags: code-golf, math, decision-problem, graph-theory
---


title: ASCII Brainfuck

text:
# Question
Title: ASCII Brainfuck
Given a random code written using Brainfuck commands. You program should translate that code into the following ascii art: each Brainfuck command represents as `5x9` array of `A` and `B` symbols. All commands are concatenated with `5x3` arrays of `A` symbols. Symbols `A` and `B` you choose yourself.

For example, when input is `><+,.[]` your program might output:

```
==                 ==       =                                 = = =       = = =
    ==         ==           =                                 =               =
       ==   ==          = = = = =                             =               =
    ==         ==           =           =           =         =               =
==                 ==       =          =                      = = =       = = =

```

Or

```
@@                 @@       @                                 @ @ @       @ @ @
    @@         @@           @                                 @               @
       @@   @@          @ @ @ @ @                             @               @
    @@         @@           @           @           @         @               @
@@                 @@       @          @                      @ @ @       @ @ @

```

Or even

```
..ooooooooooooooooo..ooooooo.ooooooooooooooooooooooooooooooooo.o.o.ooooooo.o.o.oo
oooo..ooooooooo..ooooooooooo.ooooooooooooooooooooooooooooooooo.ooooooooooooooo.oo
ooooooo..ooo..oooooooooo.o.o.o.o.ooooooooooooooooooooooooooooo.ooooooooooooooo.oo
oooo..ooooooooo..ooooooooooo.ooooooooooo.ooooooooooo.ooooooooo.ooooooooooooooo.oo
..ooooooooooooooooo..ooooooo.oooooooooo.oooooooooooooooooooooo.o.o.ooooooo.o.o.oo

```

And etc. Trailing spaces and `A` symbols are allowed.

It is guaranteed that the input will consist only of the symbols `>` `<` `+` `,` `.` `[` `]`.

This is a code-golf challenge so the shortest solution wins.

# Answer
> 5 votes
# Jelly, 57 bytes

```
“ṾÆxÑ3øḤC⁵ịJYSLẇɱ⁼’Bs3ŒBJṫ⁴Ɗ¦z1m€0Ṛs€9
⁽HṠ,17ḥⱮịⱮ¢j€⁶ẋ3¤Y

```

A full program accepting a string as the first program argument that prints the result, using `0` for ink and `1` for no ink.

**Try it online!** (The footer just replaces the `1`s with spaces to make it easier to inspect.)

### How?

```
“...’Bs3ŒBJṫ⁴Ɗ¦z1m€0Ṛs€9 - Link 1: no arguments
“...’                    - 43552819895870853685529620449548093603391
     B                   - in binary
      s3                 - split into chunks of length 3
                           -> columns of the bottom half of 5 of the 7 characters
                              the '[' and '>' are created using reflection later
                              the comma is reversed too, we'll use its reflection
              ¦          - sparse application...
             Ɗ           - ...to indices: last three links as a monad:
          J              -   range of length
            ⁴            -   16
           ṫ             -   tail (covers the columns containing ',' and '.')
        ŒB               - ...apply: bounce ("something" -> "somethingnihtemos")
               z1        - transpose with filler 1 (fills where we didn't reflect)
                 m€0     - reflect each (constructing our ']', '>', and ',')
                    Ṛ    - reverse
                           -> a list of the lines of a representation (without
                              any spacing) of ",.+<][>+.," where the first
                              comma is reversed.
                     s€9 - split each line into chunks of length 9

⁽HṠ,17ḥⱮịⱮ¢j€⁶ẋ3¤Y - Main Link: list of characters, C
⁽HṠ,17             - [19206,17]
       Ɱ           - map across C with:
      ḥ            -   hash with salt 19206 and domain [1,2,...,17]
                       -> maps: ".[,+<]>" to 2,6,10,13,14,15,17
          ¢        - call Link 1 as a nilad
         Ɱ         - map across the lines of the result with:
        ị          -   index into
                       -> 1-indexed and modular, so e.g. 17 gets the 7th item,
                          the part of the line for a '>'.
                ¤  - nilad followed by links as a nilad:
             ⁶     -   space character
              ẋ3   -   repeated three times
           j€      - join each list of line parts with three spaces
                 Y - join with newline characters
                   - implicit, smashing print

```

# Answer
> 1 votes
# 05AB1E, 73 bytes

```
T>740SúÂX4úD‚„1 9∍ª1D‚7bš9j3δ._Ðí)εû.B}X3úĆS4ú€ûÐ3èÀ4ǝ‚«Ž5¹.IIÇ52%èø3ð×ý»

```

Uses spaces for \\$A\\$ and `1` for \\$B\\$.

It could definitely be golfed by using a different approach, but this will do for now.

Try it online.

**Explanation:**

Step 1: Create a list of all shapes:

Step 1a: top halve of `<`:

```
T>            # Push 11 (10 increments by 1)
  740S        # Push 740 as list: [7,4,0]
      ú       # Pad the "11" with that many leading spaces:
              #  ["       11","    11","11"]

```

Step 1b: top halve of `>`:

```
 Â            # Bifurcate it (short for Duplicate & Reverse copy):
              #  ["11","    11","       11"]

```

Step 1c: top halve of `+`:

```
X             # Push 1
 4ú           # Pad it with 4 leading spaces: "    1"
   D‚         # Pair it with a copy of itself: ["    1","    1"]
     „1       # Push string "1 "
        9∍    # Enlarge it to size 9: "1 1 1 1 1"
          ª   # Append it to the pair:
              #  ["    1","    1","1 1 1 1 1"]

```

Step 1d: top halve of `]`:

```
 1D‚          # Push pair [1,1]
    7bš       # Prepend "111" (7 as binary string): [111,1,1]
       9j     # Prepend spaces until all are length 9:
              #  ["      111","        1","        1"]
          δ   # Map over each string:
         3 ._ #  Rotate it 3 times towards the left:
              #   ["   111   ","     1   ","     1   "]

```

Step 1e: top halve of `[`:

```
Ð             # Triplicate the list
 í            # Reverse each inner string:
              #  ["   111   ","   1     ","   1     "]

```

Step 1f: palindromize all of the top halves pushed thus far to get the full shapes:

```
)             # Wrap the items on the stack into a list
 ε            # Map over each inner list:
  û           #  Palindromize the list to add the bottom halves
   .B         #  Box: add trailing spaces to each line up to the longest line
 }            # Close the map

```

Step 1g: `.`:

```
X             # Push 1
 3ú           # Pad it with 3 leading spaces: "   1"
   Ć          # Enclose; append its own head: "   1 "
    S         # Convert it to a character-list: [" "," "," ","1"," "]
     4ú       # Pad each with 4 spaces:
              #  ["     ","     ","     ","    1","     "]
       €û     # Palindromize each inner string
              #  ["         ","         ","         ","    1    ","         "]

```

Step 1h: `,`:

```
Ð             # Triplicate the list
 3è           # Pop one and leave its 4th string: "    1    "
   À          # Rotate it once towards the right: "   1   "
    4ǝ        # Replace the 5th string with this:
              #  ["         ","         ","         ","    1    ","   1     "]
‚             # Pair the shapes for `.` and `,` together
 «            # Merge them to the earlier list of shapes

```

We now have a list of all shapes (with an additional shape for `[` due to the triplicate instead of duplicate we've used in step 1e, which will be ignored in (but is necessary for) step 2.

Try just step 1 online.

Step 2: Use the input to get the correct shapes from this list:

```
Ž5¹           # Push compressed integer 1459
   .I         # Get the (0-based) 1459'th permutation of the list of shapes:
              #  It converts shape-order `<>+]][.,` to `<]>+,].[`
I             # Push the input-string
 Ç            # Convert it to a list of codepoints
              #  "><+,.[]" would become [62,60,43,44,46,91,93]
  52%         # Modulo-52 each: [10,8,43,44,46,39,41]
     è        # 0-based modular index it into the list of shapes
              # (the implicit modular indexing acts as modulo-8: [2,0,3,4,6,7,1])

```

Try just steps 1 and 2 online.

Step 3: Convert the list of shapes to the correct format and output it as result:

```
ø             # Zip/transpose the list of shapes; swapping rows/columns
 3ð×          # Push a string of 3 spaces: "   "
    ý         # Join each inner list with this delimiter
     »        # Then join the list of lines by newlines
              # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž5¹` is `1459`

# Answer
> 0 votes
# , <sup>~~272~~</sup> 236 bytes

```
l=.|."1 r =.5 9&$@((36$2)&#:)51545900568
p=.5 9&$@((27$2)&#:)4202837
d=.,&(9$0)@}:c=.|.((2 9&$@((15$2)&#:)2050),3 9$0)
m=.|."1 n =.5 9&$@((43$2)&#:)1445260697621
{&' #'@>@(,.&.>/)({&(r;l;p;c;d;n;m;5 3$0)@('><+,.[]_'&i.))"0@((,'_'&,)/) y

```

-36 bytes by using Catalogue `{` instead of Agenda `@.`

Try it online!

# Answer
> 0 votes
# Python 3.8 (pre-release), 257 bytes

```
lambda s:'\n'.join(list(map(lambda i:print("111".join([list(map(lambda s:str(s)[3:],map(bin,[0x9FFF9EFFFFFF57AB,0xF9F9FEFFFFFF7FFB,0xFF0FEAAFFFFF7FFB,0xF9F9FEFF7FBF7FFB,0x9FFF9EFEFFFF57AB])))[i][(p:="><+,.[]".index(c))*9:(p+1)*9]for c in s])),[0,1,2,3,4])))

```

I don't know why it gives me an TypeError, but it works :)

Try it online!

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


title: Can the Tune be Played?

text:
# Question
Title: Can the Tune be Played?
# Can the Tune be Played?

## Explanation

A broken musical keyboard has keys labelled with positive integers. It is broken in two ways:

1. It takes a long time to process key presses: after pressing the key labelled with the number \\$n\\$, there is a gap of \\$n\\$ seconds before the \\$n\\$th note is heard.
So, for example, the \\$5\\$th key must be pressed \\$5\\$ seconds early for its note to sound in the right place.
2. Only one key can be **pressed** at a time.

Because of these problems, some tunes cannot be played on the keyboard. To understand why, let us first define a tune:

A tune will be defined as a list of positive integers representing the order in which notes should be **heard** (not the order in which keys should be pressed). A number \\$n\\$ represents the note heard when the \\$n\\$th note on the keyboard is pressed. This definition does not allow for rests, chords or notes of differing lengths, so you can imagine that all notes are played at a speed of exactly one note per second.

## Invalid Tune Example

An example of a tune would be `[3, 1, 2]`. This means that the note \\$3\\$ should be heard, then, one second later, the note \\$1\\$, and a second after that, the note \\$2\\$.

However, when trying to play this tune on the keyboard, there is a problem. To understand why, shift each of the numbers \\$n\\$ in the tune back by \\$n\\$ spaces. The result represents the order in which keys must be pressed for the notes to sound in the correct place:

```
Tune                      [            3 , 1 , 2]
Index                      -3  -2  -1  0   1   2
How keys would be pressed [3 ,        1&2       ]

```

The problem here is that keys \\$1\\$ and \\$2\\$ must be pressed at the same time for their notes to sound in the right place, but it is impossible to press two keys at once on the keyboard. Therefore, the tune `[3, 1, 2]` cannot be played.

## Valid Tune Example

An example of a valid tune would be `[2, 1, 3]`. To see why, shift the numbers back to find out when the keys must be pressed:

```
Tune                      [        2 , 1 , 3]
Index                      -2  -1  0   1   2
How keys would be pressed [2 , 3 , 1        ]

```

Having shifted each of the numbers back (\\$2\\$ moved back \\$2\\$ spaces, \\$1\\$ moved back \\$1\\$ space and \\$3\\$ moved back \\$3\\$ spaces), none of them have landed in the same position. Therefore, this tune can be played on the broken keyboard: the keys would be pressed in the order `[2, 3, 1]`.

## Task

Your task is to write a program which takes as input a list representing a tune, and outputs a truthy/falsy value depending on whether or not the tune can be played on the broken keyboard.

## Assumptions

* You can assume that input lists will always contain only positive integers.
* You can assume that input lists will always have at least one element.
* You can assume that inputs will always be lists.
* Standard loopholes are forbidden.

## Test Cases

```
[1, 2, 3] -> False
[3, 1, 2] -> False
[3, 2, 1] -> True
[6, 4, 7, 3, 5, 2, 1] -> True
[4, 7, 6, 5, 2, 1, 3] -> False // 6 and 4 land in same position
[4, 6, 4, 2, 1, 4] -> False
[2, 1, 6, 4, 4, 4] -> False // 4 and 1
[2, 1, 6, 4, 2, 4] -> True

```

## Scoring

This is so the shortest answer (as measured in bytes) wins!

# Answer
# JavaScript (ES6), 30 bytes

Returns a Boolean value.

```
a=>a.every(b=(n,i)=>b[i-n]^=1)

```

Try it online!
> 10 votes

# Answer
# Vyxal, 4 bytes

```
ż-Þu

```

My first Vyxal answer. Similar approach as the other answer.

Try it online or verify all test cases.

**Explanation:**

```
ż     # Push a list in the range [1, input-length]
 -    # Subtract it from the input at the same positions
  Þu  # Check if all values in this list are unique
      # (after which the result is output implicitly)

```
> 7 votes

# Answer
# , 34 bytes

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

```
function(v)all(table(seq(!v)-v)<2)

```

Try it online!
> 6 votes

# Answer
# Jelly, 4 bytes

```
_JQƑ

```

Try it online!

```
_J     -- difference between each element and its 1-based index
   Ƒ   -- is this list invariant under:
  Q    --   removing duplicates?

```
> 6 votes

# Answer
# Python 2, 42 bytes

-7 thanks to Jonathan :)

```
lambda n:n[len({a-n.index(a)for a in n}):]

```

Try it online!
> 5 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~52~~ 51 bytes

```
j=>j.Count==j.Select((x,y)=>y-x).Distinct().Count()

```

Try it online!

Nice thing about how verbose C# is is that it is makes the code relatively self-explanatory. The downside is that it makes it hard to golf in. Interactive Compiler C# lets us cheat a bit by removing all the boilerplate.

A technical breakdown: If we can show that two keys need to play at the same time, we know it cannot be played. This approach tackles this by determining when they should play and checking for any duplicates. If we store when they should play and make that list distinct, all duplicates will be removed, however, the number of elements in the list will decrease as a result. By comparing that count against the original's, we get the true/false value we need.

To do this, we use the index overload of Linq's Select. This use of Select converts our collection of integers into another collection of integers, but with different values, that is, the original value subtracted from its respective index. Distinct and Count are both self-explanatory.

Saved one byte by taking a List instead of int\[\]. 'Count' is a property on a List; the eqivalent on an array is 'Length,' which is one extra byte. On an IEnumerable, 'Count' is a function, which is why 'Count' at the end requires the parens. It's not the best naming choices, but I have no control over that.
> 5 votes

# Answer
# MATL, ~~9~~ 8 bytes

```
tf-&=sqa

```

Try it online!

0 for
1 for broken keyboard leads to broken ❤.

**Explanation**:

`tf-` : Subtract from each input element its (1-based) index
`&=` : Compare each value against the whole array, giving a boolean matrix
`s` : sum each column to get a row vector of sums
`q` : Decrement each sum by 1 to take away the self-equality 1s
`a` : Check if there are any non-zero values still

---

A more obvious way is `tf- 8#uqa` (count how many times each unique value occurs in `input - indices` and see if it's all 1), but unfortunately the need for space between `-` and `8` pushes it to 9 bytes.
Edit: Luis Mendo's answer on another question taught me the trick of `&` at the end, to print only the top of the stack, with which this can instead be `tf-&uqa&` \- also 8 bytes. Only works on the current master of MATL though - neither TIO nor MATL Online have the `&u` feature available yet.

Another 9-byter is `tf-&=XRaa`.
> 4 votes

# Answer
# Wolfram Language (Mathematica), 24 bytes

```
i!=##&@@(i=0;i++-#&/@#)&

```

Try it online!

```
                  &/@#  for each:
         i=0;i++-#        index minus value
i!=##&@@(             ) all distinct (and unequal to length)

```
> 4 votes

# Answer
# APL+WIN, 20 bytes

Prompts for tune. 1=true, 0=false

```
0=+/2=/m[⍋m←n-⍳⍴n←⎕]

```

Try it online! Thanks to Dyalog Classic
> 3 votes

# Answer
# Julia 1.0, ~~26~~ 23 bytes

```
~v=allunique(v-keys(v))

```

Try it online!

*-3 bytes thanks to @MarcMush*

`true` for can be played, `false` otherwise.
> 3 votes

# Answer
# Retina 0.8.2, 33 bytes

```
\d+(?=((,)|.)*)
$*1$#2$*
D`1+
,\B

```

Try it online! Link includes test cases. Outputs a truthy value if the tune can't be played and a falsy value if it can. Explanation:

```
\d+(?=((,)|.)*)

```

Match values but also count the number of following values.

```
$*1$#2$*

```

Convert to unary and add on the number of following values. (This is easier to do than subtracting from number of preceding values.)

```
D`1+

```

Delete duplicates.

```
,\B

```

Check for a deletion.

19 bytes in Retina 1:

```
\d+
*_$;&*
D`_+
,\B

```

Try it online! Link includes test cases. Explanation: In Retina 1 `$;&` automatically counts the number of remaining matches i.e. the number of following values.
> 2 votes

# Answer
# Charcoal, 12 bytes

```
ＵＭθ⁻κι⊙θ⊖№θι

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if the tune can't be played and nothing if it can. Explanation:

```
ＵＭθ⁻κι

```

Subtract each element's value from its index.

```
⊙θ⊖№θι

```

Check whether any of the results were duplicated.
> 2 votes

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

```
{x~?x-:!#x}

```

Try it online!

* `!#x` generate `0..len(input)`
* `x-:` subtract the above from the input, "inplace" (i.e. updating `x`)
* `x~?` is the above composed of only distinct/unique values?
> 2 votes

# Answer
# Pyth, <sup>~~13~~ ~~12~~</sup> 9 bytes

```
L{I.e-bkb

```

Try it online!

```
L{I.e-bkb

L           # lambda b:
   .e-bkb   # difference between each element in the list b and its index
 {          # removes duplicates in the list
  I         # invariant?

```
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
ā-DÙQ

```

Try it online or verify all test cases.

**Explanation:**

```
ā      # Push a list in the range [1, input-length]
 -     # Subtract it from the values in the input at the same positions
       # Check if all values are unique:
  D    # Duplicate the list
   Ù   # Unquify the copy
    Q  # Check if both lists are still the same
       # (after which the result is output implicitly)

```
> 2 votes

# Answer
# MathGolf, 7 bytes

```
h╒m-_▀=

```

Try it online.

**Explanation:**

```
h        # Push the length of the (implicit) input-array
 ╒       # Pop and push a list in the range [1,length]
  m-     # Subtract these values from the input at the same positions
    _    # Duplicate this list
     ▀   # Uniquify the values in the copy
      =  # Check if the two lists are still the same
         # (after which the entire stack is output implicitly as result)

```
> 2 votes

# Answer
# Factor, 31 bytes

```
[ [ - ] map-index all-unique? ]

```

Try it online!

* `[ - ] map-index` Subtract each index from its element.
* `all-unique?` Are they all unique?
> 1 votes

# Answer
# Haskell, 45 bytes

```
f l|j<-zipWith(-)[1..]l=[x|x<-j,y<-j,x==y]==j

```

Try it online!

We put in *j* the tune as it would be played.
Then we check if its product has only *j* as duplicates using a list comprehension.
> 1 votes

# Answer
# Pip, 11 bytes

```
g#=UQ$-*ENg

```

Takes the numbers as separate command-line arguments. Attempt This Online!

### Explanation

```
          g  ; List of command-line args
        EN   ; Enumerate: list of [index; element] pairs
     $-*     ; Fold each on subtraction, giving index-element
   UQ        ; Uniquify
 #=          ; Return truthy if the result is the same length as
g            ; the original list

```
> 1 votes

# Answer
# Matlab, 33 bytes

```
K=@(x)all(diff(sort(x-find(x))));

```

find(x) is the array of 1:length(x), and subtracting the index of each note from the notes value produces the new index of when the note is played. By sorting the resulting array and taking the diff of sequential values, we can determine if there is overlap by making sure that there are no 0 differences (indicating two values are overlapping)

Try it online!
> 0 votes

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


title: Print a physical multiplication table

text:
# Question
Title: Print a physical multiplication table
Rectangles have this nice property - an \\$n \times m\\$ rectangle consists of exactly \\$n \times m\\$ characters!

A.. more interesting property is that the rectangles can be aligned nicely in a multiplication table - for example, a \\$3 \times 3\\$ table:

```
# ## ###

# ## ###
# ## ###

# ## ###
# ## ###
# ## ###

```

Your challenge is to, given a number \\$n\\$ (\\$ n \> 1\\$), output a formatted \\$n \times n\\$ multiplication table.

## Rules

* You can take the input one above or below \\$n\\$
* Default I/O rules apply
* You can choose any non-whitespace character to represent the blocks; every other character (though newlines are special) is considered whitespace. The chosen character can be different for different inputs, but must be the same throughout the input
* The result can have unneeded characters, as long as the table aligns up and there are no occurrences of the chosen character that aren't part of the required output
* The separators must be 1 character wide/tall, and the rectangles must be packed (i.e. no separators between their characters)
* The empty lines can be empty, padding isn't required
* The result can be a string, matrix, vector of lines, array of character arrays, or anything 2Dish
* You may alternatively output a matrix/vector-of-vectors/anything 2Dish of numbers, but the background & foreground must be 2 distinct numbers (which can vary input to input, but not throughout an output) and no other numbers can be present. Extra surrounding characters are allowed with this format too (though they must match the background number)
* This is , shortest answer in bytes, per-language, wins!

# Examples

For the input `2`, a valid ascii-art output, with the character , is:

```
        ∙ ∙∙

Result: ∙ ∙∙.
        ∙ ∙∙

```

yes the period is there just to confuse you
Another valid answer as a number matrix, with 2 being the background number and 9 the foreground:

```
[[9,2,9,9,2,2],
 [2,2,2,2,2,2],
 [9,2,9,9,2,2],
 [9,2,9,9,2,2]]

```

An invalid output example would be

```
#  # #

#  # #

#  # #

```

as the rectangles have separators in between them.

Example outputs for \\$4 \times 4\\$:

```
# ## ### ####

# ## ### ####
# ## ### ####

# ## ### ####
# ## ### ####
# ## ### ####

# ## ### ####
# ## ### ####
# ## ### ####
# ## ### ####

1 0 1 1 0 1 1 1 0 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 1 1 0 1 1 1 0 1 1 1 1
1 0 1 1 0 1 1 1 0 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 1 1 0 1 1 1 0 1 1 1 1
1 0 1 1 0 1 1 1 0 1 1 1 1
1 0 1 1 0 1 1 1 0 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 1 1 0 1 1 1 0 1 1 1 1
1 0 1 1 0 1 1 1 0 1 1 1 1
1 0 1 1 0 1 1 1 0 1 1 1 1
1 0 1 1 0 1 1 1 0 1 1 1 1

```

# Answer
> 10 votes
# , ~~56~~ ~~54~~ ~~43~~ ~~36~~ 30 bytes

```
x=!!sequence(2:scan())-1;x%o%x

```

Try it online!

Takes input one above \\$n\\$ (so returns 3x3 matrix for \\$n = 4\\$). Returns a matrix of \\$1s\\$ (foreground), and \\$0s\\$ (background) with an extra row/column of zeroes in front.

Thanks to digEmAll for -7 bytes.

# Answer
> 10 votes
# Haskell, 43 bytes

```
f n=map=<<flip(map.max)$show.(10^)=<<[1..n]

```

Try it online!

A clever approach by Ørjan Johansen outputting with 0's and 1's, generating each `10...00` part as the string representation of a power of 10.

```
111111111
101001000
111111111
101001000
101001000
111111111
101001000
101001000
101001000

```

---

**Haskell, 49 bytes**

```
f n=map=<<flip(map.max)$[0^i|x<-[1..n],i<-[0..x]]

```

Try it online!

Generates a pattern like `[1,0,1,0,0,1,0,0,0,...]`, then makes a 2D by taking the `min` of pairs. The pointfree weirdness saves 2 bytes over the more readable:

```
f n|l<-do x<-[1..n];0:(1<$[1..x])=[[a*b|a<-l]|b<-l]

```

Try it online!

# Answer
> 6 votes
# JavaScript (ES6),  ~~73 72~~  69 bytes

Returns a string made of 1's, spaces and line feeds.

```
n=>(g=s=>n-->0?g(s+`${p+=1} `):s[~n]?(+s[~n]?s:'')+`
`+g(s):'')(p='')

```

Try it online!

---

# JavaScript (ES7),  ~~87 83~~  82 bytes

*Saved 3 bytes thanks to @dzaima*

Returns a binary matrix, which is built cell by cell.

```
n=>[...Array(n*(n+3)/2)].map((_,y,a)=>a.map(h=(z,x)=>(17+8*x)**.5%1&&(z||h(1,y))))

```

Try it online!

### How?

The width \\$w\\$ of the matrix is given by:

$$w=T\_n+n-1={n+1\choose 2}+n-1=\frac{n(n + 3)}{2}-1$$

(NB: As allowed by the challenge rules, we output a matrix of width \\$w+1\\$ instead.)

Similarly, the cell located at \\$(X,Y)\\$ is empty if the following quadratic admits an integer root for either \\$k=X\\$ or \\$k=Y\\$:

$$\frac{x(x+3)}{2}-1-k=0\\ x^2+3x-2-2k=0 $$

whose determinant is:

$$\Delta=9-4(-2-2k)=17+8k$$

# Answer
> 5 votes
# MATL, ~~14~~ 10 bytes

```
:"@:Fv]g&*

```

This answer uses `1` for the blocks and `0` for the background

Try it at MATL Online

**Explanation**

```
     % Implicitly grab the input as an integer, N
     %   STACK: { 3 }
:    % Create an array from 1...N
     %   STACK: { [1, 2, 3] }
"    % For each element M in this array
  @: % Create an array from 1...M
     %   STACK (for 1st iteration): { [1] }
     %   STACK (for 2nd iteration): { [1; 0], [1, 2] }
     %   STACK (for 3rd iteration): { [1; 0; 1; 2; 0], [1, 2, 3] }
  F  % Push a zero to the stack
     %   STACK (for 1st iteration): { [1], 0 }
     %   STACK (for 2nd iteration): { [1; 0], [1, 2], 0 }
     %   STACK (for 3rd iteration): { [1; 0; 1; 2; 0], [1, 2, 3], 0 }
  v  % Vertically concatenate everything on the stack
     %   STACK (for 1st iteration): { [1; 0] }
     %   STACK (for 2nd iteration): { [1; 0; 1; 2; 0] }
     %   STACK (for 3rd iteration): { [1; 0; 1; 2; 0; 1; 2; 3; 0] }
]
g    % Convert everything to be boolean (turns all non-zeros to 1)
     %   STACK: { [1; 0; 1; 1; 0; 1; 1; 1; 0] }
&*   % Perform element-wise multiplication to expand this array out into the 2D grid
     % Implicitly display the result

```

# Answer
> 4 votes
# Jelly, 8 bytes

```
1ẋⱮj0ȧþ`

```

Try it online!

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~12~~ ~~10~~ 12 bytesSBCS

```
∘.×⍨∊,\0,⎕⍴1

```

Try it online!

**Edit:** -2 bytes from ngn. +2 bytes because the previous answers were invalid (with idea thanks to ngn and dzaima).

## Explanation

```
∘.×⍨∊,\0,⎕⍴1

         ⎕    Take input.
           ⍴1  An array of 1s of length our input. Example: 1 1 1
       0,      Prepend a 0. Example: 0 1 1 1
     ,\        Take all the prefixes and concatenate them. Example: 0  0 1  0 1 1  0 1 1 1
    ∊          Flatten the list. Example: 0 0 1 0 1 1 0 1 1 1
∘.×⍨           Turn the above list into a multiplication table of 0s and 1s
               by multiplying the list with itself.

```

The output should look like:

```
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 1 0 1 1 0 1 1 1
0 0 0 0 0 0 0 0 0 0
0 0 1 0 1 1 0 1 1 1
0 0 1 0 1 1 0 1 1 1
0 0 0 0 0 0 0 0 0 0
0 0 1 0 1 1 0 1 1 1
0 0 1 0 1 1 0 1 1 1
0 0 1 0 1 1 0 1 1 1

```

# Answer
> 4 votes
# Jelly, 7 bytes

```
‘RÄṬ|þ`

```

Try it online!

Outputs a digit matrix, using \\$0\\$ for the rectangles and \\$1\\$ for the padding between them. The TIO link contains a footer which formats a digit matrix in a human-readable way by lining up the rows and columns.

## Explanation

```
‘RÄṬ|þ`
 R       Take a range from 1 to
‘          {the input} plus 1
  Ä      Cumulative sum; produces the first {input}+1 triangular numbers
   Ṭ     Produce an array with 1s at those indexes, 0s at other indexes
     þ   Create a table of {the array}
      `    with itself
    |      using bitwise OR

```

The number at cell \\$(x,y)\\$ of the resulting table will be \\$1\\$ if either \\$x\\$ or \\$y\\$ is a triangular number, or \\$0\\$ otherwise (because bitwise OR works like logical OR on 0 and 1). (We use `R`, range from 1, because Jelly uses 1-based indexing, so we don't have to worry about column 0 being incorrectly full of 0s; we have to add 1 to the input because the array produced by  stops at the largest element given in the input, so we need to draw a line on the right-hand side and the bottom.) The gaps between triangular numbers are the consecutive integers, so the rectangular blocks formed by the gaps between the lines end up as the sizes requested by the question; and the use of an OR operation (in this case, bitwise) allows the lines to cross each other correctly.

# Answer
> 4 votes
# 05AB1E, 9 bytes

Defines a program \\$f\texttt{: }\color{purple}{\texttt{Nat}} →\color{purple}{\texttt{List}}\texttt{\[}\color{purple}{\texttt{List}}\texttt{\[}\color{purple}{\texttt{Nat}}\texttt{\]\]}\\$.

### Code:

```
$L×0ýSDδ*

```

Uses the **05AB1E**-encoding. Try it online! or use the pretty-printed version.

### Explanation:

```
$              # Push the number 1 and the input ***n***
 L             # Create the list [1, 2, 3, ..., ***n***]
  ×            # Vectorized string multiplication: 1 × [1, 2, 3, ..., ***n***]
                 This would result in ["1", "11", "111", ..., "1" × ***n***]
   0ý          # Join the resulting list with '0', resulting in "10110111011110111110..."
     S         # Split into single digits: [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, ...]
      Dδ*      # Multiplication table with itself

```

# Answer
> 4 votes
# C# (Visual C# Interactive Compiler), ~~96~~ 95 bytes

-1 byte thanks to Embodiment of Ignorance

```
n=>{var l="";for(;n>0;)l=new string('#',n--)+' '+l;for(;n<l.Length;)WriteLine(l[n++]>32?l:"");}

```

Try it online!

# Answer
> 3 votes
# Python 2, 67 bytes

```
s='';n=input()
while n:s='#'*n+' '+s;n-=1
for c in s:print(c>' ')*s

```

Try it online!

Prints blank lines for empty lines, which the challenge allows.

Same length (with input one above `n`):

```
r=range(input())
for n in r:print(' '.join(i*'#'for i in r)+'\n')*n

```

Try it online!

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

```
a#&/@(a=Flatten@Array[{0,1~Table~#}&,#])&

```

Try it online!

# Answer
> 3 votes
# Charcoal, 18 bytes

```
≔⪫ＥＮ×#⊕ι θＥθ⭆θ⌊⟦ιλ

```

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

```
   Ｎ                Input number
  Ｅ                 Map over implicit range
       ι            Current value
      ⊕             Incremented
    ×               Repetitions of
     #              Literal `#`
 ⪫                  Join with spaces
≔        θ          Assign to variable
           θ        Retrieve variable
          Ｅ         Map over characters
             θ      Retrieve variable
            ⭆      Replace characters with
              ⌊     Minimum of
               ⟦    List of
                ι   Row character
                 λ  Column character
                    Implicitly print each row on its own line

```

# Answer
> 3 votes
# Mouse-2002, 79 bytes

Abusing Mouse's macros to repeat functionality.

```
?1+n:#P,n,j,k,b#P,j,y,k,#P,n,i,' ,#P,i,x,35;;;;$P0 2%:(1%.2%.-^4%3%!'2%.1+2%:)@

```

Try it online!

# Answer
> 3 votes
# Brain-Flak, 170 bytes

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

```

Try it online!

# Answer
> 3 votes
# PowerShell, ~~42~~ 40 bytes

-2 bytes thanks to mazzy.

```
($r=1.."$args")|%{"$($r|%{'#'*$_})
"*$_}

```

Try it online!

# Answer
> 3 votes
# C# (.NET Core), ~~208~~ 155 bytes

```
class M{static void Main(string[]a){int i=int.Parse(a[0]);var l="";for(;i>0;)l=new string('#',i--)+' '+l;for(;;)System.Console.WriteLine(l[i++]>32?l:"");}}

```

Try it online!

A much revised version thanks to various helpful people (see the comments).

# Answer
> 3 votes
# Java 11, 109 bytes

```
n->{var l="";for(;n>0;)l="x".repeat(n--)+" "+l;for(;n<l.length();)System.out.println(l.charAt(n++)>32?l:"");}

```

Port of *@ASCII-only*'s C# .NET answer.

Try it online.

```
n->{                       // Method with integer parameter and no return-type
  var l="";                //  Line-String, starting empty
  for(;n>0;)               //  Loop until `n` is 0:
    l=...+l;               //   Prepend to `l`:
       "x".repeat(n--)+" " //    Repeat "x" `n` amount of times, appended with a space
                           //    And decrease `n` by 1 afterwards with `n--`
    for(;n<l.length();)    //   Inner loop as long as `n` is smaller than the length of `l`:
      System.out.println(  //    Print with trailing newline:
        l.charAt(n++)>32?  //     If the `n`'th character of the line-String is NOT a space:
                           //     And increase `n` by 1 afterwards with `n++`
         l                 //      Print the line-String
        :                  //     Else:
         "");}             //      Print nothing (so only the newlines)

```

# Answer
> 2 votes
# APL+WIN, 29 bytes

```
m/⍉(m←¯1↓∊(⍳n),¨¯1)/(n,n←⎕)⍴1

```

Explanation:

```
(n,n←⎕)⍴1 prompt for integer n and create a nxn matrix of 1s

(m←¯1↓∊(⍳n) replicate the columns by 1,2,.....n and insert 0s between each replication

m/⍉ repeat replication and 0 insertion for the rows from above

```

Example:

```
⎕:
3
1 0 1 1 0 1 1 1
0 0 0 0 0 0 0 0
1 0 1 1 0 1 1 1
1 0 1 1 0 1 1 1
0 0 0 0 0 0 0 0
1 0 1 1 0 1 1 1
1 0 1 1 0 1 1 1
1 0 1 1 0 1 1 1

```

# Answer
> 2 votes
# , 17 bytes

```
[:*/~2=/\[:I.2+i.

```

Try it online!

# Answer
> 2 votes
# Perl 6, ~~35~~ 33 bytes

```
{((\*Xx$_+1)~"
"Xx$_+1)>>.say}o^*

```

Try it online!

Anonymous Callable that takes a number and prints the multiplication table with `*`s with a trailing newline.

### Explanation:

```
{                             }o^* # Change the input to the range 0..n-1
  (\*Xx$_+1)    # Cross string multiply '*' by all of range 1..n
                # This creates the string "* ** *** ****" etc.
            ~"\n"                 # Append a newline
                 Xx$_+1           # Cross string multiply again
 (                     )>>.say    # And print all the lines

```

# Answer
> 2 votes
# Ruby, 55 bytes

```
->n{(s=(1..n).map{|x|?#*x}*' ').chars.map{|c|c<?!?c:s}}

```

Try it online!

### How?

First, create the first line, then iterate through its chars. Print the whole line if the character is '#', otherwise print the single character (which is a space)

# Answer
> 1 votes
## Haskell, ~~69~~ 68 bytes

```
(a#b)0=[]
(a#b)n=(a#b)(n-1)++b:(a<$[1..n])
f n=((1#0)n#(0<$(1#0)n))n

```

Returns a matrix of numbers.

Try it online!

Variants of `f` with the same byte count:

```
f n=((#)<*>(0<$)$(1#0)n)n
f n|l<-(1#0)n=(l#(0<$l))n

```

# Answer
> 1 votes
# Stax, 7 bytes

```
é╫▐§╘←╘

```

Run and debug it

The chosen character is backtick. (How do you code format that in markdown?)

That means `a` and `b` are considered extraneous whitespace.

# Answer
> 1 votes
# Ink, ~~151~~ ~~152~~ 151 bytes

```
VAR k=0
=t(n)
~k=n
-(u)
~n--
{n+1:->s(k-n)->u}->->
=r(c)
->g(c)->
{k-c:<>->r(c+1)}->->
=g(n)
{n>1:@<>->g(n-1)}@->->
=s(n)
{n:
->r(1)->
->s(n-1)
}
.->->

```

Try it online!

Good thing the rules allow excess characters.

Edit: +1: Fixed spacing. Also, display using @ (which doesn't need escaping) instead of # (which does)

Edit: -1: Apparently that fix also meant I no longer needed a trailing period to force a newline on the non-empty lines. Neat.

# Answer
> 1 votes
## C++, ~~170~~ 156 bytes

Thanks to dzaima

```
#include<string>
using v=std::string;v f(int a){v s;for(int i=1;i<=a;++i,s+='\n')for(int k=0;k<i;++k,s+='\n')for(int j=1;j<=a;++j)s+=v(j,'#')+' ';return s;}

```

# Answer
> 1 votes
# MathGolf, 20 bytes

```
╒ÉÄ10;]h\■mÆε*╣¡§y╠n

```

Try it online!

MathGolf really needs to get some more functionality for splitting lists and creating 2D lists.

## Explanation

```
╒                      range(1,n+1)
 É                     start block of length 3
  Ä                    start block of length 1
   1                   push 1
    0                  push 0
     ;                 discard TOS
      ]                end array / wrap stack in array
                       the stack now contains the list [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, ...]
       h               length of array/string without popping (used for splitting string)
        \              swap top elements
         ■             cartesian product with itself for lists, next collatz item for numbers
          m            explicit map
           Æ           start block of length 5
            ε*         reduce list by multiplication (logical AND)
              ╣¡       push the string " #"
                §      get character at index 0 or 1 based on logical AND value
                       block ends here, stack is now ['#',' ','#','#',' ','#',...]
                 y     join array without separator to string
                  ╠    pop a, b, push b/a (divides the string using the length of a single line)
                   n   join array of strings with newlines

```

# Answer
> 1 votes
# Julia 1.0, 40 bytes

```
\ =join
!N=('#'.^(r=1:N)\' '*'\n').^r\'\n'

```

Try it online!

outputs a string with `#` and spaces:

```
julia> print(!3)
# ## ###

# ## ###
# ## ###

# ## ###
# ## ###
# ## ###

```

20 bytes with less strict output format, by returning a matrix of matrices: `!N=ones.(1:N,(1:N)')`

# Answer
> 0 votes
# Python 3, 88 83 bytes

-5 bytes from Jo King

```
n,l=range(int(input())),''
for i in n:l+='#'*-~i+' '
for j in n:print((l+'\n')*-~j)

```

Try it online!

# Answer
> 0 votes
# SmileBASIC, ~~83~~ 77 bytes

Graphical output. Input is `N-1`

```
INPUT N
FOR J=0TO N
X=0FOR I=0TO N
GFILL X,Y,X+I,Y+J
X=X+I+2NEXT
Y=Y+J+2NEXT

```

# Answer
> 0 votes
# C (gcc), ~~108~~ 104 bytes

-4 bytes thanks to ceilingcat

```
f(n,j){char*s,u[n*n],*t=s=u,i=0;for(;i++<n;*s++=32)for(j=i;j--;)*s++=35;for(s=t;*t;)puts(*t++>32?s:"");}

```

Try it online!

# Answer
> 0 votes
## Perl 6, 63 bytes

```
{(1..$_).map(((1..$_).map("#"x*).join(" ")~"\n")x*).join("\n")}

```

# Answer
> 0 votes
# Pyth, 19 bytes

```
VSQjb*]jdm*\#dSQNpb

```

Try it online!

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


title: What was my Wordle play?

text:
# Question
Title: What was my Wordle play?
## Task

Given a winning Wordle play results (clues), the target ("secret") word and a list of words, output a possible sequence of words leading to such results.

The words in the list will be distinct and so should be the output.

You may assume that for given inputs a solution exists. If there is more than one, you may output any or all of them.

Take your input in any convenient manner: including string of coloured rectangles, string of 3 distinct characters of your choice, array of 3 distinct values, etc. You may output list of words first-to-last or reversed.

You can omit the last row of clues as it will be all "green" or take the target word as the last row if you like. The target word is also optional in the output.

This is , so shortest answer wins.

## Example

```
input =>
clues:  00100
        00000
        11100
        01210
        22222
or
        ⬜⬜⬜⬜
        ⬜⬜⬜⬜⬜
        ⬜⬜
        ⬜⬜

target: CGOLF
words:  ABCDE,CGOLF,EDCBA,LOGOS,VLOGS,WORDS,XYZAB

output =>
ABCDE,XYZAB,LOGOS,VLOGS,CGOLF

```

## How does Wordle exactly work?

*Taken from @pxeger's related challenge.*

In Wordle, you try to guess a secret 5-letter word, and some letters in your guess are highlighted to give you hints.

If you guess a letter which matches the letter in the same position in the secret word, the letter will be highlighted green. For example, if the secret word is `LEMON` and you guess `BEACH`, then the `E` will be highlighted green.

If you guess a letter which is present in the secret word, but not in the correct corresponding position, it will be highlighted yellow.

If a letter appears more times in the guess than it does in the secret word, only upto as many occur in the secret may be highlighted. If any of the occurrences are in the same place, they should be preferentially highlighted green, leaving earlier letters unhighlighted if necessary.

For example, with the secret `LEMON` and the guess `SCOOP`, the second `O` will be green, because it is in the right place, but the first `O` will be unhighlighted, because there is only one `O` in the secret, and one `O` has already been highlighted.

Any of the remaining letters in the secret may be highlighted yellow if they match, as long as the right number are highlighted in total. For example, with the secret `LEMON` and the guess `GOOSE`, only one of the `O`s should be highlighted; it does not matter which.

## Test cases

Use `ABCDE` as target and `ABCDE,DECAB,EDCBA,QWERT` as words:

```
clues: 22222
output: ABCDE

clues: 11211
       11211
       22222
output: DECAB,EDCBA,ABCDE or EDCBA,DECAB,ABCDE

clues: 00100
       22222
output: QWERT,ABCDE

```

Use `GOOSE` as target and `GOOSE,LEMON,SCOOP` as words:

```
clues: 01010
       10210
       22222
output: LEMON,SCOOP,GOOSE

```

# Answer
> 3 votes
# Python 3, 155 bytes

Based on my submission for the related challenge, uses the same color encoding: `-1` for *Green*, `0` for *Yellow* and `1` for not highlighted.

```
def f(g,s,w):
 for l in g:k=[k for k in w if(c:='')or[-(a==b)or(c:=c+b).count(b)>sum(y!=x==b for x,y in zip(s,k))for a,b in zip(s,k)]==l][0];yield k;w-={k}

```

Try it online!

# Answer
> 2 votes
# Python 3, 164 bytes

```
f=lambda a,b,c:a and[[w]+f(a[1:],b,c-{w})for w in c for t in[[*b]]if[not a or a in t and t.remove(a)for a in[a[a==b:]or t.remove(a)for a,b in[*zip(w,t)]]]==a[0]][0]

```

Try it online!

Based on my answer to Highlight a Wordle guess

# Answer
> 1 votes
# Python3, 195 bytes:

```
S=set
f=lambda b,t,w,p=[]:f(b[1:],t,w,p+[i for i in S(w)-S(p)if sum(j==k for j,k in zip(i,t))==(J:=(F:=b[0].count)(2))and(sum(l in t for l in i)-J==F(1)or len(S(i)&S(t))-J==F(1))][:1])if b else p

```

Try it online!

---
Tags: code-golf, string, array, open-ended-function
---