gpt4 book ai didi

java - Perl 到 Java 的翻译

转载 作者:行者123 更新时间:2023-12-02 07:40:34 26 4
gpt4 key购买 nike

我想知道是否有人可以帮助解释以下代码片段中发生的情况,因为我正在尝试将其翻译为 Java,但我的 Perl 知识很少。

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;
}

最佳答案

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;
}

关于java - Perl 到 Java 的翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11670829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com