Sum of integers in an array - java

So, basically, the questions asks me to find the sum of the numbers in an array. Except the number '13' is very unlucky, so it does not count '13' and the number that come immediately after a '13'.
This is what I did:
public int sum13(int[] nums) {
int d = 0;
int sum = 0;
for (int i=0;i<nums.length;i++){
if(nums[i] == 13){
d = i;
break;
}
else{
d = nums.length;
}
}
for(int i=0;i<d;i++){
sum = sum + nums[i];
}
return sum;
}
Even though I pass most of the tests, I still can't understand how to exclude the number right next to the 13 from the sum.
For example, sum13({1, 2, 2, 1, 13}) → 6 PASSES!
sum13({13, 1, 13}) → 0 PASSES!
But, sum13({13, 1, 2, 13, 2, 1, 13}) → 3 RETURNS 0 instead as it stops at the first instance of 13.

Why are you using two loops? If the number is 13, just don't add it or the next number to the sum, like this:
public int sum13(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 13) {
i++;
} else {
sum = sum + nums[i];
}
}
return sum;
}

As per your question you exclude if the number is 13 & its immediate successor. So when you find 13 increment the loop counter once more:
for(int i=0;i<nums.length;i++){
if(nums[i] == 13) {
i++;
}
else {
sum = sum + nums[i];
}
}
This will naturally skip the next element of 13, if there's one within the array.

How about summing directly in the first for loop? Shorter, easier and faster way :)
public int sum13(int[] nums) {
int sum = 0;
for (int i=0;i<nums.length;i++){
if (nums[i] != 13) {
sum += nums[i];
} else {
i++;
}
}
return sum;
}

Did you hear what continue does?
if(nums[i] == 13){
d = i;
continue;
}

public int sum13(int[] nums) {
boolean skip = false;
int sum = 0;
for (int i=0;i<nums.length;i++){
if(nums[i] == 13){
skip=true;
continue;
}
else{
if(skip) {
skip=false;
continue;
}
sum+=nums[i];
}
}
return sum;
}

What you are actually doing is stopping at the first occurrence of 13.
try this:
public int sum13(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 13) {
i++;
} else {
sum += nums[i];
}
}
return sum;
}
I didn't test it but it should work...
Cheers!

Try this
public int mySum(int[] nums, int except) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += (nums[i] == except) ? 0: nums[i];
}
return sum;
}
Then
mySum(nums, 13)

Try this.
public int sum(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length;) {
if (nums[i] == 13)
i = i + 2;
else {
sum = sum + nums[i];
i++;
}
}
return sum;
}

use the continue; statement when the value equals to 13.
public int sum13(int[] nums) {
int sum = 0;
for (int i=0;i<nums.length;i++){
if(nums[i] == 13){
continue;
}
else{
sum = sum + nums[i];
}
}
return sum;
}

Related

Return Maximum Sum SubArray from set of elements in an array Problem

public class MaxSumSubArray
{
public int findSum (int[] arr)
{
int maxSum;
//This covers when we have just one element
if(arr.length == 1) {
maxSum = arr[0];
} else {
maxSum = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
int sum = arr[i]; // -1
for (int j = i + 1; j < arr.length; j++) {
// This is the case when your new elem is greater than the sum of prev elements
if(arr[j] > sum + arr[j]) {
sum = arr[j];
} else {
sum = sum + arr[j];
}
if (sum > maxSum) {
maxSum = sum;
}
}
}
}
return maxSum;
}
public static void main(String[] args) {
int[] arr = {-2,1,-3,4,-1,2,1,-5,4};
MaxSumSubArray subArray = new MaxSumSubArray();
System.out.println("MAx sum is:"+ subArray.findSum(arr));
}
}
I have written this code for maximum Sum subarray, I am using brute force approach.
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
This code is working for almost every set of input except one [-1,-2]. Can somebody help which I am missing here. Thanks
You should not reinitialize the sum variable in the second loop, you should choose the largest value after each add arr[j] to sum.
public int findSum (int[] arr)
{
int maxSum;
//This covers when we have just one element
if(arr.length == 1) {
maxSum = arr[0];
} else {
maxSum = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
int sum = arr[i]; // -1
if (sum > maxSum) {
maxSum = sum;
}
for (int j = i + 1; j < arr.length; j++) {
sum = sum + arr[j];
if (sum > maxSum) {
maxSum = sum;
}
}
}
}
return maxSum;
}

How do I make a triangle of stars and counts the number of stars?

I wrote the program to print a triangle of stars and also, the sum of the stars forms the triangle. When I make the call tringle(3), it should print as the following,
***
**
*
And, also it should count the sum as 6 and returns it. However, the code is not working as expected that I have provided following,
public static int triangular(int n) {
int count = 0;
count = triangular(n, count);
return count;
}
public static int triangular(int n, int count_){
int count = count_;
if(n == 0)
return count;
if(n < 0)
return -1;
for (int i = 0; i < n; i++) {
System.out.print("* ");
count = count + 1 ;
if(i == n){
return triangular(n-1, count);
}
}
System.out.println();
return count;
}
How do i improve the code ? Now, it prints
* * *
3
Please, advise.
You don't need more than one parameter... 3 + 2 + 1 + 0 = 6.
public static int triangular(int n){
if(n <= 0) return 0;
for (int i = 0; i < n; i++) {
System.out.print("* ");
}
System.out.println();
return n + triangular(n - 1);
}
Here's an iterative approach. Also, the number of stars can be calculated with the formula n(n+1)/2:
public static int triangular(int n) {
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
System.out.print("*");
}
System.out.println();
}
return n * (n + 1) / 2;
}
triangular(4):
****
***
**
*
10
It has an issue with the for loop and I changed the code. It works fine now and here it is:
public static int triangular(int n) {
int count = 0;
count = triangular(n, count);
return count;
}
public static int triangular(int n, int count_){
int count = count_;
if(n == 0)
return count;
if(n < 0)
return -1;
for (int i = 0; i < n; ) {
System.out.print("* ");
count = count + 1 ;
i++;
if(i == n){
System.out.println();
return triangular(n-1, count);
}
}
return count;
}

All the perfect numbers between 1 and 500 program algorithm says it works but it doesn't

I am writing a program to tell me all the perfect numbers between 1 and 500 and I made this program, but it doesn't work although the algorithm makes sense.
import java.util.Scanner;
class allPerfect {
public static void main(String args[]) {
int sum = 0;
System.out.println("All perfect numbers between 1 and 500 are:");
for (int j = 0; j != 501; j++) {
for (int i = 1; i < j; i++) {
if (j % i == 0) {
sum = sum + i;
if (sum == j) {
System.out.println(j);
sum = 0;
} else {
sum = 0;
}
}
}
}
}
}
What's wrong here?
Please find the comment in-line.
class allPerfect {
public static void main(String args[]){
int sum;
System.out.println("All perfect numbers between 1 and 500 are:");
for(int j = 1; j!=501; j++){
sum = 0; //**You should reset the sum at the start of the inner loop.**
for(int i = 1; i < j; i++ ){
if(j % i == 0) {
sum = sum + i;
}
}
if(sum == j) { //------ statement-1
System.out.println(j);
}
}
}
}
statement-1 you check the sum of all the divisor is equal to the number, after summing up for all the numbers less than j.
You can ignore all the odd number (j) in outer loop, because odd perfect number does not exist. To be precise: it is not known that odd perfect number exists.
You are resetting sum before you finish finding all of a numbers divisors.
for(int i = 1; i < j; i++ ){
if(j % i == 0){
sum = sum + i;
if(sum == j){
System.out.println(j);
sum = 0;
}else{
sum = 0;
}
}
}
You should do the if(sum == j) only after you exit the inner for loop.

check number of maximum and minimum element in a array

I am trying to check whether the given array has equal number of maximum and minimum array element. If their number are equal should return 1 else return 0. But instead of which return always zero.
Could you please help me?
public class MaxMinEqual {
public static void main(String[] args) {
System.out.println(MaxMinEqual.ismaxminequal(new int[]{11, 4, 9, 11, 8, 5, 4, 10}));
System.out.println(MaxMinEqual.ismaxminequal(new int[]{11, 11, 4, 9, 11, 8, 5, 4, 10}));
}
public static int ismaxminequal(int[] a) {
int maxcount = 0;
int mincount = 0;
int largest = a[0];
for (int i = 0; i < a.length; i++) {
if (a[i] > largest) {
largest = a[i];
}
if (a[i] == largest) {
maxcount = maxcount + 1;
}
}
int smallest = a[0];
for (int j = 0; j < a.length; j++) {
if (a[j] < smallest) {
smallest = a[j];
}
if (a[j] == smallest) {
mincount = mincount + 1;
}
}
if (maxcount == mincount) {
return 1;
} else {
return 0;
}
}
}
You did not reset maxcount and mincount when you find a greater or smaller value.
public static boolean isMaxMinEqual(int[] a) {
int maxcount, mincount = 0;
int largest, smallest = a[0];
for (int i = 0: a) {
if (i > largest) {
largest = i;
maxcount = 0;
}
if (i == largest) {
maxcount++;
}
if (i < smallest) {
smallest = i;
mincount = 0;
}
if (i == smallest) {
mincount++;
}
}
return maxcount == mincount;
}
Not sure if you're supposed to learn this without Data Structures, but why not take advantage of an Algorithm Efficiency Technique called presorting.
We could do something like this:
public static int ismaxminequal(int[] a) {
Arrays.sort(a);
This puts the smallest elements at the 'head' of the array and the largest elements at the 'tail'.
So, now, we must iterate from both ends to see how many of each are available (max and min).
int num_min = 1;
int num_max = 1;
int cur_value = 0; //holds a reference for comparison
cur_value = a[0];
for (int i = 1; i < a.length; i++) {
if (a[I] == cur_value)
num_min++;
else
break;
}
cur_value = a[a.length - 1];
for (int i = a.length - 1; i > 0; I--) {
if (a[I] == cur_value)
num_min++;
else
break;
}
if (num_max == num_min) {
return 1;
} else {
return 0;
}
}
}
Java 8 way. Very readable and with big arrays can be quicker that O(N) single thread implementation.
public boolean isMaxMinEqual(int[] a) {
int max = Arrays.stream(a).parallel().max().getAsInt();
int min = Arrays.stream(a).parallel().min().getAsInt();
long maxCount = Arrays.stream(a).parallel().filter(s -> s == max).count();
long minCount = Arrays.stream(a).parallel().filter(s -> s == min).count();
return maxCount == minCount;
}

Java > Array-2 > zeroMax

my code only misses 5 cases and i dont know why, somebody help me.
problem
Return a version of the given array where each zero value in the array
is replaced by the largest odd value to the right of the zero in the
array. If there is no odd value to the right of the zero, leave the
zero as a zero.
zeroMax({0, 5, 0, 3}) → {5, 5, 3, 3}
zeroMax({0, 4, 0, 3}) → {3, 4, 3, 3}
zeroMax({0, 1, 0}) → {1, 1, 0}
my code
public int[] zeroMax(int[] nums) {
int acum = 0;
int i = 0;
for( i = 0; i < nums.length;i++){
if(nums[i]==0){
for(int j = i; j < nums.length;j++){
if (nums[j]%2!=0){
acum = nums[j];
break;
}
}
nums[i]=acum;
}
}
return nums;
}
This can be done much more efficiently by rearranging the problem a bit.
Instead of traversing left-to-right, then scanning the integers on the right for the replacement, you can instead just go right-to-left. Then, you can store the previous replacement until you encounter a larger odd number.
public int[] zeroMax(final int[] nums) {
int replace = 0; // Stores previous largest odd - default to 0 to avoid replacement
for (int i = nums.length - 1; i >= 0; i--) { // start from end
final int next = nums[i];
if (next == 0) { // If we should replace
nums[i] = replace;
} else if (next % 2 == 1 && next > replace) {
// If we have an odd number that is larger than the replacement
replace = next;
}
}
return nums;
}
Given your examples, this output:
[5, 5, 3, 3]
[3, 4, 3, 3]
[1, 1, 0]
What you are missing is, that there could be more than one odd number on the right side of your zero and you need to pick the largest one.
Edit: And you also need to reset 'acum'. I updated my suggestion :)
Here's a suggestion:
public int[] zeroMax(int[] nums) {
int acum = 0;
int i = 0;
for (i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
for (int j = i; j < nums.length; j++) {
if (nums[j] % 2 != 0 && nums[j] > acum) {
acum = nums[j];
}
}
nums[i] = acum;
acum = 0;
}
}
return nums;
}
public int[] zeroMax(int[] nums) {
for (int i=0; i<nums.length; i++)
{
if (nums[i] == 0)
{
int maxindex = i;
for (int j=i+1; j<nums.length; j++)
{
if ((nums[j]%2 == 1) && (nums[j] > nums[maxindex]))
{
maxindex = j;
}
}
nums[i] = nums[maxindex];
}
}
return nums;
}
This alows you to find the index of the maximum odd number to the right, replacing the zero with the number at that index
The basic problem is that this algorithm doesn't search for the biggest odd value, but for the first odd value in the array, that is to the right of a given value. Apart from that, you might consider creating a table for the biggest odd value for all indices to simplify your code.
Here is one of the possible solutions to this :)
public int[] zeroMax(int[] nums) {
for(int i=0;i<nums.length;i++){
if(nums[i] == 0){
int val = largestOddValue(nums,i);//finding largest odd value
nums[i] = val; // assigning the odd value
}
}
return nums;
}
//finds largest odd value from the index provided to end
public int largestOddValue(int[] nums,int i){
int value = 0; // for storing value
for(int k=i;k<nums.length;k++){
if(nums[k]%2!=0 && value<nums[k]) // got the odd value
value = nums[k];
}
return value;
}
public int[] zeroMax(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == 0) {
int max = 0;
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] % 2 != 0 && nums[j] > max) {
max = nums[j];
}
}
nums[i] = max;
max = 0;
}
}
return nums;
}
public int[] zeroMax(int[] nums) {
int val = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 0) {
for(int j = i + 1; j < nums.length; j++) {
if(val <= nums[j]) {
if(nums[j] % 2 == 1) {
val = nums[j];
}
}
}
nums[i] = val;
val = 0;
}
}
return nums;
}
public int[] zeroMax(int[] nums) {
int[] result = nums.clone();
for (int i = nums.length - 1, max = 0; i >= 0; i--)
if (isOdd(nums[i])) max = Math.max(nums[i], max);
else if (nums[i] == 0) result[i] = max;
return result;
}
boolean isOdd(int num) { return (num & 1) == 1; }
We iterate backwards, always storing the biggest encountered odd number (or 0, if none was found) in max.
When we find a 0, we simply override it with max.
The input is untouched to avoid ruining somebody else's input.
Here is the code which works for every input. Try this on your IDE
public int[] m1(int a[]){
int j = 0;
for (int i = 0; i < a.length; i++) {
if(a[i]!=0){
continue;
}
else if(a[i]==0){
j=i;
while(j<a.length){
if(a[j] % 2 != 0){
if(a[i]<=a[j]){
a[i] = a[j];
j++;
}
else{
j++;
continue;
}
}
else{
j++;
continue;
}
}
}
}
return a;
}

Categories