Trouble outputting names in a backpack problem - java

I was trying to solve a problem based on value and weight. In the task i had to pick out the elements by their value and weight, and find the highest efficiency solution. I receive an answer, however i am having trouble outputting the elements that were used in order to get an answer.
I've tried creating a string in which i place the values, however it gives out an outofbounds error.
public static void main(String[] args) {
String z[] = new String[]{"a","b","c","d","e","f","g","h","l","m"};
int w[] = new int[]{10,2,4,6,8,1,7,11,4,5};
int c[] = new int[]{20,3,5,7,4,1,8,15,8,6};
int maxW = 50;
int n = c.length;
System.out.println("");
int a = Find(w,c,maxW,n,z);
System.out.println("max value is " + a);
}
static int max(int a, int b)
{
if(a>b)
{
return a;
}
return b;
}
public static int Find(int w[],int c[], int maxW,int n, String[]z)
{
int K[][] = new int[n + 1][maxW + 1];
String s = "";
// Build table K[][] in bottom up manner
for (int i = 0; i<= n; i++)
{
for(int j = 0; j<= maxW; j++)
{
if (i == 0 || j == 0)
{
K[i][j] = 0;
}
else if (w[i - 1]<= j)
{
K[i][j] = max(c[i - 1] + K[i - 1][j - w[i - 1]], K[i - 1][j]);
}
else
{
K[i][j] = K[i - 1][j];
}
}
}
return K[n][maxW];
}
}
i want to output the same index element in string z, as the index element that is used to find the efficiancy.
The ideal result would be something like this in a string:
a a a b c d e m
(Just an example)
Thank you in advance.

Related

randomized select not give steady solution

EDIT
try run in the main:
int[] arr = {646 ,94 ,366 ,754 ,948 ,678 ,121 ,320 ,528 ,36};
for(int i=0;i<10;i++){
System.out.println(randomizedSelect(arr,0,arr.length-1,5));
printArr(arr);
}
and see that i got diffrent outpot in each loop..
Got a little problem that I would like some help with, if anyone knows how.
I need to find the kth smallest value in an array by randomized partition.
I've got two problems:
I get array out of bounds with -1 and can't find a way to fix it.
Most of the time it works but sometimes it gives me wrong k place.
For example for array with length of 10, it tells me that 20 is in the 5th place but actually it should be in the 2nd place and it prints the array where not all the values on the left are smaller than 20 and not smaller than the 5th place.
Here is an example array:
{646 ,94 ,366 ,754 ,948 ,678 ,121 ,320 ,528 ,36}
The array input is done by a random number generator.
This is my code:
import java.util.Random;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
static Random rand = new Random();
public static void main(String[] args) {
int nSize = askSizeN();
int kSize = askSizeK(nSize);
int[] arr = new int[nSize];
chose(arr);
int[] arrCopy = new int[nSize];
for (int i = 0; i < arrCopy.length; i++) {
arrCopy[i] = arr[i];
}
printArr(arrCopy);
System.out.println(randomizedSelect(arrCopy, 0, arr.length - 1, kSize));
printArr(arrCopy);
}
private static int partition(int[] arr, int p, int r) {
int x = arr[r];
int i = p - 1;
for (int j = p; j < r; j++) {
if (arr[j] <= x) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[r];
arr[r] = temp;
return i + 1;
}
private static int randomizedPartition(int[] arr, int p, int r) {
int i = rand.nextInt(r - p);
int temp = arr[r];
arr[r] = arr[i];
arr[i] = temp;
return partition(arr, p, r);
}
private static int randomizedSelect(int[] arr, int p, int r, int i) {
if (p == r) {
return arr[p];
}
int q = randomizedPartition(arr, p, r);
int k = q - p + 1;
if (i == k) {
return arr[q];
}
else if (i < k) {
return randomizedSelect(arr, p, q - 1, i);
}
else {
return randomizedSelect(arr, q + 1, r, i - k);
}
}
private static int askSizeN() {
System.out.println("Please chose the size of the heap: \n" + "(the size of n)");
return scan.nextInt();
}
private static int askSizeK(int nSize) {
System.out.println(
"Please chose how much small values you want to see: \n" + "(the size of k)");
int kSize = scan.nextInt();
if (kSize > nSize) {
System.out.println("cant print more number then the size of the Heap..");
System.out.println("Please enter a number less then " + (nSize + 1));
askSizeK(nSize);
}
return kSize;
}
private static int[] chose(int[] a) {
System.out.println("Chose the option you want: \n" + "\t1. enter your own values."
+ "\n\t2. let me generate random values");
int chose = scan.nextInt();
if (chose == 1) {
for (int i = 0; i < a.length; i++) {
System.out.println("Enter value number " + (i + 1));
a[i] = scan.nextInt();
}
}
else if (chose == 2) {
System.out.println("Generate random numbers.");
for (int i = 0; i < a.length; i++) {
a[i] = rand.nextInt(1000);
}
}
else {
chose(a);
}
return a;
}
private static void printArr(int[] a){
for(int i=0;i<a.length;i++){
System.out.print(a[i] + " ");
}
System.out.println();
}
}
I've solved the problem.
Method randmizedPartition() was generating wrong random pivot for partition.
I solved it by changing the random line to:
int i = rand.nextInt((r - p) + 1) + p;

Java finding the smallest integer in a speciofic position in a sets of integer

Algorithm:
Procedure SELECT( k,S)
{ if ISI =1 then return the single element in S
else { choose an element a randomly from S;
let S1,S2,and S3 be he sequences of elements in S
less than, equal to, and greater than m, respectively;
if IS1I >=k then return SELECT(k,S1)
else
if (IS1I + IS2I >=k then return m
else return SELECT(k-IS1I-IS2I , S3);
}
}
The question is to implement the first algorithm for finding the kth smallest integer in a set of integers and test your program for different sets of integers generated by a random number generator.
Below is my solution.
import java.util.Random;
import java.util.Scanner;
public class main {
private static Random rand = new Random();
private static Scanner keyboard = new Scanner(System.in);
public static int firstAlgorithm(int k, int[] S) {
int m = S[rand.nextInt(S.length)];
int[] S1 = new int[S.length];
int[] S2 = new int[S.length];
int[] S3 = new int[S.length];
int p = 0;
int q = 0;
int r = 0;
if (S.length == 1)
return S[0];
for (int i = 0; i < S.length; i++) {
if (S[i] < m) {
S1[p] = S[i];
p++;
} else if (S[i] == m) {
S2[q] = S[i];
q++;
} else {
S3[r] = S[i];
r++;
}
}
S1 = trimToSize(S1, p);
S2 = trimToSize(S2, q);
S3 = trimToSize(S3, r);
if (S1.length >= k)
return firstAlgorithm(k, S1);
else if (S1.length + S2.length >= k)
return m;
else
return firstAlgorithm(k - S1.length - S2.length, S3);
}
private static int[] trimToSize(int[] arr, int size) {
int[] temp = new int[size];
for (int i = 0; i < size; i++) {
temp[i] = arr[i];
}
return temp;
}
public static void printArray(int[] S) {
for (int i = 0; i < S.length; i++) {
System.out.print(S[i] + "\t");
if (i % 10 == 9)
System.out.println();
}
}
// start main method
public static void main(String[] args) {
System.out.print("Enter the size of an array: ");
int size = keyboard.nextInt();
while (size < 1) {
System.out.println("Size of the array should be greater than 0.");
System.out.print("Enter the size of an array: ");
size = keyboard.nextInt();
}
System.out.print("Enter the value of k: ");
int k = keyboard.nextInt();
while (k < 1 || k > size) {
System.out.println("Value of k should be in the range 1-" + size + ".");
System.out.print("Enter the value of k: ");
k = keyboard.nextInt();
}
int[] S = new int[size];
for (int i = 0; i < size; i++) {
S[i] = 100 + rand.nextInt(900);
}
System.out.println("\nRandom values generated in the array:");
printArray(S);
System.out.println();
System.out.println(k + "th smallest value in the array using Algorithm #1: " + firstAlgorithm(k, S));
}
}
But I need to implement the above algorithm without using a temporary array for partitioning. How can I do it?
The algorithm is Dijkstra's 3-way partition.
You will have to modify the original S.
Untested (pseudo) code ahead
public static int partition(int left, int right, int[] S) {
int m = rand.nextInt(right-left); // protect against malicious data
swap(S[left+m], S[right]);
int equal = left;
while (left < right) {
if (a[left] < a[n])
swap(S, left++, equal++)
else if (a[left] == a[n])
swap(S, left, --right);
else
left++;
}
return left, equal;
}
public static int firstAlgorithm(int k, int left, int right, int[] S) {
if (left == right)
return S[left];
int p, e = partition(left, right, S); // returns 2 values. S1=[0,p), S2=[p,e), S3=[e, n)
if (p >= k)
return firstAlgorithm(k, left, p, S);
else if (e >= k) // p < k
return S[p]; // p is the first equal, e is first larger than equal
else // e < k
return firstAlgorithm(k, e, right, S);
}
// test
S = {1, 4, 2, 6, 2};
k = 2;
int result = firstAlgorithm(2, 0, S.length-1, S);
assert(result == 2);
Warning syntax and off-by-one errors guarantied.
See here multiple ways to return 2 values in java.

Rolling hash: my codes fails with modulo for long string

I'm trying to solve https://leetcode.com/problems/longest-repeating-substring/
I want to use rolling hash to match strings.
However, my codes don't seem to work when I deal with modulo.
For a string with all same characters, the maximum length of repeating substring should be string.length - 1.
public class Main {
public static void main(String[] args) {
String str = "bbbbbbbbbbbbbbbbbbb";
System.out.println(str.length() - 1);
Solution s = new Solution();
System.out.println(s.longestRepeatingSubstring(str));
}
}
class Solution {
public int longestRepeatingSubstring(String S) {
HashSet<Long> h = new HashSet();
long mod = (long)1e7 + 7;
for(int i = S.length() - 1; i >0; i--){
h = new HashSet();
long c = 0;
int j = 0;
for(; j < i; j ++){
c = (c*26 % mod + S.charAt(j) - 'a')% mod;
}
h.add(c);
for(; j < S.length(); j++){
c -= (S.charAt(j - i ) - 'a') * Math.pow(26,i-1)% mod;
c = (c*26 % mod + S.charAt(j) - 'a')% mod;
if(h.contains(c)){
return i;
}
h.add(c);
}
}
return 0;
}
}
Playground for my codes: https://leetcode.com/playground/F4HkxbFQ
We cannot see your original link, we need a password.
The usage of modulo seems to be really complex.
Why not try something like this
class Scratch {
// "static void main" must be defined in a public class.
public static void main(String[] args) {
String str = "bbaaabbbbccbbbbbbzzzbbbbb";
System.out.println(str.length() - 1);
Solution s = new Solution();
System.out.println(s.longestRepeatingSubstring(str));
}
static class Solution {
public int longestRepeatingSubstring(String s) {
int max = -1;
int currentLength = 1;
char[] array = s.toCharArray();
for (int index = 1; index < array.length; index++) {
if (array[index - 1] == array[index]) {
currentLength++;
max = Math.max(max, currentLength);
} else {
currentLength = 1;
}
}
return max;
}
}
}

Method to add the even/odd numbers

I have an array with several numbers:
int[] tab = {1,2,3,4};
I have to create two methods the first is the sum() method and the second is numberOdd().
It's Ok for this step !
int length = tab.length;
length = numberOdd(tab,length);
int sum_odd = sum(tab, length);
System.out.println(" 1) - Calculate the sum of the odds numbers : => " + sum_odd);
public static int sum(int[] tab, int length){
int total = 0;
for(int i=0;i<length;i++){
total += tab[i];
}
return total;
}
public static int numberOdd(int[] tab, int length){
int n = 0;
for(int i=0;i<length;i++){
if(tab[i] % 2 != 0){
tab[n++] = tab[i];
}
}
return n;
}
Now, I have to add the even numbers with the numberEven() method and I get the value "0".
I don't understand why I retrieve the value => 0 ???????
Here is my code:
int[] tab = {1,2,3,4};
int length = tab.length;
length = numberOdd(tab,length);
int sum_odd = sum(tab, length);
length = numberEven(tab,length);
int sum_even = sum(tab, length);
System.out.println(" 1) - Calculate the sum of the odds numbers : => " + sum_odd);
System.out.println(" 2) - Calculate the sum of the evens numbers : => " + sum_even);
}
public static int numberEven(int[] tab, int length){
int n = 0;
for(int i=0;i<length;i++){
if(tab[i] % 2 == 0){
tab[n++] = tab[i];
}
}
return n;
}
For information: I share the code here => https://repl.it/repls/CriminalAdolescentKilobyte
Thank you for your help.
You need to add tab[i] to n
Having length as a parameter to numberEven does not cause any harm but you don't need it.
Given below is the working example:
public class Main {
public static void main(String[] args) {
int[] tab = { 1, 2, 3, 4 };
System.out.println(numberEven(tab));
}
public static int numberEven(int[] tab) {
int n = 0;
for (int i = 0; i < tab.length; i++) {
if (tab[i] % 2 == 0) {
n += tab[i];
}
}
return n;
}
}
Output:
6
you have changed the array in your numberOdd() method.
try replacing tab[n++] = tab[i]; with n++;
public static int sumEven(int[] tab){
int sumEven = 0;
for(int i=0;i<tab.length;i++){
if(tab[i] % 2 == 0){
sumEven = sumEven + tab[i];
}
}
return sumEven;
}
This should work.

Void merge sort method java

So, my computer science teacher has told me to make every method here void, except for copyPartArray. I have no idea how to do this, when I try, the sort simply fails.
public static ArrayList<String> mergeSortHelper(ArrayList<String> a) {
int mid = a.size() / 2 - 1;
if (a.size() <= 1)
return a;
return merge(mergeSortHelper(copyPartArray(a, 0, mid)),
mergeSortHelper(copyPartArray(a, mid + 1, a.size() - 1)));
}
public static void mergeSort(ArrayList<String> a) {
ArrayList<String> x = mergeSortHelper(a);
for (int i = 0; i < a.size(); i++) {
a.set(i, x.get(i));
}
}
public static ArrayList<String> merge(ArrayList<String> a,
ArrayList<String> b) {
ArrayList<String> x = new ArrayList<String>(a.size() + b.size());
int aCount = 0;
int bCount = 0;
for (int i = 0; i < a.size() + b.size(); i++) {
if (aCount > a.size() - 1) {
for (int j = bCount; j < b.size(); j++) {
x.add(b.get(j));
}
break;
}
if (bCount > b.size() - 1) {
for (int j = aCount; j < a.size(); j++) {
x.add(a.get(j));
}
break;
}
if ((a.get(aCount)).compareTo(b.get(bCount)) < 0) {
x.add(a.get(aCount));
aCount++;
} else {
x.add(b.get(bCount));
bCount++;
}
}
return x;
}
public static ArrayList<String> copyPartArray(ArrayList<String> a, int s,
int e) {
ArrayList<String> x = new ArrayList<String>();
for (int i = s; i <= e; i++) {
x.add(a.get(i));
}
return x;
I have tried to change my mergeSort to:
public static void mergeSort(ArrayList<String> a) {
int mid = a.size() / 2 - 1;
if (a.size() <= 1)
return;
mergeSort(copyPartArray(a, 0, mid));
mergeSort(copyPartArray(a, mid + 1, a.size() - 1));
merge(a, copyPartArray(a, 0, mid),
copyPartArray(a, mid + 1, a.size() - 1));
}
and get rid of the mergeSortHelper all together.
Now I have:
public static void mergeSort(ArrayList<String> a, int start, int end) {
int mid = (start + end) / 2;
if (a.size() <= 1)
return;
mergeSort(a, start, mid);
mergeSort(a, mid + 1, end);
how would I incorporate my merge method into this?
copyPartArray is going to make a copy of the array so that's no good, your lecturer wants you to pass the array by reference and then also pass in the start/end (or start/length) integers. Try doing something like this:
public static void mergeSort(ArrayList<String> a, int start, int length) {
// refer to 'the array' as a[start] to a[start + length]
}
a will be passed by reference which means you don't need a return value.
So I would change your methods to take a start and length and get rid of copyPartArray all together, you can do your merging in-place on the one array.
I use this method in my blog post on Quicksort.

Categories