Modeling a constraint using Choco Solver - constraint-programming

i want to model the following constraint in CHOCO. Any help please
//cSelected[i]=1 ==> ∀ j∈{1,…,i-1} xCategory[i]!= xCategory[j]
cSelected[i]=0, otherwise
this is what i am trying to do
int[] x = new int[]{0, 1, 0, 0, 1, 0};
int[] xCategory = new int[]{3, 1, 2, 2, 3, 0};
int[] xCategorySize = new int[]{0, 100, 200, 300};
IntVar[] cSelected = model.intVarArray("d", 6, 0, 1);
// 3. Post constraints
// i want to add and post this constraint:
//cSelected [i]=1 ==> ∀ j∈{1,…,i-1} xCategory[i]!= xCategory[j]
//cSelected [i]=0, otherwise
for (int i=0; i<x.length;i++)
sum += (1-x[i]) * cSelected[i].getValue() * xCategorySize[xCategory[i]];

You'll need to reify the constraint for each test xCategory[i]!= xCategory[j] and put the result of the reification in a BoolVar contained in a BoolVar[][] cMatrix. Then you post an or constraint of every vector BoolVar[] in that matrix, saving it in your cSelected (which also is a BoolVarArray, not an IntVarArray):
for (int i=0; i<x.length;i++){
for (int j=0; j<x.length;j++){
xCategory[i].neq(xCategory[j]).reifyWith(cMatrix[i][j]);
}
cSelected[i] = model.or(cMatrix[i]).reify();
}

Related

Obtaining physical address trace from GEM5

I've been trying to extract physical address accessed by the application in order to analyze the row hits.
In doing so, I followed this page with little variation due to version change.
I fixed CacheConfig.py as:
system.monitor2 = CommMonitor()
system.monitor2.trace = MemTraceProbe(trace_file = "CT_mon2.trc.gz")
system.monitor2.slave = system.l2.mem_side
system.membus.slave = system.monitor2.master
system.l2.cpu_side = system.tol2bus.master
And ran a code:
build/X86/gem5.opt --debug-flag=CommMonitor configs/example/se.py --caches --l2cache --l2_size=2MB --mem-type=DDR4_2400_16x4 -c tests/test-progs/mm/bin/x86/linux/mm --cpu-type=TimingSimpleCPU
The mm is a binary from a simple matrix multiplication:
// C program to multiply two square matrices.
#include <stdio.h>
#define N 4
// This function multiplies mat1[][] and mat2[][],
// and stores the result in res[][]
void multiply(int mat1[][N], int mat2[][N], int res[][N])
{
int i, j, k;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
res[i][j] = 0;
for (k = 0; k < N; k++)
res[i][j] += mat1[i][k]*mat2[k][j];
}
}
}
int main()
{
int mat1[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int mat2[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int res[N][N]; // To store result
int i, j;
multiply(mat1, mat2, res);
printf("Result matrix is \n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%d ", res[i][j]);
printf("\n");
}
return 0;
}
After decoding the "CT_mon2.trc.gz", the memory trace are shown as:
5,u,15360,64,256,11500
6,u,183808,64,2,101000
5,u,18816,64,256,187000
6,u,183744,64,2,285000
5,u,18880,64,256,357000
6,u,171072,64,3,438000
6,u,171648,64,3,526000
6,u,172032,64,3,601000
6,u,174528,64,3,689000
5,u,18944,64,256,765000
The third one indicates physical address.
What I'm confusing is the "u" part. From decode stage, whatever that isn't read(r) or write(w) are notated as "u".
With debugging, commands were repeating with "UpgradeFailResp" and "ReadCleanReq".
I was expecting a trace with reads and writes, but I'm not sure what is happening here.
Can anyone tell me what am I missing?
Or even better way to obtain physical address will be a huge help.
Thanks,
jwlee
5,u,15360,64,256,11500
You can find the meaning of these numbers from the packet decoding script in the util folder. For example, 5 means the master(port) id. "u" means it was not either read or write command.
If you want to know the command itself, one possible way is to edit the gem5/src/mem/comm_monitor.cc where timing requests and responses are handled. For example:
DPRINTF(CommMonitor, "cmd: %s, cmdIndex: %d, addr: %lld masterId: %d \n", pkt->cmdString(),pkt->cmdToIndex(),pkt->getAddr(), pkt->masterId());
pkt->cmdString() shows the command or you can simply use pkt->print() to see the packet information. You can investigate packet.cc for more information.
You need to rebuild gem5 every time you change anything in the src folder.
The reason you will see traffic beyond reads and writes has to do with the placement of the CommMonitor. In your system, the membus is likely the point of coherency, so you will get all sorts of traffic generated by the l2 cache that is meant for cache coherency operations with other l2 caches (if they existed). If you move your CommMonitor beneath the point of coherency, e.g. between the membus and and your memory controllers, you should see only read and write traffic.

c# assigning a random result from an array to a variable returns outofrange error

I'm trying to create a program that generates random numbers; indexes a table; stores the results in some lists; then shows the results from the lists at a later point. I have a int variable called FreqMod which I'm trying to assign the random result from an array called FrequencyModifiers[]. This is throwing a runtime error "OutOfRange" as if it's getting a null value. But I don't see how. Let me see if I can post all the relevant code:
int TheHour = 0, TheMinute = 0, PlaceHolder = 0, FreqMod = 0;
int[] FrequencyModifier =
{
-3, -2, -1, 0, 0, 0, 1, 2, 3, 4, 6
};// int array FrequencyModifier
DiceResult = 0;
DiceResult = RollDice.TwoD6();
FreqMod = FrequencyModifier[DiceResult - 1];
This will be a modifier added to the results of later dice rolls.
tried this after some research and still no joy:
int[] FrequencyModifier =
{
-3, -2, -1, 0, 0, 0, 1, 2, 3, 4, 6
} ;// int array FrequencyModifier
FrequencyModifier = new int[11];
DiceResult = 0;
DiceResult = RollDice.TwoD6();
FreqMod = FrequencyModifier[DiceResult - 1];
from a class called dice, of which RollDice is an object:
public int TwoD6()
{
diceresult = 0;
numdice = 2;
for(int i = 1; i <= numdice; i++)
{
dieresult = 0;
lowest = 1;
highest = 6;
diceresult = diceresult + (1 + Rolldie.Next(lowest-1, highest));
}
return diceresult;
DiceResult should be the random number returned from the method RollDice.TwoD6.
I am trying to use it to assign the corresponding number from the array to FreqMod. So that if the random number returned is 3, then it would assign -2.
Before Christmas it had been almost 20 years since I looked at C and C++; I'm now trying to learn C#.

DP Print (not count) all possible path classic climbing stair

I came across this classic question and found may many solution to it. for loop and DP/ reclusive + memorization.
Also found a twisted version of the questions asking to print all possible path instead of counting. Wondering for the twisted version, if we have DP solution ?
Q: If there are n stairs, you can either take 1 or 2 steps at a time, how may way can you finish the stairs. we can just using fib to calculate it. What if you are ask print out all possible ways(not revision please). For example, if n = 5. we have as solution. pseudo code is welcome or any language.
[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 2, 1]
[1, 2, 1, 1]
[1, 2, 2]
[2, 1, 1, 1]
[2, 1, 2]
[2, 2, 1]
I have divided the solution into two subsections. First one using Memoization and the second one using Recursion.
Hope it helps!
Memoization Approach: It uses an array and calculates forward the solution based on base condition. I am using an array of type string array to store all the possible paths. To add a new path we are performing cartesian using Union.
Example:
To reach 1 we have path {1}
To reach 2 we have two paths {1, 2}
To reach 3 we have three paths {1 1 1, 1 2, 2 1} which is cartesian of above two paths.
Note: I have used two arrays just to make the solution understandable. We should be good with a single array.
Demo Memoization Approach
Full Program using Memoization Approach:
namespace Solutions
{
using System;
using System.Linq;
class Program
{
static void Main()
{
// Total Number of steps in stairs
var totalNumberOfSteps = 4;
// Total Number of allowed steps
var numberOfStepsAllowed = 2;
dynamic result = ClimbSteps(numberOfStepsAllowed, totalNumberOfSteps);
Console.WriteLine(result.Mem);
Console.WriteLine(string.Join(", ", result.Print));
Console.ReadLine();
}
private static dynamic ClimbSteps(int numberOfStepsAllowed, int totalNumberOfSteps)
{
var memList = Enumerable.Repeat(0, totalNumberOfSteps + 1).ToArray();
var printList = new string[totalNumberOfSteps + 1][];
if (numberOfStepsAllowed != 0)
{
memList[0] = 0;
printList[0] = new[] { "" };
memList[1] = 1;
printList[1] = new[] { "1" };
memList[2] = 2;
printList[2] = numberOfStepsAllowed > 1 ? new[] { "1 1", "2" } : new[] { "1 1" };
for (var indexTot = 3; indexTot <= totalNumberOfSteps; indexTot++)
{
for (var indexSteps = 1; indexSteps <= numberOfStepsAllowed && indexTot - indexSteps > 0; indexSteps++)
{
var indexTotalStep = indexTot;
var indexAllowedStep = indexSteps;
memList[indexTot] += memList[indexTot - indexSteps];
var cartesianValues = (from x in printList[indexSteps] from y in printList[indexTotalStep - indexAllowedStep] select x + " " + y)
.Union(from x in printList[indexSteps] from y in printList[indexTotalStep - indexAllowedStep] select y + " " + x).Distinct();
printList[indexTot] = printList[indexTot] == null
? cartesianValues.ToArray()
: printList[indexTot].Union(cartesianValues).Distinct().ToArray();
}
}
}
return new { Mem = memList[totalNumberOfSteps], Print = printList[totalNumberOfSteps] };
}
}
}
Output:
5
1 1 1 1, 1 1 2, 1 2 1, 2 1 1, 2 2
Recursive Approach
Demo Recursive Approach
Full Program using Recursive Approach:
namespace Solutions
{
using System;
class Program
{
static void Main()
{
// Total Number of steps in stairs
var totalNumberOfSteps = 4;
// Total Number of allowed steps
var numberOfStepsAllowed = 2;
ClimbSteps(numberOfStepsAllowed, totalNumberOfSteps);
Console.ReadLine();
}
private static void ClimbSteps(int numberOfStepsAllowed, int totalNumberOfSteps)
{
// Reach from [totalNumberOfSteps - [1..numberOfStepsAllowed]]
ClimbStep(stepsAllowed: numberOfStepsAllowed, totalNumberOfSteps: totalNumberOfSteps, currentStep: 0, stepsTaken: String.Empty);
}
private static void ClimbStep(int stepsAllowed, int totalNumberOfSteps, int currentStep, string stepsTaken)
{
if (currentStep == totalNumberOfSteps)
{
Console.WriteLine(stepsTaken);
}
for (int i = 1; i <= stepsAllowed && currentStep + i <= totalNumberOfSteps; i++)
{
ClimbStep(stepsAllowed, totalNumberOfSteps, currentStep + i, stepsTaken + i + " ");
}
}
}
}
Ouput:
1 1 1 1
1 1 2
1 2 1
2 1 1
2 2

coin change recurrence solution

Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter.There is additional restriction though: you can only give change with exactly K coins.
For example, for N = 4, k = 2 and S = {1,2,3}, there are two solutions: {2,2},{1,3}. So output should be 2.
Solution:
int getways(int coins, int target, int total_coins, int *denomination, int size, int idx)
{
int sum = 0, i;
if (coins > target || total_coins < 0)
return 0;
if (target == coins && total_coins == 0)
return 1;
if (target == coins && total_coins < 0)
return 0;
for (i=idx;i<size;i++) {
sum += getways(coins+denomination[i], target, total_coins-1, denomination, size, i);
}
return sum;
}
int main()
{
int target = 49;
int total_coins = 15;
int denomination[] = {1, 2, 3, 4, 5};
int size = sizeof(denomination)/sizeof(denomination[0]);
printf("%d\n", getways(0, target, total_coins, denomination, size, 0));
}
Above is recursive solution. However i need help with my dynamic programming solution:
Let dp[i][j][k] represent sum up to i with j elements and k coins.
So,
dp[i][j][k] = dp[i][j-1][k] + dp[i-a[j]][j][k-1]
Is my recurrence relation right?
I don't really understand your recurrence relation:
Let dp[i][j][k] represent sum up to i with j elements and k coins.
I think you're on the right track, but I suggest simply dropping the middle dimension [j], and use dp[sum][coinsLeft] as follows:
dp[0][0] = 1 // coins: 0, desired sum: 0 => 1 solution
dp[i][0] = 0 // coins: 0, desired sum: i => 0 solutions
dp[sum][coinsLeft] = dp[sum - S1][coinsLeft-1]
+ dp[sum - S2][coinsLeft-1]
+ ...
+ dp[sum - SM][coinsLeft-1]
The answer is then to be found at dp[N][K] (= number of ways to add K coins to get N cents)
Here's some sample code (I advice you to not look until you've tried to solve it yourself. It's a good exercise):
public static int combinations(int numCoinsToUse, int targetSum, int[] denom) {
// dp[numCoins][sum] == ways to get sum using numCoins
int[][] dp = new int[numCoinsToUse+1][targetSum];
// Any sum (except 0) is impossible with 0 coins
for (int sum = 0; sum < targetSum; sum++) {
dp[0][sum] = sum == 0 ? 1 : 0;
}
// Gradually increase number of coins
for (int c = 1; c <= numCoinsToUse; c++)
for (int sum = 0; sum < targetSum; sum++)
for (int d : denom)
if (sum >= d)
dp[c][sum] += dp[c-1][sum - d];
return dp[numCoinsToUse][targetSum-1];
}
Using your example input:
combinations(2, 4, new int[] {1, 2, 3} ) // gives 2

Common Elements Sequence

I have two arrays of integer type.
int[] righttarray=new int[] {6,9,8,1,5,3};
int[] leftarray=new int[] {1,3};
Now I have to find out the common elements between these two as well as I need to match common elements indexes. If the indexes are same then its ok, if not then sequence will be maintained from rightarray.
I am getting Common elements by intersect method in C#.
See, element 1 and 3 are common in both the arrays. But in "leftarray" their sequence in 0,1 and in "rightarray" their sequence in 3,5. How to check this is my question. Thanks !!
Help me out doing this.
Ok, try something like:
int[] righttarray = new int[] { 6, 3, 8, 1, 5, 3 };
int[] leftarray = new int[] { 1, 3 };
if (righttarray.Length < leftarray.Length)
{
var result = righttarray.Where((x, i) => righttarray[i] == leftarray[i]);
}
else
{
var result = leftarray.Where((x, i) => leftarray[i] == righttarray[i]);
}
This will give you the number 3, which is in the same index and with the same element number. In your example, the output will be empty, I have changed only to check it ;)

Resources