Mi jefe ahora quiere que implemente un mecanismo que le permita buscar un elemento en una matriz y le proporcione los índices / índices donde se produce ese valor.
Tu tarea:
Escriba un programa o función que reciba una matriz y un valor (String, Integer, Float o Boolean) y devuelva los índices de la matriz en la que se produce el valor (0 o 1 indexado, lo que prefiera). Si el valor no está en la matriz, devuelva una matriz vacía.
Entrada:
Una matriz A y un valor V, que pueden o no estar presentes en A.
Salida:
Una matriz que contiene el (los) índice (s) en los que ocurre V en A o, si V no ocurre en A, una matriz vacía.
Casos de prueba:
Tenga en cuenta que los casos de prueba están basados en 0.
12, [12,14,14,2,"Hello World!",3,12,12] -> [0,6,7]
"Hello World", ["Hi", "Hi World!", 12,2,3,True] -> []
"a", ["A",True,False,"aa","a"] -> [4]
12, [12,"12",12] -> [0,2]
Puntuación:
Este es el código de golf , por lo que gana la puntuación más baja en bytes.
code-golf
array-manipulation
Gryphon - Restablece a Monica
fuente
fuente
Respuestas:
Pyth , 2 bytes
0 indexado.
Pruébalo en línea!o marque todos los casos de prueba
Explicación
fuente
MATL , 2 bytes
El
m
consume dos argumentos y comprueba cada elemento de la matriz si es igual al otro argumento,f
devuelve los índices de las entradas Truthy de una matriz.Pruébalo en línea!
fuente
ismember
lugar de=
manejar adecuadamente las matrices de cadenas.mf
Python 3 , 45 bytes
-3 bytes gracias a @EriktheOutgolfer y @Chris_Rands
Banco de pruebas.
Hoy aprendí
enumerate(x) == zip(range(len(x)),x)
.Python 3 , 47 bytes
Pruébalo en línea! o marque todos los casos de prueba
fuente
enumerate()
para bajarlo un par de byteslambda n,l:[x for x,y in enumerate(l)if y==n]
R (+ pryr), 20 bytes
Que evalúa la función
Donde
a
puede ser el valor a buscar yb
el vector, o al revés. Cuando se le presentan dos vectores de longitudes desiguales (un solo valor cuenta como un vector de longitud 1 en R), R envolverá el más corto para que coincida con la longitud del más largo. Luego se verifica la igualdad. Esto genera un vector lógico.which
proporciona los índices donde este vector es verdadero.Pruébalo en línea!
fuente
JavaScript, 39 bytes
Es posible que el fragmento anterior no funcione en todos los navegadores, así que aquí hay un enlace TIO .
fuente
JavaScript (ES6),
4443 bytesTachado 44 sigue siendo regular 44; (
Guardado 1 bytes gracias a @Arnauld
fuente
===
un normal==
por un byte menos? Se me ocurrió literalmente lo mismo, nombres de variables y todo jaja.===
es necesario distinguir12
de"12"
05AB1E , 4 bytes
Pruébalo en línea!
1 indexado.
fuente
12
y[12,'12']
, a menos que él diga que es frío para los idiomas que realmente no escriben tipos concretos, no les importan los tipos.12
≠'12'
en 05AB1E porque a veces se comportan de manera diferente ... aunque no estoy seguro de si hay alguna prueba de igualdad que pueda soportar tal cosa.is_alpha (a)
yis_number (d)
, pero supongo que podemos suponer que las nuestras son válidas hasta que se indique lo contrario.C#,
8872 bytesSaved 16 bytes thanks to @LiefdeWen.
Try it online!
fuente
i==o
doesn't work.using System.Linq;a=>b=>a.Select((x,i)=>x.Equals(b)?i:-1).Where(x=>x>=0)
Jelly, 3 bytes
Try it online!
-1 thanks to Mr. Xcoder. (dyadic chains)
fuente
Haskell,
4139 bytesTry it online!
Saved two bytes thanks to @flawr
Haskell is statically typed, so I had to use a little workaround to run the test cases.
fuente
v#l=...
instead off v l=...
, will save you two bytes:)v!l=...
, but didn't kow if it was accepted. I'll edit the answer. Thanks!map
on somefilter
expression is often an indicator that a list comprehension might be shorter:v!l=[i|(i,x)<-zip[1..]l,x==v]
.Husk, 5 bytes
Try it online! 1-indexed.
Explanation
fuente
Ruby,
46 4039 bytesSaved 7 bytes!!! thanks to Eric Duminil.
Try it online.
fuente
!1
forfalse
.Ruby, 38 bytes
Try it online!
fuente
Google Sheets, 101 bytes
Value
V
inA1
and arrayA
inB1
with each entry separated by a comma. Null entires are not allowed (row 5 below shows what happens).Explanation:
Offset(A1,0,0,1,Counta(Split(B1,",")))
returns a range that is one row tall and as many columns wide as there are entries inA1
.=IfError(Join(",",Filter(Column(~),Exact(Split(B1,","),A1))),"")
filters the column numbers of that range based on whether or not the value inA1
is exactly each of the values inB1
and concatenates them all in a comma-delineated list.fuente
Clojure, 40 bytes
First attempt at code golf.
keep-indexed
maps a function over a collection here, passing the current index into the callback and yielding any non-nil return values.Try it online!
fuente
APL (Dyalog Unicode), 2 bytesSBCS
Takes item to look for as left argument (must be scalar to find an item of the lookup array rather than a subarray) and the lookup array (which may have up to 15 dimensions) as right argument. Returns list of indices, each of which may has as many elements as the number of dimensions in the lookup array.
Try it online!
⍸
ɩndices where⍷
foundfuente
⍸
isn't in the character set. Still, since Dyalog uses way less than 256 unique chars, it could have been a single byte. When we add new glyphs, we refrain from changing the character set so that backwards compatibility is maintained.Batch, 86 bytes
Takes input as command line parameters (value then the array elements as separate parameters). Note: String quoting is considered part of the match e.g.
"1"
won't equal1
(would cost 6 bytes).fuente
Python 2, 49 bytes
Try it online!
Not short enough, but I thought it was cool. ¯\_(ツ)_/¯
fuente
Perl 5, 28 bytes
Try it online!
The output is 1-indexed.
An anonymous function is quite unusual for Perl, but it happens to be the shortest I could think of.
grep ..., 1 .. @_
iterates over the indexes of the input array (actually it goes one cell beyond the last, but it doesn't matter), keeping only the index that satisfy$_[$_]eq$_[0]
, ie. the ones where the value of the element ($_[$_]
) is the same as the value we need to keep ($_[0]
).Slightly longer (31 bytes (30 +
-l
flag)), but as a full program:Try it online!
fuente
Haskell,
3733 bytesThanks @Laikoni for -4 bytes!
Try it online!
fuente
findIndices.(==)
elemIndices
?Java 8,
146113112111110108 bytes-2 bytes thanks to @TAsk by using
Vector
instead ofArrayList
.-1 byte by using
Stack
instead ofVector
.-2 bytes thanks to @Jakob by inputting a
ArrayList
instead of an array.0-indexed
Explanation:
Try it here.
fuente
Vector
may save few bytes. :)List
+ArrayList
pretty often.List r=new Vector();
will work, too.null
, but that's fine.05AB1E, 4 bytes
Try it online!
It is 1-indexed, as shown below:
fuente
Mathematica, 12 bytes
1-Indexed
input [Array,Value]
output
fuente
Position
?Haskell, 29 bytes
Try it online!
fuente
Japt, 9 bytes
1-indexed.
Japt input doesn't support booleans, so they have been replaced with
0
and1
in the test cases.Try it online! with the
-Q
flag to format the array output.0-indexed Solution, 11 bytes
Try it online!
fuente
¶
rather than¥
comes in handy :P I was thinking of doing something along the lines ofm@Y*(X¶V} f
, but I hadn't realized that wouldn't work for index0
. 1-indexing is clever...Perl 6, 21 bytes
Try it online!
The
:k
adverb togrep
tells it to return the matching keys (indices) of the input sequence that match the predicate* === $^v
.If strings and numbers were considered equivalent, one could use a grep predicate of just
$^v
instead of* === $^v
.fuente
eqv
might be better than===
depending on what you want to consider equivalent values.Common Lisp, 66 bytes
Try it online!
fuente
TXR Lisp, 26 bytes
In other words, "Where is argument 2 equal to argument 1?"
Run:
fuente
Clojure,
3938 bytesA bit obscure :) The first input argument is a
vec
of values and the second one is the searched value.%
maps indexes to values, and the set#{%2}
returns truthy (the input argument%2
) or falsynil
for that value. comp composes these together.fuente
C
340362166115 BytesHello all. My first time here. I figured since I enjoy (attempting) to write optimized code I may as well give this a try.
@Rodney - ~39 bytes from the includes
@Zacharý - 7 bytes with implicit typing
0-indexed.
How to Run:
As per @Arnolds suggestion, the program takes arguments in a much more C friendly manner. This let me reduce the size of the file by a little more than half.
The arguments should be passed in the following order
value [element1 ...]
where braces indicate optional argumentsYou may or may not have to add escaped quotes to any strings that are provided in order to satisfy the condition of
12 != "12"
. On my system the this can be done in the following mannergolfed
ungolfed
fuente
i = 0
. These can be removed. I suggest playing around with the whitespace a bit.,12
and second argument of[12,14,14,2,"Hello World!",3,12,12]
prints[5,6]
which is technically incorrect.#include
statements,strstr(h+i,n)-h ==i
has an extra space, and you can doreturn-1
instead ofreturn -1
.#include
statements