2012-07-03 19 views
0

我想製作一個簡單的Perl腳本來獲取一系列數字(0..255),遍歷每個數字並找到不在另一個數組中的數字。如何運行一系列數字並查找包含在數組中的數字?

這個問題的關鍵在於我可以找到哪些Minecraft塊id尚未在我的遊戲中佔用。第一個數組的範圍是0..255,它是最大可能的阻止ID。下一個數組是已經使用的已經使用了列表的ID。

所以我想要一些循環檢查每個可能的塊ID。我將發佈我的電腦時所擁有的內容。

+0

我試過使用每個想法,但他們都給出了相同的結果。他們只給我一個0-255的數字,這是錯誤的。我會盡力解決我的問題,以便更好地關注我正在努力完成的任務。 – ianc1215

回答

4

最簡單,最快的方式是其他數組轉換爲散列,並檢查按鍵是否存在有:

my %hash = map { $_ => 0 } @array2; 

print (exists $hash{$_} ? "$_ is there\n" : "$_ is not there\n") for(0..255); 
+0

哦!我從來沒有想到這一點。不錯,我會試試看。謝謝。 – ianc1215

0

兩個陣列之間的差異並不一定意味着你需要一個for循環或while等等。這會打印@allblocks中不在@occupiedones中的項目。

#!usr/bin/perl 
use warnings; 
use strict; 
my @allblocks=(0...255); 
my @occupiedones=(1,2,80,255) 

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

# the difference of two arrays 

my @diff=grep(!defined $occupiedones{$_}, @allblocks); 

# proof it works 
print "This is in one array and not the other:\t$_\n" foreach (@diff); 
0

這是做你想做的。代碼中的註釋說明。

#!/usr/bin/perl 

use warnings; 
use strict; 

# Print members of @b that are not in @a. 
# That is, loosely speaking, print @b minus @a. 

my @a = (10, 20, 30, 40, 50); 
my @b = (22, 25, 30, 40, 42); 

my %a = map {$_=>1} @a; 
$a{$_} or print "$_ " for @b; 
print "\n"; 

的想法是把@a到散%a,然後使用哈希來控制減法。在散列中,只有密鑰是有意義的;對應的值都是1,這對於這種應用程序來說是常規的(虛擬值是Perl實現C++中將被稱爲集合)的方式。

1

爲什麼不使用

$occupied_lookup[$_] = 1 for 4,5,6; 

,而不是

@occupied_indexes = (4,5,6); 

更容易和更快,使一些佔領:

$occupied_lookup[$_] = 1; 
更容易

,更快,使一些無人居住:

$occupied_lookup[$_] = 0; 

更加方便快捷地檢查,如果事情被佔用:

if ($occupied_lookup[$_]) 

找到所有被佔領指數仍容易:

my @occupied_indexes = grep $occupied_lookup[$_], 0..$#occupied_lookup; 

(也有人建議哈希,而是一個數組更快。)

相關問題