[Question]
      [
I'm looking for tips for golfing in the R statistical language. R is perhaps an unconventional choice for Golf. However, it does certain things very compactly (sequences, randomness, vectors, and lists), many of the built-in functions have [very short names](https://stackoverflow.com/questions/6979630/what-1-2-letter-object-names-conflict-with-existing-r-objects), and it has an optional line terminator (;). What tips and tricks can you give to help solve code golf problems in R?

[Answer]
Some tips:
1. In R, it's recommended to use `<-` over `=`. For golfing, the
opposite holds since `=` is shorter...
2. If you call a function more than once, it is often beneficial to
define a short alias for it:
```
as.numeric(x)+as.numeric(y)
a=as.numeric;a(x)+a(y)
```
3. Partial matching can be your friend, especially when functions
 return lists which you only need one item of. Compare
 `rle(x)$lengths` to `rle(x)$l`
4. Many challenges require you to read input. `scan` is often a good fit for this (the user ends the input by entring an empty line).
```
scan()    # reads numbers into a vector
scan(,'') # reads strings into a vector
```
5. Coercion can be useful. `t=1` is much shorter than `t=TRUE`. Alternatively, `switch` can save you precious characters as well, but you'll want to use 1,2 rather than 0,1.
```
if(length(x)) {} # TRUE if length != 0
sum(x<3)         # Adds all the TRUE:s (count TRUE)
```
6. If a function computes something complicated and you need various other types of calculations based on the same core value, it is often beneficial to either: a) break it up into smaller functions, b) return all the results you need as a list, or c) have it return different types of values depending on an argument to the function.
7. As in any language, know it well - R has thousands of functions, there is probably some that can solve the problem in very few characters - the trick is to know which ones!
Some obscure but useful functions:
```
sequence
diff
rle
embed
gl # Like rep(seq(),each=...) but returns a factor
```
Some built-in data sets and symbols:
```
letters     # 'a','b','c'...
LETTERS     # 'A','B','C'...
month.abb   # 'Jan','Feb'...
month.name  # 'January','Feburary'...
T           # TRUE
F           # FALSE
pi          # 3.14...
```
[Answer]
1. Instead of importing a package with `library`, grab the variable from the package using `::` . Compare the followings:
```
library(splancs);inout(...)
splancs::inout(...)
```
Of course, it is only valid if one single function is used from the package.
2. This is trivial but a rule of thumb for when to use @Tommy's trick of aliasing a function: if your function name has a length of `m` and is used `n` times, then alias only if `m*n > m+n+3` (because when defining the alias you spend `m+3` and then you still spend 1 everytime the alias is used). An example:
```
nrow(a)+nrow(b)     # 4*2 < 4+3+2
n=nrow;n(a)+n(b)
length(a)+length(b) # 6*2 > 6+3+2
l=length;l(a)+l(b)
```
3. Coercion as side-effect of functions:
	* instead of using `as.integer`, character strings can be coerced to integer using `:` :

	```
	as.integer("19")
	("19":1)[1] #Shorter version using force coercion.

	```
	* integer, numeric, etc. can be similarly coerced to character using `paste` instead of `as.character`:

	```
	as.character(19)
	paste(19) #Shorter version using force coercion.

	```
[Answer]
Some very specific golfing tips:
* if you need to extract the length of a vector, `sum(x|1)` is shorter than `length(x)` as long as `x` is numeric, integer, complex or logical.
* if you need to extract the last element of a vector, it may be cheaper (if possible) to initialise the vector *backwards* using `rev()` and then calling `x[1]` rather than `x[length(x)]` (or using the above tip, `x[sum(x|1)]`) (or `tail(x,1)` --- thanks Giuseppe!). A slight variation on this (where the second-last element was desired) can be seen [here](https://codegolf.stackexchange.com/a/163922/55516). Even if you can't initialise the vector backwards, `rev(x)[1]` is still shorter than `x[sum(x|1)]` (and it works for character vectors too). Sometimes you don't even need `rev`, for example using `n:1` instead of `1:n`.
* (As seen [here](https://codegolf.stackexchange.com/a/96915/55516)). If you want to coerce a data frame to a matrix, don't use `as.matrix(x)`. Take the transpose of the transpose, `t(t(x))`.
* `if` is a formal function. For example, `"if"(x<y,2,3)` is shorter than `if(x<y)2 else 3` (though of course, `3-(x<y)` is shorter than either). This only saves characters if you don't need an extra pair of braces to formulate it this way, which you often do.
* For testing non-equality of numeric objects, `if(x-y)` is shorter than `if(x!=y)`. Any nonzero numeric is regarded as `TRUE`. If you are testing equality, say, `if(x==y)a else b` then try `if(x-y)b else a` instead. Also see the previous point.
* The function `el` is useful when you need to extract an item from a list. The most common example is probably `strsplit`: `el(strsplit(x,""))` is one fewer byte than `strsplit(x,"")[[1]]`.
* (As used [here](https://codegolf.stackexchange.com/a/97389/55516)) Vector extension can save you characters: if vector `v` has length `n` you can assign into `v[n+1]` without error. For example, if you wanted to print the first ten factorials you could do: `v=1;for(i in 2:10)v[i]=v[i-1]*i` rather than `v=1:10:for(...)` (though as always, there is another, better, way: `cumprod(1:10)`)
* Sometimes, for text based challenges (particularly 2-D ones), it's easier to `plot` the text rather than `cat` it. the argument `pch=` to `plot` controls which characters are plotted. This can be shortened to `pc=` (which will also give a warning) to save a byte. Example [here](https://codegolf.stackexchange.com/a/91930/55516).
* To take the floor of a number, don't use `floor(x)`. Use `x%/%1` instead.
* To test if the elements of a numeric or integer vector are all equal, you can often use `sd` rather than something verbose such as `all.equal`. If all the elements are the same, their standard deviation is zero (`FALSE`) else the standard deviation is positive (`TRUE`). Example [here](https://codegolf.stackexchange.com/a/146481/55516).
* Some functions which you would expect to require integer input actually don't. For example, `seq(3.5)` will return `1 2 3` (the same is true for the `:` operator). This can avoid calls to `floor` and sometimes means you can use `/` instead of `%/%`.
* The most common function for text output is `cat`. But if you needed to use `print` for some reason, then you might be able to save a character by using `show` instead (which in most circumstances just calls `print` anyway though you forego any extra arguments like `digits`)
* don't forget about complex numbers! The functions to operate on them (`Re`, `Im`, `Mod`, `Arg`) have quite short names which can occasionally be useful, and complex numbers as a concept can sometimes yield simple solutions to some calculations.
* for functions with very long names (>13–15 characters), you can use `get` to get at the function. For example, in R 3.4.4 with no packages loaded other than the default, `get(ls(9)[501])` is more economical than `getDLLRegisteredRoutines`. This can also get around source code restrictions such as [this answer](https://codegolf.stackexchange.com/a/90666/55516). Note that using this trick makes your code R-version-dependent (and perhaps platform dependent), so make sure you include the version in your header so it can be reproduced if necessary.
[Answer]
1. Abuse the builtins `T` and `F`. By default, they evaluate to `TRUE` and `FALSE`, which can be automatically converted to numerics `1` and `0`, and they can be re-defined at will. This means that you don't need to initialize a counter (e.g. `i=0` ... `i=i+1`), you can just use `T` or `F` as needed (and jump straight to `F=F+1` later).
2. Remember that functions return the last object called and do not need an explicit `return()` call.
3. Defining short aliases for commonly used functions is great, such as `p=paste`. If you use a function a lot, and with *exactly two* arguments, it is possible that an *infixing* alias will save you some bytes. Infixing aliases must be surrounded by `%`. For example:
```
`%p%`=paste
```
And subsequently `x%p%y`, which is 1 byte shorter than `p(x,y)`. The infixing alias definition is 4 bytes longer than the non-infixing `p=paste` though, so you have to be sure it's worth it.
[Answer]
# Using `if`, `ifelse`, and ``if``
There are several ways to do if-statements in R. Golf-optimal solutions can vary a lot.
### The basics
1. `if` is for control flow. It is not vectorized, i.e. can only evaluate conditions of length 1. It requires `else` to (optionally) return an else value.
2. `ifelse` is a function. It is vectorized, and can return values of arbitrary length. Its third argument (the else value) is obligatory.\*
3. ``if`` is a function, with the same syntax as `ifelse`. It is not vectorized, nor are any of the return arguments obligatory.
\* It's not technically obligatory; `ifelse(TRUE,x)` works just fine, but it throws an error if the third argument is empty and the condition evaluates to `FALSE`. So it's only safe to use if you are sure that the condition is always `TRUE`, and if that's the case, why are you even bothering with an if-statement?
### Examples
These are all equivalent:
```
if(x)y else z # 13 bytes
ifelse(x,y,z) # 13 bytes
`if`(x,y,z)   # 11 bytes
```
Note that the spaces around `else` are not required if you are using strings directly in the code:
```
if(x)"foo"else"bar"   # 19 bytes
ifelse(x,"foo","bar") # 21 bytes
`if`(x,"foo","bar")   # 19 bytes
```
So far, ``if`` looks to be the winner, as long as we don't have vectorized input. But what about cases where we don't care about the else condition? Say we only want to execute some code if the condition is `TRUE`. For one line of code alone, `if` is usually best:
```
if(x)z=f(y)         # 11 bytes
ifelse(x,z<-f(y),0) # 19 bytes
`if`(x,z<-f(y))     # 15 bytes
```
For multiple lines of code, `if` is still the winner:
```
if(x){z=f(y);a=g(y)}        # 20 bytes
ifelse(x,{z=f(y);a=g(y)},0) # 27 bytes
`if`(x,{z=f(y);a=g(y)})     # 23 bytes
```
There's also the possibility where we *do* care about the else condition, and where we want to execute arbitrary code rather than return a value. In these cases, `if` and ``if`` are equivalent in byte count.
```
if(x)a=b else z=b   # 17 bytes
ifelse(x,a<-b,z<-b) # 19 bytes
`if`(x,a<-b,z<-b)   # 17 bytes
if(x){z=y;a=b}else z=b   # 22 bytes
ifelse(x,{z=y;a=b},z<-b) # 24 bytes
`if`(x,{z=y;a=b},z<-b)   # 22 bytes
if(x)a=b else{z=b;a=y}   # 22 bytes
ifelse(x,a<-b,{z=b;a=y}) # 24 bytes
`if`(x,a<-b,{z=b;a=y})   # 22 bytes
if(x){z=y;a=b}else{z=b;a=y}   # 27 bytes
ifelse(x,{z=y;a=b},{z=b;a=y}) # 29 bytes
`if`(x,{z=y;a=b},{z=b;a=y})   # 27 bytes
```
### Summary
1. Use `ifelse` when you have input of length > 1.
2. If you're returning a simple value rather than executing many lines of code, using the ``if`` function is probably shorter than a full `if`...`else` statement.
3. If you just want a single value when `TRUE`, use `if`.
4. For executing arbitrary code, ``if`` and `if` are usually the same in terms of byte count; I recommend `if` mainly because it's easier to read.
[Answer]
1. You can assign a variable to the current environment while simultaneously supplying it as an argument to a function:
```
sum(x <- 4, y <- 5)
x
y
```
2. If you are subseting a `data.frame` and your condition depends on several of its columns, you can avoid repeating the `data.frame` name by using `with` (or `subset`).
```
d <- data.frame(a=letters[1:3], b=1:3, c=4:6, e=7:9)
with(d, d[a=='b' & b==2 & c==5 & e==8,])
```
instead of
```
d[d$a=='b' & d$b==2 & d$c==5 & d$e==8,]
```
Of course, this only saves characters if the length of your references to the `data.frame` exceeds the length of `with(,)`
3. `if...else` blocks can return the value of the final statement in which ever part of the block executes. For instance, instead of
```
a <- 3
if (a==1) y<-1 else
if (a==2) y<-2 else y<-3
```
you can write
```
y <- if (a==1) 1 else
     if (a==2) 2 else 3
```
[Answer]
## Do-while loops in R
Occasionally, I find myself wishing R had a `do-while` loop, because:
```
 some_code
while(condition){
 some_code # repeated
}
```
is far too long and very un-golfy. However, we can recover this behavior and shave off some bytes with the power of the `{` function.
`{` and `(` are each `.Primitive` functions in R.
The documentation for them reads:
>
> Effectively, `(` is semantically equivalent to the identity `function(x) x`, whereas `{` is slightly more interesting, see examples.
>
>
>
and under Value,
>
> For `(`, the result of evaluating the argument. This has visibility set, so will auto-print if used at top-level.
>
>
> For `{`, **the result of the last expression evaluated**. This has the visibility of the last evaluation.
>
>
>
(emphasis added)
So, what does this mean? It means a do-while loop is as simple as
```
while({some_code;condition})0
```
because the expressions inside `{}` are each evaluated, and only the *last one* is returned by `{`, allowing us to evaluate `some_code` before entering the loop, and it runs each time `condition` is `TRUE` (or truthy). The `0` is one of the many 1-byte expressions that forms the "real" body of the `while` loop.
Additionally, this can be combined with `print` (which invisibly returns its argument) to repeatedly print an intermediate result until (and including) it reaches `0`. An example of this can be found [here](https://codegolf.stackexchange.com/a/218160/67312).
[Answer]
1. **Save values in-line**: Others have mentioned that you can pass values in-order and assign them for use elsewhere, i.e.
```
 sum(x<- 1:10, y<- seq(10,1,2))
```
However, you can also *save* values inline for use *in the same line*!
For instance
```
    n=scan();(x=1:n)[abs(x-n/2)<4]
```
reads from `stdin`, creates a variable `x=1:n`, then indexes into `x` using that value of `x`. This can sometimes save bytes.
2. **Alias for the empty vector** You can use `{}` as the empty vector `c()` as they both return `NULL`.
3. **Base Conversion** For integer digits of `n` in base 10, use `n%/%10^(0:nchar(n))%%10`. This will leave a trailing zero, so if that is important to you, use `n%/%10^(1:nchar(n)-1)%%10` ot `n%/%10^(0:log10(n))`. This can be adapted to other bases, using `0:log(n,b)` instead of `log10(n)`.
4. **Using `seq` and `:`**: Rather than using `1:length(l)` (or `1:sum(x|1)`), you can use `seq(l)` as long as `l` is a `list` or `vector` of length greater than 1, as it defaults to `seq_along(l)`. If `l` is numeric and could potentially be length `1`, `seq(!l)` or `seq(a=l)` will [do the trick](https://codegolf.stackexchange.com/questions/206967/sum-the-array-times-n-except-the-last/207064#207064).
Additionally, `:` will (with a warning) use the first element of its arguments.
5. **Removing attributes** Using `c()` on an `array` (or `matrix`) will do the same as `as.vector`; it generally removes non-name attributes.
6. **Factorial** Using `gamma(n+1)` is shorter than using `factorial(n)` and `factorial` is defined as `gamma(n+1)` anyway.
7. **Coin Flipping** When needing to do a random task 50% of the time, using `rt(1,1)<0` is shorter than `runif(1)<0.5` by three bytes.
8. **Extracting/Excluding elements** `head` and `tail` are often useful to extract the first/last few elements of an array; `head(x,-1)` extracts all but the last element and is shorter than using negative indexing, if you don't already know the length:
```
head(x,-1)
x[-length(x)]
x[-sum(x|1)]
```
[Answer]
# Implicit type conversion
The functions `as.character`, `as.numeric`, and `as.logical` are too byte-heavy. Let's trim them down.
## Conversion to logical from numeric (4 bytes)
Suppose `x` is a numeric vector. Using the logical not operator `!` implicitly recasts the numeric to a logical vector, where `0` is `FALSE` and nonzero values are `TRUE`. `!` then inverts that.
```
x=!x
```
`x=0:3;x=!x` returns `TRUE FALSE FALSE FALSE`.
## Conversion to character from numeric or logical (7 bytes)
This is a fun one. (From [this tweet](https://twitter.com/johnmyleswhite/status/986335685585133568).)
```
x[0]=''
```
R sees that you're updating the vector `x` with `''`, which is of class `character`. So it casts `x` into class `character` so it's compatible with the new data point. Next, it goes to put `''` in the appropriate place... but the index `0` doesn't exist (this trick also works with `Inf`, `NaN`, `NA`, `NULL`, and so on). As a result, `x` is modified in class only.
`x=1:3;x[0]=''` returns `"1" "2" "3"`, and `x=c(TRUE,FALSE);x[0]=''` returns `"TRUE" "FALSE"`.
If you have a character object already defined in your workspace, you can use that instead of `''` to save a byte. E.g., `x[0]=y`!
## Conversion to character from numeric or logical under certain conditions (6 bytes)
[J.Doe](https://codegolf.stackexchange.com/users/81549/j-doe) pointed out in the comments a six-byte solution:
```
c(x,"")
```
This works if `x` is atomic and if you intend to pass it to a function which requires an atomic vector. (The function may throw a warning about ignoring elements of the argument.)
# Conversion to numeric from logical (4 bytes)
You can use the funky indexing trick from above (e.g. `x[0]=3`), but there's actually a quicker way:
```
x=+x
```
The positive operator implicitly recasts the vector as a numeric vector, so `TRUE FALSE` becomes `1 0`.
[Answer]
1. Abuse `outer` to apply an arbitrary function to all the combinations of two lists. Imagine a matrix with i, j indexed by the first args, then you can define an arbitrary function(i,j) for each pair.
2. Use `Map` as a shortcut for `mapply`. My claim is that `mapply` is cheaper than a for loop in situations where you need to access the index. Abuse the list structure in R. `unlist` is expensive. `methods::el` allows you to cheaply unlist the first element. Try to use functions with list support natively.
3. Use `do.call` to generalize function calls with arbitrary inputs.
4. The accumulate args for `Reduce` is extremely helpful for code golf.
5. Writing to console line by line with `cat(blah, "\n")` is cheaper with `write(blah, 1)`. Hard coded strings with "\n" may be cheaper in some situations.
6. If a function comes with default arguments, you can use function(,,n-arg) to specify the n-th argument directly. Example:`seq(1, 10, , 101)` In some functions, partial argument matching is supported. Example: `seq(1, 10, l = 101)`.
7. If you see a challenge involving string manipulation, just press the back button and read the next question. `strsplit` is single handily responsible for ruining R golf.
Now for some newly discovered tips from 2018
8. `A[cbind(i,j)] = z` can be a good way to manipulate matrices. This operation is very byte efficient assuming you design `i, j, z` as vectors with correct lengths. You may save even more by calling the actual index/assign function `"[<-"(cbind(i,j), z)`. This way of calling returns the modified matrix.
9. Use a new line instead of `\n` for line breaks.
10. Squeezing down line counts can save you bytes. In-line assignment `lapply(A<-1:10,function(y) blah)` and function args assignment `function(X, U = X^2, V = X^3)` are ways of doing this.
11. So `"[<-"` is a function in R (and is related to [my ancient question on SO](https://stackoverflow.com/questions/27515050/is-there-a-way-to-call-the-function-in-form))! That is the underlying function responsible for operations such as `x[1:5] = rnorm(5)`. The neat property of calling the function by name allows you to return the modified vector. In order words `"[<-"(x, 1:5, normr(5))` does almost the same thing as the code above except it returns the modified x. The related "length<-", "names<-", "anything<-" all return modified output
[Answer]
# Change the meaning of operators
R operators are just functions that get special treatment by the parser. For example `<` is actually a function of two variables. These two lines of code do the same thing:
```
x < 3
`<`(x, 3)
```
You can reassign another function to an operator, and the parser will still do it's thing, including respecting operator precedence, but the final function call will be the new one rather than the original. For example:
```
`<`=rep
```
now means these two lines of code do the same thing:
```
rep("a", 3)
"a"<3
```
and precedence is respected, resulting in things like
```
"a"<3+2
#[1] "a" "a" "a" "a" "a"
```
See for example [this answer](https://codegolf.stackexchange.com/a/164336/80010), and also [the operator precedence page](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html). As a side effect, your code will become as cryptic as one written in a golf language.
Some operators like `+` and `-` can accept either one or two parameters, so you can even do things like:
```
`-`=sample
set.seed(1)
-5  # means sample(5)
#[1] 2 5 4 3 1
5-2 # means sample(5, 2)
#[1] 5 4
```
See for example [this answer](https://codegolf.stackexchange.com/a/171490/79980).
See also [this answer](https://codegolf.stackexchange.com/a/185021/80010) for using `[` as a two-byte, three-argument operator.
[Answer]
# Scenarios where you can avoid `paste(...,collapse="")` and `strsplit`
These are a pain in the usual string challenges. There are some workarounds.
* `Reduce(paste0,letters)` for -5 bytes from `paste0(letters,collapse="")`
* A [2-byte golf](https://codegolf.stackexchange.com/questions/70837/say-what-you-see/104416#comment414550_104416) where you have a list containing two vectors `c(1,2,3)` and `c(4,5,6)` and want to concatenate them element-wise to a string `"142536"`. Operator abuse gives you `p=paste0;"^"=Reduce;p^p^r` which saves two bytes on the usual `paste0` call.
* Instead of `paste0("(.{",n,"})")` to construct (eg) a regex for 20 bytes, consider a regex in a regex: `sub(0,"(.{0})",n)` for 17 bytes.
Sometimes (quite often, actually) you'll need to iterate through a vector of characters or strings, or split a word into letters. There are two common use cases: one where you need to take a vector of characters as input to a function or program, and one where you know the vector in advance and need to store it in your code somewhere.
a. Where you need to take a string as **input** and split it into either *words* or *characters*.
1. If you need **words** (including characters as a special case):
	* If a newline `0x10` (ASCII 16) separating the words is OK, `x=scan(,"")` is preferred to wrapping your code in `function(s,x=el(strsplit(s," ")))`.
	* If the words can be separated by **any other whitespace**, including multiple spaces, tabs, newlines etc, you can use @ngm's [**double scan trick**](https://codegolf.stackexchange.com/revisions/b356bbc3-90b6-41cd-91c0-7152e47d314b/view-source): `x=scan(,"",t=scan(,""))`. This gives the scanned in string to `scan` as the `text` arg and separates it by whitespace.
	* The second argument in `scan` can be any string so if you have created one, you can [recycle it](https://codegolf.stackexchange.com/a/173514/81549) to save a byte.
2. If you need to turn an input string into a **vector of characters**:
	* `x=el(strsplit(s,""))` is the shortest *general* solution. The `split` argument works on anything of length zero including `c()`, `{}` etc so if you happen to have created a zero length variable, you could use it to save a byte.
	* If you can work with the ASCII character codes, consider `utf8ToInt`, since `utf8ToInt(x)` is shorter than the `strsplit` call. To paste them back together, `intToutf8(utf8ToInt(x))` is shorter than `Reduce(paste0,el(strsplit(x,"")))`.
	* If you need to split arbitrary strings of numbers like `"31415926535"` as input, you can use `utf8ToInt(s)-48` to save 3 bytes on `el(strsplit(s,""))`, provided you can use the integer digits instead of the characters, as is often the case. This is also shorter than the usual recipe for splitting numbers into decimal digits.
b. Where you need a **fixed vector** of either words or characters in advance.
* If you need a vector of single characters that have some regular pattern or are in alphabetic order, look at using `intToUtf8` or `chartr` applied to a sequence via `a:b` or on the built in letters sets `letters` or `LETTERS`. The pattern language built into `chartr` is [especially powerful](https://codegolf.stackexchange.com/a/169316/81549).
* For **1 to 3 characters or words**, `c("a","b","c")` is the only general shortest solution.
* If you need a fixed vector of **between 4 and 10 non whitespace characters or words**, use `scan` with `stdin` as the `file` arg:
```
f(x=scan(,""))
q
w
e
r
t
y
u
```
* If `scan` from `stdin` isn't possible, for **6 or more non whitespace characters or words**, use `scan` with the `text` argument `scan(,"",t="a b c d e f")`.
* If you need a vector of (a) **6 or more characters of any type** or (b) **10 or more non-whitespace characters** , `strsplit` via `x=el(strsplit("qwertyuiop",""))` is probably the way to go.
* You *may* be able to get away with the [following **quote trick**](https://codegolf.stackexchange.com/a/173161/81549): `quote(Q(W,E,R,T,Y))`, which creates that expression. Some functions like `strrep`, and `grep` will coerce this to a vector of strings! If you do, this is good for any length of word or character vector from 3 to 11.
* There's no good reason to use `strsplit` on words via `x=el(strsplit("q w e r t y"," "))`. It always loses to `scan(,"",t="q w e r t y"))` by a fixed overhead of 5 bytes.
Here's a table of the byte counts used by each approach to read in a vector of single characters of length `n`. The relative ordering within each row is valid for characters or words, except for `strsplit` on `""` which only works on characters.
```
| n  | c(...) | scan | scan | strsplit | quote |
|    |        |+stdin|+text | on ""    | hack  |
|    |        |      |      | CHAR ONLY|       |
|----|--------|------|------|----------|-------|
| 1  | 3      | 11   | 15   | 20       | 8     |
| 2  | 10     | 13   | 17   | 21       | 11    |
| 3  | 14     | 15   | 19   | 22       | 13    |
| 4  | 18     | 17   | 21   | 23       | 15    |
| 5  | 22     | 19   | 23   | 24       | 17    |
| 6  | 26     | 21   | 25   | 25       | 19    |
| 7  | 30     | 23   | 27   | 26       | 21    |
| 8  | 34     | 25   | 29   | 27       | 23    |
| 9  | 38     | 27   | 31   | 28       | 25    |
| 10 | 42     | 29   | 33   | 29       | 27    |
| 11 | 46     | 31   | 35   | 30       | 29    |
| 12 | 50     | 33   | 37   | 31       | 31    |
```
c. If you need to input **text as a character matrix**, a few recipes that seem short are
```
s="hello\nworld\n foo"
# 43 bytes, returns "" padded data frame
# If lines > 5 are longer than lines <= 5, wraps around and causes error
read.csv(t=gsub("(?<=.)(?=.)",",",s,,T),,F)
# 54 bytes with readLines(), "" padded matrix
sapply(p<-readLines(),substring,p<-1:max(nchar(p)),p))
# plyr not available on TIO
# 58 bytes, returns NA padded matrix, all words split by whitespace
plyr::rbind.fill.matrix(Map(t,strsplit(scan(,"",t=s),"")))
# 61 bytes, returns NA padded matrix
plyr::rbind.fill.matrix(Map(t,(a=strsplit)(el(a(s,"\n")),"")))
```
[Answer]
Some basic concepts but should be somewhat useful:
1. In control flow statements you can abuse that any number not equal to zero will be evaluated as `TRUE`, e.g.: `if(x)` is equivalent to `if(x!=0)`. Conversely, `if(!x)` is equivalent to `if(x==0)`.
2. When generating sequences using `:` (e.g. `1:5`) one can abuse the fact that the exponentiation operator `^` is the only operator that has precedence over the `:`-operator (as opposed to `+-*/`).
```
1:2^2 => 1 2 3 4
```
which saves you two bytes on the parentheses that you would normally have to use in case you wanted to e.g. loop over the elements of an `n x n` matrix (`1:n^2`) or any other integer that can be expressed in a shorter manner using exponential notation (`1:10^6`).
3. A related trick can of course be used on the vectorized operations as well `+-*/`, although most commonly applicaple to `+-`:
```
for(i in 1:(n+1)) can instead be written as for(i in 0:n+1)
```
This works because `+1`is vectorized and adds `1` to each element of `0:n` resulting in the vector `1 2 ... n+1`. Similarly `0:(n+1) == -1:n+1` saves you one byte as well.
4. When writing short functions (that can be expressed on one line), one can abuse variable assignment to save two bytes on the enclosing curly brackets `{...}`:
```
f=function(n,l=length(n))for(i in 1:l)cat(i*l,"\n")
f=function(n){l=length(n);for(i in 1:l)cat(i*l,"\n")}
```
Note that this might not always comply to rules of certain challenges.
[Answer]
# Alternatives to `rep()`
Sometimes `rep()` can be avoided with the colon operator `:` and R's vector recycling.
* For repeating `n` zeroes, where `n>0`, `0*1:n` is 3 bytes shorter than `rep(0,n)` and `!1:n`, an array of `FALSE`, is 4 bytes shorter, if the use case allows it.
* To repeat `x` `n` times, `x+!1:n` is 2 bytes shorter than `rep(x,n)`. For `n` ones, use `!!1:n` if you can use an array of `TRUE`.
* To repeat `x` `2n+1` times, where `n>=0`, `x+0*-n:n` is 4 bytes shorter than `rep(x,2*n+1)`.
* The statement `!-n:n` will give a `TRUE` flanked on both sides by `n` `FALSE`. This [can be used](https://codegolf.stackexchange.com/questions/167405/alpha-numerical-bowtie#comment414849_167413) to generate *even* numbers of characters in calls to `intToUtf8()` if you remember that a zero is ignored.
Modular arithmetic can be useful. `rep` statements with the `each` argument can sometimes be avoided using integer division.
* To generate the vector `c(-1,-1,-1,0,0,0,1,1,1)`, `-3:5%/%3` is 5 bytes shorter than `rep(-1:1,e=3)`.
* To generate the vector `c(0,1,2,0,1,2,0,1,2)`, `0:8%%3` saves 4 bytes on `rep(0:2,3)`.
* Sometimes nonlinear transformations can shorten sequence arithmetic. To map `i in 1:15` to `c(1,1,3,1,1,3,1,1,3,1,1,3,1,1,3)` inside a compound statement, the obvious golfy answer is `1+2*(!i%%3)` for 11 bytes. However, `3/(i%%3+1)` is [10 bytes](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz?page=1&tab=votes#comment417712_58637), and will floor to the same sequence, so it can be used if you need the sequence for array indexing.
[Answer]
When you do need to use a function, use `pryr::f()` instead of `function()`.
Example:
```
function(x,y){x+y}
```
is equivalent to
```
pryr::f(x,y,x+y)
```
or, even better,
```
pryr::f(x+y)
```
Since If there is only one argument, [the formals are guessed from the code](https://cran.r-project.org/web/packages/pryr/pryr.pdf).
[Answer]
# Surviving challenges involving strings
As mentioned in another answer, `unlist(strsplit(x,split="")` and `paste(...,collapse="")` can be depressing. But don't just walk away from these, there are workarounds!
* `utf8ToInt` converts a string to a vector, `intToUtf8` does the reverse operation. You're getting a vector of `int`, not a vector of `char` but sometimes this is what you're looking for. For instance to generate a list of `-`, better use`intToUtf8(rep(45,34))` than `paste(rep("-",34),collapse="")`
* `gsub` is more useful than other function of the `grep` family when operating on a single string.
The two approaches above can be combined as in [this answer](https://codegolf.stackexchange.com/a/164368/80010) which benefited from the advice of [ovs](https://codegolf.stackexchange.com/users/64121/ovs), [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) and [ngm](https://codegolf.stackexchange.com/users/79980/ngm).
* Choose a convenient I/O format as in [this answer](https://codegolf.stackexchange.com/a/157613/80010) taking input as lines of text (without quotes) or [this one](https://codegolf.stackexchange.com/a/164106/80010) taking a vector of chars. Check with the OP when in doubt.
* As pointed out in the comments, `<` compares strings lexicographically as one would expect.
[Answer]
# R 4.1.0: new shorthand function syntax
I just found out the very new release R 4.1.0 comes with some new syntax. <https://www.r-bloggers.com/2021/05/new-features-in-r-4-1-0/>
The new shorthand syntax `\(arglist) expr` performs exactly as `function(arglist) expr` and makes writing R functions 7 bytes shorter:
```
\(x,y)x+y
```
instead of
```
function(x,y)x+y
```
There's also the new native pipe `|>`, but this isn't shorter than just using parentheses (and the pipe has to be used with parentheses, unlike magrittr.)
[Answer]
Some ways to find the first non-zero element of an array.
If it has a name `x`:
```
x[!!x][1]
```
Returns `NA` if no non-zero elements (including when `x` is empty, but not `NULL` which errors.)
Anonymously:
```
Find(c, c(0,0,0,1:3))
```
Returns `NULL` if no non-zero elements, or empty or `NULL`.
[Answer]
# Tips for restricted source challenges :
1. Characters in R literals constants can be replaced by hex codes, octal codes and unicodes.
e.g. the string `"abcd"` can be written :
```
    # in octal codes
    "\141\142\143\144"
    # in hex codes
    "\x61\x62\x63\x64"
    # in unicodes
     "\u61\u62\u63\u64"
    # or
    "\U61\U62\U63\U64"
```
We can also mix characters with octal/hex/unicode and use some oct codes and some hex codes together, as long as unicode characters are not mixed with octal/hex e.g. :
```
    # Valid
    "a\142\x63\x64"
    # Valid
    "ab\u63\U64"
    # Error: mixing Unicode and octal/hex escapes in a string is not allowed
    "\141\142\x63\u64"
```
See [the end of this section](https://cran.r-project.org/doc/manuals/r-devel/R-lang.html#Literal-constants) for further details.
2. Since functions can be written using string literals, e.g. `cat()` can be written alternatively :
```
'cat'()
"cat"()
`cat`()
```
we can use octal codes, hex codes and unicode for function names as well :
```
# all equal to cat()
"\143\141\164"()
`\x63\x61\x74`()
'\u63\u61\u74'()
"ca\u74"()
```
with the only exception that unicode sequences are not supported inside backticks ``
3. Round brackets can be avoided abusing operators e.g. :
```
cat('hello')
# can be written as
`+`=cat;+'hello'
```
An application of all the three tricks can be found [in this answer](https://codegolf.stackexchange.com/questions/165518/code-generator-with-unique-characters/165548#165548)
[Answer]
# Searching datasets
R's builtin datasets can be a trove, in particular for [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenges, but searching through them is not easy.
For instance, for [this answer](https://codegolf.stackexchange.com/a/219617/86301), creating the value `100` thanks to a dataset was useful. It could be that the value was there as is, or as the sum of a column, or as the size of the dataset.
Here is the code I used; credit goes to Giuseppe [in the chat](https://chat.stackexchange.com/transcript/message/56532686#56532686):
```
x = data(package = "datasets")
res = x$results
for(dataset_name in paste0(res[,1],"::",res[,3])){
  curr = try(eval(parse(t=dataset_name)), T)
  if(length(curr) == 100) print(c("Length found in", dataset_name))
  if(100 %in% unlist(curr)) print(c("Value found in", dataset_name))
  try(if(try(sum(curr),T) == 100) print("Sum found in", dataset_name), T)
}
```
This searches all the datasets which are included by default; you can search datasets in other packages by changing the first line to `x <- data(package = .packages(all.available = TRUE))`.
You will need to make lavish use of `try` to avoid issues with different types of data. Remember that some datasets are vectors and not matrices or data frames. Other functions to try instead of `sum` include `min`, `max`, `mean`, `prod`, `sd` and `var`.
[Answer]
## `all` and `any` on lists
[Apparently](https://codegolf.stackexchange.com/a/241207/55372), `all` and `any` both accept lists of depth 1 and work just as well as on vectors (with a warning).
So, if you used `all(sapply(list,function))` in your code, in most places you may replace it with `all(Map(function,list))` for -3 bytes.
*I didn't know that before the [answer](https://codegolf.stackexchange.com/a/241207/55372) (linked above) by [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
[Answer]
## Know your `apply` functions
1. As [already mentioned](https://codegolf.stackexchange.com/a/91294/55372), use `Map` instead of `mapply` (and possibly `lapply`, depending on whether you want vectorisation also on further arguments to the function).
2. Use `sapply` when you want the result simplified when possible.
3. Use `apply` on matrices to apply a function rowwise or columnwise. But remember of functions like `colSums` and `colMeans`.
4. Use `tapply(x,y,f)` instead of `sapply(split(x,y),f)` or `Map(f,split(x,y))` - but you may want to use `simplify=FALSE` in the second case sometimes.
Remember that sometimes the function you're using can apply another function to the results (through the `FUN` argument), e.g. `combn`.
[Answer]
# Numeric Tricks
Ignoring precision error:
* `x%/%1` instead of `floor(x)` (integer part for positive x)
* `x%%1` instead of `x-floor(x)` (fractional part for positive x)
* `!x%%1`, `x%%1` to check if integer or not
* `x^.5` instead of `sqrt(x)`
* `gamma(x+1)` instead of `factorial(x)`
Constants: \$\pi\$ `pi`, \$e\$ `exp(1)`, \$1/e\$ `exp(-1)`
(if you need these for some reason) \$1 / \sqrt{2\pi}\$ `dnorm(0)`, \$\gamma\$ `-digamma(1)`
]


[Question]
      [
## Definition
Given a matrix \$M\$ of non-negative integers and a non-negative integer \$k\$, we define \$F\_k\$ as the "chop-off" function that removes all rows and all columns in \$M\$ that contain \$k\$.
*Example:*
$$\begin{align}M=\pmatrix{\color{red}6&\color{red}1&\color{white}{\bbox[red,1pt]{5}}\\1&2&\color{red}8\\\color{red}9&\color{red}8&\color{white}{\bbox[red,1pt]{5}}\\6&0&\color{red}4}\\\\F\_5(M)=\pmatrix{1&2\\6&0}\end{align}$$
## Your task
Given \$M\$ and a target sum \$S\$, your task is to find all possible values of \$k\$ such that the sum of the remaining elements in \$F\_k(M)\$ is equal to \$S\$.
*Example:*
Given the above matrix \$M\$ and \$S=9\$:
* \$k=5\$ is a solution, because \$F\_5(M)=\pmatrix{1&2\\6&0}\$ and \$1+2+6+0=9\$
* \$k=1\$ is the only other possible solution: \$F\_1(M)=\pmatrix{5\\4}\$ and \$5+4=9\$
So the expected output would be \$\{1,5\}\$.
## Clarifications and rules
* The input is guaranteed to admit at least one solution.
* The sum of the elements in the original matrix is guaranteed to be greater than \$S\$.
* You may assume \$S>0\$. It means that an empty matrix will never lead to a solution.
* The values of \$k\$ may be printed or returned in any order and in any reasonable, unambiguous format.
* You are allowed not to deduplicate the output (e.g. \$[1,1,5,5]\$ or \$[1,5,1,5]\$ are considered valid answers for the above example).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'").
## Test cases
```
M = [[6,1,5],[1,2,8],[9,8,5],[6,0,4]]
S = 9
Solution = {1,5}
M = [[7,2],[1,4]]
S = 7
Solution = {4}
M = [[12,5,2,3],[17,11,18,8]]
S = 43
Solution = {5}
M = [[7,12],[10,5],[0,13]]
S = 17
Solution = {0,13}
M = [[1,1,0,1],[2,0,0,2],[2,0,1,0]]
S = 1
Solution = {2}
M = [[57,8,33,84],[84,78,19,14],[43,14,81,30]]
S = 236
Solution = {19,43,57}
M = [[2,5,8],[3,5,8],[10,8,5],[10,6,7],[10,6,4]]
S = 49
Solution = {2,3,4,7}
M = [[5,4,0],[3,0,4],[8,2,2]]
S = 8
Solution = {0,2,3,4,5,8}
```

[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 39 bytes
```
{a@&y=x{+//x*(&/'b)&\:&/b:~x=y}/:a:,/x}
```
[Try it online!](https://tio.run/##PU/LboJQFNz7FbNoLLRauDzkck9N/Qh3lkRsxBoNWMQUYvDX6SCmm/OYzMw5c5jmu7zrMnNNF@NmXl9fHad@scbO88Yef5qxszG3et60jknNxKnbbmcyIbtcvJfmY7eqpUlaOPgt09NpWyK75F/VvshRFTgXZTW95PsfVN9blNvz5ViNlub6tGpupcnwhlrWxUGsdZbuj0IrKe2kHS1XljWDQigKHrTE0JxncBHYEttEw@ROiuBxIRjZMgkGTHkIqfJFRVAKSkPbEvgk/IsUVS4dXSjiiuJ@esh5l5t4rC7t@06ENDp4AyeM@JDvQweiA0QaKoYKeIQVWsEn3fNn1MQgGEaDrH9Mi3@vvN9nYpshGhpjBAzH10HTxyWOLiVMLpqpPFt0/@1AolHS/QE "K (ngn/k) – Try It Online")
*thanks @Adám for this explanation*:
`{`…`}` function, `x` is *M* and `y` is *S*
 `,/x` flatten *M* (these are the *k* candidates)
 `a:` assign to `a`
 `x{`…`}/:` apply the following function to each while using *M* as fixed left argument (`x`):
  `x=y` Boolean matrix indicating where elements of *M* equal the current *k* candidate
  `~` negate that
  `b:` assign that to `b`
  `&/` AND reduction (finds columns without that *k*)
  `(`…`)&\:` AND that with each of the following:
   `&/'b` AND reduction of each (finds rows without that *k*)
  `x*` multiply *M* by that
  `+//` grand sum
 `y=` list of Booleans indicating where *S* equals those sums
 `&` indices of Trues
 `a@` use that to index into the elements (the *k* candidates)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~35~~ ~~33~~ 28 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
-7 thanks to ngn.
Anonymous infix lambda. Takes *S* as left argument and *M* as right argument.
```
{⍵[⍸⍺=(+/∘,⍵×∧/∘.∧∧⌿)¨⍵≠⊂⍵]}
```
[Try it online!](https://tio.run/##bVA9SwNBEO39FemiOOrNzt7tXmFlYywMeHbHFQGJTUBbERuFEIMXtBAt7bSzEsQmEP/J/JHz7UabnHDcm483b2bf4Hy0dXIxGJ2dNs2l1h@l1p9af@2ub@7o5JlQ@X7SyWtItoHhu5tvLN7Q0NsXnV4jqK6aoY7vtZ7p7LHX1@nN4l10/ICsONrD/3i/VzR5Z9hZFg@K/mG3LDNiSisqmQx5YE4@5hklZKuqu@ZWJxyZyI9dK6ttNpRCSwLHETOxhzCo/I8SR6kkbkyIJfJaijgRTVAMMInrQ4Rq4BvJVidSh1eIkLegekvOE@fEIbMCJM8kcdi2DAnnByPkF3Hd0hEEGbm/IL7etxaTxVFhOLiH3XDCgPkD "APL (Dyalog Unicode) – Try It Online")
`{`…`}` "dfn", `⍺` and `⍵` are left and right arguments (*S* and *M*) respectively:
 `⍵[`…`]` index *M* with the following coordinates:
  `⊂⍵` enclose *M* to treat it as a single element
  `⍵=` compare each element (i.e. *k* candidate) of *M* to that entire *M*
  `(`…`)¨` apply the following tacit function to each:
   `∧⌿` vertical AND reduction (finds columns without that *k* candidate)
…`∘.∧` Cartesian Boolean product with:
    `∧/` horizontal AND reduction (finds rows without that *k* candidate)
   `⍵×` multiply *M* with that mask
   `+/∘,` sum the flattened matrix
  `⍺=` Boolean indicating where *S* equals those sums
  `⍸` indices where that's true
[Answer]
# [R](https://www.r-project.org/), ~~78~~ 73 bytes
```
function(m,s)m[Map(function(y)sum(m[(w=-which(m==y,T))[,1],w[,2]]),m)==s]
```
[Try it online!](https://tio.run/##XZBBisMwDEX3cxIL/oBlO7Gz8BG66y5k0QmEZuF2SFoyOX1GTqGtiy0LxH@y9KdtiNtwv/S38XpRCTOl9nD6Vc/SSvM9qdSqJX4v57E/qxTjiiNRC@6wtDBdR0gU49xtg0qn2zT@qV7VYFQSBgGNRIUaGo7g8LNO1yUeCQ19vRFetJwV5qXwhYKNtDGwYA9mcEAo1M5@NBSAtTAabEm4p5I/GsvHeh9WyzF7lkqJFETlZSdrEVy@PoAbsJMJ8hsYtoSNrQs8LyL8/sqE2R5JNfwjiQnV21qlT5VYqIUVNwWUYYufAm3/ "R – Try It Online")
Does not sort or deduplicate the output.
Credit to J.Doe & Giuseppe for -5 bytes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ ~~19~~ ~~17~~ ~~15~~ 14 bytes
```
pZnⱮFȦ€€ḋFẹƓịF
```
This is a monadic link that takes **M** as argument and reads **S** from STDIN.
[Try it online!](https://tio.run/##TVAxTgMxEOz3FX6Ai9tbX3z3geMPsVzSoAilTUtDkZI/UCGkdIGUkRDfuHzEzO7ZgGRpx7Mz61k/3O92h1L228fb6X3@fr09veEs5@O8fH58vSyX41yuz6DuykSRghBHYuplQ2GisaSUNt6xd0P2LqH23o0KJ9TKQtB5F3L25FKK0FRtoximwaxiHUgYbR511q@LV1tXp6KytAEWQRnt9Aa7@s5603YVD9GiiaAEVYzBuwiGkZmNCaIIfdik@daQtpz8Qc3TFlWMZeM/3FaEPGiE1WzfoS/b0n3OlH8A "Jelly – Try It Online")
### How it works
```
pZnⱮFȦ€€ḋFẹƓịF  Main link. Argument: M
 Z              Zip; transpose the rows and columns of M.
p               Take the Cartesian product of M and its transpose, yielding all pairs
                (r, c) of rows and columns of M.
    F           Flatten; yield the elements of M.
  nⱮ            Not equal map; for each element e of M, compare the elements of the
                pairs (r, c) with e.
     Ȧ€€        All each each; for each array of Booleans corresponding to an (r, c)
                pair, test if all of them are true.
         F      Flatten; yield the elements of M.
        ḋ       Take the dot product of each list of resulting Booleans and the
                elements of M.
           Ɠ    Read an integer S from STDIN.
          ẹ     Find all indices of S in the dot products.
             F  Flatten; yield the elements of M.
            ị   Retrieve the elements of the right at the indices from the left.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~88~~ ~~86~~ ~~84~~ 77 bytes
* -2 bytes thanks to [BWO](https://codegolf.stackexchange.com/questions/171550/get-me-out-of-here/171698?noredirect=1#comment414551_171698)
* -7 bytes thanks to [Tesseract](https://codegolf.stackexchange.com/users/82692/tesseract)
```
m!s=[k|k<-m>>=id,s==sum[x|r<-m,all(/=k)r,(i,x)<-zip[0..]r,all((/=k).(!!i))m]]
```
[Verify all testcases](https://tio.run/##XZFRasMwDIbfewoH9hDDny6OndiFpjfYCTwzAhvMJC4haaGM3j2T3Q6W@EWy9OmXLH93c/81DMsSsrm1/b0/FuF0av0n5radr8He7hOF0A1D/tr2fELucePH4sePttzv3ZRSKbfPs8xzHpxb/Hm8XmbWMrtjz5Nb20CgdrACFQzZA0y6NyihnAM7cPznNapEp5xe50SFmmRkBDSEgDCkSZySWxGRVMrUqoSQkRJbORqNckRUZMvUOHoUTfiarjVNLiWMIswoaANxgIg3JcnCCMhUWMlmXRrHjm@XT0tzPZZATgP956Qnq80@aigaJ9bGfVFnWkAVQcMT5na70PkzrT1049sHy9/zADZzVpzYOPnzhb2wwLIYeXzQ8gs "Haskell – Try It Online").
## Explanation
```
m ! s =                                         -- function !, taking m and s as input
    [k |                                        -- the list of all k's such that
        k <- m >>= id,                          -- * k is an entry of m
        s == sum                                -- * s equals the sum of
            [x |                                --     the list of x's such that
                r <- m,                         --     * r is a row of m
                all (/= k) r,                   --     * r does not contain k
                (i, x) <- zip [0 ..] r,         --     * i is a valid column index; also let x = r[i]
                all ((/= k) . (!! i)) m         --     * none of the rows contain k at index i
            ]
    ]
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~27 23 22 21~~ 20 bytes
```
fqvzss.DRsxLTQ-I#TQs
```
**[Test suite!](https://pyth.herokuapp.com/?code=fqvzss.DRsxLTQ-I%23TQs&input=%5B%5B6%2C1%2C5%5D%2C%5B1%2C2%2C8%5D%2C%5B9%2C8%2C5%5D%2C%5B6%2C0%2C4%5D%5D%0A9&test_suite=1&test_suite_input=%5B%5B6%2C+1%2C+5%5D%2C+%5B1%2C+2%2C+8%5D%2C+%5B9%2C+8%2C+5%5D%2C+%5B6%2C+0%2C+4%5D%5D%0A9%0A%0A%5B%5B7%2C+2%5D%2C+%5B1%2C+4%5D%5D%0A7%0A%0A%5B%5B12%2C+5%2C+2%2C+3%5D%2C+%5B17%2C+11%2C+18%2C+8%5D%5D%0A43%0A%0A%5B%5B7%2C+12%5D%2C+%5B10%2C+5%5D%2C+%5B0%2C+13%5D%5D%0A17%0A%0A%5B%5B1%2C+1%2C+0%2C+1%5D%2C+%5B2%2C+0%2C+0%2C+2%5D%2C+%5B2%2C+0%2C+1%2C+0%5D%5D%0A1%0A%0A%5B%5B57%2C+8%2C+33%2C+84%5D%2C+%5B84%2C+78%2C+19%2C+14%5D%2C+%5B43%2C+14%2C+81%2C+30%5D%5D%0A236%0A%0A%5B%5B2%2C+5%2C+8%5D%2C+%5B3%2C+5%2C+8%5D%2C+%5B10%2C+8%2C+5%5D%2C+%5B10%2C+6%2C+7%5D%2C+%5B10%2C+6%2C+4%5D%5D%0A49%0A%0A%5B%5B5%2C+4%2C+0%5D%2C+%5B3%2C+0%2C+4%5D%2C+%5B8%2C+2%2C+2%5D%5D%0A8%0A&debug=0&input_size=3)**
Does not deduplicate.
### How it works?
```
fqvzss.DRsxLTQ-I#TQs     Full program.
f                  s     Flatten M and keep only those elements T which satisfy:
 qvzss.DRsxLTQ-I#TQ      The filtering function. Breakdown:
              -I#TQ      Discard the rows that contain T. More elaborate explanation:
                # Q         |-> In M, keep only those elements that are...
               I            |-> Invariant under (equal to themselves after...)
              -  T          |-> Removing T.
                         Let's call the result of this expression CR (chopped rows).
          xLTQ           Map over the rows M and retrieve all indices of T.
         s               Collect indices in 1D list (flatten). Call this I.
      .DR                For each row left in CR, remove the elements at indices in I.
    ss                   Sum all the elements of this matrix flattened.
 qvz                     And then finally check whether they equal S.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~114~~ 108 bytes
```
lambda m,s:{a for a in sum(m,[])if s==sum(v for l in m for i,v in enumerate(l)if{a}-set(l)-set(zip(*m)[i]))}
```
[Try it online!](https://tio.run/##XVDLaoRAELzvVwzkoqECzkNnDPglxoMhSgTHFXUXEvHbTU@7IZhTv6qqu2v8Wj6vg9rb4m3va//@UQuP@XWtRXudRC26Qcw3H3mUVdy1Yi6KUN552oep57TDPRTNcPPNVC9N1BN6rbeXuVko5/DdjdGzj8uuiuNtH6duWEQblWUGibRCKaHgKOZwXGdIYKoKIo8vT2Il0Ha5/NEsFJMYYhliTgCpkJKkDigLKSEd6RPYaEb/l5Osl/DuBFIHqDyEQ3nWppupSUhFMeFTQkZdpjFLnSippb@0hjOEdQbWQeaQoTKaIpyEZrbS2fFxDpqk9iQTngou6Uekgw@7KMlgfxN2xRzOkQegfedrqJOwTDCZDiKnVOC4x8MHiXZs@w8 "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~80~~ 74 bytes
```
->\m,\s{grep {s==sum m[m.$_;[[Z](m).$_]]}o{*.grep(:k,!*.grep($_))},m[*;*]}
```
[Try it online!](https://tio.run/##NU/LboMwELz3K1wpqgBNItY22BTRD6ljRT2EHlorEaiHiPDtdG3gtOt57Hju1@G3XsJDvPWiW44f54DzOH0P17uYxq4b/4IILpwOl9a5T5@FnFfv59tUnKIoe//B67YeLnk@I7iiLfy8jF8P0WdPBkV/G14y52oQKg9HkLA8G9j0rlFCew/R5Ig6A5lUCTMrRhIV21QkDIhAlm8wr9VuouQq08kSpCJLu52jGWNG8ixTQNwYTbJVVRn@kVKwmmmrYSyoAcWXVjxhCSoZpKpXS/xW7KK2yflrKV5qmH1JVfTWr4Lm2OiJvTmJi8kosMy3yz8 "Perl 6 – Try It Online")
### Explanation
```
->\m,\s{...}  # Anonymous block taking arguments m and s
  grep {...}o{...},m[*;*]   # Filter matrix elements
                            # with combination of two functions
    *.grep(:k,!*.grep($_))  # (1) Whatever code returning matching rows
    s==sum m[               # (2) s equals sum of elements
      m.$_;                 #     in matched rows
      [                     #     (array supporting multiple iterations)
       [Z](m).$_            #     and matched columns (matched rows
                            #     of m transposed with [Z])
      ]
    ]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes
```
²˜ʒQεZ+}øεZ<~}ø_*OO¹Q
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0KbTc05NCjy3NUq79vAOIGVTB6Tjtfz9D@0M/P/fkis62kzHUMc0VifaUMdIxwJIW@pYgPlmOgY6JrGxAA "05AB1E – Try It Online")
Only after I've written this answer have I seen [Kevin's](https://codegolf.stackexchange.com/a/171762/59487). I believe this is substantially different, so I am posting it separately. My intuition says that the optimal byte count is around 18, so I'll have to revisit this and see what else I can do. With the current code, it is impossible to write a test suite but I have verified all test cases myself and the results are correct.
### Cropping Algorithm
To better illustrate the technique used, let's grab an example, with the element to crop \$k=5\$:
$$M=\left(\begin{matrix}6&1&\bbox[green,1pt]{\color{white}{5}}\\1&2&8\\9&8&\bbox[green,1pt]{\color{white}{5}}\\6&0&4\end{matrix}\right)$$
It first generates the matrix of equality with \$k\$:
$$\left(\begin{matrix}0&0&1\\0&0&0\\0&0&1\\0&0&0\end{matrix}\right)$$
Then, it goes through \$M\$ and for each row \$R\$, it adds \$\max(R)\$ to each element in \$R\$, highlighting the necessary rows while still preserving the uniqueness of the horizontal positions of the searched element:
$$\left(\begin{matrix}\color{green}{1}&\color{green}{1}&\bbox[green,1pt]{\color{white}{2}}\\0&0&0\\\color{green}{1}&\color{green}{1}&\bbox[green,1pt]{\color{white}{2}}\\0&0&0\end{matrix}\right)$$
Then, it goes through the transpose of \$M\$ and for each column \$C\$, it performs the operation \$(\max(C)-1)\space ||\space c\space\forall\space c\in C\:\$ (where \$||\$ is 05AB1E's bitwise OR – addition should work too, so replace `~` with `+` if you want to test that too), which results in:
$$\left(\begin{matrix}\color{green}{1}&\color{green}{1}&\bbox[green,1pt]{\color{white}{3}}\\0&0&\color{green}{1}\\\color{green}{1}&\color{green}{1}&\bbox[green,1pt]{\color{white}{3}}\\0&0&\color{green}{1}\end{matrix}\right)$$
Finally, it maps \$0\$ to \$1\$ and all other integers to \$0\$ and performs element-wise multiplication with \$M\$:
$$\left(\begin{matrix}\color{green}{0}&\color{green}{0}&\color{green}{0}\\1&1&\color{green}{0}\\\color{green}{0}&\color{green}{0}&\color{green}{0}\\1&1&\color{green}{0}\end{matrix}\right)\:\longrightarrow\:\left(\begin{matrix}\color{green}{0}&\color{green}{0}&\color{green}{0}\\1&2&\color{green}{0}\\\color{green}{0}&\color{green}{0}&\color{green}{0}\\6&0&\color{green}{0}\end{matrix}\right)$$
After which the sum of the resulting matrix is computed.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
˜ʒ©¹ε®å_}¹ζʒ®å_}ζ‚ζ€€OPOIQ
```
Does not sort nor uniquify the result.
Only works in the legacy (for now), because sum-each seems to be doing some odd things when part of the inner lists are integers and other are lists..
[Try it online](https://tio.run/##MzBNTDJM/f//9JxTkw6tPLTz3NZD6w4vja8FsrYBRcDsc9seNcwCEk1rgMg/wN8z8P//6GhDHUMdAx3DWJ1oIyBtoGMEZQFFY2O5DAE) or [verify all test cases](https://tio.run/##NU@7TgMxEOzvK6zUU3j9OPto0kRIqQIF6CLrhIKgzR9EQnwCJaKlQELpkg8IHUj3EfzIMWtAsrwzu7M7uzZubuV@yufLxdXy2vTzmdls78xsviYyZ4Zo@nr5fDq99ePhtP94vdn145G8wvH4/fDM7/Gdb3WxWl9OO0yltBDEAUXgkBk75MpbWIRhaLqmlARXFcoTuThEyr0mE0Qgmb1DE3wVS1XbOsZCPCtS22hFzqxjtHWoImZVQkVMdPceObCUA1KGdBBlwTMiC7yKnW8p1zV0Z/8X6fm7PEGL9A907aB3RARaqV5vowOPcCzmHw).
**Explanation:**
```
˜              # Flatten the (implicit) matrix-input
               #  i.e. [[6,1,5],[1,2,8],[9,8,5],[6,0,4]] → [6,1,5,1,2,8,9,8,5,6,0,4]
 ʒ             # Filter this list by:
  ©            #  Store the current value in a register-variable
   ¹           #  Take the matrix-input
    ε   }      #  Map it to:
     ®å_       #   0 if the current number is in this row, 1 if not
               #    i.e. [[6,1,5],[1,2,8],[9,8,5],[6,0,4]] and 6 → [0,1,1,0]
   ¹           #  Take the matrix-input again
    ζ          #  Swap its rows and columns
               #   i.e. [[6,1,5],[1,2,8],[9,8,5],[6,0,4]] → [[6,1,9,6],[1,2,8,0],[5,8,5,4]]
     ʒ   }     #  Filter it by:
      ®å_      #   Only keep the inner lists that does not contain the current number
               #    i.e. [[6,1,9,6],[1,2,8,0],[5,8,5,4]] and 6 → [[1,2,8,0],[5,8,5,4]]
               #    i.e. [[1,2,2],[1,0,0],[0,0,1],[1,2,0]] and 1 → []
          ζ    #  After filtering, swap it's rows and columns back again
               #   i.e. [[1,2,8,0],[5,8,5,4]] → [[1,5],[2,8],[8,5],[0,4]]
   ‚ζ          #  Pair both lists together and zip them
               #   i.e. [0,1,1,0] and [[1,5],[2,8],[8,5],[0,4]]
               #    → [[0,[1,5]],[1,[2,8]],[1,[8,5]],[0,[0,4]]]
               #   i.e. [0,1,0] and [] → [[0,' '],[1,' '],[0,' ']]
     €         #  Map each inner list / value to:
      €O       #   Sum each
               #    i.e. [[0,[1,5]],[1,[2,8]],[1,[8,5]],[0,[0,4]]]
               #     → [[0,6],[1,10],[1,13],[0,4]]
               #    i.e. [[0,' '],[1,' '],[0,' ']]
               #     → [[0,0],[1,0],[0,0]]
               #  (NOTE: For most test cases just `O` instead of `€€O` would be enough,
               #   but not if we removed ALL zipped inner lists for a number, like the
               #   second example above with input [[1,1,0,1],[2,0,0,2],[2,0,1,0]] and 1)
        P      #  Now take the product of each inner list
               #   i.e. [[0,6],[1,10],[1,13],[0,4]] → [0,10,13,0]
         O     #  Then take the sum of those
               #   i.e. [0,10,13,0] → 23
          IQ   #  And only keep those that are equal to the number-input
               #   i.e. 23 and 9 → 0 (falsey), so it's removed from the flattened input
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
=+Ṁ$€Z$⁺’¬×⁸FS
F³ç=⁹ƲƇ
```
[Try it online!](https://tio.run/##y0rNyan8/99W@@HOBpVHTWuiVB417nrUMPPQmsPTHzXucAvmcju0@fBy20eNO49tOtb@////aDMdQx3TWJ1oQx0jHQsgbaljAeab6RjomMT@twQA "Jelly – Try It Online")
-6 bytes using the general approach from Mr. Xcoder's 05AB1E answer.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
ＦθＦι⊞υκＩΦυ⁼ηΣＥθ∧¬№λιΣＥλ∧¬№Ｅθ§πξιν
```
[Try it online!](https://tio.run/##XYwxD4IwEIV3f8WN1@RMgJXJEE0cNCSODUMDGBprC6U1/PtaEKLxlnf33veu7oStjVAh3I0FHBgsKle9GoeF8dqhJ3gwxqD0Y/c58l1pZUwKMTo8SeVaOwfHwQs1Ykdw80@8iB4HgoNufn4pAsnYF1D/wNZyZ920E/YE08wvJc22yUPgnKeUUkJpRTyLmlC2btGtquiH/Uu9AQ "Charcoal – Try It Online") Link is to verbose version of code and includes deduplication. Explanation:
```
ＦθＦι⊞υκ
```
Flatten the first input array `q` into the predefined list `u`.
```
  υ                          Flattened array
 Φ                           Filter elements
       θ                     Input array
      Ｅ                      Map over rows
            ι                Current element
           λ                 Current row
          №                  Count matching elements
         ¬                   Logical Not
        ∧                    Logical And
               λ             Current row
              Ｅ              Map over columns
                    θ        Input array
                   Ｅ         Map over rows
                      π      Inner row
                       ξ     Column index
                     §       Inner element
                        ι    Current element
                  №          Count matching elements
                 ¬           Logical Not
                ∧            Logical And
                         ν   Current element
             Σ               Sum
     Σ                       Sum
    η                        Second input
   ⁼                         Equals
Ｉ                            Cast to string
                             Implicitly print each result on its own line
```
For each element of the list, sum the array, but if the row contains the element then use `0` instead of its sum, and when summing rows that don't contain the element, if the column contains the element then use `0` instead of the column's value. This is very slightly golfier than filtering the elements out as Charcoal can't sum an empty list.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 92 bytes
```
import StdEnv
$m s=[c\\r<-m,c<-r|sum[b\\a<-m|all((<>)c)a,b<-a&x<-[0..]|all(\u=u!!x<>c)m]==s]
```
[Try it online!](https://tio.run/##RY1NawIxEIbv@ysiSnFhIioqCoknPRR685jkMMZVAklW8iEr@NubBlvoaXhmnvcdbTv0xfWXbDvi0Phi3L0PiZzS5egfzcSRyIWWMjDqQDMaXjE7cZYS6@KF1k6nbN/qFuHMKH4MjIr5bKbeF5l5Ho0GttetU5xHVU4JQ2rG9VMKZiCcCLGBBawViAUsYVvnDrZv3sAcVkpVuWZuXaryrsI1e51M7ytOGv6Pf42/bvnWV4u3WOjnVzk8PTqj4w8 "Clean – Try It Online")
Explained:
```
$ m s                       // the function $ of `m` and `s`
 = [                        // is equal to
  c                         // the value `c`
  \\ r <- m                 // for every row `r` in `m`
  , c <- r                  // for every value `c` in `r`
  | sum [                   // where the sum of
   b                        // the value `b`
   \\ a <- m                // for every row `a` in `m`
   | all ((<>)c) a          // where `c` isn't in `a`
   , b <- a                 // for every value `b` in `a`
   & x <- [0..]             // with every column index `x` from zero
   | all (\u = u!!x <> c) m // where `c` isn't in column `x`
  ] == s                    // equals `s`
 ]
```
[Answer]
## MATLAB - 80 bytes
(*Corrected and*) Compacted:
```
function f(M,s);for k=M(:)';if sum(sum(M(~sum(M==k,2),~sum(M==k))))==s;k,end;end
```
And in a fully developped version:
```
function getthesum(M,s)
for k=M(:)'                         % For each element of M
    x = M==k ;                      % Index elements equal to "k"
    N = M( ~sum(x,2) , ~sum(x) ) ;  % New matrix with only the appropriate rows/columns
    if sum(sum(N))==s               % sum rows and columns and compare to "s"
        k                           % display "k" in console if "k" is valid
    end
end
```
---
Thanks to the comments to highlight my initial mistake. Note that this version does not de-duplicate the output.
It is possible to deduplicate the output with 5 more bytes:
```
% This will only cycle through the unique elements of 'M' (85 bytes):
function f(M,s);for k=unique(M)';if sum(sum(M(~sum(M==k,2),~sum(M==k))))==s;k,end;end
```
]


[Question]
      [
A [*nondeterministic finite automaton*](https://en.wikipedia.org/wiki/Nondeterministic_finite_automaton) is a finite state machine where a tuple \$(state,symbol)\$ is mapped to multiple states. Ie. we replace the usual \$\delta : Q \times \Sigma \to Q\ \$ transition function of a [DFA](https://en.wikipedia.org/wiki/Deterministic_finite_automaton) with another function \$\Delta : Q \times \Sigma \to \mathcal{P}(Q)\$.
If you know what an NFA is you might want to skip the next section.
### Formal Definition
An NFA is uniquely described by
* \$Q\$ a finite set of states
* \$\Sigma\$ a finite set of symbols
* \$\Delta : Q \times \Sigma \to \mathcal{P}(Q)\$ the transition function
* \$q\_0 \in Q\$ the initial state
* \$F \subseteq Q\$ a set of final states
The machine starts out in \$q\_0\$ and reads a finite string of symbols \$w \in \Sigma^\*\$, for each symbol it will simultaneously apply the transition function function with a current state and add each new set of states to the set of current states.
## Challenge
For this challenge we will ignore \$F\ \$ to simplify it, furthermore the alphabet will always be the (lower-case) letters \$\texttt{a}\ \$ to \$\texttt{z}\ \$ and the set of states will be \$\{0 \dots N\}\$ for some non-negative integer \$N\$. The initial state will always be \$0\$.
Given a word \$w \in \{\texttt{a}\dots\texttt{z}\}^\*\$ and a description of the NFA, your task is to determine all the final states.
### Example
Consider the string \$\texttt{abaab}\$ and the following description:
```
state, symbol, new-states
0, 'a', [1]
1, 'a', [0]
1, 'b', [1,2]
```
The machine will start in \$q\_0 = 0\$:
1. read an \$\texttt{a}\$: new states \$\{1\}\$
2. read a \$\texttt{b}\$: new states \$\{1,2\}\$
3. read an \$\texttt{a}\$: new states \$\{0\}\$
4. read an \$\texttt{a}\$: new states \$\{1\}\$
5. read a \$\texttt{b}\$: new states \$\{1,2\}\$
So the final states and thus the output would be \$\{1,2\}\$.
**Note:** In step *(2)* the transition of state \$2\$ maps to \$\emptyset\$ as the description only includes transitions to non-empty sets.
## Rules
The input will consist of a string and some kind of description of the NFA (without \$\epsilon\$-transitions):
* the input string will always be element of \$\{\texttt{a}\dots\texttt{z}\}^\*\$
* valid inputs (not limited to):
	+ list/array of tuples/lists
	+ new-line separated input
* the description of the NFA will only contain transitions with non-empty sets as result
	+ you may abbreviate rules with the same characters if their result is the same (eg. rules `0,'a',[1,2]` and `0,'b',[1,2]` could be abbreviated with `0,"ab",[1,2]`
	+ you may take each rule separate (eg. rule `0,'a',[1,2]` can be `0,'a',[1]` and `0,'a',[2]`)
* you may choose upper-case letters if you want
* you may take the number of states as input
* you may assume some kind of ordering of the inputs (eg. ordered by state or symbols)
The output will be a list/set/new-line separated output etc. of the final states
* order doesn't matter
* no duplicates (as it's a set)
### Test cases
These examples will be in the format `description word -> states` where `description` is a list of tuples `(state,symbol,new-states)`:
```
[]  "x" -> []
[]  "" -> [0]
[(0,'a',[1]),(1,'a',[0]),(1,'b',[1,2])]  "abaab" -> [1,2]
[(0,'a',[1]),(1,'a',[0]),(1,'b',[1,2])]  "abc" -> []
[(0,'p',[0,1]),(0,'g',[2]),(1,'c',[1]),(1,'g',[4]),(1,'p',[2]),(2,'c',[0])]  "ppcg" -> [2,4]
[(0,'f',[1]),(1,'o',[1,2]),(2,'b',[3]),(3,'a',[4]),(4,'r',[0,4])]  "foobar" -> [0,4]
[(0,'f',[1]),(1,'o',[1,2]),(2,'b',[3]),(3,'a',[4]),(4,'r',[0,4])]  "fooooooobar" -> [0,4]
[(0,'f',[1]),(1,'o',[1,2]),(2,'b',[3]),(3,'a',[4]),(4,'r',[0,4])]  "fobarfo" -> [1,2]
[(0,'f',[1]),(1,'o',[1,2]),(2,'b',[3]),(3,'a',[4]),(4,'r',[0,4])]  "foobarrf" -> [1]
[(0,'d',[1,2]),(1,'u',[2]),(2,'u',[2,3]),(2,'p',[3]),(3,'p',[3])]  "dup" -> [3]
[(0,'a',[0,2]),(0,'b',[3]),(1,'a',[1]),(1,'b',[1]),(2,'b',[1,4]),(4,'b',[2])]  "aab" -> [3,1,4]
[(0,'a',[0,2]),(0,'b',[3]),(1,'a',[1]),(1,'b',[1]),(2,'b',[1,4]),(4,'b',[2])]  "abb" -> [1,2]
```

[Answer]
# [Haskell](https://www.haskell.org/), 66 bytes
```
import Data.List
f d=foldl(\s c->nub[r|(y,r)<-d,g<-s,(g,c)==y])[0]
```
[Try it online!](https://tio.run/##Tc7NCoMwEATgu0@xSMENrEV7Np567BtYDxujNjT@kKQHoe@eVtqDt4@BGebB/tlbG6OZ1sUFuHLg8834kAyg5bBYbfHuocvr@aUa98aNnKhyTWOVe8KROiHl1oqmaKPufefMGswyg4QGsaCMM0GlIMTy5@Jvdch3X0SbTGz24urMHOAE3wOHwZQVs0rjBw "Haskell – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 42 bytes
```
,0{hẸ&t|∋₁B∋IhJ&tJ&hhC∧I∋₁C∧It∋S&hb;B,S↰}ᵘ
```
input as [string, nfa]
where nfa is a list of state transitions [ initial state, letter, new states as list ]
# Explanation
```
,0                                              # Append 0 to the input (initial state)
  {                                      }ᵘ     # Find all unique outputs
   h                                            # if first element (string)
    Ẹ                                           #   is empty
     &t                                         #   then: return last element (current state)
       |                                        #   else:
        ∋₁B                                     #       save the state transitions in "B"
           ∋I                                   #       take one of these transitions, save in "I"
             hJ                                 #       take the initial state requirement, store in "J"
               &tJ                              #       make sure "J" is actually the current state
                  &hhC                          #       Save first char of string in C
                      ∧I∋₁C                     #       make sure the char requirement for the state transition is the current char
                           ∧It∋S                #       Make "S" equal to one of the new states
                                &hb             #       Behead the string (remove first char)
                                   ;B,S         #       Add B (the state transitions) and S (the new state)
                                       ↰        #       recur this function
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X8egOuPhrh1qJTWPOrofNTU6ASnPDC@1Ei@1jAznRx3LPSHiYGYJkB2slpFk7aQT/KhtQ@3DrTP@/49WSkxKTExS0omONtBRSgTShrGxQALCNoCyQfKGOkaxsbH/owA "Brachylog – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) v2, 31 bytes
```
{b,Ȯ,Ȯ\c↔,0↔ġ₃kH&hg;Hz{∋ᵈ}ᵐtt}ᵘ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vzpJ58Q6IIpJftQ2RccASBxZ@KipOdtDLSPd2qOq@lFH98OtHbUPt04oKQGSM/7/j46ONtCxNNcxjNWJNgQxDCAMC5iIhY5RLJAFlAEyQSSIERv7PwoA "Brachylog – Try It Online") ([or with a more complex example](https://tio.run/##SypKTM6ozMlPN/r/vzpJ58Q6IIpJftQ2RccASBxZ@KipOdtDLSPd2qOq@lFH98OtHbUPt04oKQGSM/7/j46ONtBRSlTSMYjVgbKMIKwkJR1jIMsQLGYIYSVBWEZoLBMgywTMMooFMkEawDhJKTb2fxQA "Brachylog – Try It Online"))
Brachylog is really good at this sort of problem, and really bad at problems that require two separate inputs and an output. Almost all of this program is just plumbing.
Input format is a list containing two elements: the first is the list of state transitions (`[oldState, symbol, newState]`), and the second is the list of symbols. I originally planned this program to work with character codes for symbols (because Brachylog's string handling can be a bit weird sometimes), but it turns out that characters work too (although you have to write the input string as a list of characters, not as a string). If a state-symbol pair can transition to multiple different states, you write multiple transitions to deal with that.
## Explanation
```
{b,Ȯ,Ȯ\c↔,0↔ġ₃kH&hg;Hz{∋ᵈ}ᵐtt}ᵘ
{                            }ᵘ   Find all distinct outputs that can result from:
 b                                  taking the input minus its first element,
  ,Ȯ                                appending a singleton list (i.e. an element)
    ,Ȯ                              then appending that same element again
      \                             and transposing;
       c                            then concatenating the resulting lists,
        ↔,0↔                        prepending a 0,
            ġ₃                      grouping into blocks of 3 elements
              k                       (and discarding the last, incomplete, block),
               H&                   storing that while we
                 h                  take the first input element,
                  g  z              pair a copy of it with each element of
                   ;H                 the stored value,
                      {  }ᵐ         assert that for each resulting element
                       ∋ᵈ             its first element contains the second,
                        ᵈ ᵐ           returning the list of second elements,
                            t       then taking the last element of
                           t          the last element.
```
It's probably easier to follow this by looking at what some partial versions of the program would produce. Using the following input each time:
```
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]
```
we can observe the outputs of some prefixes of this program:
```
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ
[[97,98,97,97,98],L,L]
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ\
[[97,A,A],[98,B,B],[97,C,C],[97,D,D],[98,E,E]]
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ\c↔,0↔
[0,97,A,A,98,B,B,97,C,C,97,D,D,98,E,E]
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ\c↔,0↔ġ₃k
[[0,97,A],[A,98,B],[B,97,C],[C,97,D],[D,98,E]]
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ\c↔,0↔ġ₃kH&hg;Hz
[[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[0,97,A]],
 [[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[A,98,B]],
 [[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[B,97,C]],
 [[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[C,97,D]],
 [[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[D,98,E]]]
[[[0,97,1],[1,97,0],[1,98,1],[1,98,2]],[97,98,97,97,98]]b,Ȯ,Ȯ\c↔,0↔ġ₃kH&hg;Hz{∋ᵈ}ᵐ
e.g. [[0,97,1],[1,98,1],[1,97,0],[0,97,1],[1,98,1]]
```
For the first example here, `L` is initially an unknown element, but when we transpose it via `\`, Brachylog realises that the only possibility is a list with the same length as the input. The last example here is nondeterministic; we're modelling nondeterminism in the NFA using the nondeterminism in Brachylog itself.
## Possible improvements
Some of the syntax here, like `↔,0↔` and especially the mess with `H&hg;Hz{…ᵈ}ᵐ`, is fairly clunky. It wouldn't surprise me if there were a terser way to phrse this.
`{∋ᵈ}ᵐ` is in its own right a fairly suspicious structure – you'd expect to just be able to write `∋ᵈᵐ` – but it doesn't parse for some reason.
[Answer]
# Python 3, ~~103~~ 80 bytes
*thanks to @BWO*
```
w=lambda n,f,a={0}:w(n,f[1:],{y for(x,c,y)in n if c==f[0]and{x}&a})if''<f else a
```
[TIO](https://tio.run/##LcmxDoMgFIXh3ae4cSiQ3AFsJ1OehDhQFEtikVgTNIZnp0Z6pi/nD/v6nv095ygn/Xn1Gjxa1PLgqY30tBJth8cOdl7ohgZ35jx4cBaMlFbxTvv@2NJNJ@YsIU8Lw/QdQOewOL/SCs5FqihHEghyhn@JopFgc0ogMeUT1/coCqU2V@WsQ6hDMGPNKpZ/)
Previous "elegant" list comprehension(103 bytes):
```
def w(a,b):
    q=[0]
    for c in b:q=[j for s in q for i in a if s in i if i[1]==c for j in i[2]]
    return q
```
[Answer]
# JavaScript (ES6), 99 bytes
Takes input as `(nfa)(string)`. Returns a Set.
```
a=>g=([c,...b],s=[0])=>c?g(b,a.reduce((p,[x,y,z])=>s.includes(x)&y==c?[...p,...z]:p,[])):new Set(s)
```
[Try it online!](https://tio.run/##tdPdboIwFADg@z0F8WK2SUUErkzQh9hl04u2/MSF0AZkU1@e9Term2YmQy7IKZR@55Sed/pBB94f5HHVibKa6mKixa4pAOYojmNG0FDghMBix/cNYIjGfVWOvAJAInxCZ3TR74b40PF2LKsBnODruSj4HquvpV7iQrZqKoFw21Wf0Vt1BAOcuOgG0VZxKxpQA/UWLE4LCKNZr/U6Wu0iTF5uaLNjXkt@cThBS7pEeEOIutk4cTHTz1FKiM6JMkrZo4k5Tn/8D5A/vg/3dlNrUgvIeGrUqFHqPB7koZ/nLpZ@TmrnJDYjKXljUnJaivKbYB0sK3xJZjFdYKbjzBZuwBwte5NibplaCEb7q9r973saaK5AfTaoqFqEJf5xYmbZ0r4ORA/e5MpvQoFjcBxMjDI3kgHuYs2Vo/x5dB2X3e2HxHJJUNHmulOYj1PfKb5WZhM0XWOb1HNoc@cPzkmykNTbNn0B "JavaScript (Node.js) – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 81 bytes
```
function(a,b,e,s)Reduce(function(A,x)unique(e[a%in%A&b==x]),el(strsplit(s,"")),0)
```
[Try it online!](https://tio.run/##PYzRCoMwDEXf9xWlw9lABm3x1YG/sFfpg3ZVCuI6a8G/71p1I9zkJLncJQ51HMKsV/ueWYc9GvTwNK@gDfvfG9wgzPYTDDNtV9i5aG59XW8K0EzMr4t3k12ZR0oBkEO8Mo6lK7HlKJIpb2PaZGaBpU4sTs736mT388jDwxUoQqhzeqTk/iCtxEpdBqZTYC6xlwTUjDqKu8YkfU63c35nr0yqUueARyTELw "R – Try It Online")
Straightforward answer using `Reduce`. Takes rules as three vectors of `state, symbol, new-states` called `a,b,e`.
Rules are separate (eg. rule `0,'a',[1,2]` is `0,'a',1` and `0,'a',2`).
[Answer]
# [Coconut](http://coconut-lang.org/), 64 bytes
```
d->reduce$((s,c)->{r for(*y,r)in d for S in s if[S,c]==y},?,{0})
```
[Try it online!](https://tio.run/##Tc1LCoMwEAbgfU4xSMGkjKJdFmIP4dK6iImRbBKJShHr2VNToXQ137z4pZPOLnPQ/BlUVvleLbK/UDqhZFm1edDO0@uKnhkLKnZQw8EJjG5qlC3n644P3IqdBdVP0ptxNs4Ch4YWmIoUS4a0/Ko41f1mh26sJcNxrenfNyMkJr2cVzEsEZ0QXYIRMpbkTuDcvisYvbFzng/hAw "Coconut – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 68 bytes
This one based on ovs's Haskell solution is a bit shorter than my initial approach was.
*now includes a test harness*
```
import StdEnv
?d=foldl(\s c=removeDup[r\\(y,r)<-d,g<-s|(g,c)==y])[0]
```
[Try it online!](https://tio.run/##vZS7boMwFIbn8hSWOmAkI3Ebg7KkQ6UOlTICg7EBIQG2jEkbqc9eim1I3bRblTCg7/jy/8f2sUlX4WHuGZ26CvS4Hea250xIcJT0aTg5e5rWrKMdzEdAUlH17FQdJp6JPIdnJLydT1Gz88cP2CDipem58LKgmI8SC@k8AlmNcgQpyGBWoMx9d5d/4SHnwcQqDNYYwgC52PVQ6CEIQ8PByqXVrjjy1HRcYlwqjRBF/1EhVlpagG@TVg5XbvQkI0AsMdWerMy3MZEZE2gTzkmjXCKU2Ea1JcKueBNRmcaKY7MabZQgV2xJrpxoo5qxEgu9sXew0t/9/Banmv1x4LfaRlFrM9uKWuVArXKYLKtrjlfmVgqGlRWduHKJryt4K0C8qQXWIsKfVX6p7Og3bwu1Kt7cmhiFP4/sxq7l910tlrehngYiWzYsz8PeSQEeKMgubbQaiWi55jcmKEhTwCbJJwnyHECrG@l@tPZ6YOebV6eYP0nd4Wac/eeX@XAecN8SE7x2WNZM9F8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes
```
⊞υ⁰Ｆη«≔υζ≔⟦⟧υＦζＦθ¿∧⁼§λ⁰κ⁼§λ¹ιＦ§λ²¿¬№υμ⊞υμ»Ｉυ
```
[Try it online!](https://tio.run/##ZY6xCoMwFEXn5iseTnmQgro6iXToUtxDhqi1SjWiMaVY@u1pohUKHUI471wut2zkVA6yszY3uqGGQYgJqYcJaIPwIodU6/amvFic2JELBsbzmlwQ1n9EaGugqaroaTSy0zSdz6q6Pmnnexnc3fs3kbu2iN@SHxHjVngZZpoNRs1@Ru@T@9jebXiTfGqdy6R2AcTEWs55yCCQAQMeCbeV8Gjn0PGGxapZLPwlkIWURSDs8dF9AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
⊞υ⁰
```
Push `0` to the predefined empty list to set the inital state to \$\{0\}\$.
```
Ｆη«
```
Loop over the input.
```
≔υζ
```
Copy the state.
```
≔⟦⟧υ
```
Reset the state.
```
Ｆζ
```
Loop over the copy of the state.
```
Ｆθ
```
Loop over the NFA entries.
```
¿∧⁼§λ⁰κ⁼§λ¹ι
```
If the entry matches, then...
```
Ｆ§λ²
```
... loop over the new states...
```
¿¬№υμ
```
.... if they are not already in the list...
```
⊞υμ»
```
... add them to the list.
```
Ｉυ
```
Cast the list of states to string for implicit output on separate lines.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~61~~ 54 bytes
```
->\n,\s{set +s&&reduce {n.grep(*[^2]⊆@_)[*;2]},0,|s}
```
[Try it online!](https://tio.run/##tZPRboMgFIbv9xSkSxQ6ahDNbpo1ew/rFlDxZq0EZ7Km6@0u9ph7EScglTa9WeK8wPyHc77/CEdZqbfHfncAgQBP/Wqz3eNte2yrd/DQBoGqyq6owHEf1aqScJm90Pzn@@v5FWXLNc1PmODP9tS37AAEjDKSYxBlcR4VzY4jIBp1ByHCYPGxGNZ7sNoAiMbQFCFYx4ZXyEIMY4yQXo0gTnCzQxHSpYwzxqd6Hf8roLhsSNdKkx7r/EHVg6KuuPCxeid1Qp7TqE3ThtpCyqKePChOnY3wWY3rytTrHhOzldjurU2KQ2XIqUWLpuFM@ec3L9w8/@kwsEVz8/7mOhwlfLyjlxNwwHf@1VmRjEr6Xk5oetnJCZxczC2xYOJ3Gl9NJD8L6kQ6fgQfuzHj6U93guPp9Oc24te/0br/BQ "Perl 6 – Try It Online")
Takes a list of state transitions and an input string as list of characters.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 31 bytes
```
W=[W]c;Ê?ßUÅVVf!øW føUg)mÌc):Wâ
```
[Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=Vz1bV11jO8o/31XFVlZmIfhXIGb4VWcpbcxjKTpX4g==&input=ImFiYWFiIgpbWzAsImEiLFsxXV0sClsxLCJhIixbMF1dLApbMSwiYiIsWzEsMl1dXQotUQ==)
Saved 2 bytes with better use of Japt's ability to implicitly form a function out of some inputs
Explanation:
```
W=[W]c;                            Initialize the state set to [0] on the first run
       Ê?                   :Wâ    If the input is empty return the unique states; else...
             Vf!øW                 Get the transitions valid for one of the current states
                   føUg)           Of those, get the ones valid for the current character
                        mÌc)       Merge the states of the remaining transitions
         ßUÅV                      Repeat with the remaining characters as input
```
The new "initialize states" code could use a bit more detail. Japt initializes `W` to 0 if there are fewer than 3 inputs, so on the first run `[W]` is `[0]`, and `c` "flattens" an array. `[0]` is already as flat as it gets, so it isn't changed. On subsequent runs `W` has a different value, for example `[1,2]`. In that case `[W]` becomes `[[1,2]]`, a single-element array where that element is an array. This time `c` unwraps that and gets back to `[1,2]`. Thus, on the first run it's `W=[0]` and on subsequent runs it's `W=W`.
]