title: Count /[^a-z]/ig with /[a-z]/ig

text:
# Question
Title: Count /[^a-z]/ig with /[a-z]/ig
Write a program or function which takes a string of text as input and outputs the number of non-alphabetical characters in it (standard I/O rules apply). A non-alphabetical character is any character not appearing in this string:

```
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

```

In terms of ASCII character codes, that's anything not in ranges 65-90 inclusive or 97-122 inclusive.

## Rules

Your program must be able to handle all of printable ASCII, as well as any characters that appear in your code. In other words, you may assume input will not contain any characters iff they are in neither printable ASCII nor your solution. Printable ASCII here means ASCII's character codes 32-126 inclusive as well as character code 10 (Meaning you *will* have to count spaces and newlines).

You may assume that input will not be empty.

## Scoring

Your score is the number of non-alphabetical characters (not bytes!) in your code. Lowest score wins, with as a tie-breaker.

## Examples

```
"input" => output
"example" => 0
"3xampl3" => 2
"Hello, World!" => 3
"abc.def-" => 2
"     " => 5
"IT'S NORMAL" => 2
"•¥¥€???!!!" => 10
"abc
def" => 1

```

# Answer
# Vyxal, score 0, 4 bytes

```
kLFL

```

Yes, you heard me right. Flagless, score 0, 4 bytes.

## Explanation

```
kLFL
kL    Uppercase and Lowercase alphabet
  F   Filter out the input
   L  Take the length of that

```

Try it Online! | 3 bytes with flag
> 12 votes

# Answer
# Charcoal -v, 36 bytes, score 0

```
CastLengthFilterqNotCountaUppercasei

```

Try it online! Explanation: Charcoal's verbose parser is somewhat lax, not always requiring things like parentheses, spaces, commas, or correct capitalisation. The verbose program would be more conventionally written something like this:

```
Print(Cast(Length(Filter(q, Not(Count(a, Uppercase(i)))))));

```

`q` is the first input, `a` is the predefined variable for the uppercase alphabet and `i` is the default outer loop variable.
> 12 votes

# Answer
# Husk, Score 0, ~~13~~ 11 bytes\*

```
mLfopVDkDma

```

Try it online!

The basic idea is to filter for non-alphabetic characters and calculate the length. Husk has a builtin (`D`) to identify uppercase characters, and we can convert the lowercase characters to uppercase first using `a`. But now we need to filter to keep only falsy elements. This isn't very straightforward in Husk: the builtin 'NOT' command is the (non-alphabetic) `¬` character, so we need to engineer an alternative to this.

This is accomplished here by first grouping elements into lists, and getting the index of the first truthy element of each list (so, lists of truthy elements return `1` and lists of falsy elements return `0` for 'not found'). After this, getting prime factors (`p` command) was the trick: this returns a non-empty list (=truthy) containg a single `0` element for `0`, and an empty list (=falsy) for `1`.
And a few other little tricks to get the length of the resulting single-element list.

Altogether:

```
FYmLfopVDkDma
           m   # Map across each character in the input:
            a  #   convert to uppercase;
         k     # now, group the characters by:
          D    #   are they an uppercase letter?
               #   (zero for non-uppercase letters, ASCII value for uppercase letters);
    f          # now filter this list by:
     o         #   the combination of these two commands:
       VD      #      first index of an uppercase letter (or zero if not found)
      p        #      prime factors of this (so non-empty list for groups of non-letters, empty otherwise)
               # Now we've got a single-element containing all the
               # non-alphabetic characters of the input, or an empty list if there aren't any.
               # We need to get the length of this single element (or zero if there isn't one).
  m            # So: map across this list (it only has one element)
   L           #   getting the element length(s)

               # Output formatting:

F              # Fold across this (single-element) list of lengths,
 Y             #   getting the maximum value (so the value of the only element)

```

---

\*outputs an empty list for zero non-alphabetic characters, and a single-element list containing the number of non-alphabetic characters otherwise. Add 2 bytes (`FY`) to output the number of non-alphabetic characters in a non-listed fashion Try it online!
> 10 votes

# Answer
# 05AB1E, score: 0 (7 bytes)

```
ADuJSKg

```

Try it online or verify all test cases. (The `J`oin in the test suite has been replaced with a concat `«`, because it would otherwise join the input that's already on the stack with it.)

The straight-forward shortest approach would be 3 bytes with a score of 2:

```
áмg

```

Try it online or verify all test cases.

**Explanation:**

```
A       # Push the lowercase alphabet
 D      # Duplicate it
  u     # Uppercase the copy
   J    # Join the two alphabet on the stack together
    S   # Convert it to a list of characters
     K  # Remove all those characters from the (implicit) input-string
      g # Pop and push the length to get the amount of remaining non-letters
        # (which is output implicitly as result)

á       # Only leave all letters of the (implicit) input-string
 м      # Remove all those letters from the (implicit) input-string
  g     # Pop and push the length to get the amount of remaining non-letters
        # (which is output implicitly as result)

```
> 8 votes

# Answer
# Pip, score 0, 8 bytes

```
oMSaRMXA

```

Try It Online!

-3 thanks to DLosc.

```
    RM   # Remove...
      XA # Letters
   a     # From input
 MS      # Sum result when mapping each to...
o        # 1

```
> 8 votes

# Answer
# Pyth, Score 0, ~~14~~ 11 bytes

```
lfqZhxGrTZQ

```

Try it online!

`G` is the lowercase alphabet in Pyth. There's no built-in for the uppercase alphabet, so we convert each letter of the input to lowercase.

**Explanation**

`f ... Q` Filter for elements of the input where...

`xGrTZ` ...the index of the lowercased letter in the lowercase alphabet ...

`h` ...plus one...

`qZ` ... equals 0

(This works because `x` returns -1 for elements not in the string, like in Python)

`l` Length of the resulting list
> 7 votes

# Answer
# , score 9, 38 bytes

```
function(x)sum(!tolower(x)%in%letters)

```

Try it online!

Takes input as a vector of characters.

---

# , score 14, 85 bytes

```
function(x)nchar(gsub("[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]","",x))

```

Try it online!

Takes input as a proper string.
> 7 votes

# Answer
# Burlesque, Score 0, 9 bytes

```
qrdfnsait

```

Try it online!

```
qrd  # Quoted isalpha
fn   # Filter not
sa   # Non-destructive length (ordinary length is L[)
it   # Drop everything but the top of stack

```

Absolute shortest doing the same thing would be:

```
`FrdL[

`F   # Filter not
rd   # isalpha
L[   # Length

```

For fun, the inverse challenge:

```
^^ ^^ ^^ ^^ ^^           # Create 5 copies
).%++\/                  # Count isPunctuation; add; swap
).*++.+\/                # Count isSymbol; add; swap
)<>++.+\/                # Count isDigit; add; swap
" "~?)-])**++32./.+\/    # Count spaces; add; swap (is whitespace is "ra")
"   "~?)-])**++9./.+\/   # Count tabs; add; swap
"
"~?)-])**++10./.+        # Count newlines; add; swap

```

Try it online!
> 7 votes

# Answer
# Haskell, score 6, 81 bytes

```
length.filter(flip notElem"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

```

Try it online!

The non-alphabetic characters are `.( "")`.

Also score 6, but 4 bytes longer is:

```
fmap length$filter$flip notElem"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

```

Try it online!
> 6 votes

# Answer
# Java, score: 14 (46 bytes)

```
s->s.filter(c->!Character.isLetter(c)).count()

```

Input as a Character-stream.

Doesn't work if the input contains non-ASCII letters (e.g. `é`), but that's allowed according to the challenge rules.

Try it online.

**Explanation:**

```
s->                          // Method with IntStream parameter & long return
  s.filter(c->               //  Filter the character of the input-stream by:
     !Character.isLetter(c)) //   It's NOT a letter
   .count()                  //  Count how many are left

```
> 6 votes

# Answer
# Factor, score 5 (82 bytes)

```
readln "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"without length pprint

```

Try it online!

For once I can get a better score by reading from standard input!
> 6 votes

# Answer
# JavaScript (in Browser), Score 4, 120 bytes

```
eval(atob`ZXZhbCgicyAgPSIrICAiPnMubWEiKyAidGNoKCIrICIvWyIrICAiXmEtekEtWiIrICJdLyIrImcpPyIrICIubCIrImVuZyIrInRoIHwgMCIp`)

```

```
f =  eval(atob`ZXZhbCgicyAgPSIrICAiPnMubWEiKyAidGNoKCIrICIvWyIrICAiXmEtekEtWiIrICJdLyIrImcpPyIrICIubCIrImVuZyIrInRoIHwgMCIp`)

console.log(f("example"      )) // 0
console.log(f("3xampl3"      )) // 2
console.log(f("Hello, World!")) // 3
console.log(f("abc.def-"     )) // 2
console.log(f("     "        )) // 5
console.log(f("IT'S NORMAL"  )) // 2
console.log(f("•¥¥€???!!!"   )) // 10
console.log(f("abc\ndef"     )) // 1

console.log(f("eval(atob`ZXZhbCgicyAgPSIrICAiPnMubWEiKyAidGNoKCIrICIvWyIrICAiXmEtekEtWiIrICJdLyIrImcpPyIrICIubCIrImVuZyIrInRoIHwgMCIp`)"))
```

In readable form:

```
s=>s.match(/[^a-zA-Z]/g)?.length|0

```
> 6 votes

# Answer
# CJam, score 0, ~~95~~ ~~89~~ 82 bytes

```
qeuWcibWcibKAbFbAbHbAbIbfbXfbKBbKbAbDbAbKbfbKYbKbYbCbfbXdfmdUfmOGYbCbfbUfbXfbUfbXb

```

Try it.

### Explanations

```
qeu                       e# Read input and convert to upper case.
65535b65535b              e# Convert to base 65535 and back, to cast characters to integers.
91fb                      e# Convert each element to base 91.
1fb                       e# Sum the digits in each element.
                          e# Only letters would end up greater than or equal to 65.
65fb                      e# Convert each element to base 65.
2220010939706446080fb     e# Convert each element from base 2.22e18.
1dfmd                     e# Divmod each element by floating point 1 to cast to floating point.
                          e# All letters would become the same number due to floating point inaccuracy.
                          e# It will also generate some extra 0s as the remainder but doesn't matter.
0fmO                      e# Cast elements back to integers.
20736fb0fb                e# Convert each element to base 20736 and get the last digit.
                          e# 20736 is a divisor of the number about 2.2e18,
                          e# so the last digit generated from a letter would be 0.
1fb0fb                    e# Convert each element to unary and get the last digit.
1b                        e# Sum the elements.

```

With the constants:

```
0        U
1        X
65       KBbKbAbDbAbKb    Convert 20 to base 11 (=19), from base 20 (=29), to base 10,
                            from base 13 (=35), to base 10, from base 20.
91       KAbFbAbHbAbIb    Convert 20 to base 10, from base 15 (=30), to base 10,
                            from base 17 (=51), to base 10, from base 18.
*170     AZbDb            Convert 10 to base 3 (=101), from base 13.
*196     GZbDb            Convert 16 to base 3 (=121), from base 13.
20736    GYbCb            Convert 16 to base 2, from base 12.
65535    Wci              Cast -1 to character, then back to integer.
2.22e18  KYbKbYbCb        Convert 20 to base 2, from base 20, to base 2, from base 12.

*Only used in an old version.

```

It depends on floating point inaccuracy. The number 2.22e18 won't change if a small number less than 26 is added to it.

CJam has a bug using divmod on a too big high precision integer and a float.
> 6 votes

# Answer
# Zsh, score 6, 64 bytes

```
tr -d abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ|wc -c
```

Attempt This Online!
> 5 votes

# Answer
# brainfuck, 110 bytes

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

```

Try it online!

Accepts input as ASCII. outputs as binary. The header adds 48 (ASCII 0) to the count so that small outputs appear as ASCII digits.

This is a complete rewrite of my previous answer below, taking into account everything I could have done better. In particular, I set up a specific cell with a 1 in it to help with the IF operation instead of trying to use other nonzero cells to assist.

There are a few more bytes to save with this approach if I have time later. It's still the highest scoring answer, but it isn't the longest anymore, which is gnerally as good as it gets with Brainfuck.

```
+>>                     Put a 1 in cell 0 then move to cell 2
,[                      take an input in cell 2 and loop until end of string marked by 0 encountered
<++++[----->>->+>+<<<<] Put 260 mod 256=4 in cell 1; iterate 260/5=52 times to subtract 52 from cell 3 and store 52 in cells 4 and 5
----[---->-<]>-         Put minus 4 = 252 in cell 1; iterate 252/4=63 times to subtract 63 from the input; then reduce by one more
>+>                     add 1 to cell 3
[--<<-[<]<[>>>+<<]>>>]  iterate 26 times UPPERCASE using 52 in cell 4; if not zero add 1 to cell 3
<<------>>>             subtract 6 from the input
[--<<<-[<]<[>>>+<<]>>>>]iterate 26 times LOWERCASE using 52 in cell 5; if not zero add 1 to cell 3
<<<                     overall cell 3 has increased by 0 if input is a letter or 1 if not a letter
,]                      take more input into cell 2 until end of string marked by 0 encountered
>.                      output count from cell 3

```

# brainfuck,  ~~146~~  138 bytes

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

```

I misread the question and assumed all characters except `AZaz`and newline should be counted. I now realise newlines need to be counted like any other non `AZaz` character which makes the code slightly shorter. If I had not considered newlines at all, the code might be shorter still, but the setup loop 260/5=52=2\*26 is pretty efficient.

Try it online!

Accepts input as ASCII. outputs as binary. The header adds 48 (ASCII 0) to the count so that small outputs appear as ASCII digits.

**Commented code**

```
,[                        Take an input; If nonzero start looping
<++++                     Move left and add 4 to make (256+4)=260 mod 5
[-----<-<+<+<+>>>>]>      Loop 52 times to setup 3 cells with 52 and one with minus 52
----------<               Subtract 10 from input
<<<<[->>>>>-<<<<<]>>>>>-- Subtract another 52+2=54 from the input
<<<<[-->>>>-              Loop 52/2=26 times reducing the input by 1 each time for UPPERCASE
  [<]<[+>]                If the input is nonzero increment the cell that contained minus 52
<<<]                      Ultimately the cell with minus 52 will be incremented 51 times for AZaz 52 for other
>>->>------               Subtract 1 from cell that contained minus 52 to avoid it reaching 0; and 6 from input
<<<[-->>>-                Loop 52/2=26 times reducing the input by 1 each time for LOWERCASE
  [<]<[+>]                If the input is nonzero increment the cell that contained minus 52
<<]
>++                       Cell that contained minus 52 now has minus 2 for AZaz or minus 1 for other; increment by 2
[->>>+<<<]                Copy the value 0 or 1 into the final total
>>,]                      Take the next input and if nonzero continue to loop
>.                        Output the final total

```
> 5 votes

# Answer
# Perl 5 `-F/[^a-z]/si -0`, score ~~5~~ 2 (6 bytes)

*@DomHastings saves 3 points*

```
say$#F

```

Try it online!

Abusing the command line flags for all they're worth. The `-F` flag with its regex breaks the input apart on anything that isn't a letter and stores those fields in @F. Therefore, there is one element added to @F for each nonalphabetic character. `-0` grabs all of the input at once (slurp mode). The actual code code outputs the last index of @F since there will always be at least one member of @F (assuming input is not null).
> 5 votes

# Answer
# Jelly, score 3, 4 bytes

@caird-coinheringaahing saves 1 byte!

```
ḟØẠL
```

Attempt This Online!

**Explanation:** Filter alphabetic characters from input, then return length
> 5 votes

# Answer
# Wolfram Language (Mathematica), score 5, 39 bytes

```
sStringLength@s-Total@LetterCounts@s

```

Try it online!

Doesn't work if the input contains non-ASCII letters (e.g. `այբուբեն`).

The private-use character  is `\[Function]`.
> 4 votes

# Answer
# Rust, score 14, 42 bytes

```
|s|s.replace(char::is_alphabetic,"").len()
```

Attempt This Online!

Only works for ASCII inputs, because `str::len` is counting bytes instead of characters.
> 4 votes

# Answer
# Perl 5 \+ `-n0 -M5.10.0`, Score: 3, 14 bytes

```
say s M\PlMMig
```

Try it online!
> 4 votes

# Answer
# Alumin, Score 0 (82 bytes)

```
iqipkmddhhdtddtthaueyddhhhdtdhatveyddhhhhhhhdthhthcueydhhhdhathcdthavetrtahycmzfaf

```

Try it online! I thought this would be a funny submission, since it is almost impossible to get a score of anything more than 0 without introducing no-ops, since the only defined operations are the lowercase English alphabet. (Technically, you would use a space to separate two integer sequences in a row, but you can golf around that if necessary, and it didn't come up here.)

## Commented code

```
i                       PUSH INPUT CHARACTER
q                       WHILE TOP OF STACK > 0 {
  i                         PUSH INPUT CHARACTER
p                       }
k                       DISCARD EOF
m                       MAP EACH STACK ELEMENT OVER {
                            OUR STACK CONSISTS OF JUST A CHARACTER
  dd                        DUPLICATE INPUT TWICE
  hhdtddttha                PUSH (2*2)*(2*2)*(2*2)+1
                            (AKA 65)
  ue                        PUSH MAX(INPUT, 65) == INPUT
                            (AKA INPUT >= 65)
  ydd                       DUPLICATE INPUT TWICE
  hhhdtdhat                 PUSH (3*3)*((3*3)+1)
                            (AKA 90)
  ve                        PUSH MIN(INPUT, 90) == INPUT
                            (AKA INPUT <= 90)
  ydd                       DUPLICATE INPUT TWICE
  hhhhhhhdthhthc            PUSH (7*7)*2-1
                            (AKA 97)
  ue                        PUSH MAX(INPUT, 97) == INPUT
                            (AKA INPUT >= 97)
  yd                        DUPLICATE INPUT ONCE MORE
  hhhdhathcdtha             PUSH ((3*(3+1))-1)*((3*(3+1))-1)+1
                            (AKA 122)
  ve                        PUSH MIN(INPUT, 122) == INPUT
                            (AKA INPUT <= 122)
                            STACK NOW LOOKS LIKE:
                            [B1 B2 B3 B4]
  t                         PUSH AND(B3, B4)
  r                         REVERSE STACK
                            [AND(B3,B4) B2 B1]
  t                         PUSH AND(B2, B1)
  a                         PUSH OR(AND(B3,B4), AND(B2, B1))
  hyc                       PUSH NOT(^)
                            (AKA 0 FOR ALPHABETIC, 1 ELSE)
m                       }
zf                      FOLD ENTIRE STACK USING SEED 0 {
  a                         ADD TOP TWO
f                       }

```

Not 100% sure the constants are optimal, but for now I'm satisfied.
> 4 votes

# Answer
# Retina 0.8.2, 55 bytes, score 3

```
[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]

```

Try it online! Link includes test suite, so final example with newline isn't included. Try it online! Final example only.
> 3 votes

# Answer
# Python 3, score 11, 39 bytes

```
lambda s:sum(not x.isalpha()for x in s)

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), Score 12 (64 bytes)

*-1 point thanks to @l4m2*

```
s=>s.replace(/[abcdefghijklmnopqrstuvwxyz]/gi,new String).length

```

Try it online!
> 3 votes

# Answer
# C (gcc), Score 16 (48 bytes)

```
main(c){return~c?!isalpha(c)+main(getchar()):c;}

```

Try it online!
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 11 Score, 32 bytes

```
s=>s.Count(c=>!char.IsLetter(c))

```

Try it online!
> 3 votes

# Answer
# PowerShell Core, 59 bytes, score: 8 ~~10~~

```
$input-replace"[abcdefghijklmnopqrstuvwxyz]"|foreach Length

```

Try it online!

*-2 bytes thanks to user314159*
> 3 votes

# Answer
# Wolfram Language (Mathematica), score 4, 40 bytes

```
ss~StringCount~Except@LetterCharacter

```

Try it online!
> 3 votes

# Answer
# Python 2, score 9, 40 bytes

```
lambda s:map(str.isalpha,s).count(False)

```

Try it online!
> 3 votes

# Answer
# APL (APLX) Score 6, 8 bytes

```
⍴⍞∼⎕A,⎕a

```

shape of…

input…

`~` without…

`⎕A` upper case **A**lphabet…

`,` and

`⎕a` lowercase **a**lphabet
> 3 votes

# Answer
# Japt, score: 2, 5 bytes

```
;eF l
;     // Alternative initial variables, where F = "[A-Za-z]".
 eF   // Replace all occurrences of F in input with default value of empty string.
    l // Return the result's length.

```

Try it here.
> 2 votes

# Answer
# APL (NARS2000) Score 19, 31 bytes

`{≢⍵~⎕av[C,32+C←66..91]}`

## Examples

`{≢⍵~⎕av[C,32+C←66..91]} 'Hello, World!'` evaluates to `3`

`{≢⍵~⎕av[C,32+C←66..91]} '•¥¥€???!!!'` evaluates to `10`

## How it works

`⎕av[C,32+C←66..91]` generates the alphabetic string from built-in `⎕av` array. `~` performs set difference with right argument .  counts number of element in the set difference.

Score of this expression could be determined by applying it to itself:

`⎕fmt {≢⍵~⎕av[C,32+C←66..91]} '{≢⍵~⎕av[C,32+C←66..91]}'` evaluates to `19`.
> 2 votes

# Answer
# BQN, Score: 8, 60 bytes

```
+´¬∘∊⟜"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

```

Try it here!

Thanks to @thejonymyster for helping halve the score!... Of course at the cost of tripling the byte count ;D

# Explanation

* `¬∘∊⟜"..."` replace each char in input with 0 if alphabetical, 1 otherwise
* sum occurrences of 1
> 2 votes

# Answer
# Ruby, score 5, 67 bytes

```
p gets.count"^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
```

Attempt This Online!
> 2 votes

# Answer
# Alice, 32 bytes, score ~~24~~ 9

```
/qlqaq"q&qcqqqo
qIq"qzqrq-q/d\q@

```

Try it online!

# Explanation

All the `q` are useless and replace spaces to lower the score, leaving us with the following:

```
/                 Switch to ordinal mode
 Il               Read the input, lowercase
   "az"r          Build the alphabet string
        &-        For each character of the alphabet, remove it from the input
          c       Split into characters
           /      Back to cardinal mode
            d     Get the depth of the stack (the remaining characters non a-z)
             \o@  Print the depth

```
> 2 votes

# Answer
# Ruby, Score: 24, 42 bytes

```
->s{s.chars.map{_1=~/[A-Za-z]/?0:1}.sum-1}
```

Attempt This Online!

There is a -1 the end due to the \n. If you don't coun't it, it's 40 bytes and Score: 22
> 1 votes

# Answer
## Brev, score 13

```
((fn (string-length (strse x 'alpha ""))) "(fn(string-length(strse x 'alpha \"\")))")

```
> 1 votes

# Answer
# Japt v2.0a0, Score 2 (3 bytes)

```
è\L

```

Try it
> 1 votes

# Answer
# Fig, score 0, \\$4\log\_{256}(96)\approx\\$ 3.292 bytes

```
LFcB

```

Try it online!

Exact port of Vyxal. Beats it too :P
> 1 votes

# Answer
# Go, score 30, 85 bytes

```
import."unicode"
func f(s[]rune)(c int){for _,e:=range s{if!IsLetter(e){c++}}
return}

```

Attempt This Online!
> 1 votes

---
Tags: string, counting, alphabet, self-scoring
---


title: Tips for golfing in APL

text:
# Question
Title: Tips for golfing in APL
I started one code golf challenge recently and it seems like the winner is GolfScript (surprise, surprise!). What's interesting is that there was another very strong competitor that had all chances to win over GolfScript. Its name is APL. I see a lot of answers written in APL here. It seems like this language is fairly efficient for code golfing, so I decide to ask for any code golfing tips you know for APL programs. Feel free to post some code examples. It is usually very interesting to see language in action.

# Answer
> 28 votes
**Edit**: for people reading this who don't know APL at all but want to take it up, Mastering Dyalog APL is a *very* good resource.

1. Evaluation is strictly right-to-left. This includes setting variables, so take advantage of it.

`2+a, 1+a←1` -\> `3 4`

`a` is set to `1`, `1+a` evaluates to `2`, `a,2` evaluates to `1 2` and `2+1 2` evaluates to `3 4`.
2. Like C,  can be combined with a function, i.e. `a +← 3`. Unlike C, this is generic: `foo F← bar` sets `foo` to `F bar`. Somewhat unintuitively, as an expression this returns `bar`, not `F bar`.

It works with anonymous functions too:

```
       a←0
       a+←3 ⋄ a
 3
       a+←3 ⋄ a
 6
       a { ⍵/'!' } ←4 ⋄ a
 !!!!

```
3. You can assign to an array: `A[3]←8`, like you'd expect. But you can also assign multiple items at the same time: `A[3 5 6]←9 1 4`, or even `A[3 5 6]←9`, setting them all to the same item. You can, of course, add a function to the  here too. The function will then be applied to each element separately, as if you did .
4. is your friend, even if he doesn't look too happy about it.

1. If `F` is dyadic, dyadic  switches the arguments: `a F b` \<-\> `b F⍨ a`. This comes in handy when golfing because it can save you from using braces:

    ```
    (F G H x) K y      <->     y K⍨ F G H x

    ```

    This does change the evaluation order, as the right hand is always evaluated before the left hand.
    2. If `F` is dyadic, *monadic*  applies the same argument to both sides of the function:

    ```
          5⍴5
    5 5 5 5 5
          ⍴⍨5
    5 5 5 5 5

    ```

    The argument is only evaluated once. This particularly comes in handy with outer products, i.e. to compare each value in an array with the other values in the same array, you can use `∘.=⍨` instead of having to do `x∘.=x←(whatever)`.
    3. If `F` is monadic,  does nothing, but it does separate the function from the argument. So it can still save you braces if the function is complex:

    ```
          {⍵+3}⍣5 6
          ∇{⍵+3}
         ∇ ⍣ 5 6
          ({⍵+3}⍣5)6
    21
          {⍵+3}⍣5⍨6
    21

    ```
5. Learn the idioms! Then golf the idioms. For example:

```
 ((((1↑⍴X),⍴Y)↑X)^.=Y)⌿X

```

can be mechanically transformed into:

```
 X⌿⍨Y^.=⍨X↑⍨(1↑⍴X),⍴Y

```

and then further into:

```
 X⌿⍨Y^.=⍨X↑⍨(⊃⍴X),⍴Y

```

(first) being equivalent to `1↑` (take one) in this case. And possibly:

```
 X⌿⍨Y^.=⍨X↑⍨(≢X),⍴Y

```

(tally) being equivalent to `⊃⍴` (the first element of the shape) for all but scalars.

# Answer
> 19 votes
# Trains

```
A(f g h)B      ←→  (A f B)g A h B  ⍝ fork
 (f g h)B      ←→  (  f B)g   h B  ⍝ fork
A(  g h)B      ←→         g A h B  ⍝ atop
 (  g h)B      ←→         g   h B  ⍝ atop
 (A g h)       ←→  ({A} g h)       ⍝ "Agh" fork
 (f g h k)     ←→  (f (g h k))     ⍝ 4-train
 (f g h k l)   ←→  (f g (h k l))   ⍝ 5-train, etc
 (f g h k l m) ←→  (f(g h(k l m))) ⍝ groups of 3 from the right, last could be 2
  f∘g B        ←→    f g B         ⍝ "compose" operator, useful in trains
A f∘g B        ←→  A f g B

```

# Answer
> 11 votes
# Use  to combine multiplication with addition

```
(a×b)+C  ->  a⊥b,C
(C)+a×b  ->  a⊥b,C
(a×b)-C  ->  a⊥b,-C

```

Assumptions:

* `a` and `b` are terms that don't require further parentheses when used as a left argument
* `C` is an expression that may need parentheses when used as a left argument
* `a` `b` `C` evaluate to numeric scalars

# Answer
> 10 votes
## Tricks for dealing with `/` and  in trains

When using trains you may want to use reductions `f/` like sum `+/` or even replicate reduction `//` . However, if your train has more parts to the left of the reduction you need parentheses to create an atop. Here are some tricks to save bytes.

### Use `1∊` instead of monadic `∨/` or `∨⌿` on Boolean arrays

Task: Given two equal-length strings A and B, return 2 if any corresponding characters of A and B are equal, 0 otherwise. E.g. `A←'abc'` and `B←'def'` gives `0` and `A←'abc'` and `B←'dec'` gives `2`.

A dfn solution may be `A{2×∨/⍺=⍵}B` but you want to shorten it by going tacit. `A(2×∨/=)B` is not going to work because the rules of train formation parse this as `2 (× ∨/ =)` but you want `2 × (∨/=)` .

Observe that `∨/` or `∨⌿` on a Boolean vector (`∨/,` or `∨⌿,` for higher rank arrays) asks whether there is any 1 present, i.e. `1∊` , so we can write our train as `2×1∊=` .

Note that  ravels its right argument, so you cannot use it to reduce each row or column separately.

### Use `1⊥` instead of monadic `+/` or `+⌿`

Task: Given a list of lists L and an index N, return thrice the sum of the Nth list. E.g. `L←(3 1 4)(2 7)` and `N←1` gives `24`.

A dfn solution may be `N{3×+/⍺⊃⍵}L` but you want to shorten it by going tacit. `N(3×+/⊃)L` is not going to work because the rules of train formation parse this as `3(× +/ ⊃)` but you want `3 × (+/⊃)` .

Observe that evaluating a list of numbers in unary (base-1) is equivalent to summing the list because ∑{*a*, *b*, *c*, *d*} = *a* \+ *b* \+ *c* \+ *d* = (*a* × 1³) + (*b* × 1²) + (*c* × 1¹) + (*d* × 1⁰). Therefore `+/a b c d` is the same as `1⊥a b c d` , and we can write our train as `3×1⊥⊃` .

Note that on higher-rank arguments, `1⊥` is equivalent to `+⌿`.

### Use `f.g` instead of `f/g` with scalar and/or vector arguments

Task: Given a list L and a number N, return the range 1 thorough the number of minimum division remainder when the elements of L are divided by N. E.g. `L←31 41 59` and `N←7` gives `1 2 3`.

A dfn solution may be `N{⍳⌊/⍺|⍵}L` but you want to shorten it by going tacit. `N(⍳⌊/|)L` is not going to work because the rules of train formation parse this as `⍳ (⌊/) |` but you want `⍳ (⌊/|)` .

The inner product `A f.g B` of scalar two functions when the arguments are scalars and/or vectors is the same as `f/ A g B` because both are `(A[1] g B[1]) f (A[2] g B[2]) f (A[3] g B[3])` etc., so we can write our train as `⍳⌊.|` .

Note that this does not work for higher-rank arrays.

### Use `∊⊆` instead of `/` with Boolean left and simple vector right arguments

Task: Given a list L and a number N, filter the list so that only numbers greater than N remain. E.g. `L←3 1 4` and `N←1` gives `3 4`.

A dfn solution may be `N{(⍺<⍵)/⍵}L` but you want to shorten it by going tacit. `N(</⊢)L` is not going to work because the binding rules will parse this as `(</) ⊢` but you want `/` to be the function *replicate* rather than the operator *reduce*.

Dyadic  with a Boolean left argument partitions the right argument according to runs of 1s in the left argument, dropping elements indicated by 0s. This is almost what we want, save for the unwanted partitioning. However, we can get rid of the partitioning by applying monadic . Thus `{(⍺<⍵)/⍵}` can become `{∊(⍺<⍵)⊆⍵}` and thus we can write our train as `∊<⊆⊢` .

Note that this does not work for higher-rank arrays.

### Use `∊⍴¨` instead of `/` with non-Boolean left and simple vector right arguments

Task: Given a list L, replicate Nth item N times. E.g. `L←3 1 4` gives `3 1 1 4 4 4`.

A dfn solution may be `{(⍳⍵)/⍵}L` but you want to shorten it by going tacit. `(⍳/⊢)L` is not going to work because the binding rules will parse this as `(⍳/) ⊢` but you want `/` to be the function *replicate* rather than the operator *reduce*.

Dyadic  combined with `¨` copies each element of the right argument according to the matching element in the left argument. This is almost what we want (e.g. `1 2 3⍴¨3 1 4 → (3)(1 1)(4 4 4)`). Then, we can get rid of the nesting by applying monadic . Thus `{(⍳⍵)/⍵}` can become `{∊(⍳⍵)⍴¨⍵}` and thus we can write our train as `∊⍳⍴¨⊢`.

Note that this does not work for higher-rank arrays.

### Use `0⊥` instead of `⊢/` or `⊢⌿` with numeric arguments

Task: Given a list L and a number N, multiply the N with the rightmost element of L. E.g. `L←3 1 4` and `N←2` gives `8`.

A dfn solution may be `N{⍺×⊢/⍵}L` but you want to shorten it by going tacit. `N(⊣×⊢/⊢)L` is not going to work because the rules of train formation parse this as `⊣ (× ⊢/ ⊢)` but you want `⊣ × (⊢/⊢)` .

Observe that `0⊥` on a numeric array is the same as `⊢⌿` , so we can write our train as `⊣×0⊥⊢` .

Note that this selects the last major cell of higher-rank arrays.

# Answer
> 10 votes
# Complex numbers

Often overlooked, they present wonderful opportunities to shorten expressions dealing with grids, mazes, fractals, or geometry.

```
0j1⊥¨    0j1⊥   ⍝ pair(s) of reals -> complex
11 9∘○¨  11 9○  ⍝ complex -> pair(s) of reals
|z0-z1          ⍝ distance between two points
0j1×z   0j¯1×z  ⍝ rotate by ±90° around (0,0)
0j1*⍳4          ⍝ the four cardinal directions
+z       -+z    ⍝ reflect across x or y axis
+\0,z           ⍝ sequence of steps -> path
¯2-/z           ⍝ path -> sequence of steps
0j1⊥¨n-⍳2⍴1+2×n ⍝ lattice centred on (0,0)

```

# Answer
> 7 votes
# Indexing modulo vector length

`⊃i⌽a` is often shorter than the naive `⊃a[(≢a)|i]` or `a⊃⍨i|⍨≢a` (where `a` is a vector and `i` is an integer, and `⎕io` is 0)

a useful variation on this (thanks EriktheOutgolfer for pointing out) is: `I↑Y⌽⍨I×X` where `Y` is the concatenation of some length-`I` vectors and `X` is the index of the one we want to pick, for instance: `3↑'JanFeb...Dec'⌽⍨3×month`

# Answer
> 7 votes
# Generate A001057, A130472, and many variations

A001057 is a simple sequence of alternating integers, starting with `0, 1, -1, 2, -2, 3, -3, ...`. A130472 is its negation, `0, -1, 1, -2, 2, -3, 3, ...`.

APL has a surprisingly short way to generate `n`th term or first `n` terms:

### nth term of A001057 (0-indexed)

```
⎕IO←1
-/⍳

```

Try it online!

### nth term of A130472 (1-indexed)

```
⎕IO←0
-/⍳

```

Try it online!

### first n terms of A001057, leading 0 removed (`1, -1, 2, -2, ...`)

```
⎕IO←1
-\⍳

```

Try it online!

### first n terms of A130472 (`0, -1, 1, -2, 2, ...`)

```
⎕IO←0
-\⍳

```

Try it online!

Applying various primitive functions to these sequences can give many interesting results which are shorter than other alternatives:

* `1, 1, 2, 2, 3, 3, ...`: With `⎕IO←1`, `|-\⍳n` is shorter than `n↑2/⍳n` in explicit form
* `0, 1, 1, 2, 2, 3, ...`: With `⎕IO←0`, `|-\⍳n` is shorter than `⌈2÷⍨⍳n` in explicit form
* `0, 1, 0, 2, 0, 3, ...`: With any `⎕IO`, `|0⌊-\⍳n` or `-0⌊-\⍳n` is shorter than any known alternatives, both tacit and explicit
* `0, -1, 0, -2, 0, -3, ...`: With any `⎕IO`, `0⌊-\⍳n`
* `1, 0, 2, 0, 3, 0, 4, ...`: With `⎕IO←1`, `0⌈-\⍳n`
* `0, 1, 1, 0` repeated: With `⎕IO←0`, `2|-\⍳n`
* `1, 1, 0, 0` repeated: With `⎕IO←1`, `2|-\⍳n`
* Reverse odd then forward even, e.g. `7 → 5 3 1 0 2 4 6`: `⍋-\⍳n` with `⎕IO←0`. `⎕IO←1` gives `7 → 6 4 2 1 3 5 7`.
* Permutation of 0 to `n-1`, alternating front and end, e.g. `7 → 0 6 1 5 2 4 3`: `n|-\⍳n` with `⎕IO←0`.
* First n terms of A002620, `0, 1, 2, 4, 6, 9, 12, 16, 20, ...`: `-\-\⍳n` with `⎕IO←0` (`⎕IO←1` gives same sequence with leading zero removed), which is shorter than `⌊×⍨2÷⍨⍳n` with `⎕IO←1`.

# Answer
> 5 votes
# Use

### Avoid parentheses

(Commute) can save you bytes by avoiding parentheses. Whenever you have a function where the left argument needs to be parenthesised and the right argument does not, you can save a byte, e.g. `(A<B)÷C``C÷⍨A<B`.

### Double arrays

To append a copy of an array to its end, use `,⍨A` or `⍪⍨A`.

### Double numbers

Instead of using `2∘×` to double, you can use `+⍨` since it adds the argument to itself: `1+2∘×``1++⍨`.

### Square numbers

Instead of using `2*⍨Y` to square, you can use `×⍨Y` since it multiplies the argument with itself: `2*⍨A+B``×⍨A+B`.

### Random permutation

`?⍨N` will give you a random permutation of length `N`.

### Self-classify

Find the indices of the first occurrence of each major cell with `⍳⍨A`

### Count trailing 1s in a Boolean vector

Instead of `+/∧\⌽B` to count how many trailing 1s there are in `N` you can use `⊥⍨`.

### Reverse composition

`A f∘g B` is `A f g B`, but if you want `(g A) f B`, use `f⍨∘g⍨`.

### Reverse reduce

`f/ a1 a2 a3` is `a1 f (a2 f a3)`. If you want `(a1 f a2) f a3`, use `f⍨/⌽`.

### Reverse scan

`f\ A B C` is
`A (A f B) (A f (B f C))`.

`f⍨/∘⌽¨,\ A B C` is
`A (A f B) ((A f B) f C)`.

`f⍨\⌽ A B C` is
`((A f B) f C) (B f C) C`.

`⌽f/∘⌽¨,\⌽ A B C`. is
`(A f (B f C)) (B f C) C`.

# Answer
> 5 votes
# Generate all nonempty subsequences

I recently discovered the expression `(⊢,,¨)\` in this answer. If applied to a simple numeric or char vector, it does the following:

* `(⊢,,¨)/ v` gives all subsequences of `v` which include the last item.

```
  (⊢,,¨)/ '1234'
→ '1' (⊢,,¨) '2' (⊢,,¨) '3' (⊢,,¨) '4'
→ '1' (⊢,,¨) '2' (⊢,,¨) '4' '34'
→ '1' (⊢,,¨) '4' '34' '24' '234'
→ '4' '34' '24' '234' '14' '134' '124' '1234'

```
* `(⊢,,¨)\ v` applies `(⊢,,¨)/` to each prefix of `v`, giving all non-empty subsequences as a list of lists of vectors.

```
  (⊢,,¨)\ '1234'
→ '1' ('2' '12') ('3' '23' '13' '123') ('4' '34' '24' '234' '14' '134' '124' '1234')

```

The result can be flattened once using `⊃,/`, which gives the list of nonempty subsequences.

The order is the one imposed by the binary digits of `0..2^n-1`, grouped by the last item. You can use it whenever it suffices to generate all subsequences *in any order*. An interesting feature is that the original vector comes last, so you can also test e.g. "the original satisfies something but any smaller subsequence doesn't" using `</`.

Note that the order is different from plain binary/lexicographic/shortlex order, so it is hard to use when the challenge requires specific ordering of subsequences.

A nice application of this trick is "extract all subsequences of digits of a number": `⍎⍕(⊢,,¨)\⍕n`. Figuring out how it works is left as an exercise to the reader. :)

---

`(⊢,,¨)/` can be used to generate all subsequences (including empty), with the same order as binary order:

```
 ¯1↓¨¨(⊢,,¨)/'1234',0
→ '' '4' '3' '34' '2' '24' '23' '234' '1' '14' '13' '134' '12' '124' '123' '1234'

```

It's longer than the scan version, but it fits in a train better and might be useful when the order is important.

# Answer
> 4 votes
# Enumerate the characters in a string without `⍳≢`

Task: Given two strings, S and T, list the indices of their concatenation. E.g. `S←'abcd'` and `T←'xyz'` gives `1 2 3 4 5 6 7`.

A dfn solution may be `S{⍳≢⍺,⍵}T` but you want to shorten it by going tacit. `⍳≢,` is not going to work because the train parsing rules will parse this as `(⍳)≢(,)` but you want `(⍳≢),`.

Dyadic  with an empty left argument grades simple character arrays according to their current order, which is the same as `⍳≢`. Thus `{⍳≢⍺,⍵}` can become `{⍬⍋⍺,⍵}` , so we can write our train as `⍬⍋,` .

Note that this does not work for numeric or mixed arrays.

# Answer
> 4 votes
# Constant functions

`=⍨` and `≠⍨` thanks to ngn.

Sometimes you just need a single value for each element of a list. While you might be tempted to use `{value}¨` (it is shorter to use `value⊣¨` or `value⍨¨`), you can get even shorter (using `⎕IO←0`) for some common values:

`¯1`s with `⍬⍸list`

`0`s with `⍬⍳list`

`1`s with `⍬⍷list`

Note that these only work on lists (though they may be nested). For higher-rank simple arrays, you can use the following to get all 0s and all 1s:

`1`s with `=⍨`

`0`s with `≠⍨`

If you set `⎕ML←0`, all numbers can be made into zeros (as if ) with:

If you only need a single number, you may be able to use monadic  to get 1 or 0 instead of using `1⊣` or `0⊣`.

Note that Dyalog APL 18.0 added a constant operator which derives an ambivalent function that always returns the constant.

# Answer
> 4 votes
# Constructing a long complex string (char vector)

Original idea from @ngn.

We can (ab)use rotation `n⌽` and enlist  to shorten multiple concatenations:

```
'(',(⍺∇r),'|',(⍺∇s),')'
  → Rotate the last ')' to front and apply 1⌽
1⌽')(',(⍺∇r),'|',(⍺∇s)  (-1 byte)
  → We don't need parens at the end
1⌽')(',(⍺∇r),'|',⍺∇s    (-3 bytes in total)
  → Remove some concats(,) to use stranding instead and enlist(∊) later
1⌽∊')('(⍺∇r)'|',⍺∇s     (-4 bytes in total)

```

Note that we can't remove the last concat (`,`) in this case; otherwise the recursive call would be screwed up.

The  trick can also be used to shorten construction of numeric arrays:

```
0,(⍳5),0
  →
∊0(⍳5)0   (-1 byte)

```

# Answer
> 4 votes
# `⎕FMT`, the formatting function

Dyalog documentation page

In user's answer to ascii art reflection,, they used an interesting builtin called `⎕FMT` to split text on a carriage return `\r`. I feel it has potential to save a lot of bytes in and challenges. It works very well with specific output/input specifications.

## Converting carriage return separated input directly to a matrix

A string with carriage returns can be converted directly to the matrix using monadic `⎕FMT`:

```
      ⎕FMT'Hello'(⎕UCS 13)'There'
 Hello
 There
      ⍴⎕FMT'Hello'(⎕UCS 13)'There'
2 7

```

It automatically pads the matrix with spaces, just like (mix).

---

`⎕FMT` can take arrays as arguments, and can apply a format specification to each of it's elements. However, the rank of the array must not exceed 2, and the format specifier must be a proper match for the elements.

There are multiple format specifiers allowed, which give different results:

```
rAw     Alphanumeric format
rEw.s   Scaled format
rqFw.d  Decimal format
rqG⍞pattern⍞    Pattern
rqIw    Integer format
Tn  Absolute tabulation
Xn  Relative tabulation
⍞t⍞     Text insertion

```

Where:

```
r   is an optional repetition factor indicating that the format phrase is to be applied to r columns of Y
q   is an optional usage of qualifiers or affixtures from those described below.
w   is an integer value specifying the total field width per column of Y, including any affixtures.
s   is an integer value specifying the number of significant digits in Scaled format; s must be less than w-1
d   is an integer value specifying the number of places of decimal in Decimal format; d must be less than w.
n   is an integer value specifying a tab position relative to the notional left margin (for T-format) or relative to the last formatted position (for X-format) at which to begin the next format.
t   is any arbitrary text excluding the surrounding character pair.  Double quotes imply a single quote in the result.

```

This allows a lot of useful tricks like format strings, ASCII tabulation, representation of arbitrary precision floating point values, and allow you to apply them cyclically to the contents of any matrix you choose. `⎕R` might be simpler to use in the case of a single line character vector, however.

These letters and their modifiers are discussed in more depth in the Documentation.

# Answer
> 3 votes
# Base Conversions

The function `b⊥v`, where `b` is a numeric base and `v` is a vector of digit values in that base, converts the vector `v` into its decimal (base-10) equivalent. If you want to convert a base-10 number into base `b`, a naïve approach would be to try to use , but this requires figuring out (or calculating) how many digits the number would require in base `b`. Instead, use the Power operator  with a right operand of `¯1`: `(b∘⊥⍣¯1)`. This will invert the convert-to-decimal function to convert back to base `b` with exactly the minimum necessary number of digits in the base-b representation.

```
      2⊥1 1 0 1            ⍝ Convert the base-2 digit vector 1 1 0 1 to base-10
13
      (2∘⊥⍣¯1)13           ⍝ Convert 13 to its base-2 digit vector
1 1 0 1

```

# Answer
> 3 votes
# Miscellaneous ideas

Cross-post of my own J tip, because APL and J are so closely related that the two can share many ideas.

## If you're facing `-⍨/`, try `¯1⊥` instead

A common reason to use `-⍨/` is to reverse-subtract over a length-2 axis, e.g. given a 2-element array `x y`, compute `y-x`.

If this is the case, `¯1⊥` is an equivalent expression; just like `2⊥x y` computes `2x+y`, `¯1⊥x y` computes `-x+y`. While the two expressions have same length, `¯1⊥` is more likely to fit well in trains (due to being a dyadic primitive function with a left arg, vs `-⍨/` being a monadic derived function).

Note that, if you apply it to longer axis, `¯1⊥` gives you more similar result to `-/` (alternating sum), with negated result when the length is even.

## Construct a boolean square matrix where the border is ones/zeros and the interior is the opposite

This is mainly for large fixed-size matrices, say 6 by 6.

The matrix

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

```

can be generated by `∘.∨⍨` -ing the boolean vector `1 0 0 0 0 1`. The shortest known way to generate that vector is `6⍴5↑1`, so we can get the matrix above in just **9 bytes**:

```
∘.∨⍨6⍴5↑1

```

We can also get negation of it at no extra cost, by swapping  with ! (Remember that APL has NOR  and NAND ; they are rarely needed, but definitely are a byte saver when we do need them.)

# Answer
> 3 votes
# Repeat with intermediate results

This is originally @ngn's suggestion on an APL answer of mine.

While APL has the power operator  which can repeat a function certain number of times, it cannot collect intermediate results on its own (unlike J's `^:` allowing `<n` or `i.n` right operand to do the job). Usually one would collect the intermediate results by using an auxiliary variable with modified assignment, or "hack" the left operand of  to something like `(⊣/,f¨)⍣n⊂x`, or naively write down the iterations like `{⍵(f⍵)(f f⍵)}x`.

But there is a clever way using scan `⊢∘f\`. Since `x ⊢∘f y` ignores `x` and applies `f` to `y` monadically, such a scan over `n` copies of `x` (enclosed if `x` is non-scalar) gives the results of `f` applied to `x` `0..n-1` times:

```
  ⊢∘f\n⍴⊂x
→ ⊢∘f\x x x ... x
→ (x)(x ⊢∘f x)(x ⊢∘f x ⊢∘f x) ...
→ x(f x)(f f x)(f⍣3⊢x) ... (f⍣(n-1)⊢x)

```

This is shorter than several alternatives (assume `x` is a complex expression):

```
{⍵(f⍵)(f f⍵)}x  ⍝ way too long for 2nd or higher iterations
(⊣/,f¨)⍣n⊂x     ⍝ shorter, but still long
⊢∘f\n⍴⊂x        ⍝ shortest

```

Interestingly, the scan expression ties when compared to various expressions that collect only zeroth and first iterations:

```
{⍵(f⍵)}x  ⍝ dfn
(⊂,⊂∘f)x  ⍝ tacit
y(f y←x)  ⍝ intermediate assignment; this wins if f is a single primitive
⊢∘f\2⍴⊂x  ⍝ scan

```

Also note that `⊢∘f\n⍴⊂` without the right arg is also a valid train.

---

As of Dyalog 18.0, you can write `f⍤⊢\` in place of `⊢∘f\`, which may or may not save bytes depending on the structure of `f`. (The conversion never *adds* bytes, so `f⍤⊢\` can be universally used.)

# Answer
> 2 votes
When you need to encode some arbitrary data (as is common in the Kolmogorov complexity questions), it can be achieved with a string of characters from the atomic vector `⎕AV`.

For example, to encode the array `256 13 16 127 128 168 192` in Dyalog APL:

```
⎕AV[256 13 16 127 128 168 192]      ⍝ the result is: ⍣%⍵⊣⌷∧⊤

```

Then to decode it:

```
⎕AV⍳'⍣%⍵⊣⌷∧⊤'

```

Adám's SBCS (single byte character set) also allows to encode some other characters (`⊆⍠⍤⌸⌺⍸`) as a single byte.

# Answer
> 0 votes
# Encode into base b without digit limit

`b⊥⍣¯1`

Explanation:

```
  ⍣¯1 Do the inverse of...
b⊥    Decoding from base b (which is encoding to base b with no digit limit!!!)

```

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


title: Find The Real Solutions of a Cubic

text:
# Question
Title: Find The Real Solutions of a Cubic
## Description

All cubic equations can be solved, and every cubic has at least one solution. The goal of this challenge is to find the real solutions to a given cubic using inputs, and (obviously) the smallest program size.

## Rules

The solution must find the real solutions of a cubic correctly, using any method. The cubic must be in the standard form $$ax^3 + bx^2 + cx + d = 0$$

The first coefficient cannot be zero, as then it would be a quadratic. There must a different output if it is zero, and outputting nothing at all is acceptable.

## Scoring

The score is based on the size of the program alone.

## Inputs

The four coefficients of the cubic, `a`, `b`, `c`, and `d`.

The input may be formatted however you like.

## Outputs

Every real solution to the cubic. There will either be three, or one for every cubic.

## Example

### With 3 solutions

Input:

```
1
3
0
-1

```

Output:

```
-2.879
-0.653
0.532

```

### With 1 solution

Input:

```
1
1
1
1

```

Output:

```
-1

```

## Additional Info

While you can use any method, you can find an image with the cubic equation (similar to the quadratic equation, can solve any cubic every time) equation can be found here.

You can learn more about cubics here.

# Answer
> 4 votes
# Vyxal `P`, 4 bytes

```
hß∆P

```

Try It Online!

Good old built-ins. This may not work on some interpreters until the SymPy ACE vulnerabilities are fixed. Input as a list `[a,b,c,d]`.

Edit: Changed output to the input if leading coefficient is 0.

# Answer
> 9 votes
# , ~~42~~ 41 bytes

```
function(c,a=polyroot(c))a[!Im(a)]/!!c[4]

```

Try it online!

Input is vector of `d`,`c`,`b`,`a`. Outputs `Inf` if the cubic coefficient (`a`) is zero.

Using `a[!Im(a)]` to select only real solutions is very susceptible to floating-point rounding errors; the TIO header rounds values less than 0.0000000001 to zero to prevent this. Including rounding in the code costs ~~5~~ 3 more bytes.

---

# , 111 bytes

```
function(e,z=1i^(1:3)){for(i in 1:99)z=z-e%*%rbind(z^3,z^2,z,1)/(z-(x=c(z,z))[2:4])/(z-x[3:5]);if(e)z[!Im(z)]}

```

Try it online!

Non-builtin Durant-Kerner strategy copied from 97.100.97.109's answer (upvote that!). Using this approach to find all the roots in parallel works very nicely with 's vectorized operations.

# Answer
> 6 votes
# MATL, 12 bytes

```
1)?G&ZQ&Zj~)

```

Try it online!

### How it works

```
       % Implicit input
1)     % Get the first element
?      % If non-zero
  G    %   Push input again
  &ZQ  %   Implicit input. Roots of polynomial. Gives a numeric vector
  &Zj  %   Push real and imaginary parts
  ~    %   Negate. Gives "true" if imaginary part is zero, or "false" otherwise
  )    %   Keep only real parts corresponding to "true".
       % Implicit end
       % Implicit display

```

# Answer
> 6 votes
# Python, ~~143~~ ~~134~~ 133 bytes

```
f=lambda a,b,c,d,R=[-1,1j,1]:[R:=[(z:=R[2])-(((a*z+b)*z+c)*z+d)/(z-R[0])/(z-R[1])]+R for i in" "*99]and[x for x in R[:3]if x.imag==0]

```

Attempt This Online!

This is the first solution that doesn't use a builtin, and it suffers greatly for it. Instead, I'm using the Durant-Kerner method to find all approximations, then filtering for whether they're complex.

---

-9 bytes from @Steffan for various small changes.

# Answer
> 4 votes
Both functions below take a polynomial in `x`.

# PARI/GP, 27 bytes

```
p->if(#p>3,polrootsreal(p))

```

Attempt This Online!

Returns `0` for quadratics and below.

# PARI/GP, 101 bytes

```
p->k=[Pi,I,2];for(q=1,99,k-=[subst(p,x,k[i])/vecprod([k[i]-z|z<-k[^i]])|i<-[1..3]]);[r|r<-k,!imag(r)]

```

Attempt This Online!

Yet another implementation of the Durand–Kerner method.

# Answer
> 2 votes
# Jelly, 8? 11 bytes

```
ṛ/ȧÆr,N+AƲƇ

```

A monadic Link that accepts a list of the coefficients (`[d,c,b,a]`) and yields a list of the (one or three) real roots, unless `a` is zero in which case it yields an empty list.

**Try it online!** Or see the test-suite.

...\\$8\\$ bytes if we can handle `a` being zero (in which case it works for all polynomials):

```
Ær,NċAƲƇ

```

Try it online!

### How?

The heavy lifting is done by a built-in...

```
ṛ/ȧÆr,N+AƲƇ - Link: coefficients, P = [d,b,c,a]
 /          - reduce (P) by:
ṛ           -   right
               -> a
   Ær       - polynomial roots (of P)
  ȧ         - logical AND
               -> [d,c,b,a] or 0
          Ƈ - keep those for which (with 0, keep those of range(0)=[]):
         Ʋ  -   last four links as a monad - f(x):
      N     -     negate (x)
     ,      -     (P) paired with (that)
        A   -     absolute value (of x)
       ċ    -     count occurrences (of that in the pair)
                    -> Truthy (1 or 2*) if x is real, falsey (0) if not
                                  * when x=0

```

# Answer
> 2 votes
# Python 3, 99 bytes

```
import numpy
f=lambda a,b,c,d:[float(i)for i in numpy.roots([a,b,c,d])if round(float(i))!=0if a!=0]

```

Try it online!

# Answer
> 2 votes
# , 32 bytes

```
[:{:^:([:-.*./@(=+)){:@:>@p.^:{:

```

I am pretty bad at conditionals in J, but after some finagling, this was the best I could come up with. Expects coefficients as `d,c,b,a`

Attempt This Online!

```
[:{:^:([:-.*./@(=+)){:@:>@p.^:{:
                    {:@:>@p.^:{:  : u^:v executes u if v is true, else return x
                              {:  : is last item 0?
                    {:@:>@p.      : if non-zero
                          p.      : converts coefficient form to multiplier-roots form
                        >         : unbox the results
                    {:            : take the roots, not the multiplier
  {:^:([:-.*./@(=+))              : The check for only one real
      ([:-.*./@(=+))              : u(v(x)) where u is -. and v is *./@(=+)
               (=+)               : each x equal to its complex conjugate?
           *./                    : AND reduce result
         -.                       : negate result
  {:                              : if roots are not all reals, take the last value

extra:
u@v -> apply u monadically to v(x) for every application of v
u@:v -> apply u to the entire result of v(x)
[:u v -> strictly u(v(x))

```

# Answer
> 2 votes
# , 20 bytes

```
1(#~]=+)@{::[:p.]*{:

```

Attempt This Online!

Takes `d c b a`, and returns the array of real roots, or an empty array if `a` is 0.

```
1(#~]=+)@{::[:p.]*{:
                ]*{:    multiply the entire polynomial with `a`
                        which doesn't change the roots if `a` is nonzero
                        but gives 0 0 0 0 otherwise, which has zero roots according to `p.`
            [:p.    convert to multipler-roots form
1        {::        extract the roots
 (     )@      filter real roots:
  #~]=+        filter the list by "complex conjugate equals self"

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 50 bytes

Try it online!

```
g[k_]/;k[[4]]!=0:=Solve[x^Range[0,3].k==0,x,Reals]

```

Input is the number of coefficients in reverse order `{d, c, b, a}`. This defines a function `g` only if the `4th` argument is unequal 0. Otherwise this function remains undefined and returns the function call as output. Uses the built-in `Solve` function over the `Reals` domain.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 35 bytes

```
#^0NSolve[x#+#2&~Fold~!##,x,Reals]&

```

Try it online!

Input `[a, b, c, d]`. If \\$a=0\\$, returns a list of as many `{Indeterminate}`s as there would be solutions.

When given non-equation expressions, `NSolve` finds their roots.

```
          x#+#2&~Fold~!##           convert to a polynomial in x
   NSolve[               ,x,Reals]  get real solutions
#^0                                 invalidate solutions if a=0

```

# Answer
> 1 votes
# MATLAB, 29 bytes

```
syms a b c d;roots([a b c d])

```

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


title: Count Futoshiki row solutions

text:
# Question
Title: Count Futoshiki row solutions
Futoshiki is a logic puzzle where an \\$n×n\\$ Latin square must be completed based on given numbers and inequalities between adjacent cells. Each row and column must contain exactly one of each number from \\$1\\$ to \\$n\\$ while satisfying the inequalities.

In a solved Futoshiki puzzle any row (or column) forms a linear extension of the poset induced by that row's inequalities. Counting linear extensions of posets of this kind is a polynomial-time problem, as opposed to #P-complete for the general case.

Given the sequence of \\$n\ge0\\$ symbols between cells of an initially empty Futoshiki row of length \\$n+1\\$, each of which is one of \\$\<\\$, \\$\>\\$ or \\$-\\$ (nothing; no constraint), output the number of solutions of that row when considered in isolation. You may use any three distinct symbols for \\$\<,\>,-\\$, but your program must pass all test cases below in reasonable time.

This is ; fewest bytes wins.

## Test cases

```
"" -> 1
">" -> 1
"<" -> 1
"-" -> 2
"<>" -> 2
">-" -> 3
"><>" -> 5
"---" -> 24
">->>" -> 10
"><><>" -> 61
"->->-<<>" -> 11340
">-<><--<>><" -> 4573800
"><>><><<<>><>" -> 26260625
">><<>><<>><<>>" -> 120686411

```

# Answer
# JavaScript (ES6),  ~~110~~  98 bytes

```
f=(s,m=t=0,j,p)=>s[~~j]?[...s,0].map((_,v)=>m>>++v&1|p*!eval(p+s[j]+v)||f(s,m|1<<v,j+1|0,v))|t:++t

```

Try it online!

### Commented

```
f = (              // f is a recursive function taking:
  s,               //   s = input string of length N
  m =              //   m = bitmask of already used numbers
  t = 0,           //   t = number of solutions
  j,               //   j = pointer in s, initially undefined
  p                //   p = previous number in the permutation
) =>               //
s[~~j] ?           // if there's still something to process:
  [...s, 0]        //   create an array of length N + 1
  .map((_, v) =>   //   for each value at position v in there:
    m >> ++v & 1 | //     increment v; abort if v was already used
    p * !eval(     //     or p is defined and
      p + s[j] + v //       the expression p + s[j] + v
    ) ||           //     is falsy once evaluated as JS code
    f(             //     otherwise, do a recursive call:
      s,           //       pass s unchanged
      m | 1 << v,  //       update m to mark v as used
      j + 1        //       increment j
      | 0,         //       or force it to 0 if it was undefined
      v            //       set p = v
    )              //     end of recursive call
  ) | t            //   end of map(); yield t
:                  // else:
  ++t              //   increment t

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 84 bytes

```
t["-"<>#<>"-"]&
t@s_:=t@s=Tr[t/@StringReplaceList[s,"->"|"<>"|"<-"|"--"->"-"]]~Max~1

```

Try it online!

A fast solution using memoization. Finishes all test cases in a second.

Without memoization (`t@s=`) it would save 4 bytes, and the last three testcases would take 42 seconds, 4 minutes and 20 minutes respectively on my computer.

---

# Wolfram Language (Mathematica), 58 bytes

```
Count[Sign@*Differences/@Permutations@Range[0,Tr[1^#]],#]&

```

Try it online!

Brute force. Cannot pass the last three testcases in reasonable time.

Takes input as a list, where `>`, `<`, `-` are represented by `1`, `-1`, `_` respectively.
> 4 votes

# Answer
# Goruby, ~~72~~ 50 bytes

-28 bytes thanks to Dingus and G B.

I wasn't going to post this since it craps out on the last three test cases on ATO but it looks like I'll be in good company anyway, so here it is.

```
->s{[*0..s.sz].pe.ct{|a|s.a?{|t|1>t*=a.po-a[-1]}}}

```

Attempt This Online!

# Ruby, ~~95~~ 67 bytes

-22 bytes thanks to Dingus and G B.

```
->s{[*0..s.size].permutation.count{|a|s.all?{|t|1>t*=a.pop-a[-1]}}}

```

Attempt This Online!
> 3 votes

# Answer
# Python, 111 bytes

```
f=lambda s,t="",b=1:b and(s+t==""or(s<">">"<"!=t[-1:])*b*f(s[1:])*f(t[:-1])+f(s[1:],t+s[:1],b*-len(s)/~len(t)))

```

Attempt This Online!

### Python, 118 bytes

```
f=lambda s,t="",b=1:(s<">">"<"!=t[-1:]and(s+t==""or b*f(s[1:])*f(t[:-1])))+(s>""and f(s[1:],t+s[0],b*-len(s)/~len(t)))

```

Attempt This Online!

### Python, 123 bytes

```
f=lambda s,t="",b=1:(s[:1]!=">">"<"!=t[-1:]and(s+t==""or b*f(s[1:])*f(t[:-1])))+(s>""and f(s[1:],t+s[0],b*-len(s)/~len(t)))

```

Attempt This Online!

### Python, 165 bytes (@Steffan)

```
f=lambda s,b=1:s==""or sum((b:=b*(i-len(s))/~i)
*("<"<s[i]and">">s[i+1]and f(s[i+2:])*f(s[:i]))for i in range(len(s)-1))+(s<">"and f(s[1:]))+(s[-1]>"<"and f(s[:-1]))

```

Attempt This Online!

### Python, 174 bytes

```
f=lambda s,b=1:s==""or sum((b:=b*(i-len(s))/~i)
*((s[i]>"<")*(s[i+1]<">")and f(s[i+2:])*f(s[:i]))for i in range(len(s)-1))+((s[0]<">")and f(s[1:]))+((s[-1]>"<")and f(s[:-1]))

```

Attempt This Online!

This will surely be outgolfed to oblivion but it finishes all test cases in a second on ato.

Takes "=" instead of "-" because it sits conveniently between "\<" and "\>" codepointwise.

Uses a divide-and-conquer-ish approach: take the first element recurse into the two leftover halves and multiply their counts with each other and the number of ways they can be merged which is some binomial coefficient.
> 3 votes

# Answer
# Japt `-x`, 19 bytes

Pretty horrific brute force solution, exacerbated by me being so horribly out of practice!
Will crap out on inputs longer than 8 characters.

```
¬³ð á ®ã2 e@OxXqUgY

```

Try it

```
¬³ð á ®ã2 e@OxXqUgY     :Implicit input of string U
¬                       :Split
 ³                      :Push 3 (value is irrelevant, we just need an extra element)
  ð                     :0-based truthy indices (which is all of them as every element is a non-empty string, or 3)
    á                   :Permutations
      ®                 :Map
       ã2               :  Sub-arrays of length 2
          e             :  Does every pair return true
           @            :  When passed through the following function as X, at index Y
            Ox          :    Eval as JavaScript
              Xq        :      Join X with
                UgY     :      Character in U at index Y
                        :Implicit output of sum of resulting array

```
> 2 votes

# Answer
# Charcoal, 87 bytes

```
≔⪫--Ｓθ≔⦃⦄η⊞υθＦυ«§≔ηιＥΦ⊖Ｌι∧⁻>§ικ⁻<§ι⊕κ⁺⁺…ικ-✂ι⁺²κＦ⁻§ηιυ⊞υκ»ＦＬθＦΦυ⁼⊕ιＬκ§≔ηκ∨ΣＥ§ηκ§ηλ¹Ｉ§ηθ

```

Attempt This Online! Link is to verbose version of code. Explanation: Port of @alephalpha's Mathematica answer. The number of solutions for any given string of inequalities is the sum of the numbers of solutions when the highest number is placed in any legal cell (i.e. not to the right of `>` or to the left of `<`). These numbers of solutions are equivalent to the numbers of solutions of a reduced string of inequalities where the cell and its inequalities have been replaced by a separator.

```
≔⪫--Ｓθ

```

Wrap the inequalities in `-`s. This makes the legal highest cells easier to identify.

```
≔⦃⦄η

```

Start collecting lists of reduced strings of inequalities.

```
⊞υθＦυ«

```

Start a breadth-first search with the wrapped input string.

```
§≔ηιＥΦ⊖Ｌι∧⁻>§ικ⁻<§ι⊕κ⁺⁺…ικ-✂ι⁺²κ

```

Get the possible reduced strings of inequalities for this string and save them in the dictionary.

```
Ｆ⁻§ηιυ⊞υκ

```

Add those strings that have not yet been seen to the search for further processing.

```
»ＦＬθＦΦυ⁼⊕ιＬκ

```

Process the strings of inequalities in increasing order of length.

```
§≔ηκ∨ΣＥ§ηκ§ηλ¹

```

Update the dictionary with the total count for this string of inequalities.

```
Ｉ§ηθ

```

Output the total count for the wrapped input string.

# Charcoal, 50 bytes

```
≔⁺-Ｓθ⊞υ⟦⟧Ｆθ≔ΣＥυＥΦ⁻Ｅθνκ∧∨⁻ι<‹↨κ⁰μ∨⁻ι>›↨κ⁰μ⁺κ⟦μ⟧υＩＬυ

```

Attempt This Online! Link is to verbose version of code. Brute force, so the last few test cases will time out on ATO. Explanation:

```
≔⁺-Ｓθ

```

Prepend a `-` to the input string as the first number is not constrained by any previous number.

```
⊞υ⟦⟧

```

Start with a list of no numbers found.

```
Ｆθ

```

Loop over each constraint.

```
≔ΣＥυＥΦ⁻Ｅθνκ∧∨⁻ι<‹↨κ⁰μ∨⁻ι>›↨κ⁰μ⁺κ⟦μ⟧υ

```

For each list so far find all the numbers that satisfy the next constraint and create a new list of lists.

```
ＩＬυ

```

Output the number of lists found.
> 2 votes

# Answer
# Jelly, Fast: 47 bytes / Slow: 13 bytes

### Slow:

```
L‘Œ!IṠnẠ¥ƇV€L

```

A monadic Link that accepts a list of characters - `<->` represented as `-01` respectively and yields the solution count.

**Try it online!** Or see the, truncated test-suite (shows the Link input in parentheses).

##### How?

```
L‘Œ!IṠnẠ¥ƇV€L - Link: list of characters, A, from '-01' (equivalent to '<->' respectively):
L             - length (of A)
 ‘            - increment
  Œ!          - all permutations of [1..that]
    I         - deltas (b-a for each neighbouring pair (a,b) in each list)
     Ṡ        - signs -> 1 if a<b; -1 if a>b
          V€  - evaluate each (of A) as Jelly code -> '-': -1, '0' -> 0, '1' -> 1
        ¥Ƈ    - keep those (of the delta lists) for which:
      n       -   not equal? (vectorises)
       Ạ      -   all?
            L - length

```

---

### Fast:

```
ḅ3$Ɲ%6ỊTœP€⁸;ḊŻ$}¥/€Ñ€Sȯ1
i@‘ịɗ,Ç$;ɼ0ịƲe?®
Ø0jÇ

```

A monadic Link that accepts a list of integers - `<->` represented as `[2,0,1]` respectively and yields the solution count.

**Try it online!** Or see the test-suite (shows the Link input in parentheses).

##### How?

Implements the same algorithm as alephalpha's Mathematica answer \- go show some love :)

No built-in cache so this implements one. It's not got particularly great performance because (a) Jelly has no dictionary or hash-map data type, (b) Jelly only has a single register, so I keep values alongside their corresponding keys so it must search through those too (they can never match as keys are lists while values are positive integers), and (c) I went with a golfy implementation which looks up the key twice.

Note: the main Link is the one at the bottom, `Ø0jÇ`.

```
ḅ3$Ɲ%6ỊTœP€⁸;ḊŻ$}¥/€Ñ€Sȯ1 - Link 1, calculate count: list of integers, A, from [0,1,2] (equivalent to '-><' respectively):
ḅ3$Ɲ                      - convert each neighbouring pair from base 3
    %6                    - modulo by six (vectorises)
      Ị                   - insignificant? (effectively is that 0 or 1?)
       T                  - truthy indices
                            -> starts of substrings equivalent to: '->', '<-', '<>', and '--'
                               i.e. possible surrounding chars of the highest value
        œP€⁸              - partition (A) at each of those (discarding the index itself)
                 ¥/€      - reduce each by:
               $}         -   apply to the right hand one:
             Ḋ            -     dequeue
              Ż           -     prefix a zero (equivalent to a '-')
            ;             -   (left one) concatenate (that)
                    Ñ€    - call Link 2 (below) for each (if any)
                      S   - sum
                       ȯ1 - logical OR with one

i@‘ịɗ,Ç$;ɼ0ịƲe?® - Link 2, get count: list of integers, A, from [0,1,2] (equivalent to '-><' respectively):
               ® - recall from the register
                     Our cache: initially zero, but becomes a list of inputs (lists)
                                and outputs (positive integers) with a zero prefix
                                e.g. [0, [2], 1, [2,2], 1, [1], 1, [1,2], 2, ...]
                                         '<'=1   '<<'=1    '>'=1   '><'=2    ...

              ?  - if...
             e   - ...condition: exists?
    ɗ            - ...then: last three links as a dyad - f(A, cache)
i@               -   index (of A) in (the cache)
  ‘              -   increment -> index of the pre-calculated value
   ị             -   index into the cache -> pre-calculated value
            Ʋ    - ...else: last four links as a monad - f(A):
       $         -   last two links as a monad - f(A):
      Ç          -     call Link 1 (above)
     ,           -     (A) paired with that
         ɼ       -     apply to the register & yield:
        ;        -       (register) concatenate (that) -> adds the "key" A (a list) and value
          0ị     -     0 index into -> gets the value back out

Ø0jÇ - Link 3 (main Link): list of integers, A, from [0,1,2] (equivalent to '-><' respectively):
Ø0   - [0,0] (equivalent to "--")
  j  - join with A
   Ç - call Link 2 (above)

```

---

### Also:

Fast version taking the characters as given in the question \\$51\\$ bytes:

```
*Ɲ%87%5ḂTœP€⁸;45;Ḋ}ʋ/€Ñ€Sȯ1
i@‘ịɗ,Ç$;ɼ0ịƲe?®
⁾--jOÇ

```

**Try it online!**
> 2 votes

# Answer
# 05AB1E (non-competing), 16 bytes

<sup>*† Non-competing, because the challenge states* "your program must pass all test cases below in reasonable time"*, which this brute-force approach definitely doesn't do. (And yes, I know the challenge doesn't contain a tag, so it isn't a hard requirement.)*</sup>

```
Ćāœεü2I‚øε».V]PO

```

Uses //`1` for `<`/`>`/ respectively, and takes the input as a list of characters.

Try it online or verify some of the smaller test cases.

**Explanation:**

```
Ć             # Enclose the (implicit) input-list; appending its own first item
 ā            # Push a list in the range [1,length] (without popping), which will
              # be a list in the range [1, input-length + 1] due to the enclose
  œ           # Get all permutations of this list
   ε          # Map each permutation to:
    ü2        #  Create overlapping pairs of the integer-list
      I‚      #  Pair it with the input character-list
        ø     #  Zip/transpose; swapping rows/columns
         ε    #  Map over each pair of pair + character:
          »   #   Join the inner pair by spaces, and then both items by newlines
              #   (e.g. [[1,2],"‹"] becomes "1 2\n‹")
           .V #   Evaluate and execute it as 05AB1E code
   ]          # Close both maps
    P         # Get the product of each inner list
     O        # Sum the list to get the amount of truthy values
              # (which is output implicitly as result)

```
> 1 votes

# Answer
# Rust \+ itertools, 149 bytes

```
use itertools::*;|s|(1..(s.len()as i8+2)).permutations(s.len()+1).filter(|p|p.windows(2).zip(s).all(|(a,&c)|c==1||(a[1]-a[0]).signum()==c-1)).count()

```

Try it online!

Can be assigned to a variable of type `fn(&[i8]) -> usize`. It uses this mapping of characters to ints as input:

```
'>' 0
'<' 2
'-' 1

```
> 1 votes

# Answer
# Pyth, 130 bytes

```
DgGHI!GR]1=Tgt^2tl.BGtH=bYVhG ab1FdUtHIv@.[\0tH.BNd=k-tHd Xb_1-/*s<>T.<.>Nktk^2tkhH.!k@b_1)))Rb;J.!hlzVcz)=/*Jegim!!xNdN2lN.!hlN;J

```

Try it online!

Uses input `<>`  in place of `<>-`.

Okay, so... this is pretty bad. For one thing it's like 17 bytes longer than the current best python, and it's slower. Depending on what "reasonable" means it may not even meet the requirements. Alright, so why did I bother sharing it? Well because I think the algorithm is cool, and I'm really just amazed I got it to work. It uses a formula presented in this OEIS, I'll give a brief explanation.

So first we can split the sequence along any `-` into some number of subsequences. Our base point for the final answer is then the number of permutations of the whole sequence divided by each subsequences, this is computed with simple factorials. Then all we need is the number of valid subsequence orders. This is where the OEIS formula comes into play, it basically comes down to a particular sum of sequences one less in length than itself. We multiply all of these by the base point and that's our answer.
> 1 votes

---
Tags: code-golf, math, combinatorics, game, puzzle-solver
---


title: Thin Paper Folding

text:
# Question
Title: Thin Paper Folding
# Thin Paper Folding

---

**This is a "lighter" version of the challenge Paper Folding for the win. This challenge is being posted as a different challenge with many modifications in order to try and get wider range of interesting answers. For anyone who is answering the first challenge, I marked the changes with `bold` (also note that the examples and the cases are different).**

---

"How many times can you fold a paper?" - This well known question led to many arguments, competition, myths and theories.

Well, the answer to that question depends on many properties of the paper (length, strength, thickness, etc...).

In this challenge we will try to fold a piece of paper as much as we can, however, there will be some constraints and assumptions.

---

### Assumptions:

* The paper will be represented in pixel-sized cells. The length and width of the paper is `N x M` respectively (which means you can not fold a pixel/cell in the middle).
* **Each spot (pixel) of the paper has its own thickness (as a result of a fold).**

---

### A paper:

A paper will be represented as a 2D `M x N` Matrix as the top-view of the paper. Each cell of the matrix will contain a number that will represent the thickness of the paper's pixel. **The initial thickness of all pixels is 1.**

Paper representation example:

```
     Option 1                        Option 2

1 1 1 1 1 1 1 1 1              [[1,1,1,1,1,1,1,1,1],
1 1 1 1 1 1 1 1 1              [1,1,1,1,1,1,1,1,1],
1 1 1 1 1 1 1 1 1              [1,1,1,1,1,1,1,1,1],
1 1 1 1 1 1 1 1 1              [1,1,1,1,1,1,1,1,1],
1 1 1 1 1 1 1 1 1              [1,1,1,1,1,1,1,1,1]]

```

---

### A fold:

A fold is a manipulation on the matrix defined as follows:

Assuming there is a 2 pixels fold from the right side of the paper in the example above, the size of the paper will now be `N-2 x M` and the new thickness of the pixels will be the summation of the previous thickness of the cell + the thickness of the mirrored cell relative to the fold cut:

```
            ___
           /   \
          \/<-- |
1 1 1 1 1 1 1|1 1            1 1 1 1 1 2 2
1 1 1 1 1 1 1|1 1            1 1 1 1 1 2 2
1 1 1 1 1 1 1|1 1    ===>    1 1 1 1 1 2 2
1 1 1 1 1 1 1|1 1            1 1 1 1 1 2 2
1 1 1 1 1 1 1|1 1            1 1 1 1 1 2 2

```

---

### Goal:

The goal is to write a program that will output a set of folds that result in the minimum possible number of remaining pixels for any given input (size of paper and threshold).

---

### Constraints:

* You can fold a paper from 4 directions only: Top, Left, Right, Bottom.
* The fold will be symmetric, which means, if you fold 2 pixels of the paper from the left, all of the cells in the first and second columns will be folded 2 pixels "mirrorly".
* **A thickness threshold of a paper cell will be given as an input**, a cell can not exceed that threshold at any time, which means, you will not be able to fold the paper, if that specific fold will result exceeding the thickness threshold.
* Number of pixels being fold must be between 0 and the length/width of the paper.
* Do not exceed with your folding the initial dimensions and position of the paper. ( there is no pixel -1 )

---

### Input:

* **Two integers `N` and `M` for the size of the paper**
* Thickness threshold

---

### Output:

* A list of folds that yields a valid paper (with no pixels exceeding the thickness threshold) folded in any way you want (using any heuristic or algorithm you've implemented).

---

### Scoring:

Since this is a , the shortest code wins.

---

### Examples:

**Example 1:**

```
Input: N=6 , M=4, Threshold=9

1 1 1 1 1 1
1 1 1 1 1 1    fold 2 pixels from top   2 2 2 2 2 2    fold 3 pixels from right   4 4 4    fold 1 pixel from top
1 1 1 1 1 1    ======================>  2 2 2 2 2 2    =======================>   4 4 4    =====================>   8 8 8    No more fold possible
1 1 1 1 1 1

Optional outputs:
[2T,3R,1T]
------------or----------
[[2,top],[3,right],[1,top]]
------------or----------
Top 2
Right 3
Top 1
------or any other sensible readable way------
--------notice the order is inportant---------

```

**Example 2:**

```
Input: N=6 , M=4, Threshold=16

1 1 1 1 1 1
1 1 1 1 1 1    fold 2 pixels from top   2 2 2 2 2 2    fold 3 pixels from right   4 4 4    fold 1 pixel from top             fold 1 pixel from left
1 1 1 1 1 1    ======================>  2 2 2 2 2 2    =======================>   4 4 4    =====================>   8 8 8    =====================>   16 8    No more fold possible
1 1 1 1 1 1

Optional outputs:
[2T,3R,1T,1L]
------------or----------
[[2,top],[3,right],[1,top],[1,left]]
------------or----------
Top 2
Right 3
Top 1
Left 1
------or any other sensible readable way------
--------notice the order is inportant---------

```

---

### Some Test cases:

**Case 1:**

```
Input: N = 16 , M = 6 , Threshold =  3
Output: [2, top], [2, top]
(This fold will result 32 remaining pixels)
(Example for bad output will be splitting in half, yields 48 remaining pixels)

```

**Case 2:**

```
Input: N = 16 , M = 6 , Threshold =  24
Output:
8 RIGHT
4 RIGHT
3 BOTTOM
1 TOP
1 TOP
(This fold will result 4 remaining pixels)

```

**Case 3:**

```
Input: N=6 , M=4, Threshold=9
Output: [2T,3R,1T]

```

**Case 4:**

```
Input: N=6 , M=4, Threshold=16
Output: [2T,3R,1T,1L]

```

---

## Check validity

**In the previous challenge I wrote a program that checks the validity of foldings and the validity of the resulted paper after folding (no exceeding threshold). You can use the same program, but you need to generate the paper itself as a matrix as an input to the function:**

This nodejs program will:

1. Check if your folded papers are valid
2. Check if your steps are valid

# How to use:

Call the desired function in the footer.

Call **validator** with threshold, initial paper, and a list of steps with the format `[x,d]` for folding `x` pixels from `d` direction. `d` is one of the following strings: "RIGHT","LEFT","TOP","BOTTOM". This function will print if the final paper as a matrix and the amount of pixels reduced.

Output will look like this:

```
*** PAPER IS VALID ***
Init length: 240, New length: 180, Pixels removed (score): 60

```

Or, if the paper isn't valid:

```
*** PAPER UNVALID ***
NO SCORE :(

```

**You can see call examples commented in the code.**

You can also remove the comment in the line `// console.log(paper); // If you want to print the paper after each step` to "debug" and print the folded paper after each fold.

# Answer
# , 179 bytes

(or **175 bytes** without labelling 'T' and 'L')

```
function(m,n,t,z=function(l,t){while(t>1){F=c(F,g<-l%/%t);l=l-g;t=t-1};list(l=l,f=F[F>0])})
list(T=z(m,b<-order(sapply(1:t,function(f)z(m,f)$l*z(n,t%/%f)$l))[1])$f,L=z(n,t%/%b)$f)

```

Try it online!

Outputs a list of \['T' = horizontal folds from top, 'L' = vertical folds from left\].

**How does it work?**

First, note that the final maximal thickness after a combination of horizontal & vertical folds is simply the product of the maximal thicknesses that would be obtained using the horizontal or only the vertical folds. So we can separate the problem into (1) finding the folds in one-dimension (either horizontal or vertical) that minimize the final length for a target thickness, and (2) choosing the best combination of target thicknesses for horizontal & vertical folds that yields the smallest product of lengths.

Now, to find the best set of folds in one-dimension, we note that since the number of folds isn't limited, so it's just as effective to 'roll-up' as to repeatedly fold in half.
Rolling-up has the advantage that if the length isn't perfectly divisible by the target thickness, we can do 'loose' rolls, and minimize the final length by doing the tighter rolls before the 'loose' rolls.

Final algorithm:

* test all combinations of t1, t2, where t1 x t2 \<= target thickness
* for each t1, find the smallest length l1 achievable by rolling-up the paper along dimension m, starting at the top
* for each t2, find the smallest length l2 achievable by rolling-up the paper along dimension n, starting on the left
* choose the combination of t1,t2 that gives the smallest final paper size = l1 x l2

Readable code:

```
fold_paper=function(m,n,t){                 # m=height, n=width, t=thickness threshold
    min_length=function(l,t){               # min_length=local function that calculates the best
                                            #   way to roll-up a strip of length l up to a
                                            #   thickness threshold of t
        while(t>1){                         # try to use-up all of the thickness t:
            F=c(F,g<-l%/%t)                 #   each fold g is the current length l integer-divided by the
                                            #   remaining thickness that we need to use-up
                                            #   (save the list of folds in F)
            l=l-g                           #   reduce the current length after each fold
            t=t-1                           #   and reduce the remaining thickness to use-up
        }
        list(l=l,f=F[F>0])                  #   return l = the final length, f = the list of folds
    }
    best_combo<-order(                      # now pick the best combination of t1,t2
        sapply(1:t,function(f)              # cycle through f=1..t for t1, and inteter(t/f) for t2
            min_length(m,f)$l * min_length(n,t%/%f)$l)
                                            # find the product of lengths for each combination
        )[1]                                # and choose the first one from the list sorted by increasing size
    list( T=min_length(m,best_combo)$f, L=min_length(n,t%/%best_combo)$f )
}                                           # finally, use the best combination to re-calculate
                                            # the best set of horizontal & vertical folds

```
> 2 votes

# Answer
# Python3, 620 bytes:

```
R=lambda x,n=4:set()if n==0 else{str(x),*R([[*i[::-1]]for i in zip(*x)],n-1)}
L=range
def M(b):
 for i in L(1,len(b[0])//2+1):yield[j[:-2*i]+[a+b for a,b in zip(j[-2*i:-i],j[-i:])]for j in b];yield[[a+b for a,b in zip(j[i:2*i],j[:i])]+j[2*i:]for j in b]
T=lambda x:[*map(list,zip(*x))]
F=lambda b:[*M(b),*map(T,M(T(b)))]
def f(n,m,t):
 r,q,s={},[[[1 for _ in L(n)]for _ in L(m)]],[]
 while q:
  for B in F(q.pop(0)):
   if all(all(j<=t for j in i)for i in B):
    Y,S=R(B),sum(map(len,B))
    if all(i not in s for i in Y)and(S not in r or max(map(max,r[S]))>max(map(max,B))):q+=[B];s+=[*Y];r[S]=r[S]=B
 return r[min(r)]

```

Try it online!
> 0 votes

---
Tags: code-golf, matrix
---


title: Tips for golfing in Nim

text:
# Question
Title: Tips for golfing in Nim
What general tips do you have for golfing in Nim? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Nim (e.g. "remove comments" is not an answer).

Please post one tip per answer.

# Answer
> 9 votes
# Use the `future` module

The `future` module contains two main byte-saving features: lambdas and list comprehensions. Lambdas are extremely useful.

For example, this:

```
proc f(s:any):any=s&", world!"

```

can be shortened to this:

```
import future
s=>s&", world!"

```

which saves a byte. Note, however, that lambdas can't be used outside of a parameter list -- so to test your code, you'll have to do something like this:

```
import future
proc test(f: string -> string) = echo f "Hello"
test(s=>s&", world!")

```

As well, list comprehensions can be used with the `future` module. For example, this code prints a seq (`@[...]`) of all squares less than 100 divisible by 4:

```
import future
echo lc[x*x|(x<-1..9,x*x mod 4==0),int]

```

# Answer
> 9 votes
## Unsigned operators

When working with nonnegative integers, sometimes it's better to use unsigned operators. Specifically, if possible, use `/%` and `%%` instead of `div` and `mod`.

# Answer
> 9 votes
## Flexible call syntax

Nim is pretty flexible when it comes to function call syntax. For example, here are some ways to call a function with one argument:

```
ord(c)
ord c
c.ord

```

And ways to call a function with two arguments:

```
max(a,b)
a.max(b)
a.max b

```

Choose the golfiest version that works right for your situation, especially regarding precedence. For example, compare:

```
abs(n)+2
n.abs+2
(abs n)+2

```

As opposed to:

```
abs(n+2)
(n+2).abs
abs n+2

```

# Answer
> 4 votes
# Use `on` and `off` as a boolean value

`on` / `off` are aliases for true / false.

# Answer
> 3 votes
# Use `;` to end statements

Oftentimes, a lot of Nim bytes come from the mandatory indentation of two spaces. This can sometimes be avoided by utilizing `;` to break statements. For example (a bit contrived, but nevertheless effectively demonstrating the idea):

```
while 1>0:echo "Hello";echo"World"

```

# Answer
> 1 votes
# 1\>0 for true and 0\>1 for false

In Nim, there is no implicit conversion of int-\>bool or bool-\>int. It is thus advantageous for golfing to use `1>0` or `0>1` to get the values for true and false, as one might use `1`/`0` in C. This can help with, for example, the creation of infinite loops.

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