How to get sum of array elements between two zeros - java

first input: size of array: 5
second input: 0 -2 4 0 6
output: 2
Here is what I have tried. It is also adding the numbers before zero:
My code's output:
array size: 10
elements: 6 19 0 -3 4 8 0 -6 9 59
my output: 25 9
import java.util.Scanner;
import java.util.Vector;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
Vector<Integer> A = new Vector<Integer>();
int sum = 0;
for(int i=0; i<arr.length; i++){
arr[i] = in.nextInt();
}
for(int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
i++;
break;
}
}
for(int i=0; i < arr.length; i++)
{
if (arr[i] == 0)
{
A.add(sum);
sum = 0;
}
else
{
sum += arr[i];
}
}
for(int j = 0; j < A.size(); j++)
{
System.out.print(A.get(j) + " ");
}
}
}

You don't need 2 loops, one to look for the first zero and then sum up.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
List<Integer> sums = new ArrayList<>();
int sum = 0;
// read input
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
boolean isCounting = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0 && isCounting) {
sum += arr[i];
} else if(arr[i] == 0){
// if already counting then finish the sum
if (isCounting) {
sums.add(sum);
sum = 0;
} else { // else start counting
isCounting = true;
}
}
}
System.out.println(sums);
}
}

import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int arr[] = new int[size];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
int sum = 0;
int idx = 0;
while (arr[idx] != 0)
idx++; // After this, idx will be the index of the first 0
do {
idx++; // Keep looping from idx + 1 until the next 0
if (arr[idx] != 0 && idx < arr.length)
sum += arr[idx];
} while (idx < arr.length && arr[idx] != 0);
System.out.println("Sum = " + sum);
}
}

int sum = -1;
int j = -1;
for(int i=0; i<arr.length;i++ ){
if (arr[i] == 0) {
j = i;
if (sum == -1)
sum = 0;
else
break;
}
if ( j == -1)
continue;
sum += arr[i];
}
The above should work

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
int sum = 0;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
if (arr[i] == 0) {
list.add(i);
}
}
for (int i = list.get(0); i <= list.get(list.size()-1); i++) {
sum += arr[i];
}
System.out.println(sum);
}

Related

Find longest possible sequence for jumps on next bigger number

Guys I am thinking on this problem several days and I have no solution even I have lots of experience.
Given a sequence of numbers, calculate the longest possible sequence of jumps from each number.
You can only jump on a number that is greater than the current one
You can jump on a number, only if there isn't one with a greater value between
You can jump only from left to right
I have this solution but I need to make it much faster:
private static List<Integer> slow(int[] numbers){
int n = numbers.length;
int initialJump = 0;
int next = 0;
List<Integer> list = new ArrayList<>();
int counter = 0;
int maxNum = Arrays.stream(numbers).max().getAsInt();
for (int i = 0; i < n; i++) {
initialJump = numbers[i];
if (initialJump == maxNum) {
list.add(0);
continue;
}
for (int j = i + 1; j < n; j++) {
next = numbers[j];
if (initialJump < next) {
counter++;
initialJump = next;
}
}
list.add(counter);
counter = 0;
}
return list;
}
Here is example:
Input
1 4 2 6 3 4
Output
2 1 1 0 1 0
Explanation
Element 1:
1 -> 4 -> 6 (2 jumps)
Element 2:
4 -> 6 (1 jump)
Element 3:
2 -> 6 (1 jump)
Element 4:
6 (0 jumps)
Element 5:
3 -> 4 (1 jump)
Element 6:
4 -> (0 jumps)
Do you have any idea?
Here is what I tried :
private static List<Integer> fast(int[] numbers){
int n = numbers.length;
int[] jumplist = new int[n];
int initialJump = 0;
int count = 0;
int maxNum = Arrays.stream(numbers).max().getAsInt();
Map<Integer, Integer> map = new HashMap<>();
for(int i=n-1; i>=0; i--) {
if(i-1 >= 0 && map.get(i+1) != null && numbers[i+1] > numbers[i]){
jumplist[i] = map.get(i+1)+1;
continue;
}
initialJump = numbers[i];
if (initialJump == maxNum) {
jumplist[i] = 0;
continue;
}
for(int j=i; j<n; j++) {
if(initialJump < numbers[j]) {
count++;
initialJump = numbers[j];
map.put(i,count);
}
}
jumplist[i] = count;
count = 0;
}
return Arrays.stream(jumplist).boxed().collect(Collectors.toList());
}
Here is some test code:
int randomLimit = 50000;
Random random = new Random();
List<Integer> randomList = new ArrayList<>();
for (int i = 0; i < randomLimit; i++) {
randomList.add(random.ints(0, randomLimit).findFirst().getAsInt());
}
System.out.println("Input: " + randomList.stream().limit(20).collect(Collectors.toList()));
int[] randomArray = randomList.stream().mapToInt(i->i).toArray();
Instant fastStarts = Instant.now();
List<Integer> fastRes = fast(randomArray);
System.out.println(fastRes.stream().limit(20).collect(Collectors.toList()));
Instant fastEnds = Instant.now();
System.out.println("fast: " + Duration.between(fastStarts, fastEnds).toMillis());
Instant slowStarts = Instant.now();
List<Integer> slowRes = slow(randomArray);
System.out.println(slowRes.stream().limit(20).collect(Collectors.toList()));
Instant slowEnds = Instant.now();
System.out.println("slow: " + Duration.between(slowStarts, slowEnds).toMillis());
if(slowRes.size() != fastRes.size()){
System.out.println("Not Equal Result !!");
}else {
for (int i = 0; i < slowRes.size(); i++) {
if (!slowRes.get(i).equals(fastRes.get(i))) {
System.out.println("Not Equal Result !!");
break;
}
}
}
Here is some optimized code but I need more optimized ...
private static List<Integer> fast(int[] numbers){
int n = numbers.length;
int[] jumplist = new int[n];
Arrays.fill(jumplist, -1);
int initialJump = 0;
int count = 0;
int maxNum = Arrays.stream(numbers).max().getAsInt();
for(int i=n-1; i>=0; i--) {
if(i+1 < n && jumplist[i+1] != -1 && numbers[i+1] > numbers[i]){
jumplist[i] = jumplist[i+1] + 1;
continue;
}
initialJump = numbers[i];
if (initialJump == maxNum) {
jumplist[i] = 0;
continue;
}
for(int j=i+1; j<n; j++) {
if(initialJump < numbers[j]) {
count++;
initialJump = numbers[j];
}
}
jumplist[i] = count;
count = 0;
}
return Arrays.stream(jumplist).boxed().collect(Collectors.toList());
}

Array program not running correctly. How do I fix it?

Trying to write a program that asks the a user for 10 integers as input. The program
places the even integers into an array called evenList, the odd integers into
an array called oddList, and the negative numbers into an array called
negativeList. The program displays the contents of the three arrays after
all of the integers have been entered.
This is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int countNeg = 0;
int countOdd = 0;
int countEven = 0;
int[] list = new int[10];
System.out.println("Please enter 10 integers:");
for(int i = 0; i < list.length; i++)
{
list[i] = scan.nextInt();
if(list[i] < 0)
{
countNeg++;
}
if(list[i] % 2 == 0 && list[i] > 0)
{
countEven++;
}
if(list[i] % 2 == 1 && list[i] > 0)
{
countOdd++;
}
}
int[] oddList = new int[countOdd];
int[] evenList = new int[countEven];
int[] negativeList = new int[countNeg];
for(int i = 0; i < list.length; i++)
{
if(list[i] < 0)
{
for(int j = 0; j < countNeg; j++)
{
negativeList[j] = list[i];
}
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 0 && list[i] > 0)
{
for(int j = 0; j < countEven; j++)
{
evenList[j] = list[i];
}
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 1 && list[i] > 0)
{
for(int j = 0; j < countOdd; j++)
{
oddList[j] = list[i];
}
}
}
for (int i : negativeList)
{
System.out.print(i + " ");
}
System.out.println();
for (int i : evenList)
{
System.out.print(i + " ");
}
System.out.println();
for (int i : oddList)
{
System.out.print(i + " ");
}
}
}
The program prints the Arrays with the correct amount of values but the wrong numbers. It prints only the last negative, even, or odd number to be input. ex input is 1, 2, 3, 4, 5, 6, -1, -2, -3, -4. For negativeList it prints -4 -4 -4 -4. Im guessing something is wrong in the loops after the arrays are created. Please help!!
you can very much simplify your code with using ArrayList instead of array. For example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length = 10;
System.out.println("Please enter 10 integers:");
List<Integer> oddList = new ArrayList<>();
List<Integer> evenList = new ArrayList<>();
List<Integer> negativeList = new ArrayList<>();
for (int i = 0; i < length; i++) {
int n = scan.nextInt();
if (n < 0) {
negativeList.add(n);
} else if (n % 2 == 0) {
evenList.add(n);
} else {
oddList.add(n);
}
}
for (int i : negativeList) {
System.out.print(i + " ");
}
System.out.println();
for (int i : evenList) {
System.out.print(i + " ");
}
System.out.println();
for (int i : oddList) {
System.out.print(i + " ");
}
}
there are a few issues with the code you provided.
First, in the for loops that initialize the negativeList, evenList, and oddList arrays, you are overwriting the values at each iteration. This means that the final arrays will only contain the last value that was assigned to them. To fix this, you can use a counter variable to keep track of the next index to be filled in each array, like this:
int negCounter = 0;
int evenCounter = 0;
int oddCounter = 0;
for(int i = 0; i < list.length; i++)
{
if(list[i] < 0)
{
negativeList[negCounter] = list[i];
negCounter++;
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 0 && list[i] > 0)
{
evenList[evenCounter] = list[i];
evenCounter++;
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 1 && list[i] > 0)
{
oddList[oddCounter] = list[i];
oddCounter++;
}
}
Second, you are not checking if the input values are integers. If the user enters a non-integer value, the program will throw an exception. You can add a check to make sure that the input is an integer like this:
if(scan.hasNextInt())
{
list[i] = scan.nextInt();
// ... rest of the code
}
else
{
System.out.println("Please enter an integer.");
// If the input is not an integer, discard it and move to the next
input
scan.next();
}

Separating the 0s and Positive Numbers in two different arrays

This is the code I have written, My objective is to segregate the 0s and non 0s without changing the order of the non 0s
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int[] arx;
arx = new int[x];
int[] ary;
ary = new int[x];
for (int i = 0; i < x; i++) {
int q = sc.nextInt();
if (q != 0) {
arx[i] = q;
} else if (q == 0) {
ary[i] = q;
}
}
for (int j = 0; j < arx.length; j++) {
System.out.print(arx[j] + " ");
}
for (int j = 0; j < ary.length; j++) {
System.out.print(ary[j] + " ");
}
}
}
Sample i/p:
5
0 1 0 3 12
Sample o/p:
1 3 12 0 0
What I am getting:
o/p:
0 1 0 3 12 0 0 0 0 0
You should maintain separate index counters for the two arrays:
int x = sc.nextInt();
int ix = 0;
int iy = 0;
int[] arx;
arx = new int[x];
int[] ary;
ary = new int[x];
for (int i=0; i < x; i++) {
int q = sc.nextInt();
if (q != 0) {
arx[ix++] = q;
}
else if (q == 0) {
ary[iy++] = q;
}
}
for (int i=0; i < ix; i++) {
System.out.print(arx[i] + " ");
}
for (int i=0; i < iy; i++) {
System.out.print(ary[i] + " ");
}
For your inputs the above generated the following output:
1 3 12 0 0
Since array with arx is filled with zeroes , you can only use one array to add non zero values.
{
Scanner sc = new Scanner (System.in);
int x = sc.nextInt ();
int[] arx;
arx = new int[x];
int ind = 0;
for (int i = 0; i < x; i++) {
int q = sc.nextInt ();
if (q != 0){
arx[ind++] = q;
}
}
for (int j = 0; j < arx.length; j++){
System.out.print (arx[j] + " ");
}
}

JAVA program bug when populating array from different array

When population oddList, evenList and negativeList from the inputList the program only populates it with one int instead of all corresponding ints from the inputList array. The output should be a list from each array whose numbers correspond to its title. The numbers are input by user into inputList array and then from there it determines whether it is odd, even, and negative and then fills the corresponding arrays.
I.E. evenList is filled with even ints from inputList.
public class ProjectTenOne
{
public static void main(String[] args)
{
int[] inputList = new int[10];
int[] oddList = null;
int[] evenList = null;
int[] negativeList = null;
int evenCount = 0;
int oddCount = 0;
int negCount = 0;
Scanner input = new Scanner(System.in);
//System.out.println("Enter any ten integers: ");
for(int list = 0; list < inputList.length; list++)
{
System.out.println("Enter any " + (inputList.length - list) + " integers: ");
inputList[list] = input.nextInt();
}
System.out.println();
System.out.println("The numbers you entered: ");
for(int in = 0; in < inputList.length; in++)
{
System.out.println(inputList[in]);
}
for(int ls = 0; ls< inputList.length; ls++)
{
if(inputList[ls] % 2 == 0)
{
evenCount = evenCount +1;
}
if(inputList[ls] % 2 != 0)
{
oddCount = oddCount +1;
}
if(inputList[ls] < 0)
{
negCount = negCount +1;
}
}
evenList = new int[evenCount];
oddList = new int[oddCount];
negativeList = new int[negCount];
for(int l = 0; l < inputList.length; l++)
{
if((inputList[l] % 2) == 0)
{
for(int j = 0; j < evenList.length; j++)
{
evenList[j] = inputList[l];
}
}
if((inputList[l] % 2) != 0)
{
for(int k = 0; k < oddList.length; k++)
{
oddList[k] = inputList[l];
}
}
if(inputList[l] < 0)
{
for(int h = 0; h < negativeList.length; h++)
{
negativeList[h] = inputList[l];
}
}
}
System.out.println("The ODD List is: ");
for(int i = 0; i < oddList.length; i++)
{
System.out.println(oddList[i]);
}
System.out.println("The EVEN List is: ");
for(int j = 0; j < evenList.length; j++)
{
System.out.println(evenList[j]);
}
System.out.println("The NEGATIVE List is: ");
for(int k = 0; k < oddList.length; k++)
{
System.out.println(negativeList[k]);
}
}
}
I'll take evenList as the example here, but the same applies to the other two arrays as well.
In your code, you iterate over your inputList and check for an even number. If it is even, you set the entire evenList array to the found value, instead of just a single element.
You can solve this problem by declaring an int outside of your outer loop that keeps track of the number of even numbers entered. As an example:
int evenIndex = 0;
for(int l = 0; l < inputList.length; l++)
{
if((inputList[l] % 2) == 0)
{
evenList[evenIndex++] = inputList[l];
}
/*Other code*/
}
You also made a mistake in your last loop. You iterate over negativeList, but you use the size of evenList. This will result in an ArrayIndexOutOfBoundsException when negativeList is smaller than evenList.

Array Index out of bounds exception, when I run this, I am not able to figure out why. I am not able to view the sorted array [duplicate]

This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 7 years ago.
import java.util.Scanner;
public class Sort {
public void Countsort(int a[], int b[], int k) throws ArrayIndexOutOfBoundsException {
int[] c = new int[k + 1];
for (int i = 0; i < k; i++) {
c[i] = 0;
}
for (int i = 0; i <= a.length; i++) {
c[a[i]] = c[a[i]] + 1;
}
for (int i = 1; i <= k; i++) {
c[i] = c[i] + c[i - 1];
}
for (int i = a.length; i <= 1; i--) {
b[c[a[i]]] = a[i];
c[a[i]] = c[a[i]] - 1;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num;
int[] temp = new int[10000];
int i = 0;
while (sc.hasNextInt()) {
num = sc.nextInt();
temp[i] = num;
i++;
if (num == -1) {
break;
}
}
int A[] = new int[i];
// just a check
for (i = 0; i < temp.length; i++) {
System.out.println("temp values:" + temp[i]);
}
// just a check ends
for (int j = 0; j < A.length; j++) {
A[j] = temp[j];
System.out.println("tem copied vals:" + A[j]);
}
// a check for gthat a has temp values..
int[] B = new int[A.length];
new Sort().Countsort(A, B, 100);
for (i = 0; i < B.length; i++) {
System.out.println("Run count #" + i + " : " + B[i]);
}
}
}
First of all your while loop should be
while (sc.hasNextInt()) {
num = sc.nextInt();
if (num == -1) {
break;
}
// so that you can stop -1 to be stored
temp[i] = num;
i++;
}
Next thing is your loop
for (int i = 0; i < a.length; i++) { // always less than length of the array
c[a[i]] = c[a[i]] + 1;
}

Categories

Resources