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++;
}
}
Related
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);
}
}
The method is given NxN matrix always powers of 2 and a number,it will return true if the num is found example for 4x4 size:
this is what i wrote:
public class Search {
public static boolean Search (int [][] matrix, int num)
{
int value = matrix.length / 2;
int first_quarter_pivot = matrix[value-1][0]; // represents highest number in first quarter
int second_quarter_pivot = matrix[value-1][value]; // represents highest number in second quarter
int third_quarter_pivot = matrix[matrix.length-1][value]; // represents highest number in third quarter
int fourth_quarter_pivot = matrix[matrix.length-1][0]; // represents highest number in fourth quarter
boolean isBoolean = false;
int i=0;
int j;
// if the num is not in the range of biggest smallest number it means he can`t be there.
if(!(num >= first_quarter_pivot) && (num <= fourth_quarter_pivot)) {
return false;
}
// if num is one of the pivots return true;
if((num == first_quarter_pivot || (num ==second_quarter_pivot))
|| (num == third_quarter_pivot) || (num == fourth_quarter_pivot ))
return true;
// if num is smaller than first pivot it means num is the first quarter,we limit the search to first quarter.
// if not smaller move to the next quarter pivot
if(num < first_quarter_pivot){{
j =0;
do
if(matrix[i][j] == num) {
isBoolean = true;
break;
}
else if((j == value)) {
j = 0;
i++;
}
else if(matrix[i][j] != num){
j++;
}
while(isBoolean != true) ;
}
return isBoolean;
}
// if num is smaller than second pivot it means num is the second quarter,we limit the search to second quarter.
// if not smaller move to the next quarter pivot
if(num < second_quarter_pivot){{
j = value;// start (0,value) j++ till j=value
do
if(matrix[i][j] == num) {
isBoolean = true;
break;
}
else if((j == matrix.length-1)) {
j = value;
i++;
}
else if(matrix[i][j] != num){
j++;
}
while(isBoolean != true) ;
}
return isBoolean;
}
// if num is smaller than third pivot it means num is the third quarter,we limit the search to third quarter.
// if not smaller move to the next quarter pivot
if(num < third_quarter_pivot){{
i = value;
j = value;// start (0,value) j++ till j=value
do
if(matrix[i][j] == num) {
isBoolean = true;
break;
}
else if((j == matrix.length-1)) {
j = value;
i++;
}
else if(matrix[i][j] != num){
j++;
}
while(isBoolean != true) ;
}
return isBoolean;
}
// if num is smaller than fourth pivot it means num is the fourth quarter,we limit the search to fourth quarter.
// number must be here because we verfied his existence in the start.
if(num < fourth_quarter_pivot){
i = value;
j = 0;// start (0,value) j++ till j=value
do
if(matrix[i][j] == num) {
isBoolean = true;
break;
}
else if((j == value)) {
j = 0;
i++;
}
else if(matrix[i][j] != num){
j++;
}
while(isBoolean != true) ;
}
return isBoolean;
}
}
What i tried to do:
find in which quarter the wanted number is in,after that check
the same quarter by moving j++ until it hits the limit,than i++
until found
with the limits changing for each quarter,i cant understand if run time complexity is O(n^2) or lower? and will it be better do create one dimensional array and and move on the quarter this way: move right until limit,one down,move left until limit and il have a sorted array and just binear search
If you can map an array to a matrix, you can use a normal binary search.
You can define the translation table to achieve that like this:
X = [0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3, ...]
Y = [0, 1, 1, 0, 2, 3, 3, 2, 2, 3, 3, 2, 0, 1, 1, 0, ...]
The final program looks like this.
static final int MAX_N = 64;
static final int MAX_NN = MAX_N * MAX_N;
static final int[] DX = {0, 0, 1, 1};
static final int[] DY = {0, 1, 1, 0};
static final int[] X = new int[MAX_NN];
static final int[] Y = new int[MAX_NN];
static { // initialize X and Y
for (int i = 0; i < MAX_NN; ++i) {
int x = 0, y = 0;
for (int t = i, f = 0; t > 0; ++f) {
int mod = t & 3;
x += DX[mod] << f; y += DY[mod] << f;
t >>= 2;
}
X[i] = x; Y[i] = y;
}
}
public static boolean Search(int [][] matrix, int num) {
int n = matrix.length, nn = n * n;
int lower = 0;
int upper = nn - 1;
while (lower <= upper) {
int mid = (lower + upper) / 2;
int value = matrix[X[mid]][Y[mid]];
if (value == num)
return true;
else if (value < num)
lower = mid + 1;
else
upper = mid - 1;
}
return false;
}
and
public static void main(String[] args) {
int[][] matrix = {
{1, 3, 7, 9},
{6, 4, 15, 11},
{36, 50, 21, 22},
{60, 55, 30, 26},
};
// case: exists
System.out.println(Search(matrix, 1));
System.out.println(Search(matrix, 60));
System.out.println(Search(matrix, 11));
// case: not exists
System.out.println(Search(matrix, 0));
System.out.println(Search(matrix, 70));
System.out.println(Search(matrix, 20));
}
output:
true
true
true
false
false
false
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;
}
I am writing a program and I can't seem to make the IF action loop and check all of the arrays in the main. My job is to figure out whether there exists any pair of numbers (i.e., any two elements) in this ascending sorted array that will add up to 20. All you need to do is to sum the values these two pointers point to and see if they are equal to 20, if so, output. otherwise, inspect the sum, if the sum is greater than 20,decrement the second pointer and if the sum is less than 20, increment the first pointer. cannot use the nested for loop approach!! Not sure how to fix this... i've been at it for hours and have handwritten it with no luck. thank you!!
// if val of arr at index i is smaller than at arr j, then return
// smaller value
// This function will inspect the input to find any pair of values that
// add up to 20
// if it find such a pair, it will return the *index* of the smallest
// value
// if it does not find such as pair, it will return -1;
public class SumExperiment {
public static int check_sum(int[] array) {
int i = array[0];
int y = array.indexOf(array.length); // need value # index of array.length to begin
//loop to repeat action
for (int arraysChecked = 0; arraysChecked < 5; arraysChecked++ )
{
if ( i + y == 20)
{
return i;
// System.out.print(array[i]);
}
else if ( i + y > 20)
{
y--; //index #y
}
else if (i + y < 20)
{
i++; //index #x
}
if ( i + y != 20)
{
return -1;
}
arraysChecked++;
}
return -1; //because must return int, but this isn't correct
}
public static void main(String[] args) {
int[] array1 = new int[] { 5, 7, 8, 9, 10, 15, 16 };
if (check_sum(array1) != 0)
System.err.println("TEST1 FAILED");
int[] array2 = new int[] { 3, 5, 8, 9, 10, 15, 16 };
if (check_sum(array2) != 1)
System.err.println("TEST2 FAILED");
int[] array3 = new int[] { 3, 4, 6, 9, 10, 14, 15 };
if (check_sum(array3) != 2)
System.err.println("TEST3 FAILED");
int[] array4 = new int[] { 6, 7, 8, 9, 10, 15, 16 };
if (check_sum(array4) != -1)
System.err.println("TEST4 FAILED");
System.out.println("Done!!!");
}
}
I think you are getting confused between the values in the array and the indices of the values. Here is a working version with variable names that make it easier to understand what's going on:
public static int check_sum(int[] array) {
int leftIndex = 0;
int rightIndex = array.length - 1;
for (int arraysChecked = 0 ; arraysChecked < 5 ; arraysChecked++) {
if (leftIndex == rightIndex) {
return -1;
}
int smallerValue = array[leftIndex];
int largerValue = array[rightIndex];
int sum = smallerValue + largerValue;
if (sum == 20) {
// Returns INDEX of smaller value
return leftIndex;
} else if (sum > 20) {
rightIndex--;
} else if (sum < 20) {
leftIndex++;
}
// NO NEED FOR THIS: arraysChecked++; (for loop does it for you)
}
}
I want to find all the pairs of numbers from an array whose sum is equal to 10, and am trying to improve upon this bit of code here:
for (int j = 0; j < arrayOfIntegers.length - 1; j++)
{
for (int k = j + 1; k < arrayOfIntegers.length; k++)
{
int sum = arrayOfIntegers[j] + arrayOfIntegers[k];
if (sum == 10)
return j + "," + k;
}
}
However, I'm having trouble moving through the array. Here's what I have so far:
int[] arrayOfIntegers = {0, 5, 4, 6, 3, 7, 2, 10};
Arrays.sort(arrayOfIntegers);
System.out.println(Arrays.toString(arrayOfIntegers));
int left = arrayOfIntegers[0];
int right = (arrayOfIntegers[arrayOfIntegers.length - 1]);
while (left < right)
{
int sum = left + right;
if (sum == 10) //check to see if equal to 10
{
System.out.println(left + "," + right);
}
if (sum > 10) // if sum is more than 10, move to lesser number
{
right --;
}
if (sum < 10) // if sum is less than 10, move to greater number
{
left++;
}
} // end of while
Try this code by passing the value of the sum and array in which you want to find the pair of elements equals to a given sum using one for loop
private void pairofArrayElementsEqualstoGivenSum(int sum,Integer[] arr){
List numList = Arrays.asList(arr);
for (int i = 0; i < arr.length; i++) {
int num = sum - arr[i];
if (numList.contains(num)) {
System.out.println("" + arr[i] + " " + num + " = "+sum);
}
}
}
You need to capture the values as well as the indexes:
int[] arrayOfIntegers = {0, 5, 4, 6, 3, 7, 2, 10};
Arrays.sort(arrayOfIntegers);
System.out.println(Arrays.toString(arrayOfIntegers));
int left = 0;
int right = arrayOfIntegers.length - 1;
while (left < right)
{
int leftVal = arrayOfIntegers[left];
int rightVal = (arrayOfIntegers[right]);
int sum = leftVal + rightVal;
if (sum == 10) //check to see if equal to 10
{
System.out.println(arrayOfIntegers[left] + "," + arrayOfIntegers[right]);
right --;
left++;
}
if (sum > 10) // if sum is more than 10, move to lesser number
{
right --;
}
if (sum < 10) // if sum is less than 10, move to greater number
{
left++;
}
} // end of while
output:
[0, 2, 3, 4, 5, 6, 7, 10]
0,10
3,7
4,6
This is sample code with javascrypt. Someone can use it
var arr = [0, 5, 4, 6, 3, 7, 2, 10]
var arr1 = arr;
for(var a=0; a<arr.length;a++){
for(var b=0; b<arr.length; b++){
if(arr[a]+arr[b]===10 && a!==b){
console.log(arr[a]+" + "+arr[b])
arr.splice(a,1);
}
}
}
Java - Using single loop
public static void findElements() {
List<Integer> list = List.of(0, 5, 4, 6, 3, 7, 2, 10);
for (int i = 0; i < list.size(); i++) {
int sum = 0;
if (i < list.size() - 1) {
sum = list.get(i) + list.get(i + 1);
if (sum == 10) {
System.out.println("Element: " + list.get(i) + "," + list.get(i + 1));
}
} else {
if (list.get(i) == 10) {
System.out.println("Element: " + list.get(i));
}
}
}
}