I have an array of variables called LIST. That can be indexed from 1 to tMax, and it can assume values from an enum called SYMB.
My objective is minimize the max distance between same occurrences of SYMB in LIST.
For example, if LIST = {S1, S2, S1, S3, S2, S1}.
S1: maximum distance is 3. The S1 in position 3 and S1 in position 6.
S2: maximum distance is 3. The S1 in position 2 and S1 in position 5.
S3: maximum distance is 0. It only has 1 occurrence of S3.
int: tMax;
enum SYMB;
array[1..tMax] of var SYMB: LIST;
var int: obj;
constraint forall(i in 1..tMax, j in i+1..tMax
where LIST[i] = LIST[j])
(obj = max( abs (i - j) , obj) );
solve minimize obj;
However, this code is considering the distance from the first occurrence of S1 in position 1, and last occurrence of S1 in position 6, so the distance is 5.
I would like to know if it is possible, and how to do, to check only the first occurrence between same SYMB. S1 from the index 1 compared with S1 from the index 3, and S1 from index 3 compared with S1 from index 6.
It's a kind of 'break' the internal loop after the first comparison.
Thank you all.
Related
Looking within the xcorr function, most of it is pretty straightforward, except for one function within xcorr called "findTransformLength".
function m = findTransformLength(m)
m = 2*m;
while true
r = m;
for p = [2 3 5 7]
while (r > 1) && (mod(r, p) == 0)
r = r / p;
end
end
if r == 1
break;
end
m = m + 1;
end
With no comments, i fail to understand what this function is meant to acheive and what is the significance of p = [2 3 5 7]. Why those numbers specifically? Why not take a fixed FFT size instead? Is there a disadvantage(cause errors) to taking a fixed FFT size?
This part is used to get the integer closest to 2*m that can be written in the form:
Either:
m is already of this form, then the loop
for p = [2 3 5 7]
while (r > 1) && (mod(r, p) == 0)
r = r / p;
end
end
Will decrease r down to 1 and the break will be reached.
Or m has at least one other prime factor, and r will not reach 1. You go back to the look with m+1 and so on until you reach a number of the right form.
As per why they do this, you can see on the fft doc, in the Input arguments section:
n — Transform length [] (default) | nonnegative integer scalar
Transform length, specified as [] or a nonnegative integer scalar.
Specifying a positive integer scalar for the transform length can
increase the performance of fft. The length is typically specified as
a power of 2 or a value that can be factored into a product of small
prime numbers. If n is less than the length of the signal, then fft
ignores the remaining signal values past the nth entry and returns the
truncated result. If n is 0, then fft returns an empty matrix.
Example: n = 2^nextpow2(size(X,1))
I need some help with the following case.
let say I have the following code:
enum x= {p,k,m};
enum y= {t1,t2,t3,t4};
array[y] of set of int:against=[{1,3,6},{3,3,6},{6,1,1},{6,3,6}];
array[x] of set of int:attack=[{3,3,6},{6,2,2},{3,1,3}];
array[x] of set of y: NodesD=[{t2,t3},{t2,t3,t4},{t1,t4}];
array[x]of var y: Select;
constraint forall(p in x)(Select[p] in NodesD[p]);
So for each enum of x I should select only on enum of Y. Then I want to select the one that suitable for each set of attack in the following way:
let take the first enum of x {p} which have two possible chooses of y{t2,t3}, so I want to do like this: t2={1,1,6}, t3={6,3,3} so I want to subtract each value in x attack[] {3,3,6} from each value in y against[] and the sum up the results:
{1,1,6}-
{3,3,6}
-----------
{-2,-2,0} then sum them which is equal to -4
then do the same with t2
{6,3,3}-
{3,3,6}
------------
{3,0,-3} which is equal to 0
and in this case, t3 which is equal to 0 is better than t2=-4.
I want to do the same for each enum x and Maximize the power.
I tried to do it in the following way but it does not work
var int: power = sum(p in x)(card(against[Select[p]])-(card(attack[p])*Select[p]) );
solve maximize power ;
Any help or hint please,:)
If you want to make an element by element comparison a matrix is better suited for that than an array of sets, because that way you ensure that both matrixes have the same width and also the syntax is less cumbersome, so instead of summing with an index from 1 to the cardinality of the set you use a different set to sum over the columns of the matrix.
You could calculate the sum of the element wise difference of the sets with
sum(i in 1..min(card(set_A),card(set_B)))(set_A[i] - set_B[i]);
using the min to be sure that you only iterate over the smallest set and don't access elements that don't exist.
But written like this is cleaner in my opinion, basically, change the {} of sets for | to delimit the rows of the matrix in attack and against, and add a new variable that will index the columns of the matrix, I called it FRONTS in this example, so you pick an X and compare the difference of forces over the different battlefronts.
enum X = {p,k,m};
enum y = {t1,t2,t3,t4};
set of int : FRONTS = 1..3;
array[y,FRONTS] of int : against=[|1,3,6|3,3,6|6,1,1|6,3,6|];
array[X,FRONTS] of int : attack=[|3,3,6|6,2,2|3,1,3|];
array[X] of set of y : nodesD=[{t2,t3},{t2,t3,t4},{t1,t4}];
array[X] of var y : select;
var int: power;
constraint forall(p in X)(select[p] in nodesD[p]);
constraint power = sum(p in X)( sum(i in FRONTS)( against[ select[p], i] - attack[ p, i ] ) );
solve maximize power;
output [show(select) ++ " = " ++ show(power)];
How could I select the smallest number from each row of a 2d array while making sure the same column can at most be selected twice
(in the following case, for row 1, column 5 is chosen; for row 2, column 5 is chosen while for row 3, column 5 can no longer be selected, so column 2 is selected as the min):
(Besides, in java, it is often that ArrayList is used to add and remove elements but how is it possible to do this in Minizinc using constraints)?
int: m = 3;
int: n = 5;
array[1..m,1..n] of int: diffs = [|14,18,24,30,13
|10,12,18,24,7
| 8,7,12,18,6|]
Below is one approach which minimize the sum of the difference between the values of the selected columns and the "real" smallest values of each row.
include "globals.mzn";
int: m = 3;
int: n = 5;
array[1..m,1..n] of int: diffs = [|14,18,24,30,13
|10,12,18,24,7
| 8,7,12,18,6|];
% decision variables
array[1..m] of var 1..n: x; % which row to select
var int: z; % difference between the selected and smallest values
solve minimize z;
% solve satisfy;
% constraint 1: at_most 2 of the same column can be selected
constraint
% at most two rows can have the same column
forall(j in 1..n) (
at_most(2,x,j)
)
;
% constraint 2: calculate the least difference
constraint
% get smallest difference to the smallest value
z = sum(i in 1..m) (
% value of selected column - the smallest value of the row
diffs[i,x[i]]-min([diffs[i,j] | j in 1..n])
)
% /\ % for solve satisfy
% z = 1
;
output [
"z: \(z)\n",
"x: \(x) values:\([diffs[i,x[i]] | i in 1..m])\n"
];
For this problem instance there are two optimal solutions with z=1, i.e. the solution is 1 larger than the "real" optimal value (which would have been without the max 2 column constraint).
z: 1
x: [5, 5, 2] values:[13, 7, 7]
----------
z: 1
x: [1, 5, 5] values:[14, 7, 6]
The first solution mean that we pick the values from column 5 for the 2 first rows (i.e. the values of 13 and 7), and for the third row we pick the value from column 2 (i.e. 7). This happens to be the solution mentioned in the example.
There is an alternative approach where constraint 2 is replaced with the following constraint, i.e. which sums the selected values directly (and not the difference against minimum value of each row):
% constraint 2: calculate the least difference
constraint
z = sum([diffs[i,x[i]] | i in 1..m])
% /\ % for solve satisfy
% z = 27
;
It has - of course - the same solution of columns. The difference is only in the value of "z":
z: 27
x: [5, 5, 2] values:[13, 7, 7]
---------
z: 27
x: [1, 5, 5] values:[14, 7, 6]
Arguably this later variant is neater, but if the values in the "diffs" matrix are large then the first variant should probably be used since solvers tend to be happier to work with smaller values. (For matrices with large values it's recommended to use a restricted domain of "z" instead of "var int", but I'm a little lazy tonight. :-)
I have encountered a surprisingly challenging problem arranging a matrix-like (List of Lists) of values subject to the following constraints (or deciding it is not possible):
A matrix of m randomly generated rows with up to n distinct values (no repeats within the row) arrange the matrix such that the following holds (if possible):
1) The matrix must be "lower triangular"; the rows must be ordered in ascending lengths so the only "gaps" are in the top right corner
2) If a value appears in more than one row it must be in the same column (i.e. rearranging the order of values in a row is allowed).
Expression of the problem/solution in a functional language (e.g. Scala) is desirable.
Example 1 - which has a solution
A B
C E D
C A B
becomes (as one solution)
A B
E D C
A B C
since A, B and C all appear in columns 1, 2 and 3, respectively.
Example 2 - which has no solution
A B C
A B D
B C D
has no solution since the constraints require the third row to have the C and D in the third
column which is not possible.
I thought this was an interesting problem and have modeled a proof-of-concept-version in MiniZinc (a very high level Constraint Programming system) which seems to be correct. I'm not sure if it's of any use, and to be honest I'm not sure if it's powerful for very largest problem instances.
The first problem instance has - according to this model - 4 solutions:
B A _
E D C
B A C
----------
B A _
D E C
B A C
----------
A B _
E D C
A B C
----------
A B _
D E C
A B C
The second example is considered unsatisfiable (as it should).
The complete model is here: http://www.hakank.org/minizinc/ordering_a_list_of_lists.mzn
The basic approach is to use matrices, where shorter rows are filled with a null value (here 0, zero). The problem instance is the matrix "matrix"; the resulting solution is in the matrix "x" (the decision variables, as integers which are then translated to strings in the output). Then there is a helper matrix, "perms" which are used to ensure that each row in "x" is a permutation of the corresponding row in "matrix", done with the predicate "permutation3". There are some other helper arrays/sets which simplifies the constraints.
The main MiniZinc model (sans output) is show below.
Here are some comments/assumptions which might make the model useless:
this is just a proof-of-concept model since I thought it was an interesting
problem.
I assume that the rows in the matrix (the problem data) is already ordered
by size (lower triangular). This should be easy to do as a preprocessing step
where Constraint Programming is not needed.
the shorter lists are filled with 0 (zero) so we can work with matrices.
since MiniZinc is a strongly typed language and don't support
symbols, we just define integers 1..5 to represent the letters A..E.
Working with integers is also beneficial when using traditional
Constraint Programming systems.
% The MiniZinc model (sans output)
include "globals.mzn";
int: rows = 3;
int: cols = 3;
int: A = 1;
int: B = 2;
int: C = 3;
int: D = 4;
int: E = 5;
int: max_int = E;
array[0..max_int] of string: str = array1d(0..max_int, ["_", "A","B","C","D","E"]);
% problem A (satifiable)
array[1..rows, 1..cols] of int: matrix =
array2d(1..rows, 1..cols,
[
A,B,0, % fill this shorter array with "0"
E,D,C,
A,B,C,
]);
% the valid values (we skip 0, zero)
set of int: values = {A,B,C,D,E};
% identify which rows a specific values are.
% E.g. for problem A:
% value_rows: [{1, 3}, {1, 3}, 2..3, 2..2, 2..2]
array[1..max_int] of set of int: value_rows =
[ {i | i in 1..rows, j in 1..cols where matrix[i,j] = v} | v in values];
% decision variables
% The resulting matrix
array[1..rows, 1..cols] of var 0..max_int: x;
% the permutations from matrix to x
array[1..rows, 1..cols] of var 0..max_int: perms;
%
% permutation3(a,p,b)
%
% get the permutation from a b using the permutation p.
%
predicate permutation3(array[int] of var int: a,
array[int] of var int: p,
array[int] of var int: b) =
forall(i in index_set(a)) (
b[i] = a[p[i]]
)
;
solve satisfy;
constraint
forall(i in 1..rows) (
% ensure unicity of the values in the rows in x and perms (except for 0)
alldifferent_except_0([x[i,j] | j in 1..cols]) /\
alldifferent_except_0([perms[i,j] | j in 1..cols]) /\
permutation3([matrix[i,j] | j in 1..cols], [perms[i,j] | j in 1..cols], [x[i,j] | j in 1..cols])
)
/\ % zeros in x are where there zeros are in matrix
forall(i in 1..rows, j in 1..cols) (
if matrix[i,j] = 0 then
x[i,j] = 0
else
true
endif
)
/\ % ensure that same values are in the same column:
% - for each of the values
% - ensure that it is positioned in one column c
forall(k in 1..max_int where k in values) (
exists(j in 1..cols) (
forall(i in value_rows[k]) (
x[i,j] = k
)
)
)
;
% the output
% ...
I needed a solution in a functional language (XQuery) so I implemented this first in Scala due to its expressiveness and I post the code below. It uses a brute-force, breadth first style search for solutions. I'm inly interested in a single solution (if one exists) so the algorithm throws away the extra solutions.
def order[T](listOfLists: List[List[T]]): List[List[T]] = {
def isConsistent(list: List[T], listOfLists: List[List[T]]) = {
def isSafe(list1: List[T], list2: List[T]) =
(for (i <- list1.indices; j <- list2.indices) yield
if (list1(i) == list2(j)) i == j else true
).forall(_ == true)
(for (row <- listOfLists) yield isSafe(list, row)).forall(_ == true)
}
def solve(fixed: List[List[T]], remaining: List[List[T]]): List[List[T]] =
if (remaining.isEmpty)
fixed // Solution found so return it
else
(for {
permutation <- remaining.head.permutations.toList
if isConsistent(permutation, fixed)
ordered = solve(permutation :: fixed, remaining.tail)
if !ordered.isEmpty
} yield ordered) match {
case solution1 :: otherSolutions => // There are one or more solutions so just return one
solution1
case Nil => // There are no solutions
Nil
}
// Ensure each list has unique items (i.e. no dups within the list)
require (listOfLists.forall(list => list == list.distinct))
/*
* The only optimisations applied to an otherwise full walk through all solutions is to sort the list of list so that the lengths
* of the lists are increasing in length and then starting the ordering with the first row fixed i.e. there is one degree of freedom
* in selecting the first row; by having the shortest row first and fixing it we both guarantee that we aren't disabling a solution from being
* found (i.e. by violating the "lower triangular" requirement) and can also avoid searching through the permutations of the first row since
* these would just result in additional (essentially duplicate except for ordering differences) solutions.
*/
//solve(Nil, listOfLists).reverse // This is the unoptimised version
val sorted = listOfLists.sortWith((a, b) => a.length < b.length)
solve(List(sorted.head), sorted.tail).reverse
}
I am trying to create or find a CoffeeScript implementation of the Levenshtein Distance formula, aka Edit Distance. Here is what I have so far, any help at all would be much appreciated.
levenshtein = (s1,s2) ->
n = s1.length
m = s2.length
if n < m
return levenshtein(s2, s1)
if not s1
return s2.length
previous_row = [s2.length + 1]
for c1, i in s1
current_row = [i + 1]
for c2, j in s2
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] # is this unnescessary?-> (c1 != c2)
current_row.push(Math.min(insertions,deletions,substitutions))
previous_row = current_row
return previous_row[previous_row.length-1]
#End Levenshetein Function
Btw: I know this code is wrong on many levels, I am happy to receive any and all constructive criticism. Just looking to improve, and figure out this formula!
CodeEdit1: Patched up the errors Trevor pointed out, current code above includes those changes
Update: The question I am asking is - how do we do Levenshtein in CoffeeScript?
Here is the 'steps' for the Levenshtein Distance Algorithm to help you see what I am trying to accomplish.
Steps
1
Set n to be the length of s.
Set m to be the length of t.
If n = 0, return m and exit.
If m = 0, return n and exit.
Construct a matrix containing 0..m rows and 0..n columns.
2
Initialize the first row to 0..n.
Initialize the first column to 0..m.
3 Examine each character of s (i from 1 to n).
4 Examine each character of t (j from 1 to m).
5 If s[i] equals t[j], the cost is 0.
If s[i] doesn't equal t[j], the cost is 1.
6 Set cell d[i,j] of the matrix equal to the minimum of:
a. The cell immediately above plus 1: d[i-1,j] + 1.
b. The cell immediately to the left plus 1: d[i,j-1] + 1.
c. The cell diagonally above and to the left plus the cost: d[i-1,j-1] + cost.
7 After the iteration steps (3, 4, 5, 6) are complete, the distance is found in cell d[n,m].
source:http://www.merriampark.com/ld.htm
This page (linked to from the resource you mentioned) offers a JavaScript implementation of the Levenshtein distance algorithm. Based on both that and the code you posted, here's my CoffeeScript version:
LD = (s, t) ->
n = s.length
m = t.length
return m if n is 0
return n if m is 0
d = []
d[i] = [] for i in [0..n]
d[i][0] = i for i in [0..n]
d[0][j] = j for j in [0..m]
for c1, i in s
for c2, j in t
cost = if c1 is c2 then 0 else 1
d[i+1][j+1] = Math.min d[i][j+1]+1, d[i+1][j]+1, d[i][j] + cost
d[n][m]
It seems to hold up to light testing, but let me know if there are any problems.