title: Lonely Multiplication

text:
# Question
Title: Lonely Multiplication
Based on this question from Code Review.

Given precisely three positive integers, return the product of all of the distinct inputs. If none of the inputs are distinct, return 1. That is, implement the function:

\\$ f(a,b,c) = \cases{1 & $a = b = c $ \\ a & $ b = c $ \\ b & $ a = c $ \\ c & $ a = b $ \\ a b c & otherwise } \\$

Shortest code in each language wins.

### Test cases

```
a, b, c -> f(a,b,c)
7, 7, 7 -> 1
3, 3, 5 -> 5
2, 6, 6 -> 2
3, 4, 3 -> 4
1, 2, 3 -> 6
12, 9, 16 -> 1728

```

# Answer
# 05AB1E, 3 bytes

```
¢ÏP

```

Try it online!

```
¢       # count occurences of each number
 Ï      # keep only those where the count is 1
  P     # product (1 if the list is empty)

```
> 12 votes

# Answer
# C (gcc), <sup>~~46~~ \\$\cdots\\$ ~~43~~</sup> 42 bytes

Saved 2 bytes thanks to 79037662!!!

```
f(a,b,c){a=a^b?a^c?b^c?a*b*c:a:b:b^c?c:1;}

```

Try it online!
> 11 votes

# Answer
# JavaScript (ES6), 38 bytes

```
(a,b,c)=>a-b?b-c?c-a?a*b*c:b:a:b-c?c:1

```

Try it online!

---

# JavaScript (ES6), 53 bytes

Takes input as `[a,b,c]`.

```
A=>[[a,b,c]=A,1,a-b?a-c?a:b:c,a*b*c][new Set(A).size]

```

Try it online!

### Commented

```
A =>                // A[] = input
  [                 // lookup table:
    [a, b, c] = A,  //   set size = 0 --> impossible, so use this slot
                    //   to split A[] into 3 distinct variables
    1,              //   set size = 1 --> return 1
    a - b ?         //   set size = 2 --> if a is not equal to b:
      a - c ?       //     if a is not equal to c:
        a           //       return a
      :             //     else:
        b           //       return b
    :               //   else:
      c,            //     return c
    a * b * c       //   set size = 3 --> return a * b * c
  ]                 //
  [new Set(A).size] // index into lookup table = size of the set

```
> 10 votes

# Answer
# , 10 bytes

```
*/@-.}./.~

```

Try it online!

```
     }./.~  group by value and remove one from each group
   -.       set subtract from input
*/          product

```
> 7 votes

# Answer
# , ~~40~~ 37 bytes

-3 bytes by taking input with `scan()`.

```
prod(unique(x<-scan())^2,1/x)^!!sd(x)

```

Try it online!

`sd(x)` computes the standard deviation (which is 0 iff all entries are equal), so `!!sd(x)` is `TRUE` if some entries are different, and `FALSE` if all are equal.

* if all entries are different, then `unique(x)==x`, so we are down to `prod(x)^1`
* if 2 entries are equal, then the corresponding value gets cancelled out between `unique(x)^2` and `1/x`, so we are left with the sole "lonely" value
* if all 3 entries are equal, then we have `(...)^0` which is 1.

This is shorter than anything I could come up with based on `table`, `tabulate`, `duplicated` or `rle(sort())`.
> 6 votes

# Answer
# APL (Dyalog), 10 bytes

*Thanks to Adám and Bubbler in chat for helping golf this*

```
×/∪*1=⊢∘≢⌸

```

Try it online!

### Explanation:

```
×/             ⍝ Reduce by multiplication
  ∪            ⍝ The unique values of the input
   *           ⍝ To the power of
    1=         ⍝ Whether one is equal to
        ≢      ⍝ The length of
      ⊢∘ ⌸     ⍝ The indexes of each unique element

```
> 6 votes

# Answer
# Python, 48 bytes

```
lambda l:eval("(%sin[%s,%s]or %s)*"*3%(l*4)+"1")

```

Try it online!

Takes in a tuple. The idea is similar to an answer in the Code Review question, which can be golfed to:

**51 bytes**

```
lambda a,b,c:a**(b!=a!=c)*b**(c!=b!=a)*c**(a!=c!=b)

```

Try it online!

Each element is included in the product if it's different from the other two, with the power setting to a harmless `x**0 == 1` otherwise. We want to avoid writing the three similar terms being multiplied. Python unfortunately doesn't have a built-in list product without imports. So, we turn to `eval` shenanigans.

We use a longer expression that use logical short-circuiting:

**60 bytes**

```
lambda a,b,c:(a in[b,c]or a)*(b in[c,a]or b)*(c in[a,b]or c)

```

Try it online!

In this expression, the variable names cycle through `a,b,c` in that order four times. So, by tripling the format string `"(%sin[%s,%s]or %s)*"` and plugging in the input tuple repeated four times, we get the desired expression. We just need to append a `"1"` to deal with the trailing multiplication.
> 6 votes

# Answer
# PHP, ~~72~~ ~~71~~ bytes

```
sort($argv);[,$a,$b,$c]=$argv;echo$a-$b?$b-$c?$a*$b*$c:$a:($b-$c?$c:1);

```

Try it online!

~~Might be shorter without the `sort` but nested ternary operator precedence blows my mind.~~

-1 byte thanks to @640KB

# PHP, 66 bytes

```
fn($a,$b,$c)=>$a-$c?$a-$b?$b-$c?$a*$b*$c:$a:$b==$c?:$c:$b==$c?:$b;

```

Try it online!

Kudos to @640KB for taming the ternary operator beast!
> 4 votes

# Answer
# Jelly,  ~~7~~  6 bytes

```
ḟœ-Q$P

```

**Try it online!**

### How?

```
ḟœ-Q$P - list, L
    $  - last two links as a monad:
   Q   -   de-duplicate (L)
 œ-    -   (L) multi-set difference (that)
ḟ      - (L) filter discard if in (that)
     P - product

```

---

**7**s:

```
ĠṖÐḟị⁸P
ḟṖƙ`F$P

```
> 4 votes

# Answer
# Excel (Version 1911), ~~80 Bytes~~, 42 Bytes

```
=PRODUCT(FILTER(A1#,COUNTIF(A1#,A1#)=1,1))

```

Input entered as a static column array (e.g. `={1;2;3}`) in cell `A1`

* Saved 38 bytes due to inspiration from Grimmy's 05AB1E solution.
> 4 votes

# Answer
# Haskell, 37 bytes

```
f l=product[x|x<-l,filter(==x)l==[x]]

```

Try it online!

Pretty straightforward -- filter for elements that appear only once and take the product.
> 4 votes

# Answer
# , 36 bytes

```
prod((a=rle(sort(scan())))$v[a$l<2])

```

Try it online!

`rle()` shows its worth again. Feels like some parentheses could be golfed out somehow.

The fact that `prod()` of an empty numeric evaluates to 1 is the only reason this is efficient.
> 4 votes

# Answer
# Python 3, ~~63~~ ~~62~~ 61bytes

```
lambda l:prod(x for x in l if l.count(x)<2)
from math import*

```

You can try it online!

Thanks @FryAmTheEggman for saving me 1 byte.
> 3 votes

# Answer
# GolfScript, 31 bytes

```
...{{*}*}:m;m\.|m/-m\.|,1=\1\if

```

This was... a lot more difficult than I thought it would be. Can be optimized. So much so, that I don't really want to give this much of an explanation.

Here's the process:

Take your input array and make 3 more copies of it. Make a function m, which multiplies the elements in an array together. Do that to the first array, then eliminate dupes from a second (keeping one of each). Perform m on it, then divide it from the first number. You should have the duplicate number (if there's only one pair dupe). Remove it rom your array, then return the last number. If the "suspected dupe" is 1, then just multiply again and output. If, when you remove all of the "suspected dupe"s, you're left with an array of size 1, just output 1 instead.

This was incredibly and probably needlessly complicated, but I couldn't find any good GolfScript shortcuts besides the multiplication bit. PITA.

Try it online, I guess
> 3 votes

# Answer
# PowerShell, 44 bytes

```
,1+($args|group|? C* -eq 1|% N*)-join'*'|iex

```

Try it online!

where `|? C* -eq 1` means `|? Count -eq 1` and `|% N*` means `|% Name`.

---

# PowerShell, 45 bytes

```
$p=1;$args|group|? C* -eq 1|%{$p*=$_.Name};$p

```

Try it online!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 31 bytes

```
#&@@Times@@Tally@#~Cases~{_,1}&

```

Try it online!
> 3 votes

# Answer
# Perl 6, 27 bytes

```
{[*] .Bag.grep(0=>1)>>.key}

```

Try it online!

(Using a `Pair` as matcher compares only values and ignores the key.)
> 3 votes

# Answer
# PHP, ~~92~~ 79 bytes

```
fn($a)=>array_product(array_keys(array_intersect(array_count_values($a),[1])));

```

Try it online!

This isn't going to win for brevity, but just thought I'd try it entirely using chained PHP array functions.

Now using @Guillermo Phillips's suggestion for PHP 7.4 arrow function syntax to save 13 bytes.

# PHP, 66 bytes

```
fn($a,$b,$c)=>$a-$c?$a-$b?$b-$c?$a*$b*$c:$a:$b==$c?:$c:$b==$c?:$b;

```

Try it online!

And another crazy ternary version inspired by @Guillermo Phillips's answer!
> 3 votes

# Answer
# Burlesque, 24 bytes

```
psJ{{1j}qfcqpd}M-jNBL[!!

```

Try it online!

```
ps     # Parse to list
J      # Duplicate
{
 {1j}  # Push 1 & swap
 qfc   # Find least common element
 qpd   # Product
}M-    # Create array applying each function to make each element
       # {{Original list}, 1, least common, product}
jNB    # Remove duplicates from original list
L[     # Find length
!!     # Select that element from the array
       # (zero indexed, hence the push swap to fill zero)

```

# Burlesque, 31 bytes

```
psJU_qpd{f:{-]1==}fe[~}IEisq1if

```

Try it online!

Can probably be golfed further.

```
ps      # Parse to array
JU_     # (Non-destructive) is each element unique?
qpd     # boxed product
{
 f:     # Frequency (returns {{count val} ...})
 {
  -]1== # Count == 1
 }
 fe     # Find element where
 [~     # Take the tail
}
IE      # If unique then product, else find single
is      # Is an error (i.e. single not found)
q1      # boxed 1
if      # If error, push 1

```
> 2 votes

# Answer
# Mathematica, 40 bytes

```
f[l_]:=Times@@(If[Count[l,#]<2,#,1]&/@l)

```

You can try it online!
> 2 votes

# Answer
# Bash \+ GNU utilities, 26

```
sort|uniq -u|dc -e1?*?*?*p

```

The 3 input integers are each given on their own line.

In the case of non-distinct inputs, `dc` warnings are printed to stderr. These may be ignored.

`uniq -u` does most of the heavy lifting here. With the `-u` option, only non-duplicated lines are returned. uniq requires its input to be `sort`ed.

The `dc` expression pushes 1 to the stack, then reads up to 3 integers, multiplying each in turn, then `p`rinting the output. If uniq pipes less than 3 integers to dc, then the surplus `?` will not add to the stack and the following `*` will spit out a warning because * needs to pop 2 operands from the stack. But these are just warnings, dc continues execution until it prints the final product.

Try it online!
> 2 votes

# Answer
# Python 2, 52 bytes

```
l=input();r=1
for x in l:r*=1%l.count(x)or x
print r

```

Try it online!
> 2 votes

# Answer
# Ruby, 38 bytes

```
->*a{r=1;a.map{|w|(a-[w])[1]&&r*=w};r}

```

Try it online!
> 2 votes

# Answer
# C#, 60 bytes

```
int f(int a,int b,int c)=>a==b?a==c?1:c:a==c?b:b==c?a:a*b*c;

```
> 2 votes

# Answer
# TI BASIC, 45 Bytes

```
Prompt A,B,C
ABC
If A=B
C
If A=C
B
If B=C
A
If A=B and A=C
1
Ans

```
> 2 votes

# Answer
# Brachylog, 6 bytes

```
≡ᵍ~gˢ×

```

Try it online!

```
 ᵍ        Group elements by
≡         value.
    ˢ     For each group,
  ~g      if it is a singleton list, extract its only element,
    ˢ     else discard it.
     ×    Take the product.

```
> 2 votes

# Answer
# Factor \+ `sets.extras math.unicode`, 20 bytes

```
[ non-repeating Π ]

```

Try it online!

Factor has a word `non-repeating` that gives you every element of a sequence that doesn't repeat. Turns out the answer to this question is just taking the product of this.
> 2 votes

# Answer
# MMIX, 48 bytes (12 instrs)

```
foo CMP $255,$0,$1
    CMP $3,$1,$2
    BZ  $255,0F     // if(a == b) goto ab
    BZ  $3,1F       // if(b == c) goto bc
    CMP $255,$0,$2
    BZ  $255,2F     // if(a == c) goto ac
    MUL $0,$0,$1    // a *= b
    MUL $0,$0,$2    // a *= c
1H  POP 1,0         // bc: return a
0H  CSZ $2,$3,1     // ab: if(b == c) c = 1
    POP 3,0         // return c
2H  POP 2,0         // ac: return b

```
> 2 votes

# Answer
# Thunno 2, 4 bytes

```
cḅịp

```

Try it online!

#### Explanation

```
cḅịp  # Implicit input
c     # Counts of each number
  ị   # Only keep items of the input
 ḅ    # where the count equals 1
   p  # Product of this list

```
> 2 votes

# Answer
# Perl 5 `-MList::Util=product -apl`, ~~45~~ 44 bytes

*@FryAmTheEggman saves a byte*

```
$_=product(grep{$t=$_;2>grep$t==$_,@F}@F)||1

```

Try it online!
> 1 votes

# Answer
# Japt, ~~9~~ 6 bytes

```
ü l1 ×

```

Try it
> 1 votes

# Answer
# PowerShell, 97 bytes

```
param($n)$a,$b,$c=$n|group;(($n-join'*'|iex),(($a,$b|?{$_.count-eq1}).name,1)[$a.count-eq3])[!$c]

```

Try it online!

Not terribly impressive, but given that PowerShell doesn't have a ternary operator like JavaScript, nor the same `for` structure as Python, I don't think this is too bad.

We take input `$n` as an array, then feed that into `Group-Object`, which stores the (potentially) three values into `$a, $b, $c`. Then we use array-indexing as a pseudo-ternary. We work "backwards" on the function definition given in the challenge, starting from the bottom. If we have a `$c`, then we have three unique values, so we `-join` `$n` with `*` and `iex` it (similar to `eval`). Otherwise, we have at least a duplicate, so we re-index whether `$a`'s `.count` is `-eq`ual to `3`. If it is, then all three values are the same, and we output `1`. Otherwise, we pull out the lonely value (i.e., its `.count` is `-eq`ual to `1`) and output its `.name`. In any case, the result is left on the pipeline and output is implicit.
> 1 votes

# Answer
# Charcoal, 11 bytes

```
ＩΠＥθ⎇⊖№θι¹ι

```

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

```
   θ        Input array
  Ｅ         Map over elements
      №     Count of
        ι   Current element
       θ    In input array
     ⊖      Decremented
    ⎇       Ternary
          ι If count was 1 then original element
         ¹  Otherwise literal 1
 Π          Take the product
Ｉ           Cast to string for implicit print

```

I found other ways of formulating the condition, but they were all the same length. Alternate approach, also 11 bytes:

```
ＩΠ∨Φθ⁼¹№θι¹

```

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

```
    θ       Input array
   Φ        Filter where
       №    Count of
         ι  Current element
        θ   In input array
     ⁼      Equals
      ¹     Literal 1
  ∨         Or if list is now empty
          ¹ Then literal 1
 Π          Take the product
Ｉ           Cast to string for implicit print

```
> 1 votes

# Answer
# Retina, 51 bytes

```
N`\d+
\b(\d+)(,\1)+\b

~["^.*¶$.("|""]'_L$`\d+
$&$*

```

Try it online! Link includes test cases. Explanation:

```
N`\d+

```

Sort the input list.

```
\b(\d+)(,\1)+\b

```

Delete all duplicated numbers.

```
L`\d+

```

List all the remaining numbers, discarding any commas.

```
$`
$&$*

```

Suffix each number with a `*`.

```
|""`

```

Don't separate the numbers.

```
["^.*¶$.("`

```

Prefix the result with `^.*` on its own line and `$.(` on the same line as the numbers.

```
]'_`

```

Suffix the result with a `_`.

```
~`

```

Evaluate the result on the previous contents of the buffer. This results in one of three evaluations:

1. If all three numbers were identical, it evaluates this:

```
^.*
$.(_

```
2. If two numbers were identical, it evaluates this:

```
^.*
$.(5*_

```
3. If the numbers were distinct, it evaluates this:

```
^.*
$.(1*2*3*_

```

This takes the string `_`, and repeats it by the remaining numbers in turn, and then takes the length of the result, which is exactly the same as the product of the numbers, or 1 if there were none left.
> 1 votes

# Answer
# Zsh, 39 bytes

```
(){i=1
for n;((i*=${(M)#@:#$n}>1?1:n))}

```

Try it online!

For the first time, I can say that a zsh math function actually won out over a normal program! I knew there was potential when I got a tie a while back, here's the relevant meta post if you want to know more about them.

The meat of this is the loop where we test for distinctness:

```
${(M)#@:#$n}
${   #     }    # count
${(M)      }    # matches
${    @:#  }    # on the positional parameters.
${       $n}    # against $n
            >1  # more than 1 (not distinct)

```

We use a ternary to decide to multiply by 1 or n.
> 1 votes

# Answer
# Whitespace, 178 bytes

```
[S S S N
_Push_0][S N
S _Dupe_0][T    N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input_A][S N
S _Dupe_input_A][S N
S _Dupe_input_A][T  N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input_B][S N
S _Dupe_input_B][S N
S _Dupe_input_B][T  N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input_C][S N
S _Dupe_input_C][S T    S S T   S N
_Copy_0-based_2nd_input_B][T    S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_C==B][S N
S _Dupe_input_C][S T    S S T   T   N
_Copy_0-based_3rd_input_A][T    S S T   _Subtract][N
T   S T N
_If_0_Jump_to_Label_C!=B&&C==A][S T S S T   S N
_Push_0-based_2nd_input_A][S T  S S T   S N
_Push_0-based_2nd_input_B][T    S S T   _Subtract][N
T   S N
_If_0_Jump_to_Label_PRINT][T    S S N
_Multiply][T    S S N
_Multiply][N
S N
N
_Jump_to_Label_PRINT][N
S S T   N
_Create_Label_C!=B&&C==A][S N
N
_Discard_input_C][N
S N
N
_Jump_to_Label_PRINT][N
S S S N
_Create_Label_C==B][S N
S _Dupe_input_C][S T    S S T   T   N
_Copy_0-based_3rd_input_A][T    S S T   _Subtract][N
T   S T T   N
_If_0_Jump_to_Label_C==B&&C==A][S N
N
_Discard_input_C][S N
N
_Discard_input_B][N
S N
N
_Jump_to_Label_PRINT][N
S S T   T   N
_Create_Label_C==B&&C==A][S S S T   N
_Push_1][N
S S N
_Create_Label_PRINT][T  N
S T _Print_as_integer]

```

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

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

**Whitespace work-flow:**

```
Integer A = STDIN as integer
Integer B = STDIN as integer
Integer C = STDIN as integer                   (the stack now contains [A,B,C])
If(C==B): Jump to Label C==B
If(C==A): Jump to Label C!=B&&C==A
If(A==B): Jump to Label PRINT                  (top of the stack is here C)
Multiply top two
Multiply top two
Jump to Label PRINT                            (top of the stack is here A*B*C)

Label C!=B&&C==A:
  Discard top (C)
  Jump to Label PRINT                          (top of the stack is here B)
Label C==B:
  If(C==A): Jump to Label C==B&&C==A
  Discard top (C)
  Discard top (B)
  Jump to Label PRINT                          (top of the stack is here A)

Label C==B&C==A
  Push 1                                       (top of the stack is here 1)
Label PRINT
  Print top of the stack as integer to STDOUT

```

Since the inputs are guaranteed to be positive, it uses heap-address `0` for input `A`; heap-address `A` for input `B`; and heap-address `B` for input `C`.
> 1 votes

# Answer
# Kotlin, ~~52 51~~ 43 bytes

```
filter{z->count{z==it}<2}.fold(1){s,c->s*c}

```

Try it online!
> 1 votes

# Answer
# Stax, 11 bytes

```
äùóq◘0Jg•UÜ

```

Run and debug it

This one works for all testcases, and shorter! Uses Unrelated String's idea.

## Explanation

```
o{}/{Dz_?m$:*
o             order the array
 {}/          group equal adjacent values
    {    m    map to the following:
        ?     if:
     D        deleting the first element
              makes the array empty, then:
       _       push it again
      z        otherwise push an empty list
          $   flatten the result
           :* take the product

```
> 1 votes

# Answer
# Scala, 39 bytes

```
f=>f.filter(i=>f.count(_==i)<2).product

```

Try it online!
> 1 votes

# Answer
# C (clang), ~~199~~ 100 bytes

```
a,b;main(c){scanf("%i%i%i",&a,&b,&c);printf("%i",a-b|b-c?a-b|b==c?b-c|c==a?a-c|c==b?a*b*c:b:a:c:1);}

```

Try it online!

Don't know C? Here's how it works. We initialize 3 integers, give them input, then proceeds to multiple if-statements to check whether or not they're equal.

Thanks to ceilingcat for golfing a **whopping** 99 bytes.
> 1 votes

# Answer
# Vyxal, 10 bytes

```
Ċ't1=;f1JΠ

```

Try it Online!
> 1 votes

# Answer
## Pascal, 118 Bytes

This `function` uses the set-member-iteration statement (`for … in … do`) and the symmetric difference operator `><`. Therefore it needs a processor at least supporting features of ISO standard 10206 “Extended Pascal” (level 0).

```
function f(a,b,c:integer):integer;var r:integer;begin r:=1;if[a,b,c]<>[a]then for a in[a]><[b]><[c]do r:=r*a;f:=r end;

```

Ungolfed:

```
function f(a, b, c: integer): integer;
var
    result: integer;
begin
    { `result` needs to be initialized for the `for`-loop below. }
    result := 1;

    { If not sidelengths of an equilateral triangle: }
    if [a, b, c] <> [a] then
    begin
        { Symmetric difference of sets. }
        for a in [a] >< [b] >< [c] do
        begin
            result := result * a;
        end;
        { NB: The iterator variable `a` retains its original value
          unless you escape the `for`-statement with a `goto`. }
    end;

    { In Pascal there must be _exactly_ one assignment
      to the implicitly declared variable bearing the function’s name.
      Hence we cannot simply re-use `f` as the `result` variable. }
    f := result;
end;

```
> 1 votes

# Answer
# Racket, 74 bytes

```
λ(n)(apply *(map(λ(x)(if(=(length x)1)(car x)1))(group-by identity n))))

```

Try it online!
> 0 votes

# Answer
# Excel, 60 bytes

```
=IF(A1=B1,IF(A1=C1,1,C1),IF(B1=C1,A1,IF(A1=C1,B1,A1*B1*C1)))

```

Does not use features like `FILTER`, only available to Office Insiders.
> 0 votes

# Answer
## SQL, ~~245~~ 155 bytes

```
 DECLARE @a INT=2,@b INT=4,@c INT=8;WITH v AS(SELECT x FROM(VALUES(@a),(@b),(@c))t(x) GROUP BY x HAVING COUNT(*)=1)SELECT ISNULL(EXP(SUM(LOG(x))), 1) FROM v

```

Expanded:

```
DECLARE @a INT=2,
        @b INT=4,
        @c INT=8;

WITH v
     AS (SELECT x
           FROM(VALUES(@a),
                      (@b),
                      (@c))t(x)
          GROUP BY x
         HAVING COUNT(*) = 1)
SELECT ISNULL(EXP(SUM(LOG(x))), 1)
  FROM v

```

The straightforward solution is only 150 .. but it is boring. :)

```
DECLARE @a INT=2,@b INT=4,@c INT=2;SELECT CASE WHEN @a=@b AND @a=@c THEN 1 WHEN @a=@b THEN @c WHEN @b=@c THEN @a WHEN @a=@c THEN @b ELSE @a*@b*@c END

```

```
DECLARE @a INT=2,
        @b INT=4,
        @c INT=2;

SELECT CASE
         WHEN @a = @b
              AND @a = @c THEN 1
         WHEN @a = @b THEN @c
         WHEN @b = @c THEN @a
         WHEN @a = @c THEN @b
         ELSE @a * @b * @c
       END

```
> 0 votes

# Answer
# Stax, 13 bytes

```
üΩ1↑♂Åò←3♠'W▐

```

Run and debug it
> 0 votes

# Answer
# Uiua <sup>SBCS</sup>, 7 bytes

```
/×⊚=1°⊚

```

Try it!
> 0 votes

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

```
f=(a,b,c)=>a>f||f(b,c,[a])*(a-b&&a-c?a:1)

```

Try it online!

For shorter solution Arnauld has a 38 one
> 0 votes

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


title: Tips for golfing in Uiua

text:
# Question
Title: Tips for golfing in Uiua
What general tips do you have for golfing in Uiua?

I'm looking for ideas that can be applied to code golf problems in general that are specific to Uiua. (e.g. "remove comments" would not be an answer.)

Please post one tip per answer.

# Answer
> 6 votes
# Use complex numbers

The length of a vector given by a pair of numbers can be found with `sqrt + both(pow 2)` for 7 glyphs (or more idiomatically `under both un sqrt +` for 5).

But using complex numbers, this problem can be solved in just 2 glyphs: `abs complex`.

Other problems can benefit from clever uses of complex numbers, e.g. to represent transformations.

# Answer
> 2 votes
# Use `/f` instead of `f°⊟`

If you have an array with two rows, and want to apply a `|2.1` function to its rows, use `/ reduce` instead of `°⊟ un couple`.

An example (Pad):

```
↯2_3⇡6
⊃(
  +°⊟ # 3_5_7
| /+  # also 3_5_7
)

```

# Answer
> 1 votes
# Use an SBCS (single-byte character set)

Uiua uses Unicode glyphs that would usually take up multiple bytes each. But with an SBCS, each character is represented with one byte.

Because Uiua is currently in flux, such an encoding will also have to change to fit the changes in the language. I have been updating one since the beginning of this year. Here is the link to today's revision for Uiua 0.8.0, with the new glyphs `◴◰`: http://tinyurl.com/Uiua-SBCS-Jan-18.

---
Tags: code-golf, tips
---


# Question
Title: Generate a Markdown Template for your Post
Your task is simple: Write a program (or function) that takes no input and outputs something like this:

```
## *name*, *length* bytes
    *code*

```

Where `*name*` is the name of the language you are using, `*length*` is the number of bytes in your code, and `*code*` is your program's source code. If `*code*` contains multiple lines, it have four spaces before each line.

Here's a 124-byte example implementation in Python 3:

```
s = "## Python 3, 124 bytes{2}    s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
print(s.format(s,chr(34),chr(10)))

```

The output is:

```
## Python 3, 124 bytes
    s = "## Python 3, 124 bytes{2}    s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
    print(s.format(s,chr(34),chr(10)))

```

Which in Markdown is:

> ## Python 3, 124 bytes
>
> ```
> s = "## Python 3, 124 bytes{2}    s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
> print(s.format(s,chr(34),chr(10)))
>
> ```

This is , so the shortest answer (in bytes) wins.

# Answer
> 8 votes
# RProgN 2, 28 Bytes

```
«"  %s"F"#RProgN 2, 28 Bytes"

```

# Answer
> 6 votes
# Underload, 48 bytes

```
(#Underload, 48 bytes
)(~:S(    ):S*aSaS(:^)S):^

```

# Answer
> 2 votes
## Python 2, 58 bytes

```
_='## Python 2, 58 bytes\n    _=%r;print _%%_';print _%_

```

# Answer
> 1 votes
## reticular, 58 bytes

```
"'34'c: 4*91+c:s:e:t:y:b: 85: :,:r:a:l:u:c:i:t:e:r: :#dqO;

```

Try it online!

Explanation: `:c` pushes the single-char string `c`. This builds the string "## reticular, 58 bytes", backwards character by character, reverses the stack, and `O`utputs everything, including the string captured by the initial quote.

# Answer
> 1 votes
## CJam, 33 bytes

```
{"## CJam, 33 bytes"N@S4*\"_~"}_~

```

Works a lot like the Underload answer.

Stack trace (`N` represents `\n`)

```
{"## CJam, 33 bytes"N@S4*\"_~"}
{"## CJam, 33 bytes"N@S4*\"_~"} {"## CJam, 33 bytes"N@S4*\"_~"}
{"## CJam, 33 bytes"N@S4*\"_~"} "## CJam, 33 bytes"
{"## CJam, 33 bytes"N@S4*\"_~"} "## CJam, 33 bytes" N
"## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"}
"## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"} " "
"## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"} " " 4
"## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"} "    "
"## CJam, 33 bytes" N "    " {"## CJam, 33 bytes"N@S4*\"_~"}
"## CJam, 33 bytes" N "    " {"## CJam, 33 bytes"N@S4*\"_~"} "_~"
<implicit output>

```

# Answer
> 1 votes
# JS, ~~50~~ ~~49~~ ~~27~~ 30 bytes

```
f=_=>`#JS, 30 bytes\n    f=`+f

```

---

## Try It

```
f=_=>`#JS, 30 bytes\n    f=`+f
console.log(f())
```

# Answer
> 1 votes
# V, 25 bytes

```
ñi#V, 25 bytes<esc>o´ Ñ<esc>~"qpx

```

---

(This is not counted in the generated markdown, because I like providing explanations for my code :P)

Here is a hexdump, since the source code contains unprintable/non-ASCII characters:

```
00000000: f169 2356 2c20 3235 2062 7974 6573 1b6f  .i#V, 25 bytes.o
00000010: b420 d11b 7e22 7170 78                   . ..~"qpx

```

This answer is just a trivial modification of the standard extensible V quine.

Explanation:

```
ñ                                   " Run the following code one time, storing it in
                                    " register 'q'
 i                                  "   Enter insert mode
  #V, 25 bytes<esc>                 "   And insert the header
                   o                "   Open up a newline, and enter insert mode again
                    ´ Ñ             "   Enter four spaces, then a 'Ñ' character.
                                    "   (The reason we insert it uppercase, is because
                                    "   lowercase would end the loop now)
                       <esc>        "   Return to normal mode
                            ~       "   Toggle the case of the char under the cursor ('Ñ')
                             "qp    "   Paste the contents of register 'q' (this is the
                                    "   same as the entire program minus the initial 'ñ',
                                    "   followed by a 'ÿ' character because V is weird)
                                x   "   Delete the last character (the ÿ)

```

# Answer
> 1 votes
# Go, 102 bytes

```
import.`fmt`;func f(){s:="## Go, 102 bytes\n    import.`fmt`;func f(){s:=%q;Printf(s,s)}";Printf(s,s)}

```

Attempt This Online!

From my variant in a comment under the post below. A callable function. Prints:

```
## Go, 102 bytes
    import.`fmt`;func f(){s:="## Go, 102 bytes\n    import.`fmt`;func f(){s:=%q;Printf(s,s)}";Printf(s,s)}

```

## Go, 134 bytes

```
package main;import.`fmt`;func main(){s:="## Go, 134 bytes\n    package main;import.`fmt`;func main(){s:=%q;Printf(s,s)}";Printf(s,s)}

```

Attempt This Online!

Using the quine found here. A full program. Prints:

```
## Go, 134 bytes
    package main;import.`fmt`;func main(){s:="## Go, 134 bytes\n    package main;import.`fmt`;func main(){s:=%q;Printf(s,s)}";Printf(s,s)}

```

# Answer
> 0 votes
# Factor, 80 bytes

```
"# Factor, 80 bytes\n    %uUSE: formatting dup printf"USE: formatting dup printf

```

Try it online!

---
Tags: code-golf, quine
---


title: Multiplicative undelta

text:
# Question
Title: Multiplicative undelta
Let us define the *"multiplicative deltas"* of values \\$\[\\; a\_0, \cdots a\_N, \\;\]\\$ as:

$$ \[\\; a\_1 / a\_0, \cdots, a\_{i+1} / a\_i, \cdots, a\_N / a\_{N-1} \\;\] $$

The reverse operation - namely *"multiplicative undelta"* \- returns values such that the above operation results in the given values.

### Example

Given values \\$\[\\; 1, 5, 3, 2 \\;\]\\$ a general solution to the "*multiplicative undelta*" operation is:

$$ \[\\; a\_0, \quad \underset{a\_1}{\underbrace{a\_0 \cdot 1}}, \quad \underset{a\_2}{\underbrace{a\_1 \cdot 5}}, \quad \underset{a\_3}{\underbrace{a\_2 \cdot 3}}, \quad \underset{a\_4}{\underbrace{a\_3 \cdot 2}} \\;\] $$

A particular solution can be obtained by setting \\$a\_0\\$ to any value other than zero, for example by setting \\$a\_0 := 1 \\$ we would get:

$$ \[\\; 1, 1, 5, 15, 30 \\;\] $$

## Challenge

Your task for this challenge is to implement the operation "*multiplicative undelta*" as defined above.

## Rules

Inputs are:

* a non-zero value \\$a\_0\\$
* a non-empty list/array/vector/... of non-zero "*multiplicative deltas*"

Output is a list/array/vector/... of values such that the first element is \\$a\_0\\$ and for which the "*multiplicative deltas*" are the input.

**Note:** If your language has no support of negative integers you may replace *non-zero* by *positive*.

## Test cases

```
2 [21] -> [2,42]
1 [1,5,3,2] -> [1,1,5,15,30]
-1 [1,5,3,2] -> [-1,-1,-5,-15,-30]
7 [1,-5,3,2] -> [7,7,-35,-105,-210]
2 [-12,3,-17,1311] -> [2,-24,-72,1224,1604664]
-12 [7,-1,-12,4] -> [-12,-84,84,-1008,-4032]
1 [2,2,2,2,2,2,2,2] -> [1,2,4,8,16,32,64,128,256]

```

# Answer
> 18 votes
## Haskell, 8 bytes

```
scanl(*)

```

Try it online!

# Answer
> 9 votes
# APL(Dyalog), 3 bytes

```
×\∊

```

Try it online!

If I have to take the number on the left and the array on the right:

*-2 thanks to @H.PWiz*

**~~7~~ ~~5~~ 3 bytes**

`×\,`

# Answer
> 8 votes
# , 15 bytes

```
cumprod(scan())

```

Try it online!

Full program. Function is longer (unless we were allowed to "glue" the inputs together, so that built-in `cumprod` would suffice as a complete answer):

# , 28 bytes

```
function(i,x)cumprod(c(i,x))

```

Try it online!

# Answer
> 6 votes
# MATL, 3 bytes

```
hYp

```

Try it online!

```
            #implicit input, x_0 and A
h           #horizontally concatenate
Yp          #cumulative product
            #implicit output

```

The `hYp`e about MATL is real.

# Answer
> 4 votes
# Python 3, 39 bytes

```
def f(a,b):
    for x in[1]+b:a*=x;yield a

```

Alternative approach. Returns a generator.

Try it online!

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

```
FoldList@Times

```

Try it online!

`FoldList[Times, a0, {x1, x2, ..., xn}]` produces the desired output. `FoldList[Times]` is the curried form that produces a pure function still waiting for its `a0` and `{x1, x2, ..., xn}`.

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

Takes input as `(m)(a)`.

```
m=>a=>[m,...a.map(x=>m*=x)]

```

Try it online!

# Answer
> 3 votes
# Japt, 3 bytes

```
å*V

```

Try it

---

## Explanation

```
        :Implicit input of array U and integer V
å       :Cumulatively reduce U
 *      :By multiplication
  V     :With an initial value of V

```

# Answer
> 2 votes
# Jelly, 3 bytes

```
;×\

```

Try it online!

# Answer
> 2 votes
# Perl 6, 9 bytes

```
{[\*] @_}

```

Try it online!

# Answer
> 2 votes
# Standard ML, 32 bytes

```
fun f(x::r)a=a::f r(a*x)|f&a=[a]

```

Try it online!

**Ungolfed:**

```
fun f (x::xr) a = a :: f xr (a*x)
  | f    _    a = [a]

```

# Answer
> 2 votes
# , 6 5 bytes

-1 byte thanks to Bubbler

```
*/\@,

```

Try it online!

## Explanation:

A diadic verb, the left argument is `a0`, the rigth one - the vector

```
     @, - append the vector to a0 and
  */\   - find the running product

```

# Answer
> 2 votes
# Factor, 22 bytes

```
[ prefix cum-product ]

```

Try it online!

# Answer
> 1 votes
## Batch, 69 bytes

```
@set/pa=
@echo %a%
@for %%d in (%*) do @set/aa*=%%d&call echo %%a%%

```

Takes input of \\$a\_0\\$ on STDIN and the deltas as command-line arguments.

# Answer
> 1 votes
# MathGolf, ~~6~~ 5 bytes

```
\{\o*

```

Try it online!

~~I think this could be 5 bytes (`\{\o*`) but `\` instruction seems a little off when dealing with input.~~ This is now fixed in the latest version.

### Explanation:

```
\       Swap arguments, pushing both to stack
 {      Foreach loop over second argument
  \o    Output counter with newline
    *   Multiply counter by current element
        Implicitly output the last element

```

# Answer
> 1 votes
# Pyth, 6 bytes

```
*FR._s

```

Test that one here!

Alternatively, 7 bytes:

```
.u*NYEQ

```

Test it here!

The first takes input as a tuple, the second takes input as two separate lines.

Thanks to @Sok for helping me with getting good at mapping and saving 1 byte.

# Answer
> 1 votes
# Common Lisp, 67 bytes

```
(lambda(a l &aux(y 1))(mapcar(lambda(x)(setf y(* y x)))(cons a l)))

```

Try it online!

# Answer
> 1 votes
# Husk, 2 bytes

```
G*

```

Try it online!

This is equivalent to nimi's answer in Haskell: `scanl(*)`, which means reduce from the left using multiplication, and return all partial results.

# Answer
> 1 votes
# 05AB1E, ~~5~~ 3 bytes

```
šηP

```

-2 bytes thanks to *@BMO*.

Try it online or verify all test cases.

**Explanation:**

```
š      # Prepend the (implicit) input-integer at the start of the (implicit) input-list
       #  i.e. -12 and [7,-1,-12,4] → ["-12",7,-1,-12,4]
 η     # Prefixes of this new list
       #  i.e. ["-12",7,-1,-12,4]
       #   → [["-12"],["-12",7],["-12",7,-1],["-12",7,-1,-12],["-12",7,-1,-12,4]]
  P    # Take the product of each inner list (and output implicitly)
       #  i.e. [["-12"],["-12",7],["-12",7,-1],["-12",7,-1,-12],["-12",7,-1,-12,4]]
       #   → [-12,-84,84,-1008,-4032]

```

# Answer
> 1 votes
# Python 2, 40 bytes

```
f=lambda a,b:[a]+(b and f(a*b[0],b[1:]))

```

Try it online!

Surprisingly, the move to Python 3 and use of generators there only saves 1 byte over the recursive solution.

# Answer
> 1 votes
# PowerShell, 29 bytes

```
param($a,$b)$a;$b|%{($a*=$_)}

```

Try it online!

This assumes just outputting the values is fine.

```
> .\scratch.ps1 1 (1,5,3,2)
1
1
5
15
30

```

If that's not fine, this actually builds the list and then pushes it to toString which prints the same way.

```
param($a,$b)$c=,$a;$b|%{$c+=$_*$c[-1]};$c #41 bytes

```

# Answer
> 1 votes
# Desmos, 47 bytes

```
f(k,l)=∏_{n=1}^{[1...l.length+1]}join(k,l)[n]

```

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# K (ngn/k), 8 bytes

```
{x,x*\y}

```

Try it online!

Another easier-than-I-thought problem. `\` is the scan operator.

# Answer
> 1 votes
# Vyxal, 3 bytes

```
pɖ*

```

Try it Online!

```
p   # Prepend
 ɖ* # Cumulative product

```

# Answer
> 1 votes
# Perl 5 `-n`, 16 bytes

```
$b||=1;say$b*=$_

```

Try it online!

# Answer
> 0 votes
# Python 2, 47 bytes

```
lambda n,A:reduce(lambda a,c:a+[a[-1]*c],A,[n])

```

Try it online!

# Answer
> 0 votes
# Charcoal, 12 bytes

```
ＩＥ⁺⟦Ｎ⟧ＡΠ⊞Ｏυι

```

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

```
    Ｎ           Input a₀
   ⟦ ⟧          Wrap in a list
      Ａ         Input deltas as a list
  ⁺              Concatenate lists
 Ｅ              Map over elements
           ι    Current element
          υ     Predefined empty list variable
        ⊞Ｏ      Push and return updated list
       Π        Product
Ｉ               Cast to string
                Implicitly print each value on its own line

```

# Answer
> 0 votes
# K (oK), 9 bytes

```
{(*\)x,y}

```

Try it online!

Joins the first number to the second input as a list, and then returns successive results of multiplication

**Test Cases**

Enter your input after the function like below and then run, as I'm unsure how to use input properly for this language in TiO

```
{(*\)x,y}[1;1 5 3 2]

```

# Answer
> 0 votes
# dc, 13 bytes

```
p[*pz1<A]dsAx

```

Try it online!

```
p[*pz1<A]dsAx
p               # Print the first element
  *p            # Multiply top elements on the stack
 [  z1<A]dsAx   # until only one element is left

```

# Answer
> 0 votes
# Uiua SBCS, 3 bytes

```
\×⊂

```

Try it!

---
Tags: code-golf, array, integer
---


title: Possible moves in Othello/Reversi

text:
# Question
Title: Possible moves in Othello/Reversi
Othello/Reversi is a board game in which players take turn placing pieces of a color (dark or light) on the 8x8 board. The possible moves are positions where there are one or more pieces of the opponent's color in a straight (horizontal, vertical, or diagonal) line between that position and a piece of the player's color.

For example, on this board, the numbers on the left mark the row, the letters on the bottom mark the column, the empty spaces are marked `.`, the dark pieces are marked `D`, the light pieces are marked `L`, and the possible moves for dark are marked `*`:

```
1........
2........
3...D....
4...DD...
5.*LLLD..
6.****L..
7.....**.
8........
 abcdefgh

```

Your task is to take a board as input and output the positions of the possible moves dark can make.

# Rules

* Input and output can be in any convenient format. Possible input formats include as a string separated by newlines, as a matrix, and as a flattened list of numbers. Output positions can be in a format like `b5`, a list of two numbers, or a complex number. You may also choose to modify the input.
* The output may be in any order but cannot contain duplicates.
* You may use different values to represent `D`, `L`, and `.`, as long as they are distinct.
* You may assume that at least one move exists.
* Standard loopholes apply.
* This is , so the shortest code in bytes in each language wins.

# Test cases

```
........
........
...D....
...DD...
..LLLD..
.....L..
........
........

```

b5 b6 c6 d6 e6 f7 g7

\[\[1, 4\], \[1, 5\], \[2, 5\], \[3, 5\], \[4, 5\], \[5, 6\], \[6, 6\]\]

---

```
........
........
........
...LD...
...DL...
........
........
........

```

c4 d3 e6 f5

\[\[2, 3\], \[3, 2\], \[4, 5\], \[5, 4\]\]

---

```
.....L..
...LL...
.DDDD.L.
.LDDDLL.
.LLDLLL.
.L.LD...
..LLL...
.L...L..

```

a4 a5 a6 a7 b7 c1 c6 c8 d1 d8 e1 e8 f6 g6 h3 h4 h5 h6

\[\[0, 3\], \[0, 4\], \[0, 5\], \[0, 6\], \[1, 6\], \[2, 0\], \[2, 5\], \[2, 7\], \[3, 0\], \[3, 7\], \[4, 0\], \[4, 7\], \[5, 5\], \[6, 5\], \[7, 2\], \[7, 3\], \[7, 4\], \[7, 5\]\]

# Answer
# Python 3, ~~245~~ ~~238~~ ~~212~~ ~~197~~ ~~191~~ 184 bytes

```
def f(T,*R):
 for m in range(576):
  for q in range(1,8*T[m//72][m%8]):
   w,z=m//72+m%9//3*q-q,m%8+m%9%3*q-q;d=T[w][z];b=(w>=0<=z)*(q>1<2-d)
   if-~d+b:R+=((z,w),)*b;break
 return{*R}

```

Try it online!

A function that receives a list of strings and outputs a set containing sized-2 tuples.

* *-21* bytes by removing `i`, `j`, `a` and `b`, and replacing the `if T[i][j]=='D':` with a multiplication inside the `range`
* *-7 bytes* thank to @Dingus by using two if-s instead of if-elif-else
* *-26 bytes* by removing the `f`lag variable and compacting loops `m` and `n` into one
* *-15 bytes* thank to @Yousername (OP) by accepting a matrix of integers instead of a matrix of strings, where the empty slot is \\$0\\$, a dark piece is \\$1\\$, and a light piece is \\$-1\\$
* *-6 bytes* by inlining `i` and `j` and simplifying `b`
* *-5 bytes* thank to @Dingus by inlining `n`!
* *-2 bytes* by replacing a default argument list with an `*args` tuple

# Python 3, ~~270~~ 266 bytes

Original version.

```
def f(T):
 R=[]
 for m in range(64):
  i=m//8;j=m%8
  if T[i][j]=='D':
   for n in range(9):
    a=n//3;b=n%3;f=0
    for q in range(1,8):
     w,z=i+q*a-q,j+q*b-q;d=T[w][z]
     if'L'==d:f=1
     elif(d=='.')*f*(w>=0<=z):R+=[(z,w)];break
     else:break
 return{*R}

```

Try it online!

* *-4 bytes* by using a set-literal instead of a set-function

---

**How does it work?**

The output variable here is `R`. Since the board is 8x8, we can iterate over it as a continuous range (`for m in range(64):`), storing the current row and column on `i` and `j`, respectively.

Every "D" piece has 8 possible directions to be validated: north, south, east, west, northwest, northeast, southwest and southeast. We also assume a "D" piece will be validated against itself: this case will be basically a no-op, and it's only considered here so that we can directly do `for n in range(9):` instead of iterating over a `range(8)` and making additional checks.

We then split `n` into two variables `a` and `b`, each containing values from 0 to 2. Basically, the following transformation is applied:

```
n = 0  -->  a = 0; b = 0  --(-1)->  a = -1; b = -1  (southwest)
n = 1  -->  a = 0; b = 1  --(-1)->  a = -1; b =  0  (south)
n = 2  -->  a = 0; b = 2  --(-1)->  a = -1; b = +1  (southeast)
n = 3  -->  a = 1; b = 0  --(-1)->  a =  0; b = -1  (west)
n = 4  -->  a = 1; b = 1  --(-1)->  a =  0; b =  0  (no-op)
n = 5  -->  a = 1; b = 2  --(-1)->  a =  0; b = +1  (east)
n = 6  -->  a = 2; b = 0  --(-1)->  a = +1; b = -1  (northwest)
n = 7  -->  a = 2; b = 1  --(-1)->  a = +1; b =  0  (north)
n = 8  -->  a = 2; b = 2  --(-1)->  a = +1; b = +1  (northeast)

```

Since a board has a limit of 8 pieces in each direction (8x8), we iterate over `range(1, 8)`. The variable `q` here describes how far we are going into the direction described by `n`: if `n` is north and `q` is 1, we are looking at the first slot on the top of `(i, j)`; if `n` is east and `q` is 2, we are looking at the second slot on the right of `(i, j)`. That slot has coordinates `(w, z)`, with value `d`.

If that slot contains a "L" piece, we can proceed with the validation; set `f`lag to true. That flag implements the requirement

> The possible moves are positions where there are one or more pieces of the opponent's color in a straight (horizontal, vertical, or diagonal) line **between that position and a piece of the player's color**.

We can only add a possible move to `R` if the `f`lag has been set; that is, if there is an "L" piece between a "D" piece and an empty slot.

If the next slot on that direction is an empty spot, a "L" piece has already been visited (i.e. if `f` is true) and if `(w, z)` is a valid spot on the board, then add it to `R` and stop validating.

Continue for all "D" pieces, for all possible directions, for all possible offsets.
> 4 votes

# Answer
# Charcoal, 40 bytes

```
Ｅ⁸ＳＦ⁸Ｆ⁸«Ｊικ¿⊙Ｅ⁸⁺⪫ＫＤ⁸✳λω.D⁼⌕⁺..×⁶L…λ⌕λD¹*

```

Attempt This Online! (Only using ATO here because the version of Charcoal on TIO erroneously extends the canvas when you use `PeekDirection`.) Link is to verbose version of code. Outputs by drawing `*`s where the possible moves are. Explanation:

```
Ｅ⁸Ｓ

```

Copy the input to the canvas.

```
Ｆ⁸Ｆ⁸«Ｊικ

```

Jump to each square in turn.

```
¿⊙Ｅ⁸⁺⪫ＫＤ⁸✳λω.D

```

For every direction, peek in that direction, appending `.D` to the peeked string...

```
⁼⌕⁺..×⁶L…λ⌕λD¹

```

... if after truncating the string at the position of the first `D`, the result is not `.` but is a prefix of `.LLLLLL`...

```
*

```

... overwrite the `.` with a `*`.
> 3 votes

# Answer
# JavaScript (ES11), 115 bytes

Expects a matrix with \\$0\\$ for *empty*, \\$1\\$ for *light*, \\$2\\$ for *dark*. Returns another matrix in the same format, using \\$3\\$ for the possible moves for dark.

```
m=>m.map((r,y)=>r.map((n,x)=>[...35678+m].some(d=>(g=X=>(q=m[Y+=~-(d/3)]?.[X+=d%3-1])&1&&g(X)|!n)(x,Y=y)*q&2)?3:n))

```

Attempt This Online!

### Commented

```
m =>                         // m[] = input matrix
m.map((r, y) =>              // for each row r[] at index y in m[]:
  r.map((n, x) =>            //   for each value n at index x in r[]:
    [...35678 + m]           //     we coerce 35678 to a string and get the values
                             //     0, 1 and 2 from m[] (if the board does not
                             //     contain at least one empty, one light and one
                             //     dark square, then there's no possible move and
                             //     some() would fail anyway)
    .some(d =>               //     for each direction d:
      (g = X =>              //       g is a recursive function taking X
        ( q =                //         q is the value of the square on
          m[Y += ~-(d / 3)]  //         the updated row Y
          ?.[X += d % 3 - 1] //         and the updated column X
        ) & 1 &&             //         if it's a light one:
          g(X)               //           do a recursive call
          | !n               //           and set the final result if n != 0
      )(x, Y = y)            //       initial call to g with the current position
      * q & 2                //       test whether the last square is dark
    ) ?                      //     end of some(); if truthy:
      3                      //       set this square as a possible move
    :                        //     else:
      n                      //       leave it unchanged
  )                          //   end of inner map()
)                            // end of outer map()

```
> 1 votes

# Answer
# Perl (`-p`), 60 bytes

```
for$i(0,7..9){s/D(.{$i}(L.{$i})+)\K\.|\.(?=(?1)D)/*/s&&redo}

```

Attempt This Online!
> 1 votes

# Answer
# Google Sheets, 253 bytes

```
=let(_,lambda(a,r,regexmatch(join(,a),r)),f,"^L+D",b,"DL+$",if((H8=".")*or(_(A8:G8,b),_(I8:O8,f),_(H1:H7,b),_(H9:H15,f),_({A1,B2,C3,D4,E5,F6,G7},b),_({A15,B14,C13,D12,E11,F10,G9},b),_({I7,J6,K5,L4,M3,N2,O1},f),_({I9,J10,K11,L12,M13,N14,O15},f)),"*",H8))

```

Put the input in cells `H8:O15` and the formula in cell `X8`, and copy the formula cell to the range `X8:AE15`. The output is returned as a matrix in the latter cells, mimicking the format shown in the example in the question.

Try it.

Generates strings by joining seven values to the left, right, up and down, and diagonally from a cell. Matches each string against a regex that looks at the start or at the end, depending on the string's direction from the origin.

Ungolfed:

```
=let(
  isMatch_, lambda(a, x,
    regexmatch(join("", a), x)
  ),
  left, A8:G8,
  right, I8:O8,
  up, H1:H7,
  down, H9:H15,
  leftup, { A1, B2, C3, D4, E5, F6, G7 },
  leftdown, { A15, B14, C13, D12, E11, F10, G9 },
  rightup, { I7, J6, K5, L4, M3, N2, O1 },
  rightdown, { I9, J10, K11, L12, M13, N14, O15 },
  forward, "^L+D",
  backward, "DL+$",
  if(
    and(
      (H8 = "."),
      or(
        isMatch_(left, backward),
        isMatch_(right, forward),
        isMatch_(up, backward),
        isMatch_(down, forward),
        isMatch_(leftup, backward),
        isMatch_(leftdown, backward),
        isMatch_(rightup, forward),
        isMatch_(rightdown, forward)
      )
    ),
    "*",
    H8
  )
)

```
> 0 votes

# Answer
# Jelly, 30 bytes

```
ŒJðŒṬ⁹_ZṚ,ƊŒD;$€ẎẆ€ẎẠƇQ€ḂḄ5eðƇ

```

A monadic Link that accepts a list of lists of `0`s (spaces), `1`s (dark pieces), and `2`s (light pieces) and yields a list of valid spaces at which dark may play - each as 1-indexed `[row, column]`.

**Try it online!** (The footer translates to the input above, calls the Link, and transforms the output to the sorted, 0-indexed `[column, row]` format used in the question's examples.)

pretty-print version.

### How?

```
ŒJðŒṬ⁹_ZṚ,ƊŒD;$€ẎẆ€ẎẠƇQ€ḂḄ5eðƇ - Link: Board (.:0  D:1  L:2)
ŒJ                             - multidimensional indices -> all coords
  ð                         ðƇ - keep those for which - f(coord, Board):
   ŒṬ                          -   array with a 1 at {coord} and 0s elsewhere
     ⁹_                        -   Board subtract that (i.e. Board -1 @ coord)
       ZṚ,Ɗ                    -   rotate {that} a quarter and pair with {that}
           ŒD;$€               -   concatenate each to its forward diagonals
                Ẏ              -   tighten
                 Ẇ€            -   sublists of each
                   Ẏ           -   tighten
                    ẠƇ         -   keep if: all? (those with no 0s (spaces))
                      Q€       -   deduplicate each
                        Ḃ      -   mod two
                         Ḅ     -   convert from binary
                          5e   -   five exists?

```
> 0 votes

# Answer
# Retina 0.8.2, 105 bytes

```
s`\.(?=(L+|(.{7}L)+.{7}|(.{8}L)+.{8}|(.{9}L)+.{9})D|(?<=D(L+|(.{7}L)+.{7}|(.{8}L)+.{8}|(.{9}L)+.{9}).))
*

```

Try it online! Link is to test suite that accepts multiple double-spaced boards. Outputs by drawing `*`s where the possible moves are. Explanation: From each `.` the regular expression tries to look both ahead or behind in each possible direction for at least one `L` followed by a `D`.

# Retina 1, 70 bytes

```
+s,T,,`.`*`([.D])(L+|(.{7}L)+.{7}|(.{8}L)+.{8}|(.{9}L)+.{9})(?!\1)[.D]

```

Try it online! Link is to test suite that accepts multiple double-spaced boards. Outputs by drawing `*`s where the possible moves are. Explanation: The regular expression matches every pair of `.` and `D` (in either order) that are separated by a run of `L`s in any of the forward directions. The `,T,,` command then transliterates the first and last character (`,,` is a step range using defaults of all three values) of each match (`,` is a regular range using defaults and is only needed so that the second range can be specified) from `.` to `*` (the `D` is therefore unaffected). The `+` then repeats until there are no more matches.
> 0 votes

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


title: Hamming numbers

text:
# Question
Title: Hamming numbers
Hamming numbers are numbers which evenly divide a power of 60. Equivalently, their prime factors are all \\$ \le 5 \\$.

Given a positive integer, print that many Hamming numbers, in order.

Rules:

* Input will be a positive integer \\$n \le 1,000,000 \\$
* Output should be the first \\$n\\$ terms of https://oeis.org/A051037
* Execution time must be \\$\<1\\$ minute
* This is ; shortest code wins

# Answer
> 9 votes
## Haskell, ~~101~~ ~~97~~ 92+|n| characters

```
h=1:m 2h&m 3h&m 5h
m=map.(*)
c@(a:b)&o@(m:n)|a<m=a:b&o|a>m=m:c&n|0<1=a:b&n
main=print$take 1000000h

```

Computes the full million in 3.7s on the machine I tested on (variably more if you actually want the output stored)

Ungolfed:

```
-- print out the first million Hamming numbers
main = print $ take 1000000 h

-- h is the entire Hamming sequence.
-- It starts with 1; for each number in the
-- sequence, 2n, 3n and 5n are also in.
h = 1 : (m 2 h) & (m 3 h) & (m 5 h)

-- helper: m scales a list by a constant factor
m f xs = map (f*) xs

-- helper: (&) merges two ordered sequences
a@(ha:ta) & b@(hb:tb)
    |    ha < hb = ha : ta & b
    |    ha > hb = hb :  a & tb
    |  otherwise = ha : ta & tb

```

All Haskell is notoriously good at: defining a list as a lazy function of itself, in a way that actually works.

# Answer
> 4 votes
**Python 181 Characters**

```
h=[]
h.append(1)
n=input()
i=j=k=0
while n:
    print h[-1]
    while h[i]*2<=h[-1]:
        i+=1
    while h[j]*3<=h[-1]:
        j+=1
    while h[k]*5<=h[-1]:
        k+=1
    h.append(min(h[i]*2,h[j]*3,h[k]*5))
    n-=1

```

# Answer
> 4 votes
# APL (Dyalog Classic), ~~34~~ 23 bytes

```
{⍺⍴{⍵[⍋⍵]}∪,⍵∘.×⍳5}⍣≡∘1

```

Try it online!

TIO throws a WS FULL error for \\$n = 1000000\\$, but Dyalog on my laptop runs in about 45 seconds, not counting the scrolling to display numbers.

```
{⍺⍴{⍵[⍋⍵]}∪,⍵∘.×⍳5}⍣≡∘1     Monadic function:
{⍺⍴{⍵[⍋⍵]}∪,⍵∘.×⍳5}         Define the following helper function g(⍺,⍵):
             ⍵∘.×⍳5             Make a multiplication table between ⍵ and (1 2 3 4 5).
                                (Including 4 is unnecessary but saves bytes.)
            ,                   Flatten the table into an array.
           ∪                    Keep unique elements.
    {⍵[⍋⍵]}                     Grade up the array and access it at those indices.
                                (This is the APL idiom to sort an array.)
 ⍺⍴                             Keep the first ⍺ elements; pad by repeating the array.
{⍺⍴{⍵[⍋⍵]}∪,⍵∘.×⍳5}⍣≡       Repeatedly apply g with some fixed left argument
                             until a fixed point is reached.
                             At this point we have a dyadic function that takes
                             n on the left and the starting value on the right,
                             and returns multiples of the n Hamming numbers.
                      ∘1     Fix 1 as the right argument.

```

# Answer
> 4 votes
# Vyxal `j`, 8 bytes

```
λdǏG7<;ȯ

```

Try it Online!

```
λ     ;ȯ # First n numbers where
 dǏG     # Maximum of prime factors
    7<   # Less than 7

```

# Answer
> 3 votes
# Vyxal, ~~29~~ 26 bytes, times out when n\>=200,000 on online interpreter.

My first ever Vyxal post. 29-\>26, adviced by @lyxal.

```
6ɽ{:L?<|:2*$:3*$:5*∪∪∪}s?Ẏ

```

## How it works

```
# let first hamming numbers are 1 to 6
6ɽ
# while items of they are less than n; do
{:L?<|
# for each item, multiply with those numbers
# and then unify them; done
  :2*$:3*$:5*∪∪∪}
# sort
s
# take first n items
?Ẏ

```

Try it Online!

# Answer
> 2 votes
## Ruby - 154 231 characters

```
def k i,n;(l=Math).log(i,2)*l.log(i,3)*l.log(i,5)/6>n end
def l i,n;k(i,n)?[i]:[i]+l(5*i,n)end
def j i,n;k(i,n)?[i]:[i]+j(3*i,n)+l(5*i,n)end
def h i,n;k(i,n)?[i]:[i]+h(2*i,n)+j(3*i,n)+l(5*i,n)end
puts h(1,n=gets.to_i).sort.first n

```

And now it's fast enough, there is definitely a lot of golfing that can still happen though.

```
→ time echo 1000000 | ruby golf-hamming.rb | wc
1000000 1000000 64103205
echo 1000000  0.00s user 0.00s system 0% cpu 0.003 total
ruby golf-hamming.rb  40.39s user 0.81s system 99% cpu 41.229 total
wc  1.58s user 0.05s system 3% cpu 41.228 total

```

# Answer
> 2 votes
# MMIX, 92 bytes (23 instrs)

I'm cheating a bit; instead of printing (which would take a lot of work, this being machine language), I instead pass the numbers to a function passed in!

```
00000000: fe020004 34000100 e3030000 c1040300  “£¡¥4¡¢¡ẉ¤¡¡Ḋ¥¤¡
00000010: e7030001 da040403 3c040304 1d050403  ḃ¤¡¢ḷ¥¥¤<¥¤¥ø¦¥¤
00000020: feff0006 6204ff05 43fffffd 1d050405  “”¡©b¥”¦C””’ø¦¥¦
00000030: feff0006 6204ff05 43fffffd 31ff0401  “”¡©b¥”¦C””’1”¥¢
00000040: 5bfffff3 e7000001 c1050300 bf040100  [””ṙḃ¡¡¢Ḋ¦¤¡Ḃ¥¢¡
00000050: 5b00ffef f6040002 f8000000           [¡”ṁẇ¥¡£ẏ¡¡¡

```

```
smooth5 GET    $2,rJ
        NEG    $0,1,$0      // n = 1 - n
        SETL   $3,0         // i = 0
0H      SET    $4,$3
        INCL   $3,1         // loop: j = i++
        SADD   $4,$4,$3     // j = popcnt(j & ~i)
        SR     $4,$3,$4     // j = i >> j (cheap way of getting out factors of 2)
1H      DIV    $5,$4,3      // lp3: k = j / 3
        GET    $255,rR      // tmp = j % 3
        CSZ    $4,$255,$5   // if(!tmp) j = k
        BZ     $255,1B      // if(!tmp) goto lp3
1H      DIV    $5,$4,5      // lp5: k = j / 5
        GET    $255,rR      // tmp = j % 5
        CSZ    $4,$255,$5   // if(!tmp) j = k
        BZ     $255,1B      // if(!tmp) goto lp3
        CMP    $255,$4,1    // tmp = j <=> 1
        PBNZ   $255,0B      // iflikely(tmp) goto loop
        INCL   $0,1         // n++
        SET    $5,$3
        PUSHGO $4,$1,0      // f(i)
        PBNZ   $0,0B        // iflikely(n) goto loop
        PUT    rJ,$2
        POP    0,0          // return

```

# Answer
> 2 votes
# Jelly, 9 bytes

```
RḤÆfṀ€<7T

```

Try it online!

Returns all hamming numbers under n.

**How?**

```
RḤÆfṀ€<7T     Main Link. Takes n on the left
        T     Filter by
R             Inclusive range
 Ḥ            Double each
  Æf          Prime factors
     €        For each
    Ṁ         Maximum
      <7      Less than 7

```

My first serious jelly answer

# Answer
> 2 votes
# Python 3.8 (pre-release), 97 bytes

Inefficient but golfy. Lot's of keywords and whitespace, so potential for more golfing.

```
def f(n):
 h=[1]
 while(n:=n-1):h+=[min(j*k for j in(2,3,5)for k in h if j*k not in h)]
 return h

```

Try it online!

# Python 3.8 (pre-release), 165 bytes

Slightly golfed version of the original Python entry.

Reposted, because of its age.

```
def f(n):
 h=[1];i=j=k=0
 while(n:=n-1):
  m=h[-1]
  while(h[i]*2<=m):i+=1
  while(h[j]*3<=m):j+=1
  while(h[k]*5<=m):k+=1
  h+=[min(h[i]*2,h[j]*3,h[k]*5)]
 return h

```

Try it online!

# Answer
> 1 votes
# GAWK `-M`, ~~138~~ 120 bytes.

It was originally a post on rosetta code. Without `-M` it overflows when huge value is input.

```
{a=2
b=3
c=5
for(s=h[0]=1;--$0;c-z||c=5*h[++k]){z=a<b?a:b
s=s" "(z=h[++n]=z<c?z:c)
a-z||a=2*h[++i]
b-z||b=3*h[++j]}}$0=s

```

Try it online!

## Usage

Given from stdin, as a line consists of a string of decimal natural number.

## Execution time

Tested in my Termux. CPU is:

```
Architecture:        aarch64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              8
On-line CPU(s) list: 0-7
Thread(s) per core:  1
Core(s) per socket:  4
Socket(s):           2
Vendor ID:           ARM
Model:               4
Model name:          Cortex-A53
Stepping:            r0p4
CPU max MHz:         1768.0000
CPU min MHz:         449.0000
BogoMIPS:            52.00
Flags:               fp asimd evtstrm aes pmull sha1 sha2 crc32

```

### With original code

10^6th Hamming number is `519312780448388736089589843750000000000000000000000000000000000000000000000000000000`.

```
$ time echo 1000000 | awk -Mf Textfile/ham.awk
# lots of output
real    2m36.842s
user    0m25.224s
sys     0m5.356s

```

### If `$0=s` is removed

```
$ time echo 1000000 | awk -Mf Textfile/ham.awk
real    0m25.404s
user    0m24.676s
sys     0m0.716s

```

## Note

* Original 138 bytes of post outputs incorrectly: it outputs n+1 numbers, not n.

# Answer
> 1 votes
# JavaScript (ES6), 110 bytes

```
f=h=>eval("g=n=>n-1n?n%2n?n%3n?n%5n?0:g(n/5n):g(n/3n):g(n/2n):1;r=[i=1n];while(!r[h-1])if(g(++i))r.push(i);r")

```

Theoretically works for arbitrarily large inputs, but prohibitively slow.

# Answer
> 1 votes
# Vyxal 3, 7 bytes

```
ЧdḟG7<Ẇ

```

Try it Online!

Port of Emanrasu's Vyxal answer

# Answer
> 0 votes
## Ursala, 103

```
#import std
#import nat
smooth"p" "n" = ~&z take/"n" nleq-< (rep(length "n") ^Ts/~& product*K0/"p") <1>

```

**Output** for `main = smooth<2,3,5>* nrange(1,20)`

```
<1,2,3,4,5,6,8,9,10,12,15,16,18,20,24,25,27,30,32,36>

```

# Answer
> -2 votes
## Haskell, 71

```
h n = drop n $ iterate (\(_,(a:t))-> (a,union t [2*a,3*a,5*a])) (0,[1])

```

**Output**

```
*Main> map fst $ take 20 $ h 1
[1,2,3,4,5,6,8,9,10,12,15,16,18,20,24,25,27,30,32,36]

```

---
Tags: code-golf, sequence, number-theory, restricted-time
---


title: Binary Expansion Counting Sequence

text:
# Question
Title: Binary Expansion Counting Sequence
*I found another sequence not yet in the OEIS*

The binary expansion sequence is defines as follows, assuming 0 indexing:

* The even numbers of the sequence are how often 0 has appeared in the binary expansion of all previous items in the sequence
* The odd elements are the same, but for 1s.

If you choose to 1-index, reverse "even" and "odd" in the description above to get the same sequence.

Leave at least one digit in the binary expansion.

Thus the first terms are:

* 0, because this is even, we count the numbers of 0s. There are none
* 0, because this is odd, we count the 1s. There are none
* 2, because this is even, we count the 0s, there has been 2 zeros
* 1 next, the number 2 had 1 1
* 3, two zeros from the first 2 terms, 1 from 2
* 4, 1 from 2, 1 from 1, 2 from 3

First 200 terms:

```
0
0
2
1
3
4
5
7
6
12
9
16
15
21
17
26
22
32
29
37
33
42
40
47
45
56
50
62
54
71
59
80
65
84
74
90
81
97
89
104
96
109
103
119
106
129
115
136
123
144
130
148
141
155
148
163
157
172
164
179
172
188
179
198
186
207
191
220
195
229
202
238
208
247
214
259
223
269
229
278
237
288
246
296
254
306
260
312
272
318
282
328
293
335
301
346
309
356
318
366
324
375
332
386
343
395
350
406
357
416
367
426
373
437
379
450
386
457
396
466
405
476
412
487
418
498
426
509
431
524
440
532
451
540
461
550
470
560
480
567
489
579
498
589
506
601
513
608
528
613
541
623
549
634
559
646
569
655
578
664
591
674
601
683
610
693
620
704
632
712
643
720
655
730
663
742
671
755
677
767
683
782
692
792
703
804
711
814
719
827
725
840
735
852
742
863
748
877
755
891

```

Sequence rules apply, you may either:

* Given n, output the nth element of the sequence
* Given n, output the first N terms
* Output the sequence infinity

Either 0 or 1 based indexing is acceptable.

# Answer
# JavaScript (ES6), 62 bytes

Returns the \\$n\\$-th term, 0-indexed.

```
f=(n,g=k=>k&&(k+n&1)+g(k>>1))=>n>2?g(f(--n))+g(p=f(n-1))+p:n&2

```

Try it online!

### Formula

Let \\$c\_0\\$ and \\$c\_1\\$ be functions counting the number of \\$0\\$'s and \\$1\\$'s respectively in the binary expansion.

Then:

$$a(0)=0,\\:a(1)=0$$

and for \\$n\ge2\\$:

$$a(n)=c\_{n\bmod2}(a(n-1))+c\_{n\bmod2}(a(n-2))+a(n-2)$$

### Implementation

In the JS implementation, we use the same helper function \\$g\\$ for both \\$c\_0\\$ and \\$c\_1\\$. However, this function considers that there is no \\$0\\$ in the binary expansion of \\$0\\$. So we have to handle \\$a(2)=2\\$ as a special edge case.
> 5 votes

# Answer
# Wolfram Language (Mathematica), 47 bytes

```
a@n_:=a@n=Tr@DigitCount[Array[a,n,0],2,n~Mod~2]

```

Try it online!

-13 bytes from @Greg Martin
Also, we can remove memoization `a@n=` to save 4 bytes, but I'll keep it.
-15 bytes from @att
> 4 votes

# Answer
# Vyxal 3, 8 bytes

```
Ṇ¤b∥fLḃC

```

Try it Online!

Finally a use for the generator structure!

## Explained

```
relation<         ## A relation based on
 ¤ to-binary !!:  ## Converting all previously generated values to binary and
   flatten        ##   flattening that
   length         ##   as well as getting the length of that
 parity count     ## get the count of the bit parity of the length in the flattened binary.

```
> 4 votes

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

```
f=(n,g=k=>k&&(k+n&1)+g(k>>1))=>n-->2?g(f(n))+f(n,g):-~n*!g(1)

```

Try it online!

Modified from Arnauld's

Pass `g` to use `n` of parent `f` than `n` inside

# JavaScript (Node.js), 68 bytes, 0-index

```
for(i=1,s='';;s+=a.toString(2))console.log(a=s.split(i^=1).length-1)

```

Try it online!

# JavaScript (Node.js), 66 bytes, 1-index

```
for(i=s='';;s+=a.toString(2))console.log(a=s.split(i^=1).length-1)

```

Try it online!
> 2 votes

# Answer
# Jelly, 10 bytes

```
LḂ=BFSṄṭ⁸ß

```

A full program that takes no arguments and prints indefinitely.

**Try it online!** (You can click the run button again to kill it after a couple of seconds and see what was output if you don't want to hang around for sixty seconds!)

### How?

```
LḂ=BFSṄṭ⁸ß - Main Link: no arguments
L          - length {X=sequence so far}
               N.B. the first X is implicitly zero, which has length one
                    later X's will be the sequence so far (a list of integers)
 Ḃ         - {that length} mod two -> P = 1 or 0
   B       - convert {X} to binary -> BinaryExpansions(X)
  =        - {P} equals {BinaryExpansions(X)} (vectorises)
              -> list of lists of 1s (correct parity) and 0s (incorrect parity)
    F      - flatten
     S     - sum -> next number in the sequence
      Ṅ    - print and yield it
       ṭ⁸  - tack it to the end of X
         ß - call this Link again with that

```
> 2 votes

# Answer
# Google Sheets, 103 bytes

```
=index(decimal(reduce(0,sequence(A1),lambda(a,n,{a;base(len(substitute(join(,a),1-isodd(n),)),2)})),2))

```

Put \\$n\\$ in cell `A1` and the formula in cell `B1`. The formula outputs the first \\$n + 1\\$ terms.
> 2 votes

# Answer
# Ruby, 42 bytes

```
a="";0.step{a+=p(a.count"#{_1%2}").to_s 2}

```

Attempt This Online!

Prints the sequence indefinitely.
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
0λλbJNÉ¢

```

Outputs the infinite sequence.

Try it online.

**Explanation:**

```
 λ        # Start a recursive environment
          # to output the lazy infinite sequence
          # (which is output at the end implicitly)
0         # Starting with a(0)=0
          # And where every following a(n) is calculated as:
  λ       #  Push the sequence thus far: [a(0),a(1),...,a(n-1)]
   b      #  Convert each integer to a binary string
    J     #  Join those strings together
     N    #  Push the current n
      É   #  Check whether it's odd (1 if n is odd; 0 if n is even)
       ¢  #  Count how many 1s/0s there are in the joined binary string

```
> 2 votes

# Answer
# Charcoal, 16 bytes

```
ＦＮ⊞υ№⭆υ⍘κ²Ｉ﹪ι²Ｉυ

```

Try it online! Link is to verbose version of code. Outputs the first `n` terms. Explanation:

```
ＦＮ

```

Repeat `n` times.

```
⊞υ№⭆υ⍘κ²Ｉ﹪ι²

```

Convert all of the terms of the list so far to binary, then count either `0`s or `1`s depending on whether the current index is even or odd, and push that to the predefined empty list.

```
Ｉυ

```

Output the resulting list.
> 1 votes

# Answer
# Zsh, 46 bytes

```
for ((c=1;;c=!c))s+=$[[##2]n=${#s//$c}]&&<<<$n

```

Attempt This Online!

Output is in binary due to Zsh overzealously detecting what base I want. This can be prevented for +2 bytes.

Explanation:

```
                                                (implicitly set $s = "")
      c=1                                       initialise $c
for ((   ;;    ))                               loop forever:
                             ${ s//$c}           remove $c characters from $s
                             ${#     }           count the length of what's left
                           n=                    save to $n
                    $[[##2]           ]          convert to binary
                 s+=                             append to $s
                                       &&<<<$n   then print $n
           c=!c                                  invert $c

```
> 1 votes

# Answer
# Haskell, 82 bytes

```
f=h<$>[0..]
n#b=[1|mod n 2==b]++[x|n>1,x<-div n 2#b]
h n=sum$(#mod n 2)=<<take n f

```

Try it online!

`f` generates the infinite sequence
> 1 votes

# Answer
# Perl 5 `-p`, 57 bytes

```
map{$t=$_%2;$r.=sprintf"%b",$\=grep$t-$_,$r=~/./g}1..$_}{

```

Try it online!

1-indexed because it's a byte shorter that way.
> 1 votes

# Answer
# Python 3.8 (pre-release), ~~79~~ 75 bytes

Calculates the first n terms, zero indexed.

```
f=lambda n:n and(s:=f(n-1))+[sum(f"{k:b}".count("01"[n%2])for k in s)]or[0]

```

Try it online!
> 1 votes

# Answer
# PARI/GP, 57 bytes

```
f(n)=sum(i=1,n-1,#[1|d<-binary(f(i)),d-n%2])+2*(n>2&&n%2)

```

Attempt This Online!

1-index.
> 0 votes

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


title: Solve an 0h n0 board

text:
# Question
Title: Solve an 0h n0 board
0h n0 is a very simple and enjoyable game, a bit like Sudoku or minesweeper.

## Game rules

(I recommend using the tutorial in the game if you can, it is very simple and useful)

The puzzle starts with an `n * n` board containing some fixed pieces and some empty cells, and the solver must find a way to fill the empty cells with pieces and satisfy all of the constraints imposed by the fixed pieces. Here are the piece types we will be using with the abbreviation:

* `#` Red piece (blocks view of a blue piece)
* `O` Blue piece
* `.` Empty location
* `number` Numbered blue piece (`number` is a one digit number \>0)

All the numbered pieces must see exactly the same amount of blue pieces as the number. For example:

```
#1O#O
...O.

```

The `1` piece can see only one other blue piece.

### How pieces see each other

Two blue pieces can see each other if they are in the same row or column and no red piece is between them. Example:

(`S` is a location that the `O` piece can see, `X` can't be seen)

```
   S
   S
X#SOSS
   #
   X

```

Each blue piece must see at least one other blue piece:

```
#O#

```

Wont work, but:

```
#OO

```

Or:

```
###

```

Do work.

### Demo board solve

```
.1..
..1.
....
22#2

```

The right bottom 2 can only see above itself, so they must be blue, and the top right must be red.

```
.1.#
..1O
...O
22#2

```

Since the `1` is filled, we can surround it with red pieces.

```
.1##
.#1O
..#O
22#2

```

The top left `1` can only see in one direction now, so we can fill it in.

```
O1##
.#1O
..#O
22#2

```

Now about those last `2`s. We can put 2 blue pieces over them.

```
O1##
.#1O
OO#O
22#2

```

The last one will be filled with `#`

```
O1##
##1O
OO#O
22#2

```

## Input

Input is a multi-line string. The size will be `9x9` without trailing space. It has the following piece types:

* `.` Empty
* `#` Preset red, cannot be changed
* `number` Preset number, cannot be changed

(Note that blue will not ever be in the input)

## Output

Output is the same as input, with the change that empty (`.`) is replaced with either a red or a blue to solve the board, and numbers are replaced with blue pieces (`O`).

## Examples

(Note that multiple solutions may be possible for each puzzle, but you only need to show one of them)

```
Input:
........4
...3.1...
45...2.3.
..9......
1..6#44..
....4..5.
....4.36.
2.......6
1....4...

Output:
OOO###OOO
OOOO#O#OO
OOO#OO#OO
#OOOO#O##
O#OO#OOOO
O#OOOO#OO
#OOOO#OOO
OO#O#OOOO
O#OOOO#O#

Input:
..7..#...
#...8..11
2....5...
..5...48.
...#...4.
.5...6...
...1.2...
2.....6.8
.7..#....

Output:
OOOOO####
##OOOO#OO
O#OOOO###
OOO#OOOOO
OO##O##O#
#O##OOOOO
#O#O#O#OO
OO#OOOOOO
OOO###O#O

Input:
5.3..33..
...4...23
.6.6.34..
...3#....
....5..4.
.5....3..
7.98.6#.3
.5.6..2..
..6...2..

Output:
OOOOO####
##OOOO#OO
O#OOOO###
OOO#OOOOO
OO##O##O#
#O##OOOOO
#O#O#O#OO
OO#OOOOOO
OOO###O#O

```

Thanks to @PeterTaylor and @apsillers for all their help in the sandbox!

# Answer
> 2 votes
# Haskell, 224 bytes

Not fully tested, because it's so slow (at least `O(n*2^n^2)`).

```
t=1<2
x!p|p<0=0|t=mod(div x$2^p)2
l#x=[[sum$map(p&)[-1,1,l+1,-l-1]|p<-[q..q+l]]|q<-[0,l..l*l],let i&v|x!i<1=0|t=x!(i+v)+(i+v)&v]
b%v|b<1=t|t=b==v
s b|l<-length b-1=[l#x|x<-[0..2^l^2],and.map and$zipWith(zipWith(%))b(l#x)]!!0

```

# Explanation:

Basic idea is to represent a board of `Red, Blue` pieces as a list of lists of `0, 1`, where the list of lists is packed into a single integer for easier enumeration. All such integers for the board size are generated and converted to a form with neighbor counts. The first such board that is a valid solution of the input is returned.

```
-- integer x at position p with out of bounds defined to be 0 (so no bounds checking)
(!) :: (Integral b, Integral r) => r -> b -> r
x ! p | p < 0     = 0
      | otherwise = mod (div x (2^p)) 2

-- Sum of values from position p along vector v (x is implicit)
-- Note that a cartesian vector (x,y) in this representation is (l*x + y)
(&) :: (Integral a, Integral b) => b -> b -> a
p & v | x ! p == 0 = 0
      | otherwise  = x ! (p+v)  +  (p+v) & v

-- Value of board at position p (implicit x, l)
value :: Integral a => a -> a
value p = sum $ map (p&) [-1, 1, l+1, -l-1]

-- Integer to board, where l is length, x is input integer
(#) :: (Integral t, Integral a) => a -> t -> [[t]]
l # x = [[sum $ map (p&) [-1,1,l+1,-l-1] | p <- [q..q+l-1]] | q <- [0,l..l*l]]

-- Comparison operator, to see whether a solved board is a solution of the input
(%) :: (Num a, Ord a) => a -> a -> Bool
b % v | b == 0    = True
      | otherwise = b == v

-- Check one possible solution
check :: Integral a => [[a]] -> Int -> [[a]] -> Bool
check b l x = (and . (map and)) zipWith(zipWith (%)) b (l # x)

-- Solver
solve :: Integral t => [[t]] -> [[t]]
solve b = [l # x | x <- [0..2^l^2], check b l x]
  where
    l = length b

```

The part that could probably be most golfed is: `and.map and$zipWith(zipWith(%))`. Otherwise, I caught a few off-by-one errors that added length and could probably be golfed more.

# Answer
> 1 votes
# Python3 1244 bytes

Very long, but optimized to crunch all the test cases (and some others) in ~0.5 seconds.

```
E=enumerate
from itertools import*
M=[(0,1),(0,-1),(-1,0),(1,0)]
def T(v,D,d):
 s,c=[],0
 for l,X,Y in D.pop(1):s+=[(l[0][1],X,Y)];c+=len(l[0][1]);D[0]+=[(l[1:],X,Y)]
 if c>v:return
 q=[(D[0],c,s)]
 while q:
  O,c,s=q.pop(0)
  if c==v:yield s;continue
  if[]==O:continue
  q+=[(O[1:],c,s)]
  L,X,Y=O[0]
  for i,(_,U)in E(L):
   if 0==i%2:
    for I in range(1,len(U)+1):
     if len(Q:=[j for k in L[:i]for j in k[1]]+U[:I]+(L[i+1][1]if I==len(U)and L[i+1:]else[]))+c<=v:q+=[(O[1:],c+len(Q),s+[(Q,X,Y)])]
def B(x,y,v,d):
 q=[(x,y,X,Y,[])for X,Y in M]
 while q:
  x,y,X,Y,p=q.pop(0)
  if not(V:=d.get(g:=(x+X,y+Y)))or'#'==V:yield([(a,[*b])for a,b in groupby(p,key=lambda x:d[x]!='.')],X,Y);continue
  q+=[(*g,X,Y,p+[g])]
def f(b):
 d={(x,y):v for x,r in E(b)for y,v in E(r)}
 q=[([(i,d[i])for i in d if d[i].isdigit()],d)]
 while q:
  o,d=q.pop(0)
  if[]==o:return d
  W=[]
  for(x,y),v in o:
   D={0:[],1:[]}
   for V,X,Y in B(x,y,v,d):
    if V:D[V[0][0]]+=[(V,X,Y)]
   W+=[((x,y),v,[*T(int(v),D,d)])]
  if all(i[2]for i in W):
   (x,y),v,L=W[0]
   for w in L:
    D={**d}
    for l,X,Y in w:
     for j,k in l:D[(j,k)]='O'
     if(j+X,k+Y)in D:D[(j+X,k+Y)]='#'
    for X,Y in M:
     if'.'==D.get(H:=(x+X,y+Y)):D[H]='#'
    q+=[(o[1:],D)]

```

Try it online!

---
Tags: code-golf, puzzle-solver
---


title: Split into three!

text:
# Question
Title: Split into three!
> Given a string, you've to split it into groups of three characters (by padding `_` at the end).
>
> Related, but still it's different.

---

**Sample I/O:**

* `'abcde' -> 'abc', 'de_'`
* `'1234' -> '123', '4__'`
* `'' -> [] or falsey value`
* `'Three spree!' -> 'Thr', 'ee ', 'spr', 'ee!'`
* 6 MB string

This is a , so fewest bytes will win!

**Edit:** Finally, output is *unrestricted*.

# Answer
# 05AB1E, ~~9~~ 8 bytes

```
…___«3ô¨

```

Try it online! or as a Test Suite

**Explanation**

```
…___«      # append "___" to input
     3ô    # split into groups of 3
       ¨   # discard the last group

```
> 10 votes

# Answer
# Python 3, ~~58 47~~ 34 bytes

~~I'm sure someone else can do better~~ Someone else did better. Thanks Jo King for ~~-11~~ -24 bytes!

Output is unrestricted, welcome to tuple hell. Returns empty list (falsy) on empty input

```
lambda x:[*zip(*[iter(x+"__")]*3)]

```

TIO
> 8 votes

# Answer
# JavaScript, 25 bytes

```
s=>`${s}__`.match(/.../g)

```

Try it
> 6 votes

# Answer
# APL+WIN ~~36 24~~ 22 bytes

12 bytes saved as a result of output now being de-restricted and using the code in @Adám's first comment modified to work in APL+WIN and a further 2 with his second comment. Thanks.

```
(⌈(↑⍴s)÷3)3⍴(s←⎕),'__'

```

Prompts for input of the string and outputs the result as a nx3 array

Try it online! Courtesy of Dyalog Classic
> 5 votes

# Answer
# Perl 5, ~~16~~ 15 bytes

```
"@_\__"=~/.../g

```

Try it online!
> 5 votes

# Answer
# JavaScript, ~~51 50 48 27~~ 25

```
b=>(b+"__").match(/.../g)

```

Try it online!
> 4 votes

# Answer
# Perl 6, 19 bytes

```
{$_~"__"~~m:g/.../}

```

Try it online!

Pads the string by two underscores then splits the string into chunks of three characters. Returns as an array of Match objects.
> 3 votes

# Answer
# Japt, 8 bytes

+1 byte to special case the empty string. Can save 2 if we can choose our padding character.

```
©ò3 ú'_3

```

Try it

```
©ò3 ú'_3     :Implicit input of string
©            :Logical AND with
 ò3          :Split into chunks of 3
    ú'_3     :Right pad each with "_" to length 3

```
> 3 votes

# Answer
# Stax, 7 bytes

```
é☻εgP▀╪

```

Run and debug it

For an empty string input, the result is an empty array, which is a falsey value in stax.
> 2 votes

# Answer
# CJam, 11 bytes

```
q'_3*+3/);p

```

Try it online!

For empty input this gives an empty string, which is falsy.

### How it works

```
q     e# Read input as a string
'_    e# Push char '_'
3*    e# String formed by that char repeated 3 times
+     e# Concatenate to input string
3/    e# Split in groups of 3, the last of which may be shorter. Gives array of strings
);    e# Detach last string from the array and delete it
p     e# Print string representation of the array

```
> 2 votes

# Answer
# Retina 0.8.2, 10 bytes

```
$
__
!`...

```

Try it online! Link includes test cases. Explanation:

```
$
__

```

Append two `_`s, in case the last group needs to be padded.

```
!`...

```

Match as many groups of three as possible, outputting the matches themselves rather than the count. (In Retina 1 this would be `L` instead of `!`.)
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~28~~ 21 bytes

-7: No longer requires falsy (`False`) value on empty input

```
Partition[#,3,1,1,_]&

```

Try it online!

Takes a list of characters as input. Returns a list of 3-tuples of characters padded with `Blank`s (`_`).

---

### ~~34~~ 27 bytes

```
StringPartition[#<>"__",3]&

```

Try it online!

String input, list of strings output
> 2 votes

# Answer
# C (gcc), 67 bytes

```
i;f(char*_){for(;*_;puts(""))for(i=3;i--;)putchar(*_?*_++:95);_=0;}

```

Try it online!

Always returns a falsey value (0).
> 2 votes

# Answer
# **Ruby, 73 42 bytes**

```
a=gets
a.length!=0?a.scan(/.{1,3}/).map{|s|(s+'_'*3)[0,3]}:'falsey value'

```

Edit: As falsey value looks like it's not required:

```
gets.scan(/.{1,3}/).map{|s|(s+'_'*3)[0,3]}

```
> 2 votes

# Answer
# C (clang), 128 126 94 67 63 bytes

*63 bytes thanks to @ceilingcat.*

```
f(char*k){for(;*k;k++)printf("%c%c%c\n",*k,*++k?:95,*++k?:95);}

```

Try it online!
> 1 votes

# Answer
# Jelly, 9 bytes

```
s3o€“___”

```

A monadic Link accepting a list of characters which yields a list of lists of characters (an empty input yields empty output).

**Try it online!**

### How?

```
s3o€“___” - Link: list of characters
s3        - split into chunks of three
   €      - for each chunk:
  o       -   OR (vectorises):
    “___” -     list of characters = ['_', '_', '_']

```

Notes:
The  is only necessary to handle the edge case of an empty input.
A full program can drop a trailing , but here we can't do that as the printing behaviour of a full program smashes everything together.

---

Equivalent 9:

```
o3ÐƤ“___”

```

Try it

---

Alternative 9:

```
;“___”s3Ṗ

```

Try it
> 1 votes

# Answer
# , 16 bytes

```
[:}:_3]\'___',~]

```

Try it online!

# K (oK), ~~19~~ 17 bytes

-2 bytes thanks to ngn!

```
{-1_0N 3#x,"___"}

```

Try it online!
> 1 votes

# Answer
# Java 10, ~~116~~ 113 bytes

```
s->{s+="__";int l=s.length()/3,i=l;var r=new String[l];for(;i-->0;)r[i]=s.substring(i*3,i*3+3);return l<1?0>1:r;}

```

Try it online.

Or **~~104~~ 101 bytes** if an empty array instead of `false` is allowed as output..

```
s->{s+="__";int l=s.length()/3;var r=new String[l];for(;l-->0;)r[l]=s.substring(l*3,l*3+3);return r;}

```

Try it online.

**Explanation:**

```
s->{                             // Method with String as both parameter and return-type
  s+="__";                       //  Append two "_" to the input-String
  int l=s.length()/3;            //  Get the length, integer-divided by 3
  var r=new String[l];           //  Create a string-array with that many parts
  for(;l-->0;)                   //  Loop `l` in the range (l, 0]:
    r[l]=                        //   Set the `l`'th value of the array to:
         s.substring(l*3,l*3+3); //   Get the substring of size 3 from index `l*3` from `s`
  return r;}                     //  Return the array

```
> 1 votes

# Answer
## C# (Visual C# Interactive Compiler), 74 bytes

Just append two underscores '\_' at the end of the input to make sure they get printed if the length of the input isn't a factor of 3.

```
s=>Enumerable.Range(0,(s.Length+2)/3).Select(i=>(s+"__").Substring(i*3,3))

```

Try it online!
> 1 votes

# Answer
# Kotlin, 34 bytes

```
{"${it}__".chunked(3).dropLast(1)}

```

Try it online!
> 1 votes

# Answer
# C (gcc), 55 bytes

```
i;f(char*s){for(;i%4|*s;)putchar(++i%4?*s?*s++:95:10);}

```

Try it online!
> 1 votes

# Answer
# Bash, 90 bytes

This uses Bash features rather than a combination of more traditional Bourne shell plus \*nix commands (which one version I created ended up at 205 bytes). I cheated by using the dodge of adding two _ characters to the string.

```
c=;read a;a=${a}__;while (($(echo ${#a})>2));do b=${a:0:3};c=$c\ $b;a=${a#$b};done;echo $c

```

Try it online!
> 1 votes

# Answer
# PowerShell, ~~58~~ 35 bytes

```
$args-split'(...)'-ne''|% *ht 3 '_'

```

-23 bytes thanks to mazzy.

Try it online!
> 1 votes

# Answer
## GNU sed, 27 bytes

```
s:$:__:
s:...:& :g
s: _*$::

```

Try it online!

It gets a bit tricky regarding the empty string input, since sed has no meaning of a falsy value. So to deal with this, I provide you with two possible interpretations of the rules to validate my submission:

---

**A.** You essentially provide nothing as input, not even a trailing newline (as it is the case with all the examples, including that 6 Mb file).

**Usage:**

```
echo -n ""|sed -f script

```

**Output:** nothing is printed, because sed doesn't even run the script without input.

---

**B.** One could consider as falsy value for sed to be an unique string, i.e., returned only when the input is an empty string.

**Usage:**

```
echo ""|sed -f script

```

**Output:**

```
__

```

---

I prefer the first interpretation so much more, as I believe it to be the closest to the intended rule, but the last one helps if you run the script using that TIO link.
> 1 votes

# Answer
# APL(NARS), 30 chars, 60 bytes

```
{(3/⍳3÷⍨≢v)⊂v←⍵,'_'⍴⍨3∣3-3∣≢⍵}

```

test:

```
  f←{(3/⍳3÷⍨≢v)⊂v←⍵,'_'⍴⍨3∣3-3∣≢⍵}
  ⎕fmt f 'abcde'
┌2────────────┐
│┌3───┐ ┌3───┐│
││ abc│ │ de_││
│└────┘ └────┘2
└∊────────────┘
  ⎕fmt f '1234'
┌2────────────┐
│┌3───┐ ┌3───┐│
││ 123│ │ 4__││
│└────┘ └────┘2
└∊────────────┘
  ⎕fmt f ''
┌0──┐
│┌0┐│
││ ││
│└¯┘2
└∊──┘
  ⎕fmt f 'Three spree!'
┌4──────────────────────────┐
│┌3───┐ ┌3───┐ ┌3───┐ ┌3───┐│
││ Thr│ │ ee │ │ spr│ │ ee!││
│└────┘ └────┘ └────┘ └────┘2
└∊──────────────────────────┘

```
> 1 votes

# Answer
# Jelly, 6 bytes

```
s3Zz”_

```

Try it online!

## How it works

```
s3Zz”_ - Main link. Takes a string S on the left
s3     - Split into chunks of 3
  Z    - Transpose
   z”_ - Transpose, using "_" as a filler

```
> 1 votes

# Answer
# Vyxal, 7 bytes

```
3ẇ∩\_ÞṪ

```

Try it Online!

## How?

```
3ẇ∩\_ÞṪ
3ẇ      # Split into chunks of three
  ∩     # Transpose
   \_ÞṪ # Transpose with "_" as filler

```
> 1 votes

# Answer
# Factor \+ `grouping.extras`, 27 bytes

```
[ 3 95 pad-groups 3 group ]

```
> 1 votes

# Answer
# Thunno 2, 5 bytes

```
³'_3Ŀ

```

Try it online!

```
³'_ƬṬ

```

Try it online!

#### Explanation

```
³'_3Ŀ  '# Implicit input
³       # Split into threes
    Ŀ   # Left-justify each,
 '_    '# padding with "_"s
   3    # to length 3
        # Implicit output

```

```
³'_ƬṬ  '# Implicit input
³       # Split into threes
   Ƭ    # Transpose with
 '_    '# filler "_"
    Ṭ   # Tranpose again
        # Implicit output

```
> 1 votes

# Answer
# Haskell, 40 bytes

```
f(a:b:c:t)=[a,b,c]:f t
f _=[]
f.(++"__")

```
> 1 votes

# Answer
# JavaScript (Babel Node), 45 bytes

```
_=>_.match(/.{1,3}/g).map(a=>a.padEnd(3,`_`))

```

Try it online!
> 0 votes

# Answer
# Jelly, 10 bytes

```
s3;€⁾__ḣ€3

```

Try it online!

It feels like an 8 or 9 should be possible, but haven’t found one yet.
> 0 votes

# Answer
# Pyth, 10 9 bytes

```
Pc+z*3\_3

```

Try it online!

-1 from u\_ndefined.

Is it ok if it throws an error on empty input? (does that count as falsey)
> 0 votes

# Answer
# Attache, ~~34~~ 23 bytes

```
PadRight&"_"&3=>@Chop&3

```

Try it online!

## Explanation (outdated)

```
{On[#_-1,PadRight&"_"&3,_]}@Chop&3
                           @Chop&3    chop the input string into groups of 3s
{On[#_-1               ,_]}           on the last group
        ,PadRight                         pad it
                     &3                   to length three
                 &"_"                     with underscores

```
> 0 votes

# Answer
# Charcoal, 10 bytes

```
Ｅ⪪Ｓ³…⁺ι__³

```

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

```
  Ｓ         Input string
 ⪪ ³        Split into groups of up to 3 characters
Ｅ           Map over each group
      ι     Current group
     ⁺      Concatenated with
       __   Literal `__`
    …    ³  Moulded to length 3
            Each group implicitly printed on its own line

```
> 0 votes

# Answer
# Scala, 31 bytes

```
(s+"___").grouped(3).toSeq.init

```

Try it online!

**Explanation**

```
(s+"___")       // add "___"
  .grouped(3)   // make groups of 3
  .toSeq        // change to Seq
  .init         // take all but last

```
> 0 votes

# Answer
# Befunge-93, ~~30~~ 29 bytes

```
~:1+%,~:1+!"`"*+,~:1+!"`"*+,,

```

Try it online!

Outputs nothing for an empty input, otherwise outputs strings of length 3 separated by NUL characters.

Explanation:

```
~                               Push character of input to stack
 :1+                            Duplicate input and add 1
    %                           Modulo top 2 values of stack and push result
                                If input was -1 (end of stream), calculate -1%0 -> halt
                                Otherwise calculate input%(input+1) -> input
     ,                          Pop and output character
      ~                         Push character of input to stack
       :1+!                     Duplicate input, add 1 and perform logical NOT
           "`"*                 Multiply by 96 (ASCII code for '`')
                                This returns 96 or 0 depending on the result of the NOT
               +                Add the top 2 values from the stack and push the result
                                If the input was -1 (end of stream), pushes -1+96=95, or the ASCII code for '_'
                                Otherwise pushes input+0
                ,               Pop and output character
                 ~:1+!"`"*+,    Same block again to handle the third character
                            ,   Output a NUL character (stack is empty, so popping from stack just returns 0)

The instruction pointer wraps around at the end, looping the entire line.

```
> 0 votes

# Answer
# Haskell, ~~62~~ ~~61~~ 59 bytes

```
z(a:b:c:d)=[a,b,c]:z d
f s=takeWhile(/="___")$z$s++cycle"_"

```

Infinite lists and strings!

Try it online!
> 0 votes

# Answer
# Rust, 93 bytes

Works for ASCII input strings. Empties the input string and returns a `Vec<String>`.

```
|mut s:String|{s+="__";let mut v=vec![];while s.len()>2{let t=s.split_off(3);v.push(s);s=t}v}

```

Try It Online
> 0 votes

# Answer
# GoLang, 84 bytes

```
func(x string)[]string{return regexp.MustCompile("...").FindAllString(x+"__",-1)}(s)

```

Try it !
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), 93 bytes

```
	S =INPUT
	S =S DUPL('_',REMDR(3 - REMDR(SIZE(S),3),3))
R	S LEN(3) . OUTPUT REM . S	:S(R)
END

```

Try it online!

SNOBOL has a size limit on the length of its input (1023 bytes).
> 0 votes

# Answer
# Julia 1.0, 40 bytes

```
s->[(s*"__")[i:i+3] for i=1:3:length(s)]

```

Try it online!
> 0 votes

# Answer
# GolfScript, 10 bytes

```
"___"+3/);

```

Try it online!
> 0 votes

# Answer
# Husk, ~~9~~ 6 bytes

```
TT'_C3

```

Try it online!

look ma, no unicode!(-3)

## Explanation

```
TT'_C3
    C3 cut into pieces of 3
 T'_   transpose, padding with underscore
T      transpose again

```
> 0 votes

# Answer
# Ruby, ~~27~~ 21 bytes

```
p"#{$_}__".scan /.../

```

Try it online!

-6 bytes thanks to vrintle
> 0 votes

# Answer
# Uiua SBCS, 8 bytes

```
⬚@_↯¯1_3

```

Try it!
> 0 votes

# Answer
# Nibbles, 8 bytes (16 nibbles)

In literal form:

```
`/3;_<3:$"__"

```

Attempt This Online!

```
`/             chunks of
  3              3 characters
   ;_            for input string
               then, apply map(\chunk->...):
     <3          take first 3 characters of
       :$"__"    concatenation of chunk and "__"

```
> 0 votes

# Answer
# Rattle, 21 bytes

```
\__|!II^/3P[[gb>]3B]`

```

Try it Online!

Outputs groups of 3 separated by newlines.

# Explanation:

```
\__|                  take input and concatenate "__"
    !                 disable implicit output
     I                save characters of the input in consecutive memory slots
      I^              get length of the input
        /3            divide by 3 to get n
          [...]`      loop n times (ignoring any values after the decimal point)

[...]3                loop 3 times
 g                    get the character at the pointer
  b                   add this character to the print buffer
   >                  move pointer right
      B               print contents of buffer and reset

```
> 0 votes

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


# Question
Title: Solving Reverse Polish Notation with GolfScript and Eval Function
I am exploring a unique approach to the classic problem of Reverse Polish Notation on code.golf. Unlike the conventional solutions, my focus lies on leveraging the `eval` function in GolfScript. This twist was inspired by a comment in a related thread, where the absence of `eval` was deemed a limitation.

> "It's a shame no eval is allowed, otherwise the GolfScript solution is 1 character: ~. :-P" – C. K. Young

Despite being intrigued by the idea of solving the problem with minimal characters, I'm encountering challenges in implementing the solution. The specifications, as outlined on code.golf, involve computing a list of arguments in polish notation stored in the stack `n`. The goal is to evaluate and print the result of each expression on a separate line. The expected results are non-negative integers not exceeding 32,767, with guaranteed exact integer results for division.

I am currently attempting a concise GolfScript solution using the `n*` stack initialization for arguments. Following C. K. Young's hint, I have tried variations like `~n*` and `n*~` to no avail. I believe the solution is close but needs some expert insight to refine it further.

If you are well-versed in GolfScript or have experience with similar challenges, I would greatly appreciate your assistance. My goal is to gain a deeper understanding of this fascinating language and unlock the potential of the `eval` function within the constraints of the problem.

# Answer
> The specifications \[...\] involve computing a list of arguments in polish notation stored in the stack `n`.

I think you are slightly misunderstanding the code.golf specification. The input is not a variable `n`, but rather a list of strings already present on the stack when the program begins.

In GolfScript, there is a variable called `n`, but it is not the input to the program; it is a string containing a single newline.

Your attempt `~n*` is pretty close. The problem is that `~` only does `eval` if its argument—the top of the stack—is a string. In this case, the top of the stack is actually a list of strings.

Therefore, you have to use the map `%` function to loop over each element of the list:

```
{~}%

```

Once we have this, we need to join the results on newlines. We can simply do:

```
{~}%n*

```

As I think you figured out already, `n*` means join (`*`) on newlines (`n`).

However, if we use the function each (`/`) instead of map (`%`), we can just push the newline to the stack during each iteration, saving a byte:

```
{~n}/

```

When a GolfScript program has finished execution, the entire stack is printed without a seperator. Here, each `eval`'d result is followed by a newline on the stack, which does the equivalent of joining the list on newlines.

Try the final program on TIO.run!
> 0 votes

---
Tags: code-golf, tips, golfscript
---