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");
}
}``
Related
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 want to single out only positive numbers in one line and only negative numbers in one line, but they only show one by one with the text.
Here's my code:
int[] array = {2, -5, 4, 12, 54, -2, -50, 150};
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
System.out.println("Less than 0: " + array[i]);
} else if (array[i] > 0) {
System.out.println("Greater than 0: " + array[i]);
}
}
You are currently printing a line for each element (and whether it is less than 0 or greater than 0), instead I would use an IntStream and filter() it for the desired elements (and collect those with Collectors.joining()). Like,
int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
System.out.println("Less than 0: " + IntStream.of(array) //
.filter(x -> x < 0).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
System.out.println("Greater than 0: " + IntStream.of(array) //
.filter(x -> x > 0).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
Outputs
Less than 0: -50, -5, -2
Greater than 0: 2, 4, 12, 54, 150
You could achieve the same result with a pair of StringJoiner(s) a for-each loop and (just because) formatted io. Like,
int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
StringJoiner sjLess = new StringJoiner(", ");
StringJoiner sjGreater = new StringJoiner(", ");
for (int x : array) {
if (x < 0) {
sjLess.add(String.valueOf(x));
} else if (x > 0) {
sjGreater.add(String.valueOf(x));
}
}
System.out.printf("Less than 0: %s%n", sjLess.toString());
System.out.printf("Greater than 0: %s%n", sjGreater.toString());
Since you sorted the values, you know all negative values come before the positive values, so you start printing values and then switch to new line when you encounter the first positive value.
E.g. like below, which can also handle an array of all negative values, an array of all positive values, and even an empty array.
This only uses Java constructs you've already shown you know.
int[] array = {2, -5, 4, 12, 54, -2, -50, 150};
Arrays.sort(array);
for (int i = 0, iFirstPositive = 0; i < array.length; i++) {
if (array[i] < 0)
iFirstPositive = i + 1; // Assume index of first positive value is next
if (i == iFirstPositive) {
if (i != 0)
System.out.println(); // End line of negative values
System.out.print("Greater than 0: "); // Start line of positive values
} else if (i == 0) {
System.out.print("Less than 0: "); // Start line of negative values
} else {
System.out.print(", ");
}
System.out.print(array[i]);
}
if (array.length != 0) {
System.out.println(); // End line if anything printed
}
Output
Less than 0: -50, -5, -2
Greater than 0: 2, 4, 12, 54, 150
Simpler, but slightly less optimal, you can also just do it with two loops:
int[] array = {2, -5, 4, 12, 54, -2, -50, 150};
Arrays.sort(array);
System.out.print("Less than 0:");
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
System.out.print(" " + array[i]);
}
}
System.out.println();
System.out.print("Greater than 0:");
for (int i = 0; i < array.length; i++) {
if (array[i] > 0) {
System.out.print(" " + array[i]);
}
}
System.out.println();
Output
Less than 0: -50 -5 -2
Greater than 0: 2 4 12 54 150
Do something like this:
Arrays.sort(array);
String negative = "Less than 0: ";
String positive = "Greater than 0: ";
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
negative.concat(array[i] + ",");
}
else (array[i] > 0) {
positive.concat(array[i] + ",");
}
}
System.out.println(positive);
System.out.println(negative);
Store the values in a string and then print them after the for loop.
This is a perfect use case for streams:
System.out.println(Arrays.stream(array).filter(n -> n < 0).collect(Collectors.toList()));
I tried to change your code as little as possible.
int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
boolean firstHalf = true;
System.out.print("Less than 0: ");
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
System.out.print(array[i] + " ");
} else if (array[i] > 0) {
if (firstHalf){
System.out.print("\nGreater than 0: ");
firstHalf = false;
}
System.out.print(array[i] + " ");
}
}
I think using of partitioningBy (that introduced in java 8) is exactly for this situation. you don't need to sort array too.
Map<Boolean,List<Integer>> map = IntStream.range(0,array.length)
.mapToObj(i->array[i])
.collect(Collectors.partitioningBy(a->a>0));
print positive number
map.get(true).forEach(integer -> System.out.print(integer+","));
print negative number
map.get(false).forEach(integer -> System.out.print(integer+","));
if you want to sort it you can do it like bellow.
map.get(false).stream().sorted()....
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)
}
}
It prints all the even numbers, but is only printing the odd numbers 13 and 11. Not 3 or 5. Does anyone know what I am doing wrong? Thanks in advance.
public class ReadjustingArray {
public static void main (String[]args){
int[]A={13,3,4,6,8,5,10,11};
int temp=0;
for (int i=0; i< A.length; i++){
if (A[i] % 2 ==0){
temp=A[i];
A[i-1] = A[i];
temp=A[i];
System.out.print(A[i] + " ");
}
}
for (int j=0; j< A.length; j++){
if (A[j] % 2 !=0){
System.out.print(A[j] + " ");
}
}
}
}
Don't modify the array with your first loop, then your second loop will work as you expect. Alternatively, in Java 8+, you might use IntStream and filter like
int[] A = { 13, 3, 4, 6, 8, 5, 10, 11 };
IntStream.of(A).filter(x -> x % 2 == 0)
.forEachOrdered(x -> System.out.printf("%d ", x));
IntStream.of(A).filter(x -> x % 2 != 0)
.forEachOrdered(x -> System.out.printf("%d ", x));
System.out.println(); // <-- Adds a new line (and an implicit flush)
this can help you.
public static void main(String[] args) {
int[] A = { 13, 3, 4, 6, 8, 5, 10, 11 };
for (int i : A) {
if (isEven(i)) {
System.out.println(i + " is even");
} else {
System.out.println(i + " is odd");
}
}
}
static boolean isEven(int number) {
if ((number % 2) == 0) {
return true;
}
return false;
}
There is no need to modify the Array. Just print the odds in the same way you are printing the evens. Use their corresponding comparative logic.
I am separating the Odd Numbers and Even Numbers from an Arrays.
My Code is:
public class EvenAndOdd {
public static void main (String[] args)
{
int countEven = 0;
int countOdd = 0;
int[] myArray = {1, 2, 3, 4, 5, 6, 7};
for(int i : myArray) {
if(i%2 == 0) {
countEven++;
System.out.println("EVEN numbers: " + i);
}
else {
countOdd++;
System.out.println("ODD numbers: " + i);
}
}
System.out.println("Total Even Number: " + countEven);
System.out.println("Total Odd Number " + countOdd);
}
}
Getting correct result from above Code. But i want to now compare every Odd Number with Every Even Number, if any of Even number is greater than odd Number then return o and no odd Number is greater than Even number return 1.
code is as below
for(int i=0;i<myArray.length;i+=2)
{
j=i+1; //odd number
//if even number is greater
if(myArray[i]>=myArray[j])
System.out.println(1);
else //if odd is greater
System.out.println(0);
}
I don't understand "if any even number is greater than an odd number return 0" and "if no odd number greater than even return 1" because there is a 7 which is greater than, say 2, but there is a 4 which is greater than 3, or 1. So this means both cases match so there is a flaw in your logic, or poor phrasing of the question. In any case, you might find this useful
import java.util.*;
import java.lang.*;
import java.io.*;
class EvenAndOdd{
public static void main(String[] args){
int countEven = 0;
int countOdd = 0;
int result = 0;
int[] myArray = {1, 2, 3, 4, 5, 6, 7};
List<Integer> evens = new ArrayList<Integer>();
List<Integer> odds = new ArrayList<Integer>();
for(int i : myArray){
if(i%2 == 0) {
countEven++;
System.out.println("EVEN numbers: " + i);
evens.add(i);
}
else {
countOdd++;
System.out.println("ODD numbers: " + i);
odds.add(i);
}
}
for(int i : evens){
for(int j : odds){
if(i > j)
result = 1;
else
result = 0;
}
}
System.out.println("Result: " + result );
}
}