谁能将此函数变成递归的通用函数,以便我可以用它来检索n
个大小的组合?
这是我目前拥有的,并且只能在$size: 2
@function combinations($list, $size, $separator: comma){
$result: null;
@each $item in $list {
@if ($size == 1) {
$result: append($result, #{$item}, $separator);
} @else {
@each $val in $list {
$result: join($result, #{$item}#{$val}, $separator);
}
}
}
@return $result;
}
$list: a, b, c;
test {
val: combinations($list, 2);
}
输出尺寸:1
a,b,c
尺寸输出:2
a,b,c,aa,ab,ac,ba,bb,bc,ca,cb,cc
但是我需要继续$size: n
和n <= length($list)
答案 0 :(得分:1)
经过多次尝试和大量研究,我终于找到了解决方案。
@function combinations($list, $size: length($list), $combs: (), $separator: comma){
@if ($combs == ()) {
$combs: $list;
}
@if ($size == 1) {
@return $combs
}
$newCombs: null;
@each $comb in $combs {
@each $item in $list {
@if not index($newCombs, $comb) {
$newCombs: join($newCombs, #{$comb}#{$item}, $separator);
}
}
}
@return join($combs, #{combinations($list, abs($size - 1), $newCombs)});
}
$list: a, b, c;
$size: n;
combinations($list, $size);
将基于$list
输出$size
中所有可能的值组合的列表。