How to go through a 2d array with two pointers? - java

I'm told to implement two pointers which will run through the first and last index of my array and try to find a pair that returns 20.
If the pair's sum is larger than 20 then lower the last index by 1 and if the pair's sum is smaller than 20 then add the first index by 1. If the pair returns 20 find the smallest number's index.
This is my checkSum method:
public static int checkSum(int[] array){
// This function will inspect the input to find any pair of values that add up to 20
// if it finds such a pair, it will return the *index* of the smallest value
// if it does not find such as pair, it will return -1;
int twenty = 20;
int zero = 0;
int checkIndex = array.length;
for (int i = 0; i < array.length - 1; i++){
for (int k = array.length - 1; k < array.length; k++){
if (array[i] + array[k] == twenty){
// 0 + 1
System.out.println("this print out 20");
System.out.println(array [k] + " + " + array[i]);
if (array [k] >= array [zero]){
//need to print out the index of the minimum value
checkIndex = zero;
}
}
else if (array[i] + array[k] > twenty){
array[k]--;
checkIndex = array[k];
}
else if (array[i] + array[k] < twenty){
//tried a different method to see if it would increment the index rather than the value
array[i+1] = array[i];
checkIndex = array[i];
}
}
}// remove the following line after you are done writing the function
System.out.println(checkIndex);
return checkIndex;
}
and this is the main method that is provided:
public static void main(String[] args) {
int[] array1 = new int[]{5, 7, 8, 9, 10, 15, 16};
if (checkSum(array1) != 0){
System.err.println("TEST1 FAILED");
}
int[] array2 = new int[]{3, 5, 8, 9, 10, 15, 16};
if (checkSum(array2) != 1){
System.err.println("TEST2 FAILED");
}
int[] array3 = new int[]{3, 4, 6, 9, 10, 14, 15};
if (checkSum(array3) != 2){
System.err.println("TEST3 FAILED");
}
int[] array4 = new int[]{6, 7, 8, 9, 10, 15, 16};
if (checkSum(array4) != -1){
System.err.println("TEST4 FAILED");
}
System.out.println("Done!!!");
}
My error is that it's doing:
Lets say array[i] + array[k] > twenty:
expected output:
array[0] + array[6] = 5 + 16 > 20
so do array[0] + array[5] = 5 + 15 = 20
than notice that 5 < 15 so the index is 0.
current output:
array[6] + array [6] - 1 = 16 + 15 > 20
so array[6] - 1 + array [6] - 1 - 1 = 15 + 14 > 20
and so forth...

You don't need a nested loop to do the task. Assuming your input array is always sorted, you can declare two variables in one for loop one starting at the first element of your array and the second at the last element. Check at each step if the sum equals 20 if yes find the index and break the loop, if not increment your first variable or decrement your second variable depending on whether the sum was greater or less than 20.
public static int checkSum(int[] array) {
int checkIndex = -1;
int first = 0;
int last = array.length -1;
for (int i = first, k = last; i < k; ) {
if (array[i] + array[k] == 20){
System.out.println("Found a pair which adds up to 20");
System.out.println(array [i] + " + " + array[k]);
//find index of smallest value
if (array[i] < array[k]){
checkIndex = i;
}
else {
checkIndex = k;
}
//break out of loop if found a valid pair
break;
}
else {
//you will get here if the sum was not 20. Increment i or decrement k according to sum > 20 0r sum < 20
if (array[i] + array[k] > 20){
k--;
}
else {
i++;
}
}
}
System.out.println("index to return" + checkIndex);
return checkIndex;
}

Related

how to find the subarrays of the given array that matches the checkvalue?

find the subarrays that matches the given sum input under conditions
only one loop is allowed
cant repeat the same index for sum
no inbuild methods allowed
my Output:
int arr[] = { 2, 2, 1, 4, 1, 6, 8, 5, 1, 2, 1, 1, 1 };
int checkval = 3;
results:
the subarrays are:
index 0 to 1
index 3
index 3
index 3 to 3
index 8 to 10
index 9 to 11
Subarray with most elements is 3
Kindly help me to avoid duplicate printing of single index values
also find solution to not to use the same index for next sum,
incorrect
index 8 to 10
index 9 to 11
correct
index 8 to 10
**next index should start with 11 not 9**
index 9 to 11
public class Main {
public static void main(String[] args) {
int arr[] = { 2, 2, 1, 4, 1, 6, 8, 5, 1, 2, 1, 1, 1 };
int sum = 0;
int indexval = 0;
int checkval = 4;
int i = 0;
int len[] = new int[10];
int l = 0;
int lm = 0;
System.out.println("the subarrays are: ");
while (indexval <= arr.length) {
int temp=i;
if (i < arr.length)
sum += arr[i];
else
break;
if (sum <= checkval) {
if (sum == checkval) {
System.out.println("index " + indexval + " to " + i);
len[l++] = i - indexval + 1;
lm = (i - indexval + 1) > len[l] ? (i - indexval + 1) : len[l];
i = indexval;
indexval += 1;
sum = 0;
}
}
else if (arr[temp] == checkval) {
System.out.println("index " + i);
i = indexval;
indexval += 1;
sum = 0;
}
else if (sum > checkval) {
i = indexval;
indexval += 1;
sum = 0;
}
i += 1;
}
System.out.println("Subarray with most elements is " + lm);
}
}

linear search for multiple integers

Im trying to implement a linear search for an array of integers that if the number is a multiply of 3 its going to print the index of the number in the array and if there is no any number that is a multiple of 3 its going to return -1
im trying to implement this without using a method for it and my problem is how im going to do the printing/returning of -1?
knowing that my code is
int[] a = {3, 5, 22, 7, 9, 8, 21};
System.out.println("the index of 3 multiplies is" );
for (int i = 0; i < a.length; i++) {
if (a[i] % 3 == 0) {
System.out.print(i + " ");
continue;
}
}
You could use a boolean found = false and set it to true if the algorithm found a multiply of 3. After the for loop you could ask for result.
int[] a = {3, 5, 22, 7, 9, 8, 21};
int multipleOfThree = 0;
System.out.println("the index of 3 multiplies is" );
for (int i = 0; i < a.length; i++) {
if (a[i] % 3 == 0) {
System.out.print(i + " ");
multipleOfThree++;
}
}
if( multipleOfThree == 0 ){
System.out.println(-1);
}
I think this is what you are looking for. If you want to use a method, instead of printing the multipleOfThree, you should return it.
int[] a = {1,5,22,7,52,8,20};
System.out.println("the index of 3 multiplies is" );
boolean found = false;
for(int i = 0; i<a.length;i++){
if(a[i]%3==0){
found = true;
System.out.println(i+" ");
}
}
if(!found){
System.out.println("-1");
}
}``

is it a Heap Max? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
For a project, am i working with heaps. In this project i have to "investigate" whether an array is a max heap.
These 2 rules apply for a max heap:
The parent shall be bigger or equal to its child / children
Each node, in a heap, shall contain an element
Therefore have i created 2 for loops checking whether these rules apply. Unfortunately for me, my code doesn't work.
I have 2 for loops:
//Checks if there's a 0 value in the array. If so: Return false
for (int i = 1; i <= A.length; i++) {
System.out.println("A.length: " + A[i]);
if (A[i] == 0) {
System.out.println("weweh: "+ A[i]);
return false;
}
//Checks if either left or right child have a bigger value than itself
for (int i = 1; i <= (A.length - 2) / 2; i++) {
System.out.println("A: " + i);
if (A[i] < A[2 * i] || A[i] < A[2 * i + 1]) {
return false;
}
}
//the array
int A[] = {0, 40, 35, 30, 25, 15, 10, 5};
The last for loop works, but for some reason i get a mistake in the first for loop. The loop can find a number. Lets say that i picked 15 to be equal with A[i], then it would work and return false, but when the selected number 0 isn't there, then it sends me the error, and it wont go further for the second loop.
//Error:
A.length: 40
A.length: 35
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
A.length: 30
A.length: 25
A.length: 15
A.length: 10
A.length: 5
at ismaxheap.IsMaxHeap.MaxHeap(IsMaxHeap.java:24)
at ismaxheap.IsMaxHeap.main(IsMaxHeap.java:15)
/Users/yusuf/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
THE WHOLE CODE:
public class IsMaxHeap {
public static void main(String[] args) {
MaxHeap();
System.out.println("Max Heap: " + MaxHeap());
}
public static boolean MaxHeap() {
int A[] = {0, 40, 35, 30, 25, 15, 10, 5};
for (int i = 1; i <= A.length; i++) {
System.out.println("A.length: " + A[i]);
if (A[i] == 0) {
System.out.println("weweh: "+ A[i]);
return false;
}
}
for (int i = 1; i <= (A.length - 2) / 2; i++) {
System.out.println("A: " + i);
if (A[i] < A[2 * i] || A[i] < A[2 * i + 1]) {
return false;
}
}
return true;
}
}
In your first loop you are looping one more than possible by using <=
for (int i = 1; i <= A.length; i++)
Since you are trying to access A[i] and if i == A.length then you are out of bounds.
Should be:
for (int i = 1; i < A.length; i++)
Now I don't know why are you starting at index 1 since indexing in Java start with 0.
Dealing with special case of one child
This is the case when you array length is 3 (Since the zero index is ignored)
All you have to check is if A[2] < A[1] to be a Max heap, otherwise return false immediately.
Otherwise do the normal loop.

Count the number of occurrences of an int

This is a program to simply return the min value and the number of time it occurs in the array. If the array is filled with {13, 28, 5, 11} it returns the min as 5 and the count as 1. However, When the array is filled with the given numbers it returns the count as 2, when it should be 1. How would I fix this? Thankyou
public class Test4{
public static void main(String[] args){
int[] array = {4, 20, 30, 4, 25, 25, 6, 2, 29, 27, 1, 29, 11, 6, 10, 17, 8};
findMin(array);
}
public static void findMin(int[] array) {
if (array == null || array.length < 1)
return;
int count = 0;
int min = array[0];
for (int i = 1; i <= array.length - 1; i++) {
if (min > array[i]) {
min = array[i];
if(min == array[i]){
count++;
}
}
}
System.out.println("The minimum is: " + min +"\n" + "The count is: " + count);
}
}
You should initialize the count to 1 and reset is to 1 whenever the current min value is changed:
int count = 1; // initial count should be 1
int min = array[0];
for (int i = 1; i <= array.length - 1; i++) {
if (min > array[i]) {
// new minimum - reset count to 1
min = array[i];
count = 1;
} else if (min == array[i]) {
// same minimum - increment count
count++;
}
}

Add two array elements using loop

I am trying a task with arrays: add two elements and check if the sum is less than or equal to 50. If the condition is satisfied, it should break.
Example program:
public class HelloWorld {
public static void main(String []args)
{
int[] nums = new int[2];
for (int i = 0; i < 100; i++)
{
nums[i] = i + 1;
System.out.println(i);
}
System.out.println(nums[1]);
System.out.println(nums[2]);
if (nums[0]+nums[1]<=50)
{
System.out.printf("Sucessfully finished");
}
}
}
Of course, my program is not working. I want i value to store in the two elements
nums[0] = 1 and nums[1] = 2. I also want to add these two elements and check if the sum is less than or equal to 50. I have allocated two elements in the array which means nums want to add and check the current two elements of i and clear and adds next two elements and check if its less than or equal to 50.
nums[0]=1;
nums[1]=2; check <=50 . fails clear the the array elements and store next i value
nums[0]=3;
nums[1]=4; check <=50 . fails clear the the array elements and store next i value
...
nums[0]=25;
nums[1]=26; check <=50 .
There are a lot of ways to do this but here is a nifty trick that solves exactly this kind of problem.
int[] nums = new int[2];
for (int i = 0; i < 100; i++) {
nums[i % nums.length] = i + 1;
if (nums[0] + nums[1] <= 50) {
System.out.println("sum is less than or equal to 50");
break;
}
}
What the mod operator (%) does is calculate the remainder of i based on the array's length. This ensures that i goes from 0 to 99 but the array index always "resets" and stays within the range of the array. For example after i == 0 and i == 1, i will be incremented to out of bounds at i == 2 but 2 % 2 == 0. When i == 3, 3 % 2 == 1 and so on.
But as a side note, the condition you've described ("if the sum is less than or equal to 50...it should break") will be satisfied immediately (sums 1 at nums[0] and 0 at nums[1]) and the loop will not execute past the first iteration (i == 0). I'm not sure that's what you are wanting. Do you mean "not less than or equal to 50"?
int[] nums = new int[2];
for (int i = 0; i < 100; i++) {
nums[i % nums.length] = i + 1;
if (nums[0] + nums[1] > 50) {
System.out.println("sum was NOT less than or equal to 50");
break;
}
}
As an alternate solution finding this result can be very much shortened to the following while loop:
int i = 0;
// note sum of two consecutive integers will never be even (never 50)
while (i + ++i < 50);
System.out.println("min increments with sum > 50 was " + (i - 1) + " and " + i);
The output is min increments with sum > 50 was 25 and 26.
I believe, you need 1 more for loop, to go about checking each num[i] + num[i+1]. You can do it in a single for loop as well, but kept the code as simple as possible for your clarity.(As you are new to java programming ;))
public class HelloWorld{
public static void main(String[] args) {
int[] nums = new int[100];
for (int i = 0; i < 100; i++) {
nums[i] = i + 1;
System.out.println(i);
}
for (int i = 0; i < 99; i++) {
System.out.println(nums[i]);
System.out.println(nums[i+1]);
if (nums[i] + nums[i+1] == 50) {
System.out.printf("Successfully finished");
}
}
}
}
I'm not sure if this is what you meant. Have a try.
public static void main(String[] args) {
int[] nums = new int[100];
nums[0] =1;
for (int i = 1; i < 100; i++) {
nums[i] = i + 1;
if ((nums[i] +nums[i-1]) >= 50) {
System.out.printf("Successfully finished");
}
}
}
I'm not entirely sure on what your end goal is. If you just want to add two numbers (i, and i+1) and see if they are less than 50 then you can use this.
for (int i =0; i < 100; i++) {
int j = i+1;
int total = i+j;
if((i+(i+1)) < 50) {
System.out.println("Numbers '" + i + "' and '" + j + "' equal '" + total + "'.");
}
}
This will print out all the pairs of numbers that add to less than 50 along with what they add to.
I accept that you're probably wanting something more. :)

Categories