Having trouble getting the rest of the numbers in an Array. Java - java

I'm having trouble in getting the rest of the numbers after I sum up the first 3 elements. This is the question that it asks me: "Write a method that takes an array. return true if the sum of the first three elements in the array is less than the sum of the rest of the elements of the array."
Therefore 5 5 5 5 2 2 should be false. Since the first 3 numbers sum are greater than the sum of 5 2 2. My program returns true for this question and I would appreciate any help.
public static boolean sumThree(int [] myArray)
{
int sum = 0;
for(int i = 0; i < myArray.length; i++)
{
sum += myArray[i];
}
int sumof3E = myArray[0] + myArray[1] + myArray[2];
if(sum > sumof3E)
{
return true;
}
else if(sumof3E < sum)
{
return false;
}
else
{
return false;
}
}

You shouldn't include the first three elements of the array. Those have to be exclusive of the summation.
Change the for loop control variable to this:
for (int i = 3; i < myArray.length; i++) {
sum += myArray[i];
}
Also, you should remove the else if block from your code, because it's redundant (the first if statement checks for that condition):
else if(sumof3E < sum)
{
return false;
}
Alternatively, with the help of java 8 features, you can shorten your code into one line:
public static boolean sumThree(int [] myArray){
return Arrays.stream(myArray).limit(3).sum() < Arrays.stream(myArray).skip(3).sum();
}
note - with the alternative solution you won't get IndexOutOfBoundsException even if the array being passed in is empty.

There are two issues in your code:
1) You don't verify that the Array even has 3 elements before you index into it, which will potentially cause errors.
2) You're summing the entire array and comparing it to the sum of the first three elements... in your loop try initializing i = 3 in the loop initialization (assuming the array has at least 4 elements)
Pseudo code:
public static boolean sumThree(int [] myArray)
{
if (myArray.length < 4) { return false; }
var first = myArray[0] + myArray[1] + myArray[2];
var rest = 0;
for(int i = 3; i<myArray.length; i++) {
rest += myArray[i];
}
return first < rest;
}

the sum loop need to be altered to start from index 2 and else if is not required.
public static boolean sumThree(int[] myArray) {
int sum = 0;
for (int i = 3; i < myArray.length; i++) {
sum += myArray[i];
}
int sumof3E = myArray[0] + myArray[1] + myArray[2];
if (sum > sumof3E) {
return true;
}
else {
return false;
}
}

for clarity make a two loop then use the conditional operator or known as ternary operator for using thee if..else easily
int sum1=0;
int sum2=0;
for(int i=0;i<=2;++i)
{
sum1+=myArray[i];
}
for(int i=3;i<myArray.length;++i)
{
sum2+=myArray[i];
}
boolean myBool = (sum1>sum2)?false:true;
return myBool;

There is no need to keep going through the whole array at a time when first sum becomes less than sum of rest:
int sumf3 =0;
int sumRest=0;
for (int i = 0; i < myArray.length; i++)
{
if (i < 3){
sumf3 += myArray[i];
} else {
sumRest += myArray[i];
}
if(sumf3 < sumRest ){
return true;
}
}
return false;
P.S. and no need to check size of array before loop as well.

Related

Extracting Prime Numbers

I need to create a method that will mark the prime numbers and return the count of the prime numbers.
I went this far:
private static int[] extractPrimesNumbers(int[] array, int countOfPrimeNumbers) {
int[] primeNumber = new int[countOfPrimeNumbers];
int position = 0;
for (int j = 2; j < array.length; j++) {
for(int key : array) {
if(j == 2) {
array[position] = j;
}
boolean isDividedByJ = j % j == 0;
boolean isDividedbyTwo = j % 2 != 0;
if(isDividedByJ && isDividedbyTwo) {
array[position] = j;
position++;
j++;
}
}
I don't know how to mark none prime numbers. I was thinking the good way is marking the none prime with 0, then calculate the amount of value from position/index which are higher than 0.
Worth to mention this all things needs to be in one method using array. Can't use any standard solution for Prime using external boolean methods.
just return an array of the numbers that are prime, no need to mark. and the diff in the cont of the new array and the old one gives you a cont of the non prime as well.
Here is my solution approach.
1) First crete a very simple method to check whether a number is prime or not. See below:
public static boolean checkPrime(int number) {
if (number <= 1) {
return false;
}
System.out.println(number);
for (int i=2; i <= Math.sqrt(number); i++) {
if(number % i == 0) {
System.out.println(i);
return false;
}
}
return true;
}
2) Create another method that will loop through your array and call the above method:
public static int numOfPrimesInArray(int[] arr){
int counter = 0;
for (int num: arr){
if (checkPrime(num)) counter++;
}
return counter;
}
3) Then simply call this from your main method:
public static void main(String[] args){
int[] nums = {1,2,3,5,6,7,8,9,10};
int primes = numOfPrimesInArray(nums);
System.out.println(primes);
}
If I did not make any mistake when writing this shoul give you the number of primes in your array.
I solved the problem with Python. I tried a couple of alternatives and this one is the quickest. Still, I encountered a memory overflow at 1000000.
n = int(input("Type a number"))
primes = 0
for j in range(2,n+1):
for k in range(2,j):
if j%k==0:
primes = primes +1
#print(j)
break
print(n-1-primes)

Returning and Summing the Odd Numbers of an Array

I'm trying to add all the odd numbers in an array and return it. Any thoughts on what I'm doing wrong?
Example:
Input:
Array- [12,6,7,15,1]
It would return 23
public static int sumOdds(int[] numbers) {
sum = 0;
for(int i = 0; i < numbers.length; i++) {
if (numbers%2==0)
return 0;
else (numbers[i] % 2 != 0) {
sum += numbers;
return sumOdds;
}
}
public static int sumOdds(int[] numbers) {
int sum = 0;
for(int i = 0; i < numbers.length; i++) {
if(numbers[i] % 2 != 0) {
sum += numbers[i];
}
}
return sum;
}
This should work. return statements should not be within your if and else statements, as they will end the execution of the program immediately.
And a Java 8+ solution would be
public static int sumOdds(int[] numbers) {
return Arrays.stream(numbers).filter(n -> n % 2 == 1).sum();
}
There are a few issues here. First of all, the mod operation is not going to work on an array. It needs to be performed on a single number. Furthermore, you are immediately returning the sumOdds without allowing the entire loop to complete.
This would work.
public static int sumOdds(final int[] numbers) {
int sumOdds = 0;
for (int number : numbers) {
if (number % 2 != 0) {
sumOdds += number;
}
}
return sumOdds;
}
Or better yet, use streams.
int sumOdds = IntStream.of(12, 6, 7, 15, 1).filter(number -> number % 2 != 0).sum()

Finding the sum of numbers in an array - excluding the number 13 and the number directly after it

I would like to write a program in Java which, given an array, finds the sum of all the numbers in the array - with an exception! Since the number 13 is very unlucky, I propose that we shall completely exclude the number 13, and the number directly after 13, if it exists, from the total sum.
The program, which I shall call sum13 , should produce the following results from the following inputs (these are just a few examples):
sum13([1,2,2,1]) = 6 This one is normal; no 13's here.
sum13([5, 13, 2]) = 5 The 13 and the number directly after the 13 are excluded.
sum13([13, 13]) = 0 The array contains only 13's, so neither of them are included.
sum13([1, 2, 13, 2, 1, 13]) = 4 A slightly longer example of the expected output.
Here is the code which I came up with for sum13 :
public int sum13(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
// we start by adding all the non-13s to the sum
if (nums[i] != 13) sum += nums[i];
}
// now we go back and remove all the non-13s directly after a 13
for (int j = 0; j < nums.length; j++) {
// the outermost loop checks if the numbers are a 13
if (nums[j] == 13 && j < nums.length - 1) {
for (int k = j + 1; k < nums.length; k++) {
// this loop checks that the number after the 13 is not a 13
if (nums[k] != 13) {
sum -= nums[k];
break;
}
}
}
}
return sum;
}
The program above works, although it does look quite messy!
Is there a better way of writing such a program that doesn't include multiple loops and nested ifs?
Well, you use i as iterator. just make i++ when the current number is 13. This way, not only you don't add 13 to the sum but you also skip the next value.
public int sum13(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
// we start by adding all the non-13s to the sum
if (nums[i] != 13){
sum += nums[i];
}
else {
i++;
}
}
return sum;
}
Kepotx shows how to do it with a traditional for loop. You can also do it with a flag in an enhanced for loop:
public int sum13(int[] nums) {
int sum = 0;
boolean skipNext = false;
for (int num : nums) {
if (num == 13) {
skipNext = true;
} else {
if (!skipNext) {
sum += num;
}
skipNext = false;
}
}
return sum;
}
Live Example with the provided inputs and expected outputs.
Hopefully someone savvy with streams shows us the clever streams approach... :-) ...and Malte Hartwig did (although as he says, there's a not-best-practice in there).
Using an AtomicBoolean can shorten to loop considerably, and it gets even shorter when you use IntStream to sum:
public static int sum13(int[] numbers)
{
AtomicBoolean was13 = new AtomicBoolean(false);
return IntStream.of(numbers)
.filter(i -> !was13.getAndSet(i == 13) && i != 13)
.sum();
}
The big advantage is that AtomicBoolean.getAndSet(boolean) allows us to check whether the previous number was 13 and store whether the current number is 13 the same time.
Warning: As Hulk pointed out in the comment, is not the best practice to change the state of objects "outside" the stream. This can come back to haunt you if you try to use the stream in parallel, for example. It is possible to avoid using outside state here using a custom Collector, but this would make the code way too complicated for this particular problem.
As soon as number 13 arrives you need to skip the 13 and next char in the loop
public class HelloWorld{
public static void main(String []args){
int arr[] = {1, 2, 4, 2, 1, 13,10};
System.out.println(sum13(arr));
}
public static int sum13(int[] nums) {
int sum = 0;
int n = nums.length;
for (int i = 0; i < n; i++) {
if (nums[i] == 13){
i=i+2;
}
if(i<n){
sum += nums[i];
}
}
return sum;
}
}
Why not using ArrayList class? It has iterator() method implemented and the code could look like this:
int sum13 (ArrayList<Integer> a) {
Iterator<Integer> iter = a.iterator();
int n;
int sum=0;
while (iter.hasNext() ) {
n = iter.next();
if (n !=13)
sum = sum + n; /* n!=13 it will be added*/
else if (iter.hasNext() )
iter.next() /* n==13 not summing and skipping next */
}
return sum;
}

I am stuck on figuring out how to end the recursion loops as soon as the list number(s) is found

I am writing a program that, using an array list of given integers (listOfNumbers), will find if any combination of sums of these numbers will add up to another given integer (CompareTo). This program uses recursion. I am stuck on figuring out how to end the recursion loops as soon as the list number(s) is found. Thanks.
int sum = 0;
for(int i = listOfNumbers.size() - 1; i > -1; i--)
{
int backup = listOfNumbers.get(i);
listOfNumbers.remove(i);
for(int k = 0; k < listOfNumbers.size(); k ++)
{
sum += listOfNumbers.get(k);
}
if(sum == compareTo)
{
//IF THIS IS TRUE KILL ALL RECURSION
return listOfNumbers;
}
sum = 0;
answer(listOfNumbers, compareTo); //CREATE NEW RECURSION LOOP
listOfNumbers.add(i, backup);
}
//IF NO COMBINATION OF ARRAY LIST NUMBERS WILL
//ADD TO = COMPARETO, RETURN ORIGINAL LIST
return listOfNumbers;
Try to compare first, and then add or remove numbers in the list. If you remove numbers before the recursive call, in subsequent returns the condition isn't meet.
int sum = 0;
for(int i = listOfNumbers.size() - 1; i > -1; i--)
{
if(sum == compareTo)
{
//IF THIS IS TRUE KILL ALL RECURSION
return listOfNumbers;
}
else
{
int backup = listOfNumbers.get(i);
listOfNumbers.remove(i);
for(int k = 0; k < listOfNumbers.size(); k ++)
{
sum += listOfNumbers.get(k);
}
sum = 0;
answer(listOfNumbers, compareTo); //CREATE NEW RECURSION LOOP
listOfNumbers.add(i, backup);
}
}
//IF NO COMBINATION OF ARRAY LIST NUMBERS WILL
//ADD TO = COMPARETO, RETURN ORIGINAL LIST
return listOfNumbers;
In fact, I would put the obvious case (sum == compareTo) in the very top of everything, and then do the rest of the stuff.
for(int k = 0; k < listOfNumbers.size(); k ++)
{
sum += listOfNumbers.get(k);
}
if(sum == compareTo)
{
//IF THIS IS TRUE KILL ALL RECURSION
return listOfNumbers;
}
// DO THE REST OF OPERATIONS HERE....

Java 2d array counts zeros in column

I start learning programming about 4 days ago by myself and iam a lil bit stuck with 2d arrays. I try to challenging myself with tasks, like get from 2d array column with most zeros or atleast just count zeros, so far i get this far
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
for(j=0;j<a[0].length;j++) {
for(i=0;i<a.length;i++) {
if(a[i][j] >-1 || a[i][j]<1) {
s++;
System.out.println(s +"\t");
s = 0;
}
}
}
}
}
Can somebody explain me why result is always 1 and why it counts columns and rows in one row?
Suppose the condition enters into if(a[i][j] >-1 || a[i][j]<1) then you increase s by 1 then print it which gives 1 then you reassign it to s=0 so it gives same 1 each time.So remove the s=0 and place the printing line after end of loop
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
for(j=0;j<a[0].length;j++){
for(i=0;i<a.length;i++)
if(a[i][j] >-1 && a[i][j]<1){
s++;
}
System.out.println("Zero in column no. "+j+" is "+s +"\t");
s=0;
}
}
}
Demo
Result will be 1 because you're re-assigning 0 to s everytime. But the issue is not only that.
Firstly your condition is using wrong indices. Instead of a[i][j] you should use a[j][i] as you're traversing column-wise. Secondly:
if(a[j][i] >-1 || a[j][i]<1){
can be simply written as:
if(a[j][i] == 0) {
So the structure is the outer for loop will iterate over each column number. And for each column number, inner for loop will find count of 0. You've to maintain a max variable outside both the loops, to track the current max. Also, you've to use another variable inside the outer for loop to store the count for current column.
Everytime the inner for loop ends, check if current column count is greater than max. If yes, reset max.
int max = 0;
for(j=0;j<a[0].length;j++){
int currentColumnCount = 0;
for(i=0;i<a.length;i++) {
if(a[j][i] == 0) {
currentColumnCount++;
}
}
if (currentColumnCount > max) {
max = currentColumnCount;
}
}

Categories