内容旋转-计算飞镖中组合的数量



我正在尝试计算在内容旋转中可以进行的组合数量。

我在飞镖中为Flutter 编码的应用程序做这件事

对于以下字符串:{hello|hi}{world|everyone}

有4种可能的组合。

对于以下内容:

其中有3个。

以下字符串我成功了:{hello|hi}{world|everyone}

使用以下算法:

final String pattern = "{ hello|hi } { world|everyone }";

RegExp regExp = RegExp(r"{([^{}]*)}");
final Iterable<RegExpMatch> matches = regExp.allMatches(pattern);

List<int> nMaches = [];
for (int i = 0; i < matches.length; i++) {
final List<String> pin = matches.elementAt(i).group(1)!.split("|");
nMaches.add(pin.length);
}
int possibilities= nMaches.fold(1, (previous, current) => previous * current);

print(possibilities);

但我在为以下字符串设计相同的代码时遇到了问题:

你能帮我吗?提前感谢

也许是这样的:

int getVariantsCount(String pattern) {
int count(
String partialPattern,
int from,
int accumulator,
) {
var endGroupIndex = 0;
var stop = false;
for (var i = 0; i < partialPattern.length; i++) {
if (partialPattern[i] == '}') {
if (i == partialPattern.length - 1 || partialPattern[i + 1] == '{') {
endGroupIndex = i + 1;
stop = i == partialPattern.length - 1;
break;
}
}
}
var substring = partialPattern.substring(0, endGroupIndex);
print(substring);
final inGroup = substring.codeUnits.fold(
1,
(previousValue, element) => element == '|'.codeUnits[0]
? (previousValue + 1)
: previousValue);
if (stop) {
return accumulator * inGroup;
}
return count(
partialPattern.substring(endGroupIndex),
endGroupIndex,
accumulator * inGroup,
);
}
return count(pattern.replaceAll(' ', ''), 0, 1);
}

一些测试:

print(getVariantsCount('{hello | hi}') == 2);
print(getVariantsCount('{nice | good {job | goal}}') == 3);
print(getVariantsCount('{hello}{world|everyone}') == 2);
print(getVariantsCount('{ hello|hi } { world|everyone }') == 4);
print(getVariantsCount('{ hello|hi|ola } { world|everyone }') == 6);
print(getVariantsCount('{hello | hi} {nice | good {job | goal}}') == 6);
print(
getVariantsCount('{hello | hi} {cute | nice | good {job | goal}}') == 8);
print(
getVariantsCount('{hello | hi | ok} {cute | nice | good {job | goal}}') ==
12);
print(getVariantsCount('{hello} {cute | nice | good {job | goal}}') == 4);
print(getVariantsCount('{hello | hi} {cute | nice | good} {job | goal}') == 12);

最新更新