Bos saya sekarang ingin saya menerapkan mekanisme yang memungkinkan dia mencari item dalam array, dan memberinya indeks / indeks di mana nilai itu terjadi.
Tugas Anda:
Tulis program atau fungsi yang menerima array dan nilai (String, Integer, Float, atau Boolean), dan mengembalikan indeks array di mana nilai terjadi (baik 0 atau 1 diindeks, mana saja yang Anda inginkan). Jika nilainya tidak ada dalam array, kembalikan array kosong.
Memasukkan:
Array A dan nilai V, yang mungkin ada atau tidak ada dalam A.
Keluaran:
Array berisi indice (s) di mana V terjadi di A, atau, jika V tidak muncul di A, array kosong.
Kasus uji:
Harap dicatat bahwa test case didasarkan pada 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]
Mencetak:
Ini adalah kode-golf , sehingga skor terendah dalam byte menang.
code-golf
array-manipulation
Gryphon - Pasang kembali Monica
sumber
sumber
Jawaban:
Pyth , 2 byte
Diindeks 0.
Cobalah online! atau Periksa semua Uji Kasus
Penjelasan
sumber
MATL , 2 byte
Itu
m
mengkonsumsi dua argumen, dan cek setiap elemen dalam array apakah sama dengan argumen lain,f
mengembalikan indeks dari entri truthy array.Cobalah online!
sumber
ismember
alih-alih=
untuk menangani array string dengan benar.mf
Python 3 , 45 byte
-3 byte terima kasih kepada @EriktheOutgolfer dan @Chris_Rands
Test Suite.
Hari ini saya belajar
enumerate(x) == zip(range(len(x)),x)
.Python 3 , 47 byte
Cobalah online! atau Periksa semua Uji Kasus
sumber
enumerate()
untuk menurunkan beberapa bytelambda n,l:[x for x,y in enumerate(l)if y==n]
R (+ pryr), 20 byte
Yang mengevaluasi fungsi
Di mana
a
bisa menjadi nilai untuk mencari danb
vektor, atau sebaliknya. Ketika disajikan dengan dua vektor dengan panjang yang tidak sama (nilai tunggal dihitung sebagai vektor panjang-1 dalam R), R akan membungkus yang lebih pendek untuk mencocokkan panjang yang lebih panjang. Kemudian kesetaraan diperiksa. Ini menghasilkan vektor logis.which
memberikan indeks di mana vektor ini benar.Cobalah online!
sumber
JavaScript, 39 byte
Cuplikan di atas mungkin tidak berfungsi di semua browser, jadi inilah tautan TIO .
sumber
JavaScript (ES6),
4443 bytesDicoret 44 masih teratur 44; (
Disimpan 1 byte berkat @Arnauld
sumber
===
normal==
untuk satu byte kurang? Saya datang dengan harfiah hal yang sama, nama variabel dan semua haha.===
diperlukan untuk membedakan12
dari"12"
05AB1E , 4 byte
Cobalah online!
1-diindeks.
sumber
12
and[12,'12']
, unless he said it's chill for languages that don't really concrete type to not care about types.12
≠'12'
in 05AB1E because sometimes they behave differently...not sure if there's any equality test which can support such a thing though.is_alpha (a)
andis_number (d)
, but I guess we can assume ours are valid until told otherwise.C#,
8872 bytesSaved 16 bytes thanks to @LiefdeWen.
Try it online!
sumber
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)
sumber
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.
sumber
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
sumber
Ruby,
46 4039 bytesSaved 7 bytes!!! thanks to Eric Duminil.
Try it online.
sumber
!1
forfalse
.Ruby, 38 bytes
Try it online!
sumber
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.sumber
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!
sumber
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⍷
foundsumber
⍸
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).sumber
Python 2, 49 bytes
Try it online!
Not short enough, but I thought it was cool. ¯\_(ツ)_/¯
sumber
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!
sumber
Haskell,
3733 bytesThanks @Laikoni for -4 bytes!
Try it online!
sumber
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.
sumber
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:
sumber
Mathematica, 12 bytes
1-Indexed
input [Array,Value]
output
sumber
Position
?Haskell, 29 bytes
Try it online!
sumber
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!
sumber
¶
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
.sumber
eqv
might be better than===
depending on what you want to consider equivalent values.Common Lisp, 66 bytes
Try it online!
sumber
TXR Lisp, 26 bytes
In other words, "Where is argument 2 equal to argument 1?"
Run:
sumber
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.sumber
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
sumber
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