I'm trying to implement memoized version of recursive rod cutting algorithm. Here is my code (I implemented it from Cormen's pseudo code)
public class simpleMemoized {
//finds maximum of two given integers
public static int max(int a, int b) {
return (a > b) ? a : b;
}
public static int MemoizedCutRod(int price, int lenght) {
int[] r = new int[lenght + 1];
for (int i = 1; i <= lenght; i++) {
r[i] = 0;
}
return MemoizedCutRodAux(price, lenght, r);
}
public static int MemoizedCutRodAux(int price, int lenght, int[] r) {
int[] priceTable = new int[11];
priceTable[1] = 1;
priceTable[2] = 5;
priceTable[3] = 8;
priceTable[4] = 9;
priceTable[5] = 10;
priceTable[6] = 17;
priceTable[7] = 17;
priceTable[8] = 20;
priceTable[9] = 24;
priceTable[10] = 30;
if (r[lenght] >= 0) {
return r[lenght];
}
if (lenght == 0) {
return 0;
}
int q = 0;
for (int i = 1; i <= lenght; i++) {
q = max(q, priceTable[i] + MemoizedCutRodAux(price, lenght, r));
r[lenght] = q;
}
return q;
}
All outputs of this code are 0. But non memorized version of this code is working. What is the problem with it? Here is the working code:
public class Simple {
//finds maximum of two given integers
public static int max(int a, int b) {
return (a > b) ? a : b;
}
public static int cormenCutRod(int price, int lenght) {
int[] priceTable = new int[11];
priceTable[1] = 1;
priceTable[2] = 5;
priceTable[3] = 8;
priceTable[4] = 9;
priceTable[5] = 10;
priceTable[6] = 17;
priceTable[7] = 17;
priceTable[8] = 20;
priceTable[9] = 24;
priceTable[10] = 30;
if (lenght == 0) {
return 0;
}
int q = 0;
for (int i = 1; i <= lenght; i++) {
q = max(q, priceTable[i] + cormenCutRod(price, lenght - i));
}
return q;
}
This should work.
static int cutRodM(int lenght)
{
int[] priceTable = new int[11];
priceTable[1] = 1;
priceTable[2] = 5;
priceTable[3] = 8;
priceTable[4] = 9;
priceTable[5] = 10;
priceTable[6] = 17;
priceTable[7] = 17;
priceTable[8] = 20;
priceTable[9] = 24;
priceTable[10] = 30;
int[] mem= new int[lenght+1];
mem[0] = 0;
int i, j;
//filling the table bottom up
for (i = 1; i<=lenght; i++)
{
int q = 0;
for (j = 1; j <= i; j++)
q = max(q, priceTable[j] + mem[i-j]);
mem[i] = q;
}
return mem[lenght];
}
Ideone link: http://ideone.com/OWgrAZ
Related
Below is my matrix code, I want to fill the gaps with unique numbers. But I can't figure out why it doesn't work. I tried going step by step in it but I can't seem to figure where I have made a mistake. So, the thing is, I have a given 9 x 9 matrix with some numbers in it, and I want to complete the rest of it with unique numbers so that every line and column there is all numbers from 1 to 9 but different on each column / row.
Please help me, thank you!
package com.javagement;
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[][] matriceBuni = new int[9][9];
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
matriceBuni[i][j] = 0;
}
}
matriceBuni[0][0] = 8;
matriceBuni[0][4] = 6;
matriceBuni[0][8] = 4;
matriceBuni[1][2] = 7;
matriceBuni[1][4] = 3;
matriceBuni[1][8] = 5;
matriceBuni[2][0] = 3;
matriceBuni[2][1] = 9;
matriceBuni[2][5] = 5;
matriceBuni[2][7] = 8;
matriceBuni[3][2] = 8;
matriceBuni[3][3] = 6;
matriceBuni[3][6] = 7;
matriceBuni[3][7] = 5;
matriceBuni[4][2] = 5;
matriceBuni[4][3] = 8;
matriceBuni[4][7] = 9;
matriceBuni[5][1] = 6;
matriceBuni[5][2] = 3;
matriceBuni[5][5] = 7;
matriceBuni[5][6] = 4;
matriceBuni[6][0] = 7;
matriceBuni[6][1] = 3;
matriceBuni[6][3] = 2;
matriceBuni[6][5] = 9;
matriceBuni[7][0] = 1;
matriceBuni[7][1] = 8;
matriceBuni[7][7] = 5;
matriceBuni[7][8] = 9;
matriceBuni[8][4] = 8;
matriceBuni[8][5] = 1;
matriceBuni[8][6] = 2;
for(int m = 0; m < 9; m++) {
for(int n = 0; n < 9; n++) {
System.out.print(matriceBuni[m][n] + " ");
}
System.out.println();
}
System.out.println("*****************************************");
for(int r = 0; r < 9; r++) {
for(int c = 0; c < 9; c++) {
if(matriceBuni[r][c] == 0) {
boolean isUnique = false;
while(!isUnique) {
int uniqueNumber = getRandomNumberInRange(1,9);
int countUnique = 0;
for(int a = 0; a < 9; a++) {
if (matriceBuni[r][a] == uniqueNumber) {
countUnique++;
}
}
for(int b = 0; b < 9; b++) {
if (matriceBuni[b][c] == uniqueNumber) {
countUnique++;
}
}
if (countUnique == 0) {
isUnique = true;
matriceBuni[r][c] = uniqueNumber;
}
}
}
}
}
for(int m = 0; m < 9; m++) {
for (int n = 0; n < 9; n++) {
System.out.print(matriceBuni[m][n] + " ");
}
System.out.println();
}
}
private static int getRandomNumberInRange(int min, int max) {
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
}
I have to build Simplex Algorithm and its working but I want to allow user to input data, in method main I made few "for" loops where I put date into arrays, but that I put the same data in another arrays, (they have exactly the same data) I have no idea how to fix it.
When I try to make just one arrays for one type of date, it's crash.
[edit]
Yep, I update those Scanners (thanks guys)
And right now I have this error:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at simplex.Simplex$Modeler.(Simplex.java:224)
at simplex.Simplex.main(Simplex.java:196)"
package simplex;
import java.awt.List;
import java.util.ArrayList;
import java.util.Scanner;
public class Simplex {
private double[][] macierz; // macierz
private int LiczbaOgraniczen; // liczba ograniczen
private int LiczbaX; // liczba zmiennych "orginalnych"
private boolean MaxCzyMin;
private static final boolean MAX = true;
private static final boolean MIN = false;
private int[] baza; // baza[i] = basic variable corresponding to row i
public Simplex(double[][] macierz, int LiczbaOgraniczen, int numberOfOriginalVariable, boolean MaxCzyMin) {
this.MaxCzyMin = MaxCzyMin;
this.LiczbaOgraniczen = LiczbaOgraniczen;
this.LiczbaX = numberOfOriginalVariable;
this.macierz = macierz;
baza = new int[LiczbaOgraniczen];
for (int i = 0; i < LiczbaOgraniczen; i++)
baza[i] = LiczbaX + i;
Licz();
}
// Licz algorytm simples od startowych BFS
private void Licz() {
while (true) {
DrukujInteracje();
int q = 0;
// znajdz kolumne q wchodzącą do bazy
if (MaxCzyMin) {
q = ZnajdzIndexPoz(); //jesli szukamy max
} else {
q = ZnajdzIndexNeg(); //jesli szukamy min
}
if (q == -1){
break; // optimum
}
// znajdz rzad p wychodzący z bazy
int p = minRatioRule(q);
if (p == -1){
throw new ArithmeticException("BLAD");
}
//wiersz - kolumna
piwot(p, q);
// zaktualizuj baze
baza[p] = q;
}
}
// znajdowanie indexu niebazowej kolumny z najbardzoje pozytywnym kosztem
private int ZnajdzIndexPoz() {
int q = 0;
for (int j = 1; j < LiczbaOgraniczen + LiczbaX; j++)
if (macierz[LiczbaOgraniczen][j] > macierz[LiczbaOgraniczen][q])
q = j;
if (macierz[LiczbaOgraniczen][q] <= 0){
return -1; // optimum
} else {
return q;
}
}
// znajdowanie indexu niebazowej kolumny z najbardziej negatywnym kosztem
private int ZnajdzIndexNeg() {
int q = 0;
for (int j = 1; j < LiczbaOgraniczen + LiczbaX; j++)
if (macierz[LiczbaOgraniczen][j] < macierz[LiczbaOgraniczen][q])
q = j;
if (macierz[LiczbaOgraniczen][q] >= 0){
return -1; // optimum
} else {
return q;
}
}
// find row p using min ratio rule (-1 if no such row)
private int minRatioRule(int q) {
int p = -1;
for (int i = 0; i < LiczbaOgraniczen; i++) {
if (macierz[i][q] <= 0)
continue;
else if (p == -1)
p = i;
else if ((macierz[i][LiczbaOgraniczen
+ LiczbaX] / macierz[i][q]) < (macierz[p][LiczbaOgraniczen
+ LiczbaX] / macierz[p][q]))
p = i;
}
return p;
}
//zastosowanie metody Gauss-Jordan, aby doprowadzic macierz do postaci bazowej
private void piwot(int p, int q) {
for (int i = 0; i <= LiczbaOgraniczen; i++)
for (int j = 0; j <= LiczbaOgraniczen + LiczbaX; j++)
if (i != p && j != q)
macierz[i][j] -= macierz[p][j] * macierz[i][q] / macierz[p][q];
for (int i = 0; i <= LiczbaOgraniczen; i++)
if (i != p)
macierz[i][q] = 0.0;
for (int j = 0; j <= LiczbaOgraniczen + LiczbaX; j++)
if (j != q)
macierz[p][j] /= macierz[p][q];
macierz[p][q] = 1.0;
}
// Metoda zwraca wartosc funkcji celu
public double WartoscFunkcjiCelu() {
return -macierz[LiczbaOgraniczen][LiczbaOgraniczen + LiczbaX];
}
// metoda zwaraca wartosc x-ow
public double[] WyliczX() {
double[] x = new double[LiczbaX];
for (int i = 0; i < LiczbaOgraniczen; i++)
if (baza[i] < LiczbaX)
x[baza[i]] = macierz[i][LiczbaOgraniczen + LiczbaX];
return x;
}
// drukuj macierz => drukuj tabele
public void DrukujInteracje() {
System.out.println("Liczba Ograniczen = " + LiczbaOgraniczen);
System.out.println("Liczba zmiennych 'orginalnych' = " + LiczbaX);
for (int i = 0; i <= LiczbaOgraniczen; i++) {
for (int j = 0; j <= LiczbaOgraniczen
+ LiczbaX; j++) {
System.out.printf("%7.2f ", macierz[i][j]);
}
System.out.println();
}
System.out.println("Funkcja celu = " + WartoscFunkcjiCelu());
for (int i = 0; i < LiczbaOgraniczen; i++)
if (baza[i] < LiczbaX)
System.out.println("x_"
+ baza[i]
+ " = "
+ macierz[i][LiczbaOgraniczen + LiczbaX]);
System.out.println();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Podaj ilosc x");
int iloscX = scan.nextInt();
double[] WspolczynnikiFunkcjiCelu = new double[iloscX + 1];
for(int ggg = 0; ggg < iloscX; ggg++){
System.out.println("Podaj x" + ggg);
WspolczynnikiFunkcjiCelu[ggg] =scan.nextDouble();
}
System.out.println("Podaj ilosc ograniczen");
int iloscOgraniczen = scan.nextInt();
double[][] LewaStronaOgraniczen = new double[iloscOgraniczen][iloscX];
double[] PrawaStronaOgraniczen = new double[iloscOgraniczen + 1];
Znaki[] OperatorOgraniczen = new Znaki [iloscOgraniczen + 1];
for(int ggh = 0;ggh <iloscOgraniczen; ggh++){
System.out.println("Podaj znak ograniczenia (lessThan - equal - greatherThan ");
OperatorOgraniczen[ggh] = Znaki.valueOf(scan.next());
System.out.println("Podaj prawa strone ograniczenia");
PrawaStronaOgraniczen[ggh] = scan.nextDouble();
for(int haha = 0; haha < iloscX; haha++){
System.out.println("Lewa strona: Podaj wspolczynnik przy x" + haha);
LewaStronaOgraniczen[ggh][haha] =scan.nextDouble();
}
}
//double[] WspolczynnikiFunkcjiCelu = {Xsy[0], Xsy[1]};
// double[][] LewaStronaOgraniczen = {
// { TablicaTablic[0][0], TablicaTablic[0][1] }, { TablicaTablic[1][0], TablicaTablic[1][1] }, { TablicaTablic[2][0], TablicaTablic[2][1] }, { TablicaTablic[3][0], TablicaTablic[3][1] } };
//Znaki[] OperatorOgraniczen = { TablicaOgraniczen[0], TablicaOgraniczen[1], TablicaOgraniczen[2], TablicaOgraniczen[3] };
//double[] PrawaStronaOgraniczen = {TablicaPrawejStrony[0],TablicaPrawejStrony[1],TablicaPrawejStrony[2],TablicaPrawejStrony[3]};
Modeler model = new Modeler(LewaStronaOgraniczen, PrawaStronaOgraniczen, OperatorOgraniczen, WspolczynnikiFunkcjiCelu);
Simplex simplex = new Simplex(model.getmacierz(),
model.getLiczbaOgraniczen(),
model.getLiczbaX(), MAX);
double[] x = simplex.WyliczX();
for (int i = 0; i < x.length; i++)
System.out.println("x[" + i + "] = " + x[i]);
System.out.println("Rozwiazanie optymalne: " + simplex.WartoscFunkcjiCelu());
}
//zbior mozliwych znakow ograniczajacych
private enum Znaki {
lessThan, equal, greatherThan
}
public static class Modeler {
private double[][] a; // macierz
private int LiczbaOgraniczen; // Liczba Ograniczen
private int LiczbaX; // Liczba x w funkcji celu
public Modeler(double[][] LewaStronaOgraniczen,double[] PrawaStronaOgraniczen, Znaki[] OperatorOgraniczen, double[] WspolczynnikiFunkcjiCelu) {
LiczbaOgraniczen = PrawaStronaOgraniczen.length;
LiczbaX = WspolczynnikiFunkcjiCelu.length;
a = new double[LiczbaOgraniczen + 1][LiczbaX + LiczbaOgraniczen + 1];
for (int i = 0; i < LiczbaOgraniczen; i++) {
for (int j = 0; j < LiczbaX; j++) {
a[i][j] = LewaStronaOgraniczen[i][j];
}
}
for (int i = 0; i < LiczbaOgraniczen; i++)
a[i][LiczbaOgraniczen + LiczbaX] = PrawaStronaOgraniczen[i];
for (int i = 0; i < LiczbaOgraniczen; i++) {
int slack = 0;
switch (OperatorOgraniczen[i]) {
case greatherThan:
slack = -1;
break;
case lessThan:
slack = 1;
break;
default:
}
a[i][LiczbaX + i] = slack;
}
for (int j = 0; j < LiczbaX; j++)
a[LiczbaOgraniczen][j] = WspolczynnikiFunkcjiCelu[j];
}
public double[][] getmacierz() {
return a;
}
public int getLiczbaOgraniczen() {
return LiczbaOgraniczen;
}
public int getLiczbaX() {
return LiczbaX;
}
}
}
why have you so many scanners? Try use only one. Declare and initialize it at the beginning main method.
I have the following error in compiler
return ans;
^
required: byte[]
found: int[]
I have this method in which i want to return a type of byte . Can anyone tell me how can i cast ans to make it compatible with me method type
public byte[] element(int m) {
//if (q!= a.length)
// throw new Exception("Array length does not equal k");
int f;
int q;
int[] t;
this.first = f;
this.second = q;
this.data = new int[q];
for (int i = 0; i < t.length; ++i) {
this.data[i] = t[i];
}
// if (!this.IsValid())
// throw new Exception("Bad value from array");
int ans[] = new int[this.second];
int a = this.first;
int b = this.second;
int x = (choose(this.first,this.second) - 1) - m; // x is the "dual" of m
for (int i = 0; i < this.second; ++i) {
ans[i] = largestV(a, b, x); // largest value v, where v < a and vCb < x
x = x - choose(ans[i], b);
a = ans[i];
b = b - 1;
}
for (int i = 0; i < this.second; ++i) {
ans[i] = (first-1) - ans[i];
return ans;
}
}
Note: i want it to return type of byte not int but i am trying to cast ans but without success .
You have to change int[] ans to Byte[] ans, you are trying to return an int array, but you have to return your byte array
int f;
int q;
int [] t;
this.first = f;
this.second = q;
this.data = new int[q];
for (int i = 0; i < t.length; ++i)
this.data[i] = t[i];
// if (!this.IsValid())
// throw new Exception("Bad value from array");
byte ans []= new byte[this.second];
int a = this.first;
int b = this.second;
int x = (choose(this.first,this.second) - 1) - m; // x is the "dual" of m
for (int i = 0; i < this.second; ++i) {
ans[i]= largestV(a, b, x); // largest value v, where v < a and vCb < x
x = x - choose(ans[i], b);
a = ans[i];
b = b - 1;
}
for (int i = 0; i < this.second; ++i)
ans[i] = (first-1) - ans[i];
return ans;
}
Dunno why you would wanna to work on int and return a byte. Dat aside, You can create a new byte array of the same size as ans and do this in the last loop
for (int i = 0; i < this.second; ++i)
{
ans[i] = (first-1) - ans[i]);
ans_byte_version[i] = (byte) ((first-1) - ans[i]);
}
return ans_byte_version;
However it'd be better if you tell us what are you trying to do. Why have you declared int when you want byte in the first place.
I'm implementing the Fiege Fiat Shamir Identification Scheme in Java, and I'm pretty sure that it's fine math-wise. (I've checked many many times) But it never works (when check is called, it is almost always false, even when called with numbers that should work). I've gotten it to work before without sequences, (k value of 1), but now it doesn't work. Help!
public class ZKPTimeTrials {
public static int gcd(int p, int q) {
if (q == 0) return p;
else return gcd(q, p % q);
}
public static int randomR(int min, int max) {
Random randgen = new Random();
return randgen.nextInt((max - min) + 1) + min;
}
public static int getRandomCoprime(int n) {
int result = n;
while (gcd(n, result) != 1) {
result = randomR(2, n-1);
}
return result;
}
public static int[] makeSi(int k, int n) {
int[] result = new int[k];
for(int i = 0; i < result.length; i++) {
result[i] = getRandomCoprime(n);
}
return result;
}
public static int[] makeVi(int[] si, int n) {
int[] result = new int[si.length];
for(int i = 0; i < result.length; i++) {
result[i] = (si[i] * si[i]) % n;
}
return result;
}
public static int[] makeEi(int k) {
int[] result = new int[k];
for(int i = 0; i < k; i++) {
result[i] = randomR(0, 1);
}
return result;
}
public static int makeY(int r, int[] ei, int[] si, int n) {
int result = r;
for(int i = 0; i < si.length; i++) {
result *= (int) Math.pow(si[i], ei[i]);
}
return result % n;
}
public static boolean check(int n, int x, int y, int[] ei, int[] vi) {
int signBit = ZKPTimeTrials.randomR(0, 1);
if(signBit == 0) {
signBit = -1;
}
int shouldY = x * signBit;
for(int i = 0; i < vi.length; i++) {
shouldY *= (int) Math.pow(vi[i], ei[i]);
}
return ((y * y) % n) == shouldY % n;
}
public static void main(String args[]) {
int n = 71 * 7;
int t = 50;
int k = 10;
int[] si = makeSi(k, n);
int[] vi = makeVi(si, n);
int r = randomR(2, n-1);
int ei[] = makeEi(k);
int s = randomR(0, 1);
if(s == 0) {
s = -1;
}
int x = (s * r * r) % n;
int y = makeY(r, ei, si, n);
for(int i = 0; i < si.length; i++) System.out.print(ei[i] + " ");
System.out.println();
for(int i = 0; i < si.length; i++) System.out.print(si[i] + " ");
System.out.println(check(n, x, y, ei, vi));
}
}
The first problem is an integer overflow in makeY and check: In both functions 'result' is very likely to overflow, because you build the product first and reduce modulo n afterwards. Try to reduce mod n after every multiplication to keep 'result' small.
For example in makeY, write:
int result = r % n;
for (int i = 0; i < si.length; i++) {
if (ei[i] == 1)
result = (result * si[i]) % n;
}
return result;
(I also removed Math.pow() to make it more readable and efficient, but this was not an error.)
The second problem is the logic of your check function: The signBit variable is not needed, but instead you should check if y*y is equal to shouldY or -shouldY.
public static boolean check(int n, int x, int y, int[] ei, int[] vi) {
int shouldY = x % n;
for (int i = 0; i < vi.length; i++) {
if (ei[i] == 1)
shouldY = (shouldY * vi[i]) % n;
}
return (y*y - shouldY) % n == 0 || (y*y + shouldY) % n == 0;
}
With these small corrections i managed to get your code running. Hope it helps...
I'm new to java and I have a weighted union find algorithm. When I run this code in eclipse on a scrapbook page, it keeps evaluating forever.
java code
public class weightedUF {
private int[] id;
private int[] sz;
public weightedUF(int N) {
id = new int[N];
sz = new int[N];
for (int i = 0; i < N; i++) {
id[i] = i;
}
for (int i = 0; i < N; i++) {
sz[i] = 1;
}
}
private int root(int i) {
while (i != id[i]) {
i = id[i];
}
return i;
}
public boolean connected(int p, int q) {
return root(p) == root(q);
}
public void union(int p, int q) {
int i = root(p);
int j = root(q);
if (sz[i] < sz[j]) {
id[i] = j;
sz[j] += sz[i];
}
else {
id[j] = i;
sz[i] += sz[j];
}
id[i] = j;
}
}
scrapbook test code
weightedUF union = new weightedUF(10);
union.union(9, 2);
union.union(5, 2);
union.union(1, 8);
union.union(5, 7);
union.union(4, 3);
union.union(0, 7);
union.union(1, 3);
union.union(2, 4);
union.union(8, 6);
union
I think you should remove your last line :
id[i] = j;
it's corrupting your id array.