Hitung kejadian satu set dalam daftar


15

Diberikan seperangkat string yang tidak kosong dan daftar string, cari tahu berapa kali set terjadi dalam daftar, yaitu berapa kali Anda bisa membuat set dengan item dari daftar. Setiap elemen dari daftar hanya dapat digunakan satu kali.

Petunjuk: satu set adalah daftar item unik yang tidak disusun.

Default Aturan input / output berlaku.

Tidak ada perpustakaan eksternal yang diizinkan. Compiler / Interpreter libs standar tidak masalah. Ini kode golf, jadi solusi terpendek diperhitungkan.


Kasus uji:

["apple", "banana"], ["apple", "pear", "apple", "banana", "banana"] => 2

["apple", "banana"], ["apple", "pear", "apple", "banana", "apple"] => 1

["apple", "banana", "pear"], ["apple", "banana", "kiwi", "apple"] => 0

["coconut"], [] => 0

EDIT: menghapus kalimat yang menyatakan bahwa params input didefinisikan dalam lingkup lokal. Ini bertentangan dengan aturan IO default yang ditautkan di atas.


Ya itu memperjelasnya. Namun saya sedikit terpaku pada kalimat ketiga. Apa yang Anda maksud dengan "tidak menangani objek"?
Post Rock Garf Hunter

@WheatWizard beberapa bahasa tidak berorientasi objek dan tidak tahu konsep membandingkan objek sewenang-wenang.
Hubert Grzeskowiak

1
Anda mungkin harus mengubahnya menjadi berorientasi objek karena setiap bahasa yang saya sadari menangani objek dari beberapa jenis bahkan jika objek adalah kelas tertutup. Saya juga harus menunjukkan bahwa ada banyak bahasa yang juga tidak bisa menangani string sama sekali.
Posting Rock Garf Hunter

@WheatWizard oke, deskripsi yang diperbarui. Paragraf itu dimaksudkan untuk bahasa seperti C, Assembler atau Maple.
Hubert Grzeskowiak

Bahasa apa yang berorientasi objek? Apa yang harus mereka gunakan jika bukan string? Saya pikir hal termudah adalah dengan membatasi hanya string. Atau, sebagai alternatif, hanya bilangan bulat. Lihat saran ini tentang penggunaan jenis paling sederhana yang cukup.
xnor

Jawaban:


12

Python, 30 byte

lambda s,l:min(map(l.count,s))

Cobalah online!


Bagus Tidak berpikir tentang menggunakan peta. Anda dapat menghemat sedikit dengan menggunakan cetak alih-alih mendefinisikan lambda BTW.
Hubert Grzeskowiak

1
@ HubertGrzeskowiak Mengubah lambdake a printmembawa jumlah byte hingga 37 karena keduanya input()diperlukan.
Posting Rock Garf Hunter

@WheatWizard seperti yang dinyatakan dalam tantangan, pertimbangkan input yang didefinisikan dalam lingkup lokal. Anda TIDAK diharuskan memiliki input yang didefinisikan secara eksplisit, misalnya sebagai parameter fungsi atau input pengguna.
Hubert Grzeskowiak

@ HubertGrzeskowiak jika tidak ada alasan yang baik untuk itu, Anda tidak boleh menimpa default kami untuk mengambil input dan output dan default
codegolf

@ovs oh, saya tidak mengetahui pos itu. Terima kasih.
Hubert Grzeskowiak

6

Jelly , 4 byte

⁼þSṂ

Cobalah online!

Bagaimana?

⁼þSṂ - Main link: list theSet, list theList
 þ   - outer product using the dyadic operation:
⁼    -     is equal? (non-vectorising)
  S  - sum (vectorises) (yields the number of times each element of theSet appears in theList)
   Ṃ - minimum (can only make the minimum as a multiple)

6

Jelly , 6 5 4 byte

ċ@€Ṃ

Cobalah online!

Argumen pertama dari program adalah himpunan, dan argumen kedua adalah daftar.

Penjelasan

ċ@€Ṃ
ċ@   -- Create a link which finds the number of occurrences of 
          its left argument in its right argument (the list)
  €  -- Map this link over each element in the first argument
          of the program (the set)
   Ṃ -- Minimum value of this.

-1 byte berkat @ETHproductions

-1 byte lagi berkat @ETHproductions


Sangat bagus! Anda dapat menyimpan satu byte dengan menggabungkan tautan menjadi satu baris: ⁹ċ$€ṂSaya punya perasaan yang dapat dibuat lebih pendek dengan menggunakan argumen benar implisit sebagai pengganti ...
ETHproductions

Saya pikir ċ@€Ṃ berfungsi untuk menyimpan byte lain ... ( @membalikkan argumen ke ċ)
ETHproductions

@ ETHproductions Bekerja dengan benar sejauh yang saya uji.
fireflame241

Itu tidak ada sampai 12 Mei tahun lalu, tetapi sebagai gantinya @€(dengan argumen terbalik ke program) menyimpan byte lain: Coba online!
String Tidak Terkait

6

JavaScript (ES6), 56 byte

f=(n,h)=>Math.min(...n.map(c=>h.filter($=>$==c).length))

Cobalah online


1
Simpan 2 byte dengan menggunakan fungsi anonim dan lainnya dengan menjelajah parameter: n=>h=>Math.min(...n.map(c=>h.filter($=>$==c).length))untuk 53 byte
Shaggy

5

JavaScript (ES6), 64 byte

(s,l)=>l.map(e=>m[s.indexOf(e)]++,m=s.map(e=>0))&&Math.min(...m)

Mengasumsikan keduanya sdan lmerupakan array objek. Menggunakan kesetaraan ketat JavaScript untuk perbandingan, jadi misalnya [] === []salah.


Solusi yang sangat menarik. Silakan kembali atau cetak hasilnya. AFAIK ini mengembalikan fungsi anonim.
Hubert Grzeskowiak

2
@HubertGrzeskowiak The code as shown evaluates to an anonymous function. When called, the function returns the count as desired.
Neil

4

Haskell, 37 34 bytes

Thanks to @Laikoni for shaving off three bytes.

s#l=minimum[sum[1|y<-l,y==x]|x<-s]

Call with (set::[a]) # (list::[a]) where a is any type deriving Eq.


Instead of length[y|y<-l,y==x] you can use sum[1|y<-l,y==x].
Laikoni

@Laikoni, are you sure about that? I think I would need to use something like sum[1|y<-l,y==x,_<-y], which comes out to two bytes longer—I could definitely be missing something there, though
Julian Wolf

Never mind, you're definitely right. Good call.
Julian Wolf

3

CJam, 11 bytes

q~f{\e=}:e<

Try it online!

Explanation

q~           e# Read and eval the input
  f{\e=}     e# Map each item in the set to the number of times it appears in the list
        :e<  e# Find the minimum of the resulting list

3

Mathematica, 24 bytes

Min[#/.Rule@@@Tally@#2]&

Pure function taking two lists as arguments in the suggested order and returning a nonnegative integer. Tally counts how many occurrences of every symbol occur in the input list, and #/.Rule@@@ converts each element of the input set into the corresponding number of occurrences.


3

T-SQL, 62 59 bytes

Previous version didn't work for sets with no matches

select top 1(select count(*)from l where l=s)from s order by 1

With s and l as tables and columns named the same as the table

select top 1         -- return only the first result
    (select count(*) -- count of rows
     from l          -- from table l
     where l=s)      -- for each l equal
from s               -- to each from s
order by 1           -- sort by count ascending

3

Swift, 39 bytes

s.map{w in l.filter{$0==w}.count}.min()

explanation:

s.map{} goes through each word in s and will produce an array of counts

w in names the mapped word for use in the next filter

l.filter{} aplies a filter to the l array

$0==w is the filter condition matching word w

.count gives the number of elements of l that met the condition

.min() returns the lowest count in the mapped result


1
Welcome to PPCG! I've added code formatting for your solution. You can do this by prepending 4 spaces to lines that contain code.
Mego

3

APL (Dyalog), 9 bytes

⌊/+/⎕∘.≡⎕

Try it online!

 get evaluated input (list of strings)

⎕∘.≡ get evaluated input (non-empty set of strings) and create equivalency table

+/ add across

⌊/ minimum across


2

Perl 6,  37  18 bytes

37

{+(($_=@^a⊍@^b)≽@a)&&.values.min}

Try it

Expanded:

{
  +( # turn into a 0 if False

    (
      $_ =        # store into $_ the result of
        @^a  @^b # use the baggy multiplication operator
    )  @a        # is that the baggy superset of the set
  )

  &&          # if that is True

  .values.min # get the minimum value from the Bag in $_
}

See Sets, Bags, and Mixes for more information.


18

{@^b.Bag{@^a}.min}

Try it

Explanation:

@^b.Bag create a Bag from the values
{@^a} key into that Bag (returns a list of counts)
.min get the minimum value of the resulting list



Neat answers, but neither of these look like functions / complete programs
Julian Wolf

@JulianWolf I was under the impression that snippets were allowed based on the statements “Consider both inputs being defined in the current scope as s and l.” and “You don't need to define a function.” I went and edited it anyway.
Brad Gilbert b2gills

Ah, you're completely right. That must've been edited into the question after I read it. In any case, I like the aesthetic of this version even more than the last—Perl's syntax will always be a mystery to me.
Julian Wolf

@JulianWolf This isn't really a good example of Perl 6 code. I would recommend seeing Ovid's 1hr talk Perl 6 — Why People Are So Excited, or looking at the Resources tab on Perl6.org.
Brad Gilbert b2gills

Yeah, sorry for the confusion. This is my first chllenge and I didn't know there already are rules for input and output. I changed it because most answers were using these rules even while it wasn't required.
Hubert Grzeskowiak

2

Axiom, 42 bytes

f(a,b)==reduce(min,[count(x,b)for x in a])

test code and results

(28) -> f(["1","2"], ["1", "2", "1", "1", "7"])
   (28)  1
                                                    Type: PositiveInteger
(29) -> f(["apple","banana"],["apple","pear","apple","banana","banana"])
   (29)  2
                                                    Type: PositiveInteger
(30) -> f(["apple","banana"],["apple","pear","apple","banana","apple"])
   (30)  1
                                                    Type: PositiveInteger
(31) -> f(["apple","banana","pear"],["apple","banana","kiwi","apple"])
   (31)  0

2

C++, 203 201 bytes

Thanks to @Quentin for saving two bytes!

#import<vector>
#import<string>
using T=std::vector<std::string>;
int f(T S,T L){for(int j,b,i=0;;++i)for(auto s:S){for(b=j=0;j<L.size();++j)if(L[j]==s){b=1;L.erase(begin(L)+j);break;}if(!b)return i;}}

Try it online!


L.begin() -> begin(L) saves one byte :)
Quentin

Also, using T=std::vector<std::string>; saves another! Who knew modern pretty syntax could also help golfing.
Quentin

@Quentin I tried that at first. Probably there was some simple typo I didn't notice.
Steadybox

1

PHP, 74 Bytes

<?foreach($_GET[0]as$v)$t[]=array_count_values($_GET[1])[$v];echo+min($t);

Testcases

PHP, 108 Bytes

<?[$x,$y]=$_GET;echo($a=array_intersect)($x,$y)==$x?min(($a._key)(array_count_values($y),array_flip($x))):0;

Testcases


1

Pyth, 5 bytes

hS/LF

Takes the list first and the set second. Test suite.

Explanation:

    F  Expand the input into l and s (not literally, 
                  since those are function names in Pyth, but...)
   L   for d in s:
  /        Count instances of d in l
   L   Package all the results as a list
 S     Sort the results smallest-first
h      grab the smallest element


1

Java, 135 bytes

int f(List<String> s,List<String> l){int n=0,i=0;while(i<s.size()){if(!l.remove(s.get(i++)))break;if(i==s.size()){n++;i=0;}};return n;}

This is my first code golf challenge and answer, so not sure about the format. Does it need to be a full compiling program? Do I need to define the parameters? Suggestions appreciated.

EDIT: wrapped code in a function. Thanks @Steadybox


An answer can be a full program, a function or some other function-like construct. You can take the parameters for example as arguments to a function or from standard input.
Steadybox


1

Java, 114 Bytes

<T>int a(Set<T>b,List<T>c){int m=2e32;b.stream().map(i->{int j=java.util.Collections.frequency(c,i);m=j<m?j:m;});return m;}

Tio coming soon

Explanation

  • creates local variable m.

  • maps the set to a stream.

  • for each element, if the number of occurances of the element in the list is less than m, m is set to that value.

  • returns m, which is the number of complete versions of the set


0

R 54 Bytes

f<-function(s,l) min(table(factor(l[l%in%s],levels=s)))

Explanation: creating a table of the counts of only the values in the list that also appear in the sublist.

I then turn the variable into a factor in order to generate zeros if a value that appears in the sublist does not appear in the list. Finally, I take the minimum of the counts.


0

R, 61 57 44 bytes

print(min(sapply(s,function(x)sum(l%in%x))))

Anonymous function. Apparently you don't have to define a function for this challenge. Saved 13 bytes thanks to count.

Explanation:

sum(l%in%x)) returns the number of times a string in s is found in l.

lapply(s,function(x)) applies that to each string in s separately and returns a list of sums.

min() returns the smallest from that list.


Could be brought down to 40 Bytes with a for-loop: z=c();for(i in s)z[i]=sum(l%in%i);min(z)
count

Or even further to 37 bytes with sapply: min(sapply(s,function(x)sum(l%in%x)))
count

Brilliant, I always forget you can sum booleans. I'll edit that in later. I've been told I need that print() if it's not a function.
BLT

0

JavaScript (ES6), 59 bytes

a=>b=>a.reduce((x,y)=>(l=b.filter(s=>s==y).length)>x?x:l)|0

Try it

f=

a=>b=>a.reduce((x,y)=>(l=b.filter(s=>s==y).length)>x?x:l)|0

console.log(f(["apple","banana"])(["apple","pear","apple","banana","banana"]))
console.log(f(["apple","banana"])(["apple", "pear", "apple", "banana", "apple"]))
console.log(f(["apple","banana","pear"])(["apple","banana","kiwi","apple"]))
console.log(f(["coconut"])([]))

Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.