| Bytes | Lang | Time | Link |
|---|---|---|---|
| 055 | Juby | 221005T210918Z | Jordan |
| 007 | Dyalog APL | 250820T172541Z | Aaron |
| 029 | tinylisp 2 | 230110T231059Z | DLosc |
| 035 | Arturo | 230109T194151Z | chunes |
| 030 | Microsoft Excel/Google Sheets | 241029T192747Z | General |
| 038 | Clojure | 240918T105816Z | Martin P |
| 062 | Setanta | 240806T155117Z | bb94 |
| nan | Swift 5.10 35 Bytes | 240806T090710Z | colmmurp |
| 006 | J | 240806T074822Z | Bubbler |
| 007 | Pip xp | 220120T031210Z | DLosc |
| 085 | Go | 221005T141449Z | bigyihsu |
| 011 | J | 221010T155230Z | Conor O& |
| nan | Fig | 221010T145948Z | Seggan |
| 002 | Japt | 221010T145150Z | Shaggy |
| 180 | Fortran | 220120T103305Z | mcocdawc |
| 073 | Java 8 | 220119T104309Z | Kevin Cr |
| 006 | K ngn/k | 221008T023015Z | oeuf |
| 031 | Ruby | 221005T205157Z | Jordan |
| 013 | Raku | 220119T224958Z | Sean |
| 016 | Julia 1.0 | 220202T194814Z | Sundar R |
| 048 | tinylisp | 220202T151714Z | Giuseppe |
| 079 | F# | 220121T130438Z | Bryan Sl |
| 034 | JavaScript Node.js | 220121T172028Z | AncientS |
| 061 | Kotlin | 220120T121157Z | h.j.k. |
| 084 | tinylisp | 220120T032923Z | DLosc |
| 020 | Pari/GP | 220119T102034Z | alephalp |
| 085 | C gcc | 220120T024025Z | ErikF |
| 060 | Nim | 220119T235640Z | Adam |
| 034 | Desmos | 220119T214407Z | Aiden Ch |
| 045 | Python 3 | 220119T215900Z | Surculos |
| 018 | Wolfram Language Mathematica | 220119T195006Z | att |
| 004 | Husk | 220119T112442Z | Dominic |
| 019 | Haskell + hgl | 220119T105516Z | Wheat Wi |
| 024 | R | 220119T110839Z | Dominic |
| 004 | APL Dyalog Unicode | 220119T112655Z | Adá |
| 035 | Ruby | 220119T102943Z | Cool guy |
| 006 | 05AB1E | 220119T101042Z | Kevin Cr |
| 028 | Haskell | 220119T102133Z | Wheat Wi |
| 034 | JavaScript V8 | 220119T101057Z | l4m2 |
| 043 | JavaScript Node.js | 220119T101009Z | Cool guy |
| 045 | Python 3.8 prerelease | 220119T100621Z | ophact |
| 002 | Vyxal | 220119T095936Z | lyxal |
J-uby, 55 bytes
Takes curried arguments with the function first and array second, e.g. F.(->x{x < 1}).([5, 2, 0]).
:& &~(~:&%(:|&:[])|:+&:select|:|&(:+@|:*))|:& &:-|:D|:~
This is equivalent to the following Ruby lambda:
->f{ ->a{ (0...a.size).select {|i| f[a[i]] } } }
Dyalog APL, 7 chars
{⍸⍺⍺¨⍵}
While @Adám's answer is shorter, I thought I'd put this operator definition here for posterity (as CodeGolf is where I myself have done all my APL learning).
My attempt at an explanation: the presence of the left-operand ⍺⍺ in the definition above flags the whole thing as an operator as opposed to a function, so its expecting a left-operand when called and then a right-argument. This means the left-operand is taken as a function definition inside the operator rather than another function to be called afterwards.
{⍵>2}{⍸⍺⍺¨⍵}1 2 3 ¯5 5
v ^
| +-----------------------------------------------+
+--> This whole function is effectively placed here >-+
{⍸⍺⍺¨⍵}
⍺⍺ # Apply the left-operand
¨ # to each element of
⍵ # the right-argument
⍸ # Return 1-based indices where true
tinylisp 2, 33 29 bytes
(\(L F)(f(. F(p nth L))(r(# L
Explanation
(\(L F)(f(. F(p nth L))(r(# L))))
(\ ) ; Lambda function
(L F) ; that takes a list L and a function F:
(f ) ; Filter
(r(# L)) ; range(length(L)), the indices of L
(. ) ; by the composition of
F ; F with
(p nth L) ; a partial application of nth to L
That is, for each index, get the element of L at that index and call F on it. If it's truthy, keep that index, otherwise discard it.
Microsoft Excel/Google Sheets, 30
LAMBDA(l,p,FILTER(l,MAP(l,p)))
Usage Example:
=LET(
argwhere,LAMBDA(l,p,FILTER(l,MAP(l,p))),
argwhere(SEQUENCE(1000),LAMBDA(x,x>5))
)
Lists numbers from 6 to 1000.
Essentially this turns the FILTER into a function that accepts a LAMBDA. Pretty handy.
Clojure, 38 bytes
#(keep-indexed(fn[i x](when(%2 x)i))%)
Example:
(#(keep-indexed(fn[i x](when(%2 x)i))%) [1, 2, 0, 0, 3, 0, 0, 0, 4] zero?)
=> (2 3 5 6 7)
Swift 5.10 35 Bytes
{l,p in l.indices.filter{p(l[$0])}}
Anonymous closure that accepts a zero-index list l of type [Any] and a predicate p of type (T) -> Bool.
Outputs an [Int] of truthy indices
Un-golfed, generic version
func argwhere<T>(l: [T], p: (T) -> Bool) -> [Int] {
l.indices.filter { index in
p(l[index])
}
}
J, 6 bytes
I.@:"+
Modifier trains are such cursed constructs.
Given the explicit definition 1 :'I.u"+y' here, note that it suffices to create a verb using u and then call it with y. The possible verb trains are [:I.u"+ and I.@:(u"+).
Looking through the table of modifier trains here, V0 V1 ?? does not exist, so the former is not an option. (I guess you can get around with the conjunction versions of ] or [, but it's already anti-golfy.)
Then I looked for V0 C1 ??. V0 C1 A2 exists and we get a 3-train I.@:("+). Can we do better?
V0 C1 C2 also exists, and I.@:" means a derived conjunction I. @: (u"v). We can attach + to the right side to get the desired adverb. That is (I.@:")+. Is it OK to remove the parens here? Apparently yes, since modifier trains are evaluated in triples from the left, as opposed to regular trains that group from the right.
Pip -xp, 7 bytes
bMa@*:1
Takes a list and a function that returns 0 (falsey) or 1 (truthy) as command-line arguments. Uses 0-indexing. Attempt This Online!
Explanation
b ; Second argument (the function)
M ; Mapped to each element of
a ; First argument (the list)
@*: ; Find all indices of
1 ; 1 (truthy)
Go, 85 bytes
func(f func(int)bool,L[]int)(A[]int){for i,e:=range L{if f(e){A=append(A,i)}}
return}
Go, generic, 90 bytes
func g[T any](f func(T)bool,L[]T)(A[]int){for i,e:=range L{if f(e){A=append(A,i)}}
return}
J, 13 11 bytes
2 bytes saved thanks to Razetime's approach of using I.
1 :'I.u"+y'
Try it online! Assumes the given predicate is a true boolean predicate, which yields 1 for truthy and 0 for falsey, as is standard in J.
I don't think there's a tacit way to make an adjective as complex as this. Technically, as per standard IO, we can have 8 bytes by assuming the function is stored in a predefined variable u:
[:I.u"+
Explanation
Approach c/o Razetime:
I.u"+y
u the given boolean function
"+ applied at each cell of
y y, the input list
I. obtain indices where truthy
Old approach:
u"0#i.@#
i. the indices from 0 to
@# the length of the input, right-exclusive
# and keeping only the elements corresponding to
u the given boolean function
"0 applied to each cell of the input
Fig, \$2\log_{256}(96)\approx\$ 1.646 bytes
TM
The '>+10x20 bit in the link is the function \$f(x) = x + 10 > 20\$.
TM # Takes a function and a list in any order
M # Map the list by the function
T # Return the truthy indexes of the resulting list
Fortran, 180 bytes
Since there are anonymous functions for other languages allowed, I assume that I can name my argwhere function with a letter and make use of the implicit typing.
function J(v,n,f)
integer v(*)
interface
logical function g(m)
end function
end interface
procedure(g) f
allocatable J(:)
J = pack([(i,i=1,n)],mask=[(f(v(i)),i=1,n)])
end function
An ungolfed version looks like this.
program test_argwhere
implicit none
abstract interface
logical pure function predicate_t(n)
integer, intent(in) :: n
end function
end interface
write(*, *) argwhere([1, 3, 4, 8, 5], is_even)
contains
pure function argwhere(vals, predicate) result(res)
integer, intent(in) :: vals(:)
procedure(predicate_t) :: predicate
integer, allocatable :: res(:)
integer :: i
res = pack([(i, i = 1, size(vals))], mask=[(predicate(vals(i)), i = 1, size(vals))])
end function
logical pure function is_even(n)
integer, intent(in) :: n
is_even = mod(n, 2) == 0
end function
end program
```
Java 8, 74 73 bytes
f->a->{for(int i=0;i<a.length;i++)if(f.test(a[i]))System.out.println(i);}
-1 byte thanks to @Unmitigated
0-based. Outputs the indices on separated newlines to STDOUT.
Explanation:
f->a->{ // Method with Function & integer-array parameters and no return
for(int i=0;i<a.length;i++)
// Loop `i` in the range [0,length):
if(f.test(a[i])) // If the Function for the `i`'th integer of the array is truthy:
System.out.println(i);}
// Print index `i` with trailing newline
K (ngn/k), 12 10 9 6 bytes
{&x'y}
Down 3 bytes thanks to Steffan
Takes x as black box function and y as list of integers.
Explanation:
{&x'y} Main function.
x'y Apply each value y to x (x(y)), return a binary list
& Get all the truthy indices
Raku, 13 bytes
{grep :k,|@_}
Raku's grep filtering built-in can return matching indices instead of matching values if given the adverb :k. This is just an anonymous function that adds :k to the arguments it's given and passes them all to grep.
Raku's function objects actually have an assuming method that returns a new function with some of the arguments to the original function fixed in advance, so this code would more idiomatically be written &grep.assuming(:k) or the even terser &grep.assuming:k, but that's too long for golf.
Julia 1.0, 16 bytes
l/f=findall(f,l)
Boring builtin, just change of order of parameters, let's move on. (The answers are all 1-indexed, by the way.)
Julia 1.0, 18 bytes
l/f=findall(f.(l))
This looks very similar, but works differently and shows off Julia's generalized broadcasting feature: f.(l) automatically maps f over each element of l, collects the results into an Array, type-infers that to be as a BitVector (a 1-D array of booleans), and passes that on to findall. This single argument version of findall accepts only arrays of booleans, and returns indices where there are true values.
Julia 1.0, 21 bytes
l/f=axes(l)[1][f.(l)]
Even avoiding findall altogether, the answer isn't too much longer!
axes(l) returns the indices in each dimension of l. Here since l is one dimensional, we take axes(l)[1] which gives the indices of the list. On that, we use Logical indexing: As seen above, f.(l) returns an array of booleans. When we use that to index within the list of indices, we get back the indices where the function f returns true.
tinylisp, 48 bytes
(load library
(d A(q((L F)(all-indices(map F L)1
The library unsurprisingly contains some rather useful functions for golfing; not sure if this should be scored as tinylisp + library. Takes the test harness from DLosc's answer.
F#, 79 bytes
let x a p = a|>Seq.mapi(fun i a -> i,a)|>Seq.filter(fun(_,a)->p a)|>Seq.map fst
JavaScript (Node.js), 34 bytes
x=>y=>x.flatMap((b,i)=>y(b)?i:[]);
f = x => y => x.flatMap((b, i) => y(b) ? i : []);
console.log(f([1, 2, 0, 0, 3, 0, 0, 0, 4])(x => x == 0))
console.log(f([4, 3, 5, 7, 11, 13, 17])(x => x % 2 == 0))
console.log(f([8, 9, 10, 11, 12, 13])(x => x + 10 > 20))
console.log(f([5, -5, 2, -2, 0])(x => x < 0))
console.log(f([5, 2, 0])(x => x < 0))
Kotlin, 72 61 bytes
fun <T> List<T>.f(p:(T)->Boolean)=indices.filter{p(this[it])}
0-based solution.
Uses built-in indices to perform a filter on.
Example:
fun main() {
println(listOf(1, 2, 0, 0, 3, 0, 0, 0, 4).f { it == 0 })
}
tinylisp, 84 bytes
(d w(q((L F N)(i L(i(F(h L))(c N(w(t L)F(a 1 N)))(w(t L)F(a N 1)))L
(q((L F)(w L F 0
The second line is an anonymous function that implements argwhere; the first line is a helper function. Uses 0-indexing (though it could just as easily be 1-indexing; simply change the number on the second line). Try it online!
Explanation
The helper function w, in addition to L (the list) and F (the function), gets an extra argument N (the current index). Its logic boils down to:
- If
Lis nonempty:- If the result of calling
Fon thehead ofLis truthy,consNto the front of a recursive call towwith arguments:tail ofLFadd 1 toN
- Else, just do the recursive call
- If the result of calling
- Else, return
L(empty list)
The anonymous function calls w with an initial index of 0.
Pari/GP, 20 bytes
-9 bytes thanks to @Joe Slater. Didn't know that select can take a flag.
(a,g)->select(g,a,1)
Pari/GP, 29 bytes
(a,g)->[i|i<-[1..#a],g(a[i])]
C (gcc), 85 bytes
1-based.
Takes an integer array with a length and a function taking an integer.
m;f(s,l,p)int*s,p();{putchar(91);for(m=l;l--;s++)p(*s)&&printf("%d,",m-l);puts("]");}
Desmos, 34 bytes
a=[1...l.length]b(l)
f(l)=a[a<1/0]
\$b(l)\$ is the inputted black box function, which you will need to change for each test case (Desmos doesn't support inputting functions as arguments). \$f(l)\$ is the argwhere function. The output will be 1-indexed.
Further details in the graph links.
Python 3, 45 bytes
def f(L,F,t=0):F(L[t])and print(t);f(L,F,t+1)
A function that prints the indices to STDOUT and terminates with an error.
Wolfram Language (Mathematica), 18 bytes
Position[1>0]@*Map
Input [f, list]. Returns a list of 1-indexed {index}s.
Finds the positions of Trues when the function is mapped onto the list.
Wolfram Language (Mathematica), 13 bytes
Position@_?#&
Input [f][list]. Returns a list of 1-indexed {index}s.
Finds the positions of elements that satisfy a predicate - basically a built-in. However, this can possibly include the index of the head of the expression ({0}) if the predicate returns True when applied to that head (List).
Husk, 5 4 bytes
Edit: -1 byte thanks to Razetime
`fNm
Razetime already pointed-out in the comments that Husk has a one-byte built-in for argwhere: the where or W function.
So this is an implementation without W or any other function that acts-on or returns indices.
`f # filter (select the elements that satisfy a condition)
N # the natural numbers
# using this list to represent yes/no:
m # map
# the black-box function provided as (implicit) argument 1
# across all elements of (implicit) argument 2
Haskell + hgl, 19 bytes
(cx<ixm pM).^m<m gu
Explanation
Here's the same code converted to a more convenient format:
f q x =
cx $ ixM pM $ m (gu q) x
To start we have gu which takes a boolean and produces [] if false and [()] if true.
We map gu q across the input list, this converts things that pass the test to [()] and things that fail to [].
pM takes a list and a value and replaces everything in that list with that value. ixM is an index map. It combines every element with its index using some function. Here we use pM as the function so that our [()]s get replaced with [index].
Then cx concats everything back together.
You can reorganize things a bit to get:
19 bytes
cx.^ixm<(pM^.)<m gu
Which is equivalent to
f q x =
cx $ ixM (\x y -> pM x $ gu $ q y)
But this is also 19 bytes so nothing is saved.
There is also:
19 bytes
(st.^^fl<fm cr)^.eu
This solution uses an entirely different set of tools to solve the problem but is the same length.
This can be translated to the more conventional
f q x =
m st $ fl (q < cr) $ eu x
First eu pairs every element with its index in the list. Then fl (q < cr) filters using q on the second element of each pair. Finally m st gets all the indices from the remaining list.
R, 24 bytes
function(x,f)which(f(x))
Uses R's built-in which function, which is pretty-close to argwhere except for the manner in which x and f are supplied...
R, 26 bytes
function(x,f)seq(!x)[f(x)]
Roll-your-own version without any built-in.
Note that many/most R functions vectorize, and this is assumed here (and indeed applies to all the test-cases). However, this isn't universal, so if f is a non-vectorizing function we'd need +7 bytes: function(x,f)seq(!x)[sapply(x,f)].
APL (Dyalog Unicode), 4 bytes
Full program. Prompts for array, then function.
⍸⎕¨⎕
⍸ where
⎕ the function
¨ mapped to
⎕ the array
05AB1E, 6 bytes
δ.Vƶ0K
The input black-box function is a string. 1-based.
Try it online or verify all test cases.
Explanation:
δ # Map over the (implicit) second input-list,
# using the first (implicit) input-string as argument:
.V # Evaluate the string as 05AB1E code
ƶ # Multiply each item by its 1-based index
0K # Remove all 0s
# (after which the result is output implicitly)
Haskell, 28 bytes
p!v=[i|(i,x)<-zip[0..]v,p x]
Explanation
To get the indices we zip the list with the natural numbers [0..]. Then we use a list comprehension to get only the correct indices.
JavaScript (Node.js), 43 bytes
x=>y=>x.reduce((a,b,i)=>y(b)?[...a,i]:a,[])
0-indexed, takes input in curry format f(array)(function)
Python 3.8 (pre-release), 45 bytes
lambda l,F:[i for i,e in enumerate(l)if F(e)]
Looks like it won't get much shorter than this.
Explanation: keep all indexes (found by unpacking; the index is the first item of each 2-element tuple in the return value of enumerate) for which the function returns True for the corresponding element.
Vyxal, 2 bytes
MT
100% pure ascii. 0-indexed
Explained
MT
M # Map the function to the list
T # and return indicies where the result is truthy