根据Perl RegEx中的频率对一组变量进行排序。

我正在尝试使用表格或数组列出和按“吃掉”的顺序排序项目/字母序列。这四个列表是完全相同的项目/字母序列,只是顺序不同,依次输入。

输入项目:这些字母代表客户端的操作或输入。

a b c d

b c d a

c d b a

d a b c

Perl正则表达式:

^(\w+) eats (a|an) (\w+)\.$

因此,matches [4]将被捕获的项目捕获。

这将在客户端中触发RegEx,“每个”字母(a,b,c,d)都要输入,分别输入四组a,b,c,d,但是会轮换顺序。上述RegEx将会触发16次(每个字母一次)。如果每次都先吃(a),则它将具有最高优先级,但它可能不总是(a),而可以是任何具有优先级的字母。

我需要将此优先级列表显示到类似Geyser的页面中。

PrioList= Geyser.MiniConsole:new({
  name="PrioList",
  x="70%", y="50%",
  width="30%", height="50%",
})

然后,我需要能够将每个字母分配到不同的优先级列表或变量中。因为每个独立的字母都表示需要采取不同的操作,所以我需要说

if (a == highestpriority) then
do action / function()
end

我不确定如何编写“for”语句,以便根据4组字母对这些项目进行排序和列出。我想这个列表必须被保存和重置,每个序列后,然后以某种方式输入表或数组,并相互比较以获取最高优先级。但这超出了我所知道的脚本范畴,但我一定很乐意学习。

点赞
用户1364945
用户1364945

如果我正确地理解了你的意思,一个选项是使用哈希来计数第一个输入字母的频率,还有使用分派表将每个字母与子例程相关联:

use strict;
use warnings;
use List::Util qw/shuffle/;

my %seen;
my %dispatchTable = (
    a => \&a_priority,
    b => \&b_priority,
    c => \&c_priority,
    d => \&d_priority
);

for my $i ( 1 .. 4 ) {
    my @chars = shuffle qw/a b c d/;
    print "Round $i: @chars\n";
    $seen{ $chars[0] }++;
}

my $priority = ( sort { $seen{$b} <=> $seen{$a} } keys %seen )[0];
print "Priority: $priority\n";

$dispatchTable{$priority}->();

sub a_priority {
    print "a priority sub called\n";
}

sub b_priority {
    print "b priority sub called\n";
}

sub c_priority {
    print "c priority sub called\n";
}

sub d_priority {
    print "d priority sub called\n";
}

样例运行输出:

Round 1: d c a b
Round 2: b a d c
Round 3: d b a c
Round 4: c d a b
Priority: d
d priority sub called

你说,“我需要能够对其进行排序,以便如果(a)每次都被吃掉…”,以上尝试选择具有最高频率的条目 - 而不是四次都是第一个的条目。

你需要决定在多个字母共享相同频率的情况下该做什么,但也许这将帮助提供一些方向。

2014-03-01 21:37:11