2012-07-26 57 views
0

我想知道是否有人可以幫助解釋下面的代碼片段中發生了什麼,因爲我正在嘗試翻譯成Java,但我的Perl知識很小。Perl到Java的翻譯

sub burble { 
    my $cw = "%START%"; 
    my $sentence; 
    my $nw; 
    my ($score, $s, $roll); 
    while ($cw ne ".") # while we're not at the end 
          # of the sentence yet 
    { 
     $score = 0; 

     # get total score to randomise within 
     foreach $s (values %{ $dict{$cw} }) { 
      $score += $s; 
     } 

     # now get a random number within that 
     $roll = int(rand() * $score); 
     $score = 0; 
     foreach $nw (keys %{ $dict{$cw} }) { 
      $score += ${ $dict{$cw} }{$nw}; 
      if ($score > $roll) # chosen a word 
      { 
       $sentence .= "$nw " unless $nw eq "."; 
       $cw = $nw; 
       last; 
      } 
     } 
    } 
    return $sentence; 
} 
+1

看一眼,這似乎構建[馬爾可夫鏈](http://en.wikipedia.org/wiki/Markov_chain)。如果這是在java中做到這一點的最好方法是有爭議的。 – 2012-07-26 13:57:25

+0

%dict的定義在哪裏? – 2012-07-26 13:57:38

+0

是的,它是一個馬爾可夫鏈。原始腳本可以在這裏找到http://www.lab6.com/old/niall-perl.html – veryphatic 2012-07-26 14:13:06

回答

2
foreach $s (values %{$dict{$cw}}) { 
    $score += $s; 
} 

就像

Map<String, Map<String, int>> dict = ...; 
... 
int score; 
Map<String, int> mcw = dict.get(cw); 

for (mcw.values() : int s) { 
    score += s; 
} 

而且

foreach $nw (keys %{$dict{$cw}}) 

就像

KEY_LOOP: 
for (mcw.keys() : String nw) { 
    ... 
} 

最後,

if ($score > $roll) # chosen a word 
{ 
    $sentence .= "$nw " unless $nw eq "."; 
    $cw = $nw; 
    last; 
} 

是這樣的:

if (score > roll) { // a break case 
    if (!nw.equals(".")) { 
     sentence = sentence + nw + " "; 
    } 
    cw  = nw 
    break KEY_LOOP; 
}