Memory Function Knapsack - java

Ok, I am having a problem with the Memory Function implementation of the Knapsack problem. My implementation if giving me the incorrect answer in Java but in C++ the same implementation is giving me the correct answer.
import java.io.*;
import java.util.*;
public class KnapsackMF {
public static void main(String args[]){
int wt;
int vl;
long start, end, runTime;
Scanner input = new Scanner(System.in);
int n, W;
System.out.println("Please enter the number of items: ");
n = input.nextInt();
System.out.println("Please enter the capacity of the knapsack: ");
W = input.nextInt();
int[][] V = new int[n+1][W+1];
int[] Wt = new int[n];
int[] Vl = new int[n];
for(int i = 0; i < n; i++){
System.out.println("Enter the weight and the value of item " + i + ": ");
wt = input.nextInt();
vl = input.nextInt();
Wt[i] = wt;
Vl[i] = vl;
}
for(int i = 0; i <= n; i++ ){
for(int j = 0; j <= W; j++){
if(j == 0 || i == 0){
V[i][j] = 0;
}
else{
V[i][j] = -1;
}
}
}
/*
for(int i= 0; i <= n; i++){
for(int j = 0; j <= W; j++){
System.out.print(V[i][j] + " ");
}
System.out.println();
}
*/
start = System.nanoTime();
System.out.println("The highest value is: " + MFKnapsack(n, W, V, Vl, Wt));
end = System.nanoTime();
runTime = (end - start);
System.out.println("Nanoseconds: " + runTime);
for(int i= 0; i <= n; i++){
for(int j = 0; j <= W; j++){
System.out.print(V[i][j] + " ");
}
System.out.println();
}
//system("PAUSE");
}
public static int MFKnapsack(int i, int j, int[][] V, int[] Vl, int[] Wt){
int value = 0;
if(V[i][j] < 0){
if(j < Wt[i-1]){
value = MFKnapsack(i-1, j, V, Vl, Wt);
}
else{
value = Math.max(MFKnapsack(i-1, j, V, Vl, Wt), Vl[i-1] + MFKnapsack(i-1, j-Wt[i-1], V, Vl, Wt));
}
}
V[i][j] = value;
return V[i][j];
}
}
The example I used is out of my book, the inputs should be:
4
5
2 12
1 10
3 20
2 15
The answer to this should be 37 but something is going on that I am not seeing and it is giving me 35.

Related

How to create a method in java which prints out the elements of a matrix in shown pattern?

The contents of the matrix starts from 1 to the product of rows and columns. The method "scan" should print out as per following:
If the row is entered 4 and column is entered 7, the contents of the matrix should look like the image provided here:
the correct matrix
So far I have tried absolutely noting because I just don't know how to make this possible. I can print in zigzag, spiral but I just have no idea about this one. Please have mercy on me and grant me an insight.
This code currently prints out in a spiral pattern.
How should I modify this "scan" method so it satisfies the aforementioned condition?
import java.util.Scanner;
import java.util.Random;
public class that {
public static void main(String[] args) {
int range;
range = 100;
Scanner scn = new Scanner(System.in);
while(true) {
int m, n;
System.out.println("Enter the number of row: ");
m = scn.nextInt();
System.out.println("Enter the number of column: ");
n = scn.nextInt();
if(m <= 0||n <= 0) break;
int[][] tab = new int[m][n];
generate(tab, range);
scan(tab);
}
scn.close();
}
static int len(int x) { return (""+x).length(); }
static void generate(int[][] tab, int range) {
// Random generation
Random rg = new Random();
for(int i=0; i<tab.length; ++i)
for(int j=0; j<tab[0].length; ++j)
tab[i][j] = rg.nextInt(2*range) - range;
}
static void scan(int[][] tab) {
int m = tab.length;
int n = tab[0].length;
int totalWidth = 0;
int num = 1;
int rowStart = m - 1, rowEnd = 0, colStart = 0, colEnd = n - 1;
// Compute column widths
int[] colw = new int[n];
for(int j=0; j<n; ++j) { // For every column look down
colw[j] = len(j); // (""+j).length();
for(int i=0; i<m; ++i) {
int w = len(tab[i][j]); //("" + tab[i][j]).length();
if(w > colw[j]) colw[j] = w;
}
totalWidth += colw[j];
}
// Printing
int ris = len(m-1); // row index size
System.out.printf("%"+ris+"s ", " ");
for(int j=0; j<n; ++j)
System.out.printf("%" + colw[j] +"d ", j);
System.out.println();
System.out.printf("%"+ris+"s+"," ");
for(int j=0; j<totalWidth+n-1; ++j)
System.out.printf("-");
System.out.println();
while (rowStart >= rowEnd && colStart <= colEnd) {
// Print leftmost column from bottom to top
if (colStart <= colEnd) {
for (int i = rowStart; i >= rowEnd; i--) {
tab[i][colStart] = num++;
}
colStart++;
}
// Print top row from right to left
if (rowStart >= rowEnd) {
for (int i = colStart; i <= colEnd; i++) {
tab[rowEnd][i] = num++;
}
rowEnd++;
}
// Print rightmost column from top to bottom
if (colStart <= colEnd) {
for (int i = rowEnd; i <= rowStart; i++) {
tab[i][colEnd] = num++;
}
colEnd--;
}
// Print bottom row from left to right
if (rowStart >= rowEnd) {
for (int i = colEnd; i >= colStart; i--) {
tab[rowStart][i] = num++;
}
rowStart--;
}
}
// Prints the matrix
for(int i=0; i<m; ++i) {
System.out.printf("%"+ris+"d|", i);
for(int j=0; j<n; ++j)
System.out.printf("%" + colw[j] +"d ", tab[i][j]);
System.out.println();
}
System.out.println();
}
}

Separating the 0s and Positive Numbers in two different arrays

This is the code I have written, My objective is to segregate the 0s and non 0s without changing the order of the non 0s
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int[] arx;
arx = new int[x];
int[] ary;
ary = new int[x];
for (int i = 0; i < x; i++) {
int q = sc.nextInt();
if (q != 0) {
arx[i] = q;
} else if (q == 0) {
ary[i] = q;
}
}
for (int j = 0; j < arx.length; j++) {
System.out.print(arx[j] + " ");
}
for (int j = 0; j < ary.length; j++) {
System.out.print(ary[j] + " ");
}
}
}
Sample i/p:
5
0 1 0 3 12
Sample o/p:
1 3 12 0 0
What I am getting:
o/p:
0 1 0 3 12 0 0 0 0 0
You should maintain separate index counters for the two arrays:
int x = sc.nextInt();
int ix = 0;
int iy = 0;
int[] arx;
arx = new int[x];
int[] ary;
ary = new int[x];
for (int i=0; i < x; i++) {
int q = sc.nextInt();
if (q != 0) {
arx[ix++] = q;
}
else if (q == 0) {
ary[iy++] = q;
}
}
for (int i=0; i < ix; i++) {
System.out.print(arx[i] + " ");
}
for (int i=0; i < iy; i++) {
System.out.print(ary[i] + " ");
}
For your inputs the above generated the following output:
1 3 12 0 0
Since array with arx is filled with zeroes , you can only use one array to add non zero values.
{
Scanner sc = new Scanner (System.in);
int x = sc.nextInt ();
int[] arx;
arx = new int[x];
int ind = 0;
for (int i = 0; i < x; i++) {
int q = sc.nextInt ();
if (q != 0){
arx[ind++] = q;
}
}
for (int j = 0; j < arx.length; j++){
System.out.print (arx[j] + " ");
}
}

Having trouble searching array

So I have everything working fine up until the point in which I need to search. I'm really new to this so my code is probably awful I'm sorry in advance. Anyway, its a user input array, and the user should be able to search for a number in an array. Im getting the error for a duplicate variable on line 50 (int i, get 1).
import java.util.Scanner;
class SearchingSorting {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("How many numbers would you like to input?");
int num = input.nextInt();
double[] array = new double[num];
for (int i = 0; i < num; i++) {
System.out.println ("Input number " + (1 + i) + ":");
array[i] = input.nextDouble();
}
for (double temp1 : array){
System.out.print (temp1 + "\t");
}
input.close();
int pass;
int i;
int hold;
for(pass = 1; pass < array.length; pass++)
{
for(i = 0; i < array.length - 1; i++)
{
if(array[i] > array[i+1])
{
hold = (int) array[i];
array[i] = array[i+1];
array[i+1] = hold;
}
}
System.out.println("\nSorted number is: ");
for(i = 0; i < array.length; i++)
System.out.print(" " + array[i]);
}
int i, get1;
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[10];
for(i = 0; i < numbers.length; i++)
{
numbers[i] = i * 10;
}
System.out.print("Enter search number: ");
get1 = keyboard.nextInt();
SearchMethod(numbers, get1);
}
public static void SearchMethod(int[] num, int get2)
{
int i ;
boolean j = false;
for(i = 0; i < num.length; i++)
{
if(num[i] == get2)
{
j = true;
break;
}
}
if(j == true)
System.out.println(get2 + " is found at num[" + i + "]");
else
System.out.println(get2 + " is not found in an array");
}
}
You are trying to declare a new variable with the same name ("i") in the same scope.
Rename your variable i on line 50.

Using for loop to find an element that appears multiple times in a random, unsorted array

My goal is to print out a user input value (and its corresponding index) if it appears 1 or more times in a random generated array of 50 integers. If I search the array for a value, and it happens to appear more than once, however, only one location of the element is printed, and then the if-else statement is executed. If I remove the break at the end of the third for loop, the whole thing falls apart. I've attached an image but here is the part of it that is giving me an issue. Apologies if the code is not clean, I'm very new.
public static void main(String[] args) {
System.out.println("IDS201 HW3:\n");
System.out.println("1. Generate 50 random integer unsorted list.\n");
Scanner stdin = new Scanner(System.in);
int[] randomNumbers = new int[50];
for(int index = 0; index < randomNumbers.length; index++) {
randomNumbers[index] = (int) (Math.random()*100);
}//end for
int count = 0;
for(int i = 0; i < randomNumbers.length; i++) {
System.out.print(randomNumbers[i] + ",");
count++;
if(count == 10) {
System.out.println();
count = 0;
}
}//end for
System.out.println("\nSearch value?");
int x = stdin.nextInt();
int i;
for(i = 0; i < randomNumbers.length; i++) {
if(randomNumbers[i] == x)
break;}
if (i != randomNumbers.length) {
System.out.println("\nFound " + x + " in array [" + i + "]");}
else {
System.out.println(x + " is not in the list");}
{int temp;
int size = randomNumbers.length;
for(i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(randomNumbers[i]>randomNumbers[j]){
temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
System.out.println("\nSmallest element of the array is: " + randomNumbers[0]);}
System.out.println("\n3. Sort the list:");
int size = randomNumbers.length;
for(i=0; i<size; i++)
{
for(int j=i+1; j<size; j++)
{
if(randomNumbers[i] > randomNumbers[j])
{
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
System.out.print("Now the Array after Sorting is :\n\n");
int count1 = 0;
for(i=0; i<size; i++)
{
System.out.print(randomNumbers[i]+ ",");
count++;
if(count == 10) {
System.out.println();
count = 0;
}
}
}
}
if statement in for loop
Implementing the comments to your question:
import java.util.Scanner;
public class NumCount {
private static final int RANDOM_NUMBER_COUNT = 50;
private static void display(int[] randomNumbers) {
int count = 0;
for (int i = 0; i < RANDOM_NUMBER_COUNT; i++) {
System.out.print(randomNumbers[i] + ",");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
}
private static int[] generateRandomNUmbers() {
int[] randomNumbers = new int[RANDOM_NUMBER_COUNT];
for (int index = 0; index < RANDOM_NUMBER_COUNT; index++) {
randomNumbers[index] = (int) (Math.random() * 100);
}
display(randomNumbers);
return randomNumbers;
}
private static int search(int[] randomNumbers, int x) {
int i;
int count = 0;
for (i = 0; i < randomNumbers.length; i++) {
if (randomNumbers[i] == x) {
System.out.println("\nFound " + x + " in array [" + i + "]");
count++;
}
}
return count;
}
private static int[] sort(int[] randomNumbers) {
int size = randomNumbers.length;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (randomNumbers[i] > randomNumbers[j]) {
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
return randomNumbers;
}
/**
* Start here.
*/
public static void main(String[] args) {
System.out.println("IDS201 HW3:\n");
System.out.println("1. Generate " + RANDOM_NUMBER_COUNT + " random integer unsorted list.\n");
int[] randomNumbers = generateRandomNUmbers();
System.out.print("\n2. Search value? ");
Scanner stdin = new Scanner(System.in);
int x = stdin.nextInt();
int count = search(randomNumbers, x);
if (count == 0) {
System.out.println(x + " is not in the list");
}
System.out.println("\n3. Sort the list:");
sort(randomNumbers);
System.out.print("Now the Array after Sorting is :\n\n");
display(randomNumbers);
}
}
Of-course there is no need to search for the smallest number because it will be the first element in the sorted array. Hence I removed that part of your code.

Convert two 1D arrays into single 2D array

I have 2 1d arrays and i am trying to populate them into a single 2d array in JAVA.
For instance:
a[] = {2,7}
b[] = {9,1}
The results should then be:
result[][] = {{2,9}, {7,1}}
This is my code
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Test Cases:\t");
int t = sc.nextInt();
int[] a;
int[] b;
int i, j, x;
for (int k = 0; k < t; k++) {
System.out.println("Enter 1st Array Limit:\t");
int len = sc.nextInt();
System.out.println("Enter 2nd Array Limit:\t");
int len1 = sc.nextInt();
a = new int[len];
b = new int[len1];
System.out.println("Enter Sum Value");
x = sc.nextInt();
System.out.println("Enter " + len + " elements:\t");
for (i = 0; i < len; i++) {
a[i] = sc.nextInt();
}
System.out.println("Enter " + len1 + " elements:\t");
for (j = 0; j < len1; j++) {
b[j] = sc.nextInt();
}
int [][] c = new int[len][2];
for (i = 0; i < len; i++) {
for (j = 0; j < len1; j++) {
if (a[i] + b[j] == x) {
for(int l = 0; i < a.length; i++){
c[l][0] = a[i];
c[l][1] = b[j];
}
}
}
}
System.out.println(Arrays.deepToString(c));
}
}
}
This still produces wrong output
i want to find Find all pairs with a given sum
int[] a = {2,7};
int[] b = {9,1};
int[][] c = new int[a.length][2];
for(int i = 0; i < a.length; i++){
c[i][0] = a[i];
c[i][1] = b[i];
}
should do the trick

Categories

Resources