私の価値はどこですか?


20

私の上司は、配列内のアイテムを検索し、その値が発生するインデックス/インデックスを彼に与えるメカニズムを実装するようになりました。

あなたのタスク:

配列と値(String、Integer、Float、またはBoolean)を受け取り、値が発生する配列のインデックスを返すプログラムまたは関数を作成します(インデックスが0または1のいずれか)。値が配列にない場合、空の配列を返します。

入力:

Aに存在する場合と存在しない場合がある配列Aと値V。

出力:

VがAで発生するインデックスを含む配列、またはVがAで発生しない場合は空の配列。

テストケース:

テストケースは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]

得点:

これはであるため、バイト単位の最低スコアが優先されます。


1
多くの言語は複数のタイプの配列またはリストをサポートしていないため、指定された配列にはこれらのタイプの1つのみ(つまり、タイプが混在する配列はない)を想定できますか。
-flawr

1
確かに、@ flawr。言語で必要な場合、配列はチェック対象の値と同じ型の値のみで構成されていると想定できます。
グリフォン-モニカの復活

2
すべての配列は1Dです。仮定?
アダム

1
@KevinCruijssen配列を検索するつもりでした。マルチDでもかまいません。
アダム

1
はい。そして、1バイトでそれを行うことができる言語がまだないことに驚いています!
ザカリー

回答:


10

Pyth、2バイト

0インデックス。

xE

オンラインでお試しください!または、すべてのテストケースを確認します


説明

xEQ  - Full Program. Takes Input from standard input. Q means evaluated input and is implicit at the end of the program.

x   - Get all the indexes of x in y
 E  - Evaluated Input #2 - The value
  Q - The list - Evaluated Input #1

最初だけでなく、すべてのオカレンスを返すことになっています。
エリックアウトゴルファー

@EriktheOutgolfer修正済み。それらを逆の順序で取ってください。
Mr Xcoder

1
Pythは、間違いなく仕事に最適なツールです:P
ミスターXcoder

7

MATL、2バイト

mf

m消費二つの引数、およびチェック他の引数と等しいかどうかを、配列の各要素は、fアレイのtruthyエントリのインデックスを返します。

オンラインでお試しください!


Octaveソリューションと同じように、提案されているテストケースでは機能しないようです。
シナスキ

ismember代わりに使用して=、文字列の配列を適切に処理する必要があります。mf
-Suever

@LuisMendo混合入力を考慮する必要はありません。OPの説明を参照してください。
-flawr

@flawrああ、なぜそれはコメントだけで、チャレンジテキストではないのですか?:-/
ルイスメンドー

私ではなく、OPに尋ねる必要があります:)
flawr

7

Python 3、45バイト

@EriktheOutgolferと@Chris_Randsのおかげで-3バイト

lambda y,x:[i for i,j in enumerate(x)if j==y]

テストスイート。

今日学びましたenumerate(x) == zip(range(len(x)),x)


Python 3、47バイト

lambda n,l:[x for x in range(len(l))if l[x]==n]

オンラインでお試しください!または、すべてのテストケースを確認します


それを使用enumerate()して、数バイトをダウンさせます
Chris_Rands

@Chris_Randsは長くなってしまいました。
Mr Xcoder

3
lambda n,l:[x for x,y in enumerate(l)if y==n]
エリックアウトゴルファー

@EriktheOutgolferが言ったことを意味した
Chris_Rands

1
@JonathanAllan修正済み。
ミスターXcoder

6

R(+ pryr)、20バイト

pryr::f(which(a==b))

関数に評価する

function (a, b) 
which(a == b)

a検索する値とbベクトル、またはその逆のいずれかです。長さが等しくない2つのベクトル(Rで1つの値が長さ1のベクトルとしてカウントされる)が提示されると、Rは短い方をラップして長い方の長さに一致させます。次に、平等がチェックされます。これにより、論理ベクトルが生成されます。whichこのベクトルが真であるインデックスを提供します。

オンラインでお試しください!


6

JavaScript、39バイト

e=>a=>[...a.keys()].filter(i=>a[i]===e)

f=
e=>a=>[...a.keys()].filter(i=>a[i]===e)

console.log(f(12)([12,14,14,2,"Hello World!",3,12,12]));
console.log(f("Hello World")(["Hi", "Hi World!", 12,2,3,true]));
console.log(f("a")(["A",true,false,"aa","a"])); 
console.log(f(12)([12,14,14,2,"Hello World!",3,12,'12']));

上記のスニペットはすべてのブラウザで機能するとは限りません。そのため、ここにTIOリンクがあります。


6

JavaScript(ES6)、44 43バイト

取り消し線44は、まだ規則的な44です;(

v=>a=>a.map((x,i)=>x===v&&++i).filter(x=>x)

@Arnauldのおかげで1バイト節約

let f=
v=>a=>a.map((x,i)=>x===v&&++i).filter(x=>x)
;

console.log(f(12)([12,14,14,2,"Hello World!",3,12,12]));         // => [1,7,8]
console.log(f("Hello World")(["Hi", "Hi World!", 12,2,3,true])); // => []
console.log(f("a")(["A",true,false,"aa","a"]));                  // => [5]


===ノーマル==を1バイト少なくすることはできますか?文字通り同じもの、変数名、そしてすべての母を思いつきました。
kamoroso94

4
===区別する必要がある12から"12"
クリストフ・

1
@ kamoroso94いいえ、ここに理由があります。
-Pureferret

5

05AB1E、4バイト

QāsÏ

オンラインでお試しください!

1インデックス付き。


私たちは両方とも、次のものの入力で混乱していると思います:12[12,'12']、彼が本当に具体的な型ではない言語が型を気にしないのは寒いと言わない限り。
魔法のタコUr

05AB1E で12≠の'12'ように振る舞うこともありますが、そのようなことをサポートできる同等性テストがあるかどうかはわかりません。
エリックアウトゴルファー

私たちは、整数の有効性のためにそれらをテストしたい場合は、当社の答えは60バイト使用するようなものだis_alpha (a)is_number (d)、私は、我々は我々のものを想定することができますねそう告げたまで有効です。
魔法のタコUr

5

C#、88 72バイト

using System.Linq;a=>o=>a.Select((i,n)=>o.Equals(i)?n:-1).Where(n=>n>=0)

@LiefdeWenのおかげで16バイト節約されました。

オンラインでお試しください!


驚くべきことに、私はまだi==oうまくいかない理由を理解しようとしていました。
-LiefdeWen

3
@LiefdeWenボックス化された値型。
TheLethalCoder

72バイトusing System.Linq;a=>b=>a.Select((x,i)=>x.Equals(b)?i:-1).Where(x=>x>=0)
-LiefdeWen

@LiefdeWenいいね、私はそれを切り替えることを考えていなかっただろう。
TheLethalCoder

:あなたはたくさん:)保存することができtio.run/...
digEmAll


3

Haskell41 39バイト

v!l=fst<$>(filter((==v).snd)$zip[1..]l)

オンラインでお試しください!

@flawrのおかげで2バイト節約

Haskellは静的に型付けされているため、テストケースを実行するために少しの回避策を使用する必要がありました。


回避策はもう必要ありません。OPのコメントを参照してください。
flawr

1
また、のv#l=...代わりに演算子を定義すると、f v l=...2バイト節約できます。)
flawr

@flawr私はのアイデアを持っていましたがv!l=...、それが受け入れられるかどうかは知りませんでした。答えを編集します。ありがとう!
-jferard

1
mapいくつかのfilter式で使用することは、リストの理解が短くなる可能性があることを示す指標ですv!l=[i|(i,x)<-zip[1..]l,x==v]
ライコニ

ビルトインもありますが、残念ながらライキオニスの提案より長いです:)
flawr

3

、5バイト

`fNm=

オンラインでお試しください!1インデックス付き。

説明

       -- implicitly input a value v and a list L
   m=  -- map "equals v" over the list L, resulting in a list of truthy and falsy values
`fN    -- filter the natural numbers N by discarding the numbers at falsy positions 
          and keeping the ones at truthy positions

しかし、これは文字列を含む配列に対して機能しますか?
officialaimm

1
@officialaimm文字列のみを含むリストで動作します:オンラインで試してください!混合型のリストはHaskellではサポートされておらず、したがってHuskでもサポートされていませんが、OPではコメントで明示的に許可されています。
ライコニ

Huskのドキュメントはありますか?
-flawr

@flawrはい、githubページのwikiにあります:github.com/barbuz/Husk/wiki
Laikoni

@flawr Huskのドキュメント全般について質問がある場合は、チャットルームにご参加ください!
-Zgarb



3

Google Sheets, 101 bytes

=IfError(Join(",",Filter(Column(Offset(A1,0,0,1,Counta(Split(B1,",")))),Exact(Split(B1,","),A1))),"")

Value V in A1 and array A in B1 with each entry separated by a comma. Null entires are not allowed (row 5 below shows what happens).

Result

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 in A1.

=IfError(Join(",",Filter(Column(~),Exact(Split(B1,","),A1))),"") filters the column numbers of that range based on whether or not the value in A1 is exactly each of the values in B1 and concatenates them all in a comma-delineated list.


3

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.

(fn[a b](keep-indexed #(if(= %2 a)%1)b))

Try it online!


3

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

 found


I was about to say it ties Pyth, but you know... Unicode. Wouldn't this be 2 bytes in APL Dyalog Classic (since it uses SBCS)?
Mr. Xcoder

@Mr.Xcoder 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.
Adám

Ah, Thanks! (I have no idea how APL / Dyalog works)
Mr. Xcoder

@Mr.Xcoder APL is a commercial language (not a golfing language), so Dyalog have certain obligations to existing subscribers.
Adám

APL isn't a golfing language, but there do exist open-source APL implementations (ngn and GNU).
Zacharý

2

Batch, 86 bytes

@set i=0
:g
@if "%~2"=="" exit/b
@if %1==%2 echo %i%
@set/ai+=1
@shift/2
@goto g

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 equal 1 (would cost 6 bytes).



2

Perl 5, 28 bytes

sub{grep$_[$_]eq$_[0],1..@_}

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:

$@=<>;$@eq$_&&print$.-1while<>

Try it online!



2

Java 8, 146 113 112 111 110 108 bytes

import java.util.*;l->o->{List r=new Stack();for(int i;(i=l.indexOf(o))>-1;l.set(i,null))r.add(i);return r;}

-2 bytes thanks to @TAsk by using Vector instead of ArrayList.
-1 byte by using Stack instead of Vector.
-2 bytes thanks to @Jakob by inputting a ArrayList instead of an array.

0-indexed

Explanation:

Try it here.

import java.util.*;    // Required import for Vector and Vector
l->o->{                // Method with List and Object parameters
  List r=new Stack();  //  Result-list
  for(int i;(i=l.indexOf(o))>=-1;
                       //  Loop as long as we can find the object in the list
    l.set(i,null))     //   After every iteration, remove the found item from the list
      r.add(i);        //    Add the index to the result-list
                       //  End of loop (implicit / single-line body)
  return r;            //  Return the result-List
}                      // End of method

1
Cool! If I am not wrong Vector may save few bytes. :)
CoderCroc

1
@TAsk Thanks! Need to remember that one. I use List+ArrayList pretty often.
Kevin Cruijssen

1
List r=new Vector(); will work, too.
CoderCroc

1
You can save 1 byte by taking a list instead: TIO. Seems like a small enough change not to merit a separate answer.
Jakob

The change breaks searching for null, but that's fine.
Jakob

1

05AB1E, 4 bytes

Qƶ0K

Try it online!

It is 1-indexed, as shown below:

IN A-#------------------------> [2,3,3,3,4]
IN B-#------------------------> 3
-----#------------------------+-----------------
Q    # Vectorized equivalence | [0,1,1,1,0]
 ƶ   # Lift by index          | [0,2,3,4,0]
  0K # Remove zeros           | [2,3,4]

1

Mathematica, 12 bytes

Position@##&

1-Indexed

input [Array,Value]

[{12, 14, 14, 2, "Hello World!", 3, 12, 12}, 12]

output

{{1}, {7}, {8}}


Why not just Position?
hftf

1

Haskell, 29 bytes

e#l=[i|(i,h)<-zip[0..]l,h==e]    

Try it online!


Does that work with the heterogeneous input cases? (Mixtures of integers, strings, a "true" value, etc).
Kaz

@Kaz: no, it doesn't. It's polymorphic and works for every type where equality is defined for, but all list elements have to be of the same type. According to a comment in the OP that's enough.
nimi

1

Japt, 9 bytes

mȶV©YÄÃf

1-indexed.

Japt input doesn't support booleans, so they have been replaced with 0 and 1 in the test cases.

Try it online! with the -Q flag to format the array output.

0-indexed Solution, 11 bytes

l o f@gX ¶V

Try it online!


One of the few times rather than ¥ comes in handy :P I was thinking of doing something along the lines of m@Y*(X¶V} f, but I hadn't realized that wouldn't work for index 0. 1-indexing is clever...
ETHproductions

1

Perl 6, 21 bytes

{grep :k,*===$^v,@^z}

Try it online!

The :k adverb to grep 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.


eqv might be better than === depending on what you want to consider equivalent values.
Brad Gilbert b2gills


1

TXR Lisp, 26 bytes

(op where(op equal @@1)@2)

In other words, "Where is argument 2 equal to argument 1?"

Run:

1> (op where(op equal @@1) @2)
#<interpreted fun: lambda (#:arg-01-0166 #:arg-02-0167 . #:rest-0165)>
2> [*1 12 #(12 14 14 2 "Hello world!" 3 12 12)]
(0 6 7)
3> [*1 "Hello World" #("Hi" "Hi world!" 12 2 3 t)]
nil

1

Clojure, 39 38 bytes

#(filter(comp #{%2}%)(range(count %)))

A 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 falsy nil for that value. comp composes these together.


1

C 340 362 166 115 Bytes

Hello 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 arguments

You 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 manner

prog-name.exe 12 3 "Hello" 12 4 "12"
Returns [2,4]     < This is incorrect

prog-name.exe 12 3 "\"Hello\"" 12 4 "\"12\""
Returns [2]       < Correct

golfed

#define P printf(
b=0;main(int c,char**v){P"[");for(--c;c-1;c--)b|=strcmp(v[1],v[c])?0:P b?",%i":"%i",c-2);P"]");}

ungolfed

#define P printf(

//Implicit only works in global(I totally knew this after almost 4 years of C :P)
b = 0;
main(int c,char**v)
{

    P"[");

    //match loop
    //b is used to determine if this is the first iteration. it can be assumed that printf will always return >0
    //subract two from c to get correct index number of match
    for(--c; c-1; c--)
        b |= strcmp(v[1], v[c]) ? 0 : P b ? ",%i" : "%i", c-2);

    P"]");

    return 0;
}

1
Welcome to the site. I notice you have a lot of extra whitespace. Particularly around operators i = 0. These can be removed. I suggest playing around with the whitespace a bit.
Wheat Wizard

With the way you handle the list, a first argument of ,12 and second argument of [12,14,14,2,"Hello World!",3,12,12] prints [5,6] which is technically incorrect.
Arnold Palmer

@ArnoldPalmer I updated the code to make it a little more verbose at detecting data types. However, since C doesn't have all the fancy type conversion such as JavaScript, it is still vulnerable to having a comma in a 'number' type. I pretty much just left it assuming correctly formatted input.
Marcos

@Marcos There's a chance you may be able to take each value of the array as it's own command line argument. I don't golf in C ever, so not quite sure what the rules are, but it doesn't seem unreasonable to me that you'd be allowed to do that. Especially since accepting the array as a list leaves you vulnerable to this problem. Also, you still have a bit of white space in your golfed code. You don't need the spaces on the #include statements, strstr(h+i,n)-h ==i has an extra space, and you can do return-1 instead of return -1.
Arnold Palmer

are implicit declarations allowed? I think you can ditch the #include statements
Rodney
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.