0

让我有矩阵

一个=

1 2 3

1 3 5

1 2 4

2 3 7

任务是重新排列矩阵,以便在任何行中没有两个元素的顺序相同。

例如,在第 1 行和第 2 行中,我们有相同顺序的数字 1 和 3。我们在第 1 行从左到右翻转 1 和 3 中的数字并得到

3 2 1

1 3 5

1 2 4

2 3 7

我的想法是这是一个搜索问题,可以通过答案集编程来解决吗?问题是,如果您尝试使用某种算法来执行此操作,那么在某些时候您最终会将两个数字按照与它们在其他行中的顺序相同的顺序排列。

这对于重新定向网格的三角形表面网格面很有用,其中面法线指向不一致的方向,以便所有法线都指向内(或外)

4

2 回答 2

0

是的,你可以用 ASP 做到这一点。

这不是最优雅的代码,但我认为如果您使用 Clingo 系列 5,您可以这样做:

%% List the numbers to fill the matrix, we must associated each with an index value
number(1,1;2,2;3,3;1,4;3,5;5,6;1,7;2,8;4,9;2,10;3,11;7,12).

%% x limits
x(0..2).

%% y limits
y(0..3).

%% Generate the matrix
{ matrix(V, I, X, Y) } :- number(V, I), x(X), y(Y).

%% Define the order of the elements
order(V1, I1, V2, I2, Y) :- matrix(V1, I1, X1, Y), matrix(V2, I2, X2, Y), X1 < X2.

%% Do not allow two different rows to have the same order of elements
:- order(V1, I1, V2, I2, Y1), order(V1, I3, V2, I4, Y2), Y1 != Y2.

%% Each number must be in the matrix exactly once
:- not { matrix(V, I, X, Y) } = 1, number(V, I).

%% Each element can contain only one number
:- not #count { V, I : matrix(V, I, X, Y) } = 1, matrix(_, _, X, Y).

%% Show the matrix
#show matrix/4.

这给了你这个作为输出:

3 1 3

4 2 3

1 1 5

2 2 7

尽管牢记在心,但有数十万(我认为数百万)方法可以订购此矩阵并获得满足您的约束的结果。

于 2019-05-03T18:20:10.603 回答
0

给定表格中的输入:

value(ROW,COL,VAL).
nrows(nr).
ncols(nc).

您可以执行以下操作:

row(1..NR) :- nrows(NR).
col(1..NC) :- ncols(NC).
is_value(V) :- value(_, _, V).

% For each position in the original matrix, say what new column it's in.
{new_place(ROW,OLDCOL,NEWCOL,VAL) : col(NEWCOL)} = 1 :- value(ROW,OLDCOL,VAL).
% Can't have more than one value in the same position.
:- {new_place(ROW,_,COL,_)} > 1; row(ROW); col(COL).
% A comes before B in row ROW if COL_A < COL_B
ordered(A,B,ROW) :- new_place(ROW,_,COL_A,A); new_place(ROW,_,COL_B,B); COL_A < COL_B.
% For any two values A and B, there exists at most one row where A comes before B
:- {ordered(A,B,ROW) : row(ROW)} > 1; is_value(A); is_value(B).

#show.
#show p(R,C,V) : new_place(R,_,C,V).

请注意,如果一行中有重复,您必须跟踪原始列。如果没有行包含重复项(如您的示例中的情况),则第二个参数 ofnew_place是不必要的。

于 2019-05-05T01:36:03.677 回答