从模板生成置换
Generating permutations from a template
我的目标是创建一个常规函数,该函数基于给定的模板和参数,创建一个二维向量,充满了排列(向量),如下所示:
- 基于模板作为函数参数向量,必须固定向量的某些位置。例如,如果给定的模板是
{0, 1, 0, -1, 3, -1}
,则意味着排列只会因-1
的数字而异。
。 -
n
。n-1
是置换可以包含的整数范围。例如。如果n = 4
,则只能出现在Vector中的0, 1, 2, 3
-
length
,这是向量的长度
请注意,如果来自模板中的数字已经出现在其中,则不会在排列中生成。
so,举一个例子:
n = 6, length = 5, template = {2, 1, 0, -1, 0, -1}
the permutations are:
{2, 1, 0, 3, 0, 3}
{2, 1, 0, 3, 0, 4}
{2, 1, 0, 3, 0, 5}
{2, 1, 0, 4, 0, 3}
{2, 1, 0, 4, 0, 4}
{2, 1, 0, 4, 0, 5}
{2, 1, 0, 5, 0, 3}
{2, 1, 0, 5, 0, 4}
{2, 1, 0, 5, 0, 5}
您可以看到,这些数字仅在索引3和5中生成(位置,位置为 -1
),也是不包括 0, 1 or 2
的地方,因为它们已经出现在模板中。
我需要在不使用<algorithm>
库的情况下生成这些排列。
我认为创建递归函数是最好的选择,但我不知道如何前进。任何建议都会有所帮助。
谢谢
由于您没有可见的尝试,我认为研究一些工作代码可能会有所帮助。这是在JavaScript中(我希望它会产生预期的输出)。我希望它可以帮助您一些想法,您可以转化为C 。
function f(template){
console.log(JSON.stringify(template));
var used = template.reduce((acc, x) => { if (x != -1) acc.add(x); return acc; }, new Set());
console.log(`used: ${Array.from(used)}`);
var needed = new Set(template.reduce((acc, x, i) => { if (!used.has(i)) acc.push(i); return acc; }, []));
console.log(`needed: ${Array.from(needed)}`);
var indexes = template.reduce((acc, x, i) => { if (x == -1) return acc.concat(i); else return acc; }, []);
console.log(`indexes: ${indexes}`);
function g(needed, indexes, template, i=0){
if (i == indexes.length)
return [template];
var result = [];
// Each member of 'needed' must appear in
// each position, indexes[i]
for (x of needed){
let _template = template.slice();
_template[ indexes[i] ] = x;
result = result.concat(
g(needed, indexes, _template, i + 1));
}
return result;
}
return g(needed, indexes, template);
}
var template = [2, 1, 0, -1, 0, -1];
var result = f(template);
var str = 'n';
for (let r of result)
str += JSON.stringify(r) + 'n';
console.log(str);
相关文章:
- 没有找到相关文章