2012-10-09 34 views
-3

可以說我有2個陣列檢查,如果在陣列中的所有字符串都在第二陣列

my @one = ("one","two","three","four","five"); 
my @two = ("three","five"); 

我怎麼能告訴我們,如果第二陣列中的所有元素都在第一?

+0

偷的念頭保證是獨一無二的集合元素的數組,或者你可以有例如'@One =(「一」,「一」, 「一」,「二」,「一」......)? – pilcrow

+0

不保證是唯一的 – Bill

+0

請澄清您的要求。你認爲'('a','a','b')的所有元素都在'('a','b')'中嗎? – pilcrow

回答

4
my %one = map { $_ => 1 } @one; 
if (grep($one{$_}, @two) == @two) { 
    ... 
} 
+0

抱歉,我是新來的Perl。你能通過這些線路正在做什麼來引導我嗎? – Bill

+0

#1創建一個散列。 '@ one'中的每個值都在散列中創建一個元素。數組中的值用作散列中的鍵。 – ikegami

+0

#2計算'@ two'中元素的數量,這些元素是'%one'中的鍵。然後,它將該計數與'@ two'中元素的數量進行比較。 – ikegami

0

另一種方法,不知道它比ikegami的更好。仍然TIMTOWTDI

#!/usr/bin/env perl 

use strict; 
use warnings; 

use List::Util qw/first/; 
use List::MoreUtils qw/all/; 

my @one = ("one","two","three","four","five"); 
my @two = ("three","five"); 

if (all { my $find = $_; first { $find eq $_ } @one } @two) { 
    print "All \@two found in \@one\n"; 
} 
+0

這實質上是@ Axeman的解決方案。智能匹配將比第一個更快,但它們都是O(M * N)。我猜你是O(M/2 * N)(平均來說,'first'只需要搜索一半數組),但'first'vs'~~'的性能會降低。 – Schwern

+0

是的,正如我的文章可能已經表明的那樣,我從List開始::(更多)Util(s)路徑並將其公佈爲「完整性」;我不驚訝它不是「最好的」。儘管我的解決方案是在@ axemans之前發佈的,我聲稱他的本質與我的一樣:-P –

0

從5.10開始,智能匹配運算符會這樣做。

my $verdict = !grep { not $_ ~~ @one } @two; 

或者與List::MoreUtils::all

my $verdict = all { $_ ~~ @one } @two; 
+0

當我嘗試第一個時,出現編譯錯誤。它說它接近「$ _ ~~」。我正在使用perl 5.8.8 – Bill

+1

@ Bill ...這是之前的5.10 – Axeman

+1

這個解決方案雖然優雅的代碼是O(M * N)。也就是說它必須執行'@one * @ two'操作。如果'@ one'和'@ two'都有5個元素,那就是25個操作。如果他們有10個,那就是100個操作。 20並且它是400.不要將它用於任何東西,但非常小的列表。 – Schwern

3

另一種方式來解決。

my %hash; 
undef @hash{@two}; # add @two to keys %hash 
delete @hash{@one}; # remove @one from keys %hash 
print !%hash;  # is there anything left? 

我從這個perlmonks node

+0

可愛。我有點喜歡它。 –

1
use strict; 

my @one = ("one","two","three","four","five"); 
my @two = ("three","five"); 

my %seen_in_one = map {$_ => 1} @one; 

if (my @missing = grep {!$seen_in_one{$_}} @two) { 
    print "The following elements are missing: @missing"; 
} else { 
    print "All were found"; 
}