So in my advanced algorithms class, we are to write an algorithm for a program to find two numbers in two sorted arrays of integers. The format is A[i] + B[j] == x. The runtime of the algorithm needs to be O(n).
I thought i had it and wanted to check so I emailed my professor and she told me my runtime was O(n^2). Here is my code:
int[] A = {1,2,3,4,5};
int[] B = {1,2,3,4,5,6};
int x = 4;
int i = 0;
int j = 0;
for(int n = 0; n < (A.length*B.length); n++) {
if(i >= A.length)
i = 0;
if(n % B.length == 0)
j++;
if(A[i] + B[j] == x) {
System.out.println(A[i] + " + " + B[j] + " = " + x);
break;
}
i++;
}
EDIT
I do apologize if this is still incorrect. I never really grasped the concept of Big-Oh. Would this change the runtime to O(n)? I got rid of the A.length*B.length and tried something a little different.
int[] A = {1,2,3,4,5};
int[] B = {1,2,3,4,5};
int x = 5;
int i = 0;
int j = 0;
while(i < A.length) {
if(B[j] == x - A[i]) {
/* exit */ }
if(j >= B.length) {
j = 0;
i++; }
j++;
}
Solution 1:
Add all values in B to a Map with B value as the map key, and B-index as the map value.
Iterate A, and calculate desired B value as B = x - A. Look for it in the map, and if found, you then have the index.
You will only iterate A and B once each. Adding a single value to map is O(1), and looking up a value is O(1), assuming a HashMap, so overall is O(n).
Solution 2:
Iterate A ascending, and B descending.
For each value in A, look at current B value. Walk down B until A + B <= x (or you reach beginning of B).
You will only iterate A and B once each, so O(n).
Solution 2 requires less memory (no map), and is likely faster (no time spent building map).
UPDATE Here is code:
The above descriptions were based on need for index of values, and the code for each solution is:
Solution 1
private static void findSum(int[] a, int[] b, int x) {
Map<Integer, Integer> bIdx = new HashMap<>();
for (int j = 0; j < b.length; j++)
bIdx.put(b[j], j);
for (int i = 0; i < a.length; i++) {
Integer j = bIdx.get(x - a[i]);
if (j != null)
System.out.println("a[" + i + "] + b[" + j + "] = " + a[i] + " + " + b[j] + " = " + x);
}
}
Solution 2
private static void findSum(int[] a, int[] b, int x) {
for (int i = 0, j = b.length - 1, sum; i < a.length && j >= 0; i++) {
while (j >= 0 && (sum = a[i] + b[j]) >= x) {
if (sum == x)
System.out.println("a[" + i + "] + b[" + j + "] = " + a[i] + " + " + b[j] + " = " + x);
j--;
}
}
}
Test
int[] a = {1,2,3,4,5};
int[] b = {1,2,3,4,5,6};
findSum(a, b, 4);
Output (same from both)
a[0] + b[2] = 1 + 3 = 4
a[1] + b[1] = 2 + 2 = 4
a[2] + b[0] = 3 + 1 = 4
Solution 1 using Set
If you don't need index position, then a Set is better for solution 1:
private static void findSum(int[] aArr, int[] bArr, int x) {
Set<Integer> bSet = new HashSet<>();
for (int b : bArr)
bSet.add(b);
for (int a : aArr)
if (bSet.contains(x - a))
System.out.println(a + " + " + (x - a) + " = " + x);
}
Output
1 + 3 = 4
2 + 2 = 4
3 + 1 = 4
Here is an example of how you can measure your time, i've included another method to find the numbers you mentioned. See the difference in runtime:
int[] A = {1,2,3,4,5};
int[] B = {1,2,3,4,5,6};
int x = 4;
int i = 0;
int j = 0;
long t1 = System.nanoTime();
for(int n = 0; n < (A.length*B.length); n++) {
if(i >= A.length)
i = 0;
if(n % B.length == 0)
j++;
if(A[i] + B[j] == x) {
System.out.println(A[i] + " + " + B[j] + " = " + x);
break;
}
i++;
}
long t2 = System.nanoTime();
System.out.println("Time 1: "+(t2-t1));
//Here's the other method
long t3 = System.nanoTime();
for (int n = 0;n<B.length;n++){
for (int m =0;m<A.length;m++){
if(A[m]+B[n]==x){
System.out.println(A[m] +" + "+B[n] +" = "+ x);
}
}
}
long t4 = System.nanoTime();
System.out.println("Time 2: "+(t4-t3));
Here is the code, for Andreas's Solution 1, that I came up with:
int[] A = {2,3,4};
int[] B = {7,9};
Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
int x = 10;
int b;
for(int i = 0; i < B.length; i++) {
hashMap.put(B[i], i);
}
for (int n = 0; n < A.length; n++){
b = x - A[n];
if(hashMap.get(b) != null)
System.out.println(A[n] + " + " + b + " = " + x);
}
Related
I'm trying to calculate the sum of the numbers in my pyramid in java. For this, mathematical rule is 2+5+8+9. I mean first row+first number of second row+ second number of third row like that.
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
System.out.println(" " + numbers[0]);
System.out.println(" " + numbers[1] + " " + numbers[2]);
System.out.println(" " + numbers[3] + " " + numbers[4] + " " + numbers[5]);
System.out.println("" + numbers[6] + " " + numbers[7] + " " + numbers[8] + " " + numbers[9]);
For example:
2
5 7
1 8 3
6 0 9 4
How can I calculate 2+5+8+9 in Java?
The simplest way of calculating 2+5+8+9 is using Java build-in feature:
int result = 2+5+8+9;
You should construct your pyramid as a 2D array.
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
int addedElements = 0;
int nextSize = 1;
ArrayList<int[]> pyramid = new ArrayList<>();
while(addedElements< numbers.size()) {
int[] level = new int[nextSize++];
for (int i = 0; i < nextSize - 1; i++) {
level[i] = numbers[addedElements++];
}
}
int result = 0;
//add maximum of each `int[]` in pyramid.
for (int[] array : pyramid) {
int currentMax = array[0];
for (int i = 0; i < array.size(); i++) {
if (array[i] > currentMax) {
currentMax = array[i];
}
result+=currentMax;
}
System.out.println(result);
Try the follwoing code :
int[] numbers = { 2,5,7,1,8,3,6,0,9,4 };
int index = 1;
int number = 2;
int result = numbers[0];
while (index < numbers.length) {
result += numbers[index + number -2];
index += number;
number += 1;
}
System.out.println(result);
But the whole whing would be much easier and clearer if you just put your pyramide into a 2 dimensional array.
int[][] numbers = { {2},
{5,7},
{1,8,3},
{6,0,9,4} };
int result = numbers[0][0];
for (int i = 1; i < numbers.length; i++) {
result += numbers[i][i-1];
}
System.out.println(result);
I'm trying to make the merge sort to use only (n/2 + 1) extra space and still O(n log n) time. This is my homework.
The original quesetion:
Write the non-recursive version of merge sort. Your program should run
in O(n log n) time and use n/2 + O(1) extra spaces.
The program will split an array in to two like normal merge sort. The left part will be in another array, which is ceil(n/2) long, so it will fit the requirement.
The right part will be in the original array. So it will be half in-place sorting
Sorry, I don't know how to explain further.
I think this is basically correct. But I kept on facing OutOfBounds error.
I know the code is quite long and messy. But can anyone help me about that?
I spent about 5 hours to implement this. Please help me.
package comp2011.lec6;
import java.util.Arrays;
public class MergeSort {
public static void printArr(int[] arr){
for(int i = 0; i < arr.length; i++){
System.out.printf("%d ", arr[i]);
}
}
public static void mergeSort(int[] arr){
if(arr.length<2) {
return;
}
int n, lBegin, rBegin;
n = 1;
int[] leftArr = new int[arr.length - (arr.length/2)];
while(n<arr.length) {
lBegin = 0;
rBegin = n;
while(rBegin + n <= arr.length) {
mergeArrays(arr, lBegin, lBegin+n, rBegin, rBegin+n, leftArr);
lBegin = rBegin+n;
rBegin = lBegin+n;
}
if(rBegin < arr.length) {
mergeArrays(arr, lBegin, lBegin+n, rBegin, arr.length, leftArr);
}
n = n*2;
}
}
public static void mergeArrays(int[] array, int startL, int stopL, int startR, int stopR, int[] leftArr) {
// int[] right = new int[stopR - startR + 1];
// int[] left = new int[stopL - startL + 1];
// for(int i = 0, k = startR; i < (right.length - 1); ++i, ++k) {
// right[i] = array[k];
// }
System.out.println("==============");
System.out.println("stopL: " + stopL +" startL: " + startL);
for(int i = 0, k = startL; i <= (stopL - startL); ++i, ++k) {
System.out.println(leftArr[i]);
leftArr[i] = array[k];
}
// right[right.length-1] = Integer.MAX_VALUE;
leftArr[stopL - startL] = Integer.MAX_VALUE;
System.out.println("leftArr: " + Arrays.toString(leftArr));
System.out.println("RightArr: " + Arrays.toString(Arrays.copyOfRange(array, startR, stopR)));
System.out.println("before: " + Arrays.toString(array));
// for(int k = startL, m = 0, n = startR; k < stopR; ++k) {
System.out.println("StartL: " + startL + " StartR: " + stopR);
for(int k = startL, m = 0, n = startR; ( (k < stopR) ); ++k) {
System.out.println("k: " + k);
System.out.println("Left: " + leftArr[m]);
System.out.println("Right: " + array[n]);
System.out.println("Array[k] before: " + array[k]);
// if(leftArr[m] == Integer.MAX_VALUE){
// System.out.println("YES");
// }
if( (leftArr[m] <= array[n]) || (n >= stopR) ) {
System.out.println("Left is smaller than right");
array[k] = leftArr[m];
m++;
}
else {
System.out.println("Right is smaller than left");
array[k] = array[n];
System.out.println("right: " + array[k]);
n++;
}
System.out.println("Array[k] after: " + array[k]+"\n");
}
System.out.println("after " + Arrays.toString(array));
}
public static void main(String[] args) {
int[] array = new int[] { 5, 2, 4, 12, 2, 10, 13, 1, 7 };
mergeSort(array);
printArr(array);
}
}
I have a question on the method and process of how to look at these generated arrays.
Basically I want to create an array of [a,b,c,(a+b+c)] and as well as a second array of [d,e,f,(d+e+f)] and if the third element in array1 and array2 are the same, display the arrays to strings.
int num = 10;
for(int a = 0; a < num; a++){
for(int b = 0; b < num; b++){
for(int c = 0; c < num; c++){
if(a<=b && b<=c){
arrayOne[0] = a;
arrayOne[1] = b;
arrayOne[2] = c;
arrayOne[3] = (a+b+c);
}
}
}
}
for(int d = 0; d < num; e++){
for(int e = 0; e < num; e++){
for(int f = 0; f < num; f++){
if(d<=e && e<=f){
arrayTwo[0] = d;
arrayTwo[1] = e;
arrayTwo[2] = f;
arrayTwo[3] = (f -(d+e));
}
}
}
}
as you can see I am beyond stump.I am not quite sure where i can get each iteration of the arrays and compare the values by matching the sums in each array and as well as displaying the respective array they are in. Thank you all in advanced.
If I understand your question correctly if a=1, b=3, c=4 and d=2, e=3, f=3 you'd like to print something along the lines of 1 + 3 + 4 = 8 = 2 + 3 + 3. First, what you're doing right now is creating two arrays like Floris described in the comment. What you want to do is store all the values in one array of arrays, as follows:
int max; \\ To determine the value of max see the edit below.
int array[][] = new int[max][num];
int index = 0;
for (int a=0; a < num; a++) {
for (int b=a; b < num; b++) {
for (int c=b; c < num; c++) {
array[index][0] = a;
array[index][1] = b;
array[index][2] = c;
array[index][3] = a + b + c;
index++;
}
}
}
for (int i = 0; i < max; i++) {
for (int j = i; j < max; j++) {
if (array[i][3] == array[j][3]) {
string outString = array[i][0] + " + " + array[i][1] + " + " + array[i][2] + " = " + array[i][3] + " = " + array[j][0] + " + " + array[j][1] + " + " + array[i][2];
System.out.println(outString);
}
}
}
You can see that I improved performance by starting b from a and c from b since you are throw out all the values where b < a or c < b. This also should eliminate the need for your if statement (I say should only because I haven't tested this). I needed to use an independent index due to the complexities of the triple nested loop.
Edit 2: Ignore me. I did the combinatorics wrong. Let An,k be the number of unordered sets of length k having elements in [n] (this will achieve what you desire). Then An,k = An-1,k + An,k-1. We know that An,1 = n (since the values are 0, 1, 2, 3, 4, ..., n), and A1,n = 1 (since the only value can be 11111...1 n times). In this case we are interested in n= num and k = 3 , so plugging in the values we get
A_num,3 = A_num-1,3 + A_num,2
Apply the equation recursively until you come to an answer. For example, if num is 5:
A_5,3 = A_4,3 + A_5,2
= A_3,3 + A_4,2 + A_4,2 + A_5,1
= A_3,3 + 2(A_4,2) + 5
= A_2,3 + A_3,2 + 2(A_3,2) + 2(A_4,1) + 5
= A_2,3 + 3(A_3,2) + 2(4) + 5
= A_1,3 + A_2,2 + 3(A_2,2) + 3(A_3,1) + 2(4) + 5
= 1 + 4(A_2,2) + 3(3) + 2(4) + 5
= 1 + 4(A_1,2) + 4(A_2,1) + 3(3) + 2(4) + 5
= 1 + 4(1) + 4(2) + 3(3) + 2(4) + 5
= 5(1) + 4(2) + 3(3) + 2(4) + 5
It looks like this may simplify to (num + (num - 1)(2) + (num - 2)(3) + ... + (2)(num - 1) + num) which is binomial(num, num) but I haven't done the work to say for sure.
int givenNumber = 10;
int []arrayOne = new int [4];
int []arrayTwo = new int [4];
int count = 0;
for ( int i = 0; i < givenNumber; i ++)
{
for ( int x = 0; x < givenNumber; x ++ )
{
for ( int a = 0; a < givenNumber; a++ ){
arrayOne[0] = (int)(a * java.lang.Math.random() + x);
arrayOne[1] = (int)(a * java.lang.Math.random() + x);
arrayOne[2] = (int)(a * java.lang.Math.random() + x);
arrayOne[3] = (int)(arrayOne[0]+arrayOne[1]+arrayOne[2]);
}
for ( int b = 0; b < givenNumber; b++ ){
arrayTwo[0] = (int)(b * java.lang.Math.random() + x);
arrayTwo[1] = (int)(b * java.lang.Math.random() + x);
arrayTwo[2] = (int)(b * java.lang.Math.random() + x);
arrayTwo[3] = (int)(arrayTwo[0]+arrayTwo[1]+arrayTwo[2]);
}
if (arrayOne[3] == arrayTwo[3])
{
for ( int a = 0; a < 2; a++ )
{
System.out.print(arrayOne[a] + " + ");
} System.out.print(arrayOne[2] + " = " + arrayOne[3] + " = ");
for ( int a = 0; a < 2; a++ )
{
System.out.print(arrayTwo[a] + " + ");
} System.out.print(arrayTwo[2]);
System.out.println("\n");
count += 1;
}
}
}
if (count == 0)
System.out.println(
"\nOops! you dont have a match...\n" +
"Please try running the program again.\n");
I have n bags of candies such that no two bags have the same number of candies inside (i.e. it's a set A[] = {a0,a1,a2,...,ai,...,aj} where ai != aj).
I know how many candies is in each bag and the total number M of candies I have.
I need to divide the bags among three children so that the candies are distributed as fairly as possible (i.e. each child gets as close to M/3 as possible).
Needless to say, I may not tear into the bags to even out the counts -- then the question would be trivial.
Does anyone have any thoughts how to solve this -- preferably in Java?
EDIT:
the interviewer wanted me to use a 2-D array to solve the problem: the first kid gets x, the second kid y, the third gets the rest: S[x][y].
This after I tried following:
1] sort array n lg n
2] starting with largest remaining bag, give bag to kid with fewest candy.
Here is my solution for partitioning to two children (it is the correct answer). Maybe it will help with getting the 3-way partition.
int evenlyForTwo(int[] A, int M) {
boolean[] S = new boolean[M+1];
S[0]=true;//empty set
for(int i=0; i<A.length; i++)
for(int x=M; x >= A[i]; x--)
if(!S[x])
S[x]=S[x-A[i]];
int k = (int) M/2;
while(!S[k])
k--;
return k;//one kid gets k the other the rest.
}//
The problem you describe is known as the 3-Partition problem and is known to be NP-hard. The problem is discussed a bit on MathOverflow. You might find some of the pointers there of some value.
Here is a little solution, crude but gives correct results. And you can even change the number of children, bags, etc.
public class BagOfCandies {
static public void main(String...args) {
int repeat = 10;
int childCount = 3;
int bagsCount = childCount + (int) (Math.random() * 10);
for (int k=0; k<repeat; k++) {
int candyCount = 0, n=0;
int[] bags = new int[bagsCount];
for (int i=0; i<bags.length; i++) {
n += 1 + (int) (Math.random() * 2);
bags[i] = n;
candyCount += n;
}
shuffle(bags); // completely optional! It works regardless
boolean[][] dist = divideBags(bags, childCount);
System.out.println("Bags of candy : " + Arrays.toString(bags) + " = " + bags.length);
System.out.println("Total calculated candies is " + candyCount);
int childCandySum = 0;
for (int c=0; c<childCount; c++) {
int childCandies = countSumBags(bags, dist[c]);
System.out.println("Child " + (c+1) + " = " + childCandies + " --> " + Arrays.toString(dist[c]));
childCandySum += childCandies;
}
System.out.println("For a total of " + childCandySum + " candies");
System.out.println("----------------");
}
}
static private void shuffle(int[] bags) {
for (int i=0, len=bags.length; i<len; i++) {
int a = (int)Math.floor(Math.random()*len);
int b = (int)Math.floor(Math.random()*len);
int v = bags[a];
bags[a] = bags[b];
bags[b] = v;
}
}
static private boolean[][] divideBags(int[] bags, int childCount) {
int bagCount = bags.length;
boolean[][] dist = new boolean[childCount][bagCount];
for (int c=0; c<childCount; c++)
Arrays.fill(dist[c], false);
for (int i=0; i<bagCount; i+=childCount)
for (int j=i, c=0; c<childCount && j<bagCount; j++, c++)
dist[c][j] = true;
if (childCount == 1) return dist; // shortcut here
int sumDiff = 1;
int oldDiff = 0;
while (sumDiff != oldDiff) {
oldDiff = sumDiff;
sumDiff = 0;
// start comparing children in pair
for (int child1=0; child1<childCount-1; child1++) {
for (int child2=child1+1; child2<childCount; child2++) {
int count1 = countSumBags(bags, dist[child1]);
int count2 = countSumBags(bags, dist[child2]);
int diff = Math.abs(count1 - count2);
// a difference less than 2 is negligeable
if (diff > 1) {
// find some bags with can swap to even their difference
int c1=-1, c2=-1, cdiff;
boolean swap = false;
for (int i=0; i<bagCount-1; i++) {
for (int j=i; j<bagCount; j++) {
if (dist[child1][i] && dist[child2][j]) {
cdiff = Math.abs((count1 - bags[i] + bags[j]) - (count2 + bags[i] - bags[j]));
if (cdiff < diff) {
c1 = i; c2 = j;
diff = cdiff;
swap = true;
}
}
if (dist[child1][j] && dist[child2][i]) {
cdiff = Math.abs((count1 - bags[j] + bags[i]) - (count2 + bags[j] - bags[i]));
if (cdiff < diff) {
c1 = j; c2 = i;
diff = cdiff;
swap = true;
}
}
}
}
if (swap) {
//System.out.println("Swaping " + c1 + " with " + c2);
dist[child1][c1] = false; dist[child1][c2] = true;
dist[child2][c1] = true; dist[child2][c2] = false;
}
}
//System.out.println("Diff between " + child1 + "(" + countSumBags(bags, dist[child1]) + ") and " + child2 + "(" + countSumBags(bags, dist[child2]) + ") is " + diff);
sumDiff += diff;
}
}
//System.out.println("oldDiff="+oldDiff+", sumDiff="+sumDiff);
}
return dist;
}
static private int countSumBags(int[] bags, boolean[] t) {
int count = 0;
for (int i=0; i<t.length; i++) {
if (t[i]) {
count+=bags[i];
}
}
return count;
}
}
I don't know if this the result you were looking for, but it seems to be, from my understanding of the question.
I am trying to solve the following problem:
Find the largest palindrome made from the product of two 3-digit numbers.
I have the following Java code:
public static void main(String[] args) {
int a = 999, b = 999;
for(int i = 100; i <= a; i++) {
for(int j = 100; j <= b; j++) {
checkPalindrome(i*j, i, j);
}
}
}
public static void checkPalindrome(int n, int a, int b) {
String s = "" + n;
boolean palindrome = false;
int j = s.length()-1;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) != s.charAt(j))
break;
j -= i;
}
if(palindrome)
System.out.println(n + ", " + a + ", " + b);
}
I'm still lacking the change of the "palindrome" variable but at the moment if I run it I get a String index out of range on line 28 which is the j -= i I just don't understand why this is happening I mean, I get that the difference is resulting in a number lower than 0 but I can't figure out WHY it happens. Could someone please explain me?
Your method can be improved like this. The condition in for loop i<=j reduced number of iterations too.
public static void checkPalindrome(int n, int a, int b) {
String s = "" + n;
boolean palindrome = false;
int j = s.length()-1;
for(int i = 0; i <= j; i++){
if(s.charAt(i) != s.charAt(j))
break;
j --;
}
if(palindrome)
System.out.println(n + ", " + a + ", " + b);
}
Hope this helps.
I think you want j-- not j -= i. Especially since i starts at 0.
change your code to:
public static void checkPalindrome(int n, int a, int b) {
String s = "" + n;
boolean palindrome = true;
int j = s.length()-1;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) != s.charAt(j))
palindrome = false;
}
if(palindrome)
System.out.println(n + ", " + a + ", " + b);
}
You're incrementing i - you want to decrement j - you DON'T want to do j -= i.
Otherwise for a string of length 5, you'd get:
i = 0, j = 4
i = 1, j = 4
i = 2 , j = 3
i = 3 , j = 1
i = 4, j = -2
Though if it's giving an index out of range message, you're running a different version of the code - j -= i can't possibly generate that.