java compare array elements - java

i have a problem with an exam test.
I have two arrays: int[] a, int[] b, with random values.
E1 return true if there are two elements of b greater then each element of a.
How do I write "there are two elements of b greater than each element of a"?
I can write "there is ONE elements of b greater than each element of a" in this way:
public static boolean e1(int[] a, int[] b){
boolean ris = false;
boolean ogniA = true;
int i = 0;
if(a != null && a.length != 0){
while(ogniA && i<a.length){
boolean es1= false;
boolean es2 = false;
int j = 0;
if(b!= null && b.length != 0){
while(!es1 && j < b.length){
if(j%2!=0){
es1 = a[i] < b[j];
}
j++;
}ris = es1 ;
}
i++;
}
}
return ris;
I need something like this. Thanks for help.

So I would solve this problem, by dividing it into smaller problems.
1st you need to find the 2 biggest values in the first array.
I presume this should be abstract and work for every array
Code (using the example from Andronicus):
"E1 return true if there are two elements of b greater then each element of a"
Basically you need the second greater value of array B and the greater value of the array A
int[] a = {3, 5, 7, 9};
int[] b = {2, 4, 3, 10, 11};
int secondGreatestOfB = IntStream.of(b).boxed()
.sorted(Comparator.reverseOrder())
.limit(2)
.sorted(Comparator.naturalOrder())
.limit(1)
.findFirst().orElse(0);
System.out.println(areTheTwoBiggestNumbersOfArrayBbiggerThanAllValuesFromArrayA(a, secondGreatestOfB));
private static boolean areTheTwoBiggestNumbersOfArrayBbiggerThanAllValuesFromArrayA(int[] a, int secondGreatestOfArrayB) {
return secondGreatestOfArrayB > IntStream.of(a).max().orElse(0);
}

Related

How do you check an array to see if it has more even values than odd?

I'm working on a project and one of the things I need to do is create a method where it takes in an int array and checks it to see if it has more even than odds. The method needs to be boolean and take in an int[]
I know I need to use a for statement with something like
for (int i = 0; i < hasMoreEvenThanOdd.length; i++)
or
for (int values : hasMoreEvenThanOdd)
But I'm confused on what the for loop would contain something like this?
if (numerator % denomEven == 0) {
boolean res = true;
return res;
} else if (numerator % denomOdd == 0) {
boolean res = true;
return res;
} else {
boolean res = false;
return res;
}
and I'm not sure how to get the math to check out in the end.
You can iterate over this array and filter only even numbers, and then check whether their count is more than half of the array:
public static boolean hasMoreEvenThanOdd(int[] arr) {
return Arrays.stream(arr).filter(i -> i % 2 == 0).count() > arr.length / 2;
}
// test
public static void main(String[] args) {
System.out.println(hasMoreEvenThanOdd(new int[]{2, 3, 4, 5, 6, 7})); // false
System.out.println(hasMoreEvenThanOdd(new int[]{2, 3, 4, 5, 6})); // true
System.out.println(hasMoreEvenThanOdd(new int[]{2, 3, 4, 5})); // false
System.out.println(hasMoreEvenThanOdd(new int[]{2, 3, 4})); // true
System.out.println(hasMoreEvenThanOdd(new int[]{2, 3})); // false
}
You should do something like that:
public boolean checkIfHasMoreEvenThanOdds(int[] hasMoreEvenThanOdds) {
int even = 0;
int odds = 0;
for (int i = 0; i < hasMoreEvenThanOdds.length; i++) {
if (hasMoreEvenThanOdds[i] % 2 == 0) {
even++;
} else {
odds++;
}
}
if (even > odds) {
return true;
}
return false;
}
The method will return true if it has more even than odds, and false if the opposite. This code "parse" the array, and checks element by element if it is or not odd, and increments in a variable (odd or even). By final, it checks which one is greater than, and return in base of that.
First if
Sum all evens
Second if
Sum all odds
Compare if evens is more than odds
Return true is true
I'm not sure if you mean counting the number of even and odd values in your array.
If so, this might help you:
for(..........) {
if (hasMoreEvenThanOdd[i] % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
return even > odd;
What you need to do is iterate over all elements in the array for instance using:
for (int values : hasMoreEvenThanOdd)
or
for (int i = 0; i < hasMoreEvenThanOdd.length; i++)
then keep track of the even numbers for instance:
if (values % 2 == 0)
total_even_numbers++;
Outside the loop:
In the end, to get the total of odd numbers you just need to subtract from the size of the array (i.e., hasMoreEvenThanOdd.length) the total of even numbers that you have found.
Finally, just compare the two values, and return accordingly.
An example:
public boolean hasMoreEvenThanOdd(int[] values){
int even = 0;
for (int value : values)
if (value % 2 == 0)
even++;
return even > (values.length - even);
}
As pointed out in other comments, you would need to maintain two variabled nEven (number of even numbers) and nOdd (number of odd numbers) while iterating the array and increment depending upon whether item at a specified index is even or odd. If you're using Java 8+, you can use streams to filter odd/even numbers and count them:
public static boolean containsMoreEvenThanOdd(int[] array) {
long nEven = Arrays.stream(array).filter(i -> i % 2 == 0).count();
long nOdd = Arrays.stream(array).filter(i -> i % 2 != 0).count();
return nEven > nOdd;
}
separate even and odd values into two groups with Collectors.partitioningBy
public boolean checkIfHasMoreEvenThanOdds(int[] evenAndOdds) {
Map<Boolean, List<Integer>> map = IntStream.of( evenAndOdds )
.boxed().collect( partitioningBy( n -> (n & 1) == 0 ) );
return(map.get( true ).size() > map.get( false ).size());
}

Sorting an array through my method error Java

I am new to programming and I need some help. I am supposed to make my own method checking if one array has a subsequence to another one. Meaning if the first array is {1, 2, 3, 4, 5} and the second one is {1, 2, 3} the second one is a subsequence of the first. However if the first is {1, 2, 3, 4, 5} and the second is {1, 4, 5} it is not a subsequence, so the second has to be in order as well.
I have tried to do it this way through strings:
private static boolean subs(int[] array, int[] subsequence) {
String a = Arrays.toString(array);
String b = Arrays.toString(subsequence);
boolean c = false;
if (a.equals(b)) {
return true;
}
for (int i = 0; i < a.length(); i++) {
if (!(b.equals(a.substring(i, b.length() + i)))) {
c = false;
} else {
c = true;
break;
}
}
if (c == true) {
return true;
} else {
return false;
}
}
However I get 3 errors, here is the printscreen :
And here is how I am testing the method:
int[] fArray = { 1, 2, 3, 4, 5 };
int[] tempArray = { 2, 3, 4 };
System.out.println(subs(fArray, tempArray));
I know I probably made a lot of mistakes, so hit me with it.
Here:
for (int i = 0; i < a.length(); i++) {
if (!(b.equals(a.substring(i, b.length() + i)))) {
Your outer loop condition makes sure that i stays smaller than a.length().
But then you try to take a substring within a that goes for b.length()+i!
In other words: for any b.length() > 0 ... that code will always try to fetch characters beyond the end of a.
And there is also a bug in your result handling - it seems very much possible that you assign
c = true;
at some point; to later overwrite that with
c = false;
In other words: your code forgets that he found a match! The much easier solution: when hitting the true case, just return true there! And if you don't return within the loop; you just return false in the end.
Finally: although it seems like a cool idea to turn your arrays into strings ... that doesn't really buy you anything. You are still doing the work of going through the first array and checking if the second is in there. Writing code that does that directly on the provided arrays ... would not be much different from what you got there with your "string detour".
Edit: when using multiple returns in a method, you simply have to make sure that any possible path has a return statement. In your case:
boolean subs(... {
if equal strings
return true
for i as index in a
if a.substring equals b
return true
return false
The issue is that fArray as String has more chars than tempArray as string, so when you start to compare char by char from a to b, is a given point where the index is going beyond the size of b and then you get the exception
Your problem line is: if (!(b.equals(a.substring(i, b.length() + i))))
Why?
Lets assume your a.length() is equals 6 and b.length() is equals 2 now your looping for (int i = 0; i < a.length(); i++) with i going from 0 to 5.
Now lets say your loop executed 3 times and i is equals 4now.
Now when you call a.substring(4, b.length() + 4) with b.length() == 2 => a.substring(4, 6) but your string only goes from 0 to 5
The simplest way to do this would be to use Collections.indexOfSubList:
private static boolean subs(int[] array, int[] subsequence) {
return Collections.indexOfSubList(toList(array), toList(subsequence)) >= 0;
}
private static List<Integer> toList(int[] array) {
List<Integer> list = new ArrayList<>(array.length);
for (int num : array) {
list.add(num);
}
return list;
}
//*******************************************************************
// NOTE: please read the 'More Info' tab to the right for shortcuts.
//*******************************************************************
import java.lang.Math; // headers MUST be above the first class
import java.util.Arrays;
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
int[] fArray = { 1,2,3,4,5 };
int[] tempArray = { 2,3,4 };
System.out.println(subs(fArray, tempArray));
}
private static boolean subs(int[] array, int[] subsequence) {
String a = Arrays.toString(array);
String b = Arrays.toString(subsequence);
boolean c = false;
if (a.equals(b)) {
return true;
}
String ss = b.substring(1,b.length()-1);
for (int i = 0; i < 8; i++) {
String substr =a.substring(i, ss.length()+i);
if (!(ss.equals( substr ))) {
System.out.println("heelllo");
c = false;
} else {
c = true;
break;
}
}
if (c == true) {
return true;
} else {
return false;
}
}
}

what is wrong with the logic of my method to add the odd numbers of an array

I am trying to write a method that will take in the array int[] numbers and return the sum of all of the odd numbers in the array. I am not sure why it is not returning the correct value. Currently it returns "3" when it should be returning "9".
public static void main(String[] args) {
int[] numbers = { 2, 1, 5, 3, 0 };
System.out.println(oddballsum(numbers));
}
public static int oddballsum(int array[]) {
int sumodds = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) { sumodds = +(array[i]);}
}
return sumodds;
}
sumodds =+ (array[i]) means "assign the value of array[i] to sumodds". The + and the () make no difference - it's semantically identical to sumodds = array[i]. Use this if you just want the last odd value in the array.
sumodds += array[i] means "increase the value of sumodds by array[i]. Use this if you're trying to sum the odd values in the array.
The reason of the error is in this piece of code...
if (array[i] % 2 != 0) {
sumodds = +(array[i]);
}
you are not summing or accumulating you are just assigning the value with a positive sign
at the end, your code is just returning the last odd value found in the array...
you have to do instead something like:
if (array[i] % 2 != 0) {
sumodds += array[i];
}
If you write too much code, you have more chance to go wrong, you should use java 8 Streams:
int sumOdd = Arrays.stream(array).filter(t -> t%2==1).sum();
System.out.println(sumOdd);
The problem was with your addition operator =+. It should be += if you want to add and assign the new value to the same variable. Please refer below working code.
public static void main(String[] args) {
int[] numbers = {2, 1, 5, 3, 0};
System.out.println(oddballsum(numbers));
}
public static int oddballsum(int array[]) {
int sumodds = 0;
for(int element : array) {
if(element % 2 != 0) {
sumodds += element;
}
}
return sumodds;
}

Find whether 2 arrays are permutations of each other recursively in Java

I need to build a recursive function that returns true if array a is permutation of array b and false otherwise.
public static boolean isPermutation (int [] a, int [] b)
Can add arguments to the function.
Can NOT use local array.
Can NOT use loops.
Can NOT use library functions.
Can NOT change the arrays.
Does anyone have an idea?
This should work for you, it's basically a loop implemented with recursion. This should execute in quadratic time.
public static boolean isPermutation(int[] a, int[] b, boolean[] ataken, boolean[] btaken, int iter, int totalTaken, int aidx, int bidx)
{
if (a.length != b.length) return false;
// totalTaken is a count of the number of matches we've "taken"
if(totalTaken == a.length) return true;
// don't "loop" b
if(bidx >= b.length)
{
return false;
}
// we should loop through a... this will yield a quadratic runtime speed
if(aidx >= a.length)
{
if (iter < a.length)
{
return isPermutation(a, b, ataken, btaken, iter + 1, totalTaken, 0, bidx);
}
// finished our loop, and "totalTaken" wasn't the whole array
return false;
}
// found a match for this b[bidx]
if(a[aidx] == b[bidx] && !ataken[aidx] && !btaken[bidx])
{
ataken[aidx] = true;
btaken[bidx] = true;
return isPermutation(a, b, ataken, btaken, iter, totalTaken + 1, aidx + 1, bidx + 1);
}
// loop through a
return isPermutation(a, b, ataken, btaken, iter, totalTaken, aidx + 1, bidx);
}
You call it with ataken and btaken arrays filled with false, but of the same length as a and b, respectively.
var isPerm = staticClassName.isPermutation(a, b, ataken, btaken, 0, 0, 0, 0);
The idea is the following: it's a permutation if the product of all members in a is equal to the product of all members in b AND the sum of all members in a is equal to the sum of all members in b.
Write a recursive helper function that will allow you to compute these sums and products and compare them.
Complexity: O(n)
Caveat: can overflow if dealing with many large numbers
See the comments for an important point made by John Carpenter

Divisors inside an array

I need to write a method that takes an array of integers and checks for every element if all its divisors (except the number itself and 1) are present in this array. If yes, the method will return true.
For example, the following array will return true:
4,5,10,2
I can't think of something efficient enough to be implemented. Could you guys help me out here?
I've been thinking to iterate through every element in the array, search for all of its divisors, put them on array, return the array and then compare to the elements in the original array.
This is a possible solution and it could work but I want to know of other possible solutions.
EDIT: Here is a code I've came up with but it is super slow. Could you guys help me optimise it a little bit?:
import java.util.Arrays;
public class Divisors {
public static void main(String[] args) {
int[] numbers = { 4, 5, 10, 2 };
boolean flag = true;
for (int num : numbers) {
if (num % 2 != 0) {
for (int subNum = 1; subNum < num / 2; num += 2) {
if(num%subNum == 0 && subNum != 1) {
if(!Arrays.asList(numbers).contains(subNum)) {
flag = false;
}
}
}
} else {
for (int subNum = 1; subNum < num / 2; num++) {
if(num%subNum == 0 && subNum != 1) {
if(!Arrays.asList(numbers).contains(subNum)) {
flag = false;
}
}
}
}
}
System.out.println("Result is: "+flag);
}
}
I think the following alogorithm solves your need. I have tested it on a few cases and it seems to work.
For example the array:
int[] set = {2, 3, 4, 5, 7, 10, 11, 15, 18, 35};
executes instantly giving the answer "true". Try removing the 7 which will give the answer "false".
You call it thus:
reduce(set, 0, 0)
The principle used is to iterative recursively through the array, reducing the array through factorization of the array by each element. If you find an element which is smaller than the last factor, it means it can't be factored. This only works if the array is sorted. Once you reach the end of the array, you know all elements have been factored.
private static boolean reduce (int[] set, int index, int factor) {
// NOTE: set must be a sorted set of integers
if (index == set.length) {
return true;
} else {
int divisor = set[index];
if (divisor != 1) {
if (divisor < factor) return false;
for (int i = index; i < set.length; i++) {
while ((set[i]%divisor) == 0) {
set[i] = set[i]/divisor;
}
}
return reduce(set, index+1, divisor);
} else {
return reduce(set, index+1, factor);
}
}
}
See if it works, let me know if you run into any problems.
1.Iterate through every element in the array
2. Find in for loop its divisor
3. While doing 2), check for every divisor if it is contained in the array. If false - return false.

Categories

Resources