patternjavaMinor
Code reduction possible with modulo operator?
Viewed 0 times
operatorwithpossiblereductioncodemodulo
Problem
I'm trying to model a puzzle in order to resolve it with the Choco solver.
One of the constraint I'm coding is cyclical (it's triplet which follow themselves) like the following example:
I think that my library isn't very known so the mathematics equivalent is :
Any idea of how I can model this problem with modulo (to avoid writing each triplet)?
One of the constraint I'm coding is cyclical (it's triplet which follow themselves) like the following example:
s.post(LogicalConstraintFactory.ifThen(
IntConstraintFactory.member(mvt[i], new int[]{1, 2, 3}),
IntConstraintFactory.not_member(mvt[i + 1], new int[]{1, 2, 3})
));
s.post(LogicalConstraintFactory.ifThen(
IntConstraintFactory.member(mvt[i], new int[]{4, 5, 6}),
IntConstraintFactory.not_member(mvt[i + 1], new int[]{4, 5, 6})
));
s.post(LogicalConstraintFactory.ifThen(
IntConstraintFactory.member(mvt[i], new int[]{7, 8, 9}),
IntConstraintFactory.not_member(mvt[i + 1], new int[]{7, 8, 9})
));
// and so one...I think that my library isn't very known so the mathematics equivalent is :
if(foo[i] is in {1, 2, 3}) then
foo[i+1] shouldn't be in {1, 2, 3}
if(foo[i] is in {4, 5, 6}) then
foo[i+1] shouldn't be in {4, 5, 6}
...Any idea of how I can model this problem with modulo (to avoid writing each triplet)?
Solution
If your triplets were zero-based (i.e., {0, 1, 2}, {3, 4, 5}, …) then the answer might have been more obvious. As it is, you have to apply an offset of -1, then divide by three to figure out which triplet an element belongs to.
if ((mvt[i] - 1) / 3 == (mvt[i + 1] - 1) / 3) {
// This shouldn't happen: mvt[i] and mvt[i + 1] are in the same triplet
}Code Snippets
if ((mvt[i] - 1) / 3 == (mvt[i + 1] - 1) / 3) {
// This shouldn't happen: mvt[i] and mvt[i + 1] are in the same triplet
}Context
StackExchange Code Review Q#41737, answer score: 6
Revisions (0)
No revisions yet.