Traditional Longest Increasing Subsequence problem.
This is recursion version ( not DP version )
I realized that version1 code had a bug, so I changed it to version2.
I don't clearly understand why version2 works and version1 has a bug for input A0
Please see version 1 and version2 below:
static int lis1(int[] v) {
int maxLen = 1;
for(int i = 1; i < v.length; i++) {
List<Integer> w = new ArrayList<Integer>();
for( int j = 0; j < i; j++) {
if( v[j] < v[i] ) {
w.add(v[j]);
}
}
// it used to be the following one line which has bug for input A0
//cand = lis1(l2a(w)) + 1; // version1
// so I changed it to the following, but can't clearly understand why it works.
// without this part, it has but for input A0
int cand = 1; // version2
if(v[i-1] < v[i])
cand = lis1(l2a(w)) + 1;
else
cand = lis1(l2a(w));
maxLen = Math.max(maxLen, cand);
}
return maxLen;
}
public static void main(String[] args) {
int[] A0 = {3, 2, 5, 6}; // for this input version1 had a bug which printed out 4 ( instead of 3 )
int[] A1 = {1, 2, 3, 3, 2, 4, 6, 7}; // 6
int[] A2 = { 10, 22, 9, 33, 21, 50, 41, 60, 80 }; // 6
int[] A3 = { 5, 0, 4, 2, 3, 7, 1 }; // 4
int[] A4 = { 2, 7, 3, 4, 9, 8, 12 }; // 5
int[] A5 = {3, 4, 2, 5 }; // 3
Actually... neither of your version works. Try putting A0={3,2,7,6}, your v2 returns 2, obviously wrong.
As for v1, for v={3,2} the answer should be 1, right? Let's see what your code does. When index i=1, your w after inner for loop equals {}. Then you made a recursive call to w={}, which should've returned 0, but it returns 1. Why, because of your maxlen variable, which is wrongly initialized with 1. This error propagates to entire {3,2,5,6} and gives wrong answer.
v2 accidentally solves this problem because your if condition then fails (3<2), and it returns the previously returned 1.
Just delete entire version 2, correct maxlen initialization. And start outer loop for(int i = 1; i < v.length; i++) with i=0, else you will get 0 for single-element array.
static int lis1(int[] v) {
int maxLen = 0;
for(int i = 0; i < v.length; i++) {
List<Integer> w = new ArrayList<Integer>();
for( int j = 0; j < i; j++) {
if( v[j] < v[i] ) {
w.add(v[j]);
}
}
cand = lis1(l2a(w)) + 1; // version1
maxLen = Math.max(maxLen, cand);
}
return maxLen;
}
Related
char arrA[ 6 ] = { 1, 2, 3, 4, 5, 0 };
char arrB[ 6 ] = {};
void setup(){
strcpy( arrB, arrA );
}
Hi all, I obtained the code above from here. My case is I need to use int arrA[6] instead of char arrA[6] when initializing variables so that it remains as values and not string. May I ask how do I actually accomplish it with arduino code. The link above only uses string as array and not numbers. Thank you for reading and have a nice day !!!
You can write a for loop to copy the contents of arrA to arrB.
int arrA[ 6 ] = { 1, 2, 3, 4, 5, 0 };
int arrB[ 6 ];
void setup(){
for(int i = 0; i < (sizeof(arrA)/sizeof(arrA[0])); i++)
{
arrB[i] = arrA[i];
}
}
In the "Writing R Extensions" manual it says
Protecting an R object automatically protects all the R objects pointed to in the
corresponding SEXPREC, for example all elements of a protected list are automatically
protected.
Does this mean that I do not need to protect individual SEXP elements of a VECSXP. For example consider the following which contains two methods that I hope illustrate where I need clarification:
#include <Rinternals.h>
#include <R.h>
SEXP copy_int_vec(int *x, int size) {
SEXP ans = allocVector(INTSXP, size);
PROTECT(ans);
int *pans = INTEGER(ans);
for (int i = 0; i < size; i ++) {
pans[i] = x[i];
}
UNPROTECT(1);
return ans;
}
// method 1 - protect VECSXP when allocated BUT NOT individual array entries
SEXP method_one() {
// setup for rep example
int N = 3;
int *graph[N];
int tmp1[3] = {1, 2, 3};
int tmp2[4] = {1, 2, 3, 4};
int tmp3[2] = {3, 4};
graph[0] = tmp1;
graph[1] = tmp2;
graph[2] = tmp3;
int neighbours[3] = {3, 4, 2};
// method
SEXP ans = allocVector(VECSXP, N);
PROTECT(ans);
for (int i = 0; i < N; i++){
SET_VECTOR_ELT(ans, i, copy_int_vec(graph[i], neighbours[i]));
}
UNPROTECT(1);
return ans;
}
// method 2 - protect VECSXP when allocated AND ALSO individual array entries
SEXP method_two() {
// setup for rep example
int N = 3;
int *graph[N];
int tmp1[3] = {1, 2, 3};
int tmp2[4] = {1, 2, 3, 4};
int tmp3[2] = {3, 4};
graph[0] = tmp1;
graph[1] = tmp2;
graph[2] = tmp3;
int neighbours[3] = {3, 4, 2};
// method 2
SEXP ans = allocVector(VECSXP, N);
PROTECT(ans);
for (int i = 0; i < N; i++){
SEXP tmp = copy_int_vec(graph[i], neighbours[i]);
PROTECT(tmp);
SET_VECTOR_ELT(ans, i, tmp);
}
UNPROTECT(N + 1);
return ans;
}
I'm hoping the answer is the first method but would appreciate clarification.
I believe method_one is fine.
To do the analysis, you need to know every point in your code that does allocations, because an allocation might trigger garbage collection, and that will release any unprotected object.
So stepping through method_one:
SEXP method_one() {
// setup for rep example
int N = 3;
int *graph[N];
int tmp1[3] = {1, 2, 3};
int tmp2[4] = {1, 2, 3, 4};
int tmp3[2] = {3, 4};
graph[0] = tmp1;
graph[1] = tmp2;
graph[2] = tmp3;
int neighbours[3] = {3, 4, 2};
None of the code above uses R's allocator; those allocations are all on the C stack, so they are safe.
// method
SEXP ans = allocVector(VECSXP, N);
PROTECT(ans);
This does an R allocation, and then immediately protects it. A more common way to write this is
SEXP ans;
PROTECT(ans = allocVector(VECSXP, N));
which makes it harder to mess things up by inserting a statement in between the allocation and protection.
for (int i = 0; i < N; i++){
SET_VECTOR_ELT(ans, i, copy_int_vec(graph[i], neighbours[i]));
}
The copy_int_vec does allocations, so garbage collection could occur in any step of this loop. However, the allocated object is immediately assigned into ans, so each one is protected and safe.
UNPROTECT(1);
Nothing is protected now; remember not to insert any code before the return.
return ans;
}
I am trying to develop a choco solver to the probelm of the Planning of telephone support center. in 12 hours from 8:00 o clock to 20:00.
variables and constraint :
Number of employees = 9
Minimum ans Maximum buisiness hours for every employee (h and H)
buisiness hours foe all employees : 42 hours <= total hours <= 42+C (C in my case equals 2)
Table of numbers of employee who work in every hour ( size of table =12 )
Contrainst who i cant'make :
I got to know the number of nuisiness hours for each employee but I can not put them in tracking hours :/
the result will be :
Final Result
but until now i got my result untill now
I think it's sort problem... please if you can just save my life and tell me what is the missing constraint in my code.
My code
package projetppc;
import java.util.Arrays;
import javax.swing.SortingFocusTraversalPolicy;
import org.chocosolver.solver.Model;
import org.chocosolver.solver.Solution;
import org.chocosolver.solver.variables.IntVar;
public class ProjetPPC {
public void modelAndSolve() {
int k = 9;
int htpj = 12;
int h = 4;
int H = 6;
int C = 2;
int HT = 42;
Model model = new Model(k + "- CAT");
int[] numOfemp = {1, 2, 4, 5, 5, 4, 5, 5, 3, 4, 2, 2};
IntVar[][] matrix = new IntVar[k][htpj];
for (int i = 0; i < k; i++) {
for (int j = 0; j < htpj; j++) {
matrix[i][j] = model.intVar("(" + i + "," + j + ")", 0, 1);
}
}
model.arithm(matrix[0][0], "=", 1).post();
int[] coeffs1 = new int[htpj];
Arrays.fill(coeffs1, 1);
// constraint 1 et 2
for (int i = 0; i < k; i++) {
model.scalar(matrix[i], coeffs1, "<=", H).post();
model.scalar(matrix[i], coeffs1, ">=", h).post();
}
int[] coeffs2 = new int[k];
Arrays.fill(coeffs2, 1);
IntVar[][] inversematrix = new IntVar[htpj][k];
for (int i = 0; i < k; i++) {
for (int j = 0; j < htpj; j++) {
inversematrix[j][i] = matrix[i][j];
}
}
// constraint
for (int i = 0; i < htpj; i++) {
model.scalar(inversematrix[i], coeffs2, "=", numOfemp[i]).post();
}
// constraint
IntVar[] alltable = new IntVar[k * htpj];
for (int i = 0; i < k; i++) {
for (int j = 0; j < htpj; j++) {
alltable[(htpj * i) + j] = matrix[i][j];
}
}
int[] coeffs3 = new int[k * htpj];
Arrays.fill(coeffs3, 1);
model.scalar(alltable, coeffs3, ">=", HT).post();
model.scalar(alltable, coeffs3, "<=", HT + C).post();
// solution
Solution solution = model.getSolver().findSolution();
if (solution != null) {
for (int i = 0; i < k; i++) {
System.out.println("employé " + i + " " + Arrays.toString(matrix[i]));
}
} else {
System.out.println("Pas de solution.");
}
}
public static void main(String[] args) {
new ProjetPPC().modelAndSolve();
}
}
I'm currently working on a small Arduino project, and I'm kinda stuck. Here's my code so far:
#include "_init.h"
void setup() {
ds_init();
Serial.begin(9600);
randomSeed(analogRead(LIGHT_SENSOR_PIN));
int rol1[] = {1, 2, 3, 4, 5};
int rol2[] = {3, 5, 1, 2, 4};
int rol3[] = {5, 1, 4, 3, 2};
int rol1Mid = random(0, 5);
int rol1Bov = rol1Mid + 1;
int rol1Ond = rol1Mid - 1;
if (rol1Bov == 5){
rol1Bov = 0;
}
if (rol1Ond == -1){
rol1Ond = 4;
}
int rol2Mid = random(0, 5);
int rol2Bov = rol2Mid + 1;
int rol2Ond = rol2Mid - 1;
if (rol2Bov == 5){
rol2Bov = 0;
}
if (rol2Ond == -1){
rol2Ond = 4;
}
int rol3Mid = random(0, 5);
int rol3Bov = rol3Mid + 1;
int rol3Ond = rol3Mid - 1;
if (rol3Bov == 5){
rol3Bov = 0;
}
if (rol3Ond == -1){
rol3Ond = 4;
}
Serial.println(rol1[rol1Bov]);
Serial.println(rol1[rol1Mid]);
Serial.println(rol1[rol1Ond]);
Serial.println("----");
Serial.println(rol2[rol2Bov]);
Serial.println(rol2[rol2Mid]);
Serial.println(rol2[rol2Ond]);
Serial.println("----");
Serial.println(rol3[rol3Bov]);
Serial.println(rol3[rol3Mid]);
Serial.println(rol3[rol3Ond]);
if(rol1[rol1Mid] && rol2[rol2Mid] == rol3[rol3Mid]){
Serial.println("Yaay!");
} else {
Serial.println("Jammer, probeer het nogmaals.");
}
/*
if(rol1[positieBov] && rol2[positieBov] == rol3[positieBov]){
Serial.println("Yaay!");
} else {
Serial.println("Jammer, probeer het nogmaals.");
}
if(rol1[positieOnd] && rol2[positieOnd] == rol3[positieOnd]){
Serial.println("Yaay!");
} else {
Serial.println("Jammer, probeer het nogmaals.");
}
*/
}
void loop() {
// put your main code here, to run repeatedly:
}
Basically, I'm trying to create a slot machine. There's probably tons of things wrong with my code, but for the time being, I'm stuck on the if statement that checks if the user won or not.
I know I shouldnt be coding in the setup() part of Arduino, but as soon as this all works, I'm going to put it in a function in the loop(), where I will use my dangershield's buttons to operate the three roll's separately.
Okay, managed to fix it... I feel silly now
if(rol1[rol1Mid] == rol2[rol2Mid] && rol2[rol2Mid] == rol3[rol3Mid])
How do you convert a decimal number to mixed radix notation?
I guess that given an input of an array of each of the bases, and the decimal number, it should output an array of the values of each column.
Pseudocode:
bases = [24, 60, 60]
input = 86462 #One day, 1 minute, 2 seconds
output = []
for base in reverse(bases)
output.prepend(input mod base)
input = input div base #div is integer division (round down)
Number -> set:
factors = [52,7,24,60,60,1000]
value = 662321
for i in n-1..0
res[i] = value mod factors[i]
value = value div factors[i]
And the reverse:
If you have the number like 32(52), 5(7), 7(24), 45(60), 15(60), 500(1000) and you want this converted to decimal:
Take number n, multiply it with the factor of n-1, continue for n-1..n=0
values = [32,5,7,45,15,500]
factors = [52,7,24,60,60,1000]
res = 0;
for i in 0..n-1
res = res * factors[i] + values[i]
And you have the number.
In Java you could do
public static int[] Number2MixedRadix(int[] base, int number) throws Exception {
//NB if the max number you want # a position is say 3 then the base# tha position
//in your base array should be 4 not 3
int[] RadixFigures = new int[base.length];
int[] PositionPowers = new int[base.length];
PositionPowers[base.length-1] = 1;
for (int k = base.length-2,pow = 1; k >-1; k--){
pow*=base[k+1];
PositionPowers[k]=pow;
}for (int k = 0; k<base.length; k++){
RadixFigures[k]=number/PositionPowers[k];
if(RadixFigures[k]>base[k])throw new Exception("RadixFigure#["+k+"] => ("+RadixFigures[k]+") is > base#["+k+"] => ("+base[k]+") | ( number is Illegal )");
number=number%PositionPowers[k];
}return RadixFigures;
}
Example
//e.g. mixed-radix base for 1day
int[] base = new int[]{1, 24, 60, 60};//max-day,max-hours,max-minutes,max-seconds
int[] MixedRadix = Number2MixedRadix(base, 19263);//19263 seconds
//this would give [0,5,21,3] => as per 0days 5hrs 21mins 3secs
Reversal
public static int MixedRadix2Number(int[] RadixFigures,int[] base) throws Exception {
if(RadixFigures.length!=base.length)throw new Exception("RadixFigures.length must be = base.length");
int number=0;
int[] PositionPowers = new int[base.length];
PositionPowers[base.length-1] = 1;
for (int k = base.length-2,pow = 1; k >-1; k--){
pow*=base[k+1];
PositionPowers[k]=pow;
}for (int k = 0; k<base.length; k++){
number+=(RadixFigures[k]*PositionPowers[k]);
if(RadixFigures[k]>base[k])throw new Exception("RadixFigure#["+k+"] => ("+RadixFigures[k]+") is > base#["+k+"] => ("+base[k]+") | ( number is Illegal )");
}return number;
}
I came up with a slightly different, and probably not as good method as the other ones here, but I thought I'd share anyway:
var theNumber = 313732097;
// ms s m h d
var bases = [1000, 60, 60, 24, 365];
var placeValues = []; // initialise an array
var currPlaceValue = 1;
for (var i = 0, l = bases.length; i < l; ++i) {
placeValues.push(currPlaceValue);
currPlaceValue *= bases[i];
}
console.log(placeValues);
// this isn't relevant for this specific problem, but might
// be useful in related problems.
var maxNumber = currPlaceValue - 1;
var output = new Array(placeValues.length);
for (var v = placeValues.length - 1; v >= 0; --v) {
output[v] = Math.floor(theNumber / placeValues[v]);
theNumber %= placeValues[v];
}
console.log(output);
// [97, 52, 8, 15, 3] --> 3 days, 15 hours, 8 minutes, 52 seconds, 97 milliseconds
I tried a few of the examples before and found an edge case they didn't cover, if you max out your scale you need to prepend the result from the last step
def intToMix(number,radix=[10]):
mixNum=[]
radix.reverse()
for i in range(0,len(radix)):
mixNum.append(number%radix[i])
number//=radix[i]
mixNum.append(number)
mixNum.reverse()
radix.reverse()
return mixNum
num=60*60*24*7
radix=[7,24,60,60]
tmp1=intToMix(num,radix)