Calculating the sum of all odd array indexes - java

I want to calculate the sum of all odd array indexes, but I'm having some trouble finding the right way to do it.
Here's my code so far:
String id = "9506265088085";
String[] strArray = id.split("");
int[] intArray = new int[strArray.length];
int sum = 0;
for (int i = 0; i < 6; i++) {
if (i%2!=0)
{
sum += Integer.parseInt(String.valueOf(id.charAt(i)));
}}
System.out.println(sum);
Any ideas on why this isn't working, or simpler ways to do it? To clarify I want to add all the numbers in the odd array index positions, so intArray[1] + intArray[3] + intArray[5] + ....
Edit:
Forgot to mention I only want to add 1, 3, 5, 7, 9, 11 and not 13.

You are looping only from i=0 to i=5

The other answer is right, you are only looping to 5. However, you're making this overly complicated; there's a neat trick you can use to avoid Integer.parseInt() and String.valueOf():
int sum = 0;
for (int i = 1; i < id.length(); i += 2) {
sum += (id.charAt(i) - '0');
}
Also note that instead of checking i%2 repeatedly, you can simply add 2 to the loop control variable at the end of each iteration (and let it start at 1 so you hit only the odd indices).

Just edited your code:
String id = "9506265088085";
int[] intArray = new int[id.length()];
int sum = 0;
for (int i = 0; i < intArray.length; i++) {
if (i%2!=0)
{
sum += Integer.parseInt(String.valueOf(id.charAt(i));
}}
System.out.println(sum);

String id = "9506265088085";
int[] intArray = new int[strArray.length];
int sum = 0;
for (int i = 1; i < id.length(); i+=2) {
sum += Integer.parseInt(String.valueOf(id.charAt(i)));
}
System.out.println(sum);

There is no Index 13 in this array as in Java index starts from 0. A solution to calculating the sum of all odd array indexes with Java 8 is:
String id = "9506265088085";
String[] strArray = id.split("");
int sum = IntStream.range(0, strArray.length)
.filter(idx -> idx % 2 == 1)
.map(idx -> Integer.parseInt(strArray[idx]))
.sum();
System.out.println(sum);

Related

Product of array in a new array except the current index value

Given an array of integers, create a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
Note: Do not use division.
import java.util.Scanner;
public class Productofarray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int prod = 1, i, j = 0;
System.out.println("How many values do you want to enter");
int n = sc.nextInt();
int a[] = new int[n];
int a2[] = new int[n];
System.out.println("Input " + n + " values:");
for (i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (i = 0; i < n; i++) {
inner:
while (j < n) {
if (a[j] == a[i]) {
j++;
continue inner;
}
prod *= a[j];
}
a2[i] = prod;
System.out.println(a2[i]);
}
}
}
I have written this code but the problem is that it is keep on running and it never ends can someone help me what I am doing wrong here.
This should get you closer; as pointed out by Maneesh's answer, you're not checking that you're at the current index i.e i == j instead of a[i]==a[j]. you also do not need the label and it is suggested that you avoid them completely.
for(int i=0; i<n; i++)
{
// this loop can be replaced with a stream.reduce - however that seems to require copying a1 in place to remove the element at index i first as reduce doesn't seem to pass the current index.
for(int j = 0; j < n; j++) {
if(j i) continue;
a2[i] *= a1[j];
}
System.out.println(a2[i]);
}
it took me a second to figure it out but here's a example using the Java 8 Stream APIs:
for(int i=0; i<n; i++) // for i -> n
{
final int currentIndex = i;
a2[i] = IntStream.range(0, a1.length)
.filter(index -> index != currentIndex) // ingore the curent index
.map(index -> a1[index]) // map the remaining indecies to the values
.reduce((subTotal, current) -> subTotal * current); // reduce to a single int through multiplication.
}
System.out.println(a2[i]);
I haven't tested it but it should work (maybe with a tweak or two). The. gist of it is making a new array (IntStream.range) that contains every element of the given array but the one at currentIndex (.filter().map()) and then multiply the elements (reduce(... subTotal * current)). Note that this solution creates a new array for every iteration through the for loop which, with extremely large arrays, is memory-inefficient.
because you are not incrementing j when i!=j. also, you should check for i==j not a[i]==a[j].

Rearrange int array so that all the negative numbers come before the positivite numbers

I am trying to write a method which takes an array of ints and then rearranges the numbers in the array so that the negative numbers come first. The array does not need to be sorted in any way. The only requirement is that the solution has to be linear and it does not use an extra array.
Input:
{1, -5, 6, -4, 8, 9, 4, -2}
Output:
{-5, -2, -4, 8, 9, 1, 4, 6}
Now as a noob in Java and programming in general I am not 100% sure on what is considered a linear solution, but my guess is that it has to be a solution that does not use a loop within a loop.
I currently have an awful solution that I know doesn't work (and I also understand why) but I can't seem to think of any other solution. This task would be easy if I were allowed to use a loop within a loop or an additional array but I am not allowed to.
My code:
public static void separateArray(int[] numbers) {
int i = 0;
int j = numbers.length-1;
while(i<j){
if(numbers[i] > 0){
int temp;
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
System.out.println(Arrays.toString(numbers));
}
i++;
j--;
}
}
You only need to change one line to get it (mostly) working. But you need to change two lines to correctly handle zeroes in the input. I have highlighted both of these minimally necessary changes with "FIXME" comments below:
public static void separateArray(int[] numbers) {
int i = 0;
int j = numbers.length-1;
while(i<j){
if(numbers[i] > 0){ // FIXME: zero is not a "negative number"
int temp;
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
i++; // FIXME: only advance left side if (numbers[i] < 0)
j--; // FIXME: only decrease right side if (numbers[j] >= 0)
}
}
Your approach with two pointers, i and j is a good start.
Think about the loop invariant that you immediately set up (vacuously):
Elements in the range 0 (inclusive) to i (exclusive) are negative;
Elements in the range j (exclusive) to numbers.length (exclusive) are non-negative.
Now, you want to be able to move i and j together until they pass each other, preserving the loop invariant:
If i < numbers.length and numbers[i] < 0, you can increase i by 1;
If j >= 0 and numbers[j] >= 0, you can decrease j by 1;
If i < numbers.length and j >= 0, then numbers[i] >= 0 and numbers[j] < 0. Swap them around.
If you keep applying this strategy until i == j + 1, then you end up with the desired situation, that:
numbers[a] < 0 for a in [0..i)
numbers[a] >= 0 for a in (j..numbers.length), also written as numbers[a] >= 0 for a in (i-1..numbers.length), also written as numbers[a] >= 0 for a in [i..numbers.length).
So, you've partitioned the array so that all negative numbers are on the left of the i-th element, and all non-negative numbers are at or to the right of the i-th element.
Hopefully, this algorithm should be easy to follow, and thus to implement.
A linear solution is a solution with a run-time complexity Big-Oh(n) also noted as O(n), in other words, you have to loop through the whole array only once. To sort in linear time you can try one of the following sorting algorithms:
Pigeonhole sort
Counting sort
Radix sort
Your code works only if all the negative numbers are located in the right half side and the positives in the left half. For example, your code swaps 6 with 9 which both are positives. So, it depends on the order of your the array elements. As scottb said, try do it by your hands first then you will notice where you did wrong. Moreover, print your array out of the while
//Move positive number left and negative number right side
public class ArrangeArray {
public static void main(String[] args) {
int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
for (int i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}
int temp = 0;
for (int i = 0; i < arr.length; i++) {
// even
if (arr[i] < 0) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] > 0) {
arr[j] = arr[i] + arr[j];
arr[i] = arr[j] - arr[i];
arr[j] = arr[j] - arr[i];
break;
}
}
}
}
System.out.println("");
for (int i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}
}
}
There is simple program it will help you. In this program i have take temp array and perform number of item iteration. In that i have start fill positive value from right and negative from left.
public static void rearrangePositiveAndNegativeValues() {
int[] a = {10,-2,-5,5,-8};
int[] b = new int[a.length];
int i = 0, j = a.length -1;
for (int k = 0; k < a.length ; k++) {
if (a[k] > 0) {
b[j--] = a[k];
} else {
b[i++] = a[k];
}
}
System.out.println("Rearranged Values : ");
printArray(b);
}
package ArrayProgramming;
import java.util.ArrayList;
import java.util.Arrays;
public class RearrangingpossitiveNegative {
public static void main(String[] args) {
int[] arr= {-1,3,4,5,-6,6,8,9,-4};
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i=0;i<arr.length;i++) {
if(arr[i]>0) {
al.add(arr[i]);
}
}
for (int i=arr.length-1;i>=0;i--) {
if(arr[i]<0) {
al.add(arr[i]);
}
}
System.out.println(al);
}
}
from array import *
size = int(input())
arr = (array('i' , list(map(int, input().split()))))
negarr = array('i')
posarr = array('i')
for i in arr:
if i>=0:
posarr.append(i)
else:
negarr.append(i)
print(*(negarr+posarr))
we can also do it by creating two new arrays and adding elements into them as per given condition. later joining both of them to produce final result.

Delete max element in array

Wrote some code to try to find the maximum element in an un-ordered array and then delete it from the array. My first loop has the logic to find the maximum element while the second loop should take in the variable from the first loop, look ahead one space and then insert into the max element.
My below code seems to work for my second idea .. but does not find the right max array element.
My array has the following values {6, 3, 5, 2, 7, 9, 4}. It is finding the max array element to be 7 .. it should be 9.
public void deleteMax() {
// set value for comparison starting from the beginning of the array
int arrayMax = arr[0];
for (int i = 0; i < nElems; i++) {
if (arr[i] > arrayMax) {
arrayMax = arr[i];
for (int k = i; k < nElems; k++) {
arr[k] = arr[k + 1];
nElems--;
break;
}
}
}
}
why not use jQuery $.grep & Math.max like:
var arr = [6, 3, 5, 2, 7, 9, 4];
var maxNum = Math.max.apply(null, arr);
var newArr = $.grep( arr, function( n ) {
return n != maxNum;
});
console.log(newArr);
Fiddle
EDIT:
Well didn't realize you're using Java as the question showed in JavaScript section...
in Java, You can find max number in array like
int maxNum = arr.get(0); // get the first number in array
for (int i = 1; i < arr.length; i++) {
if ( arr.get(i) > maxNum) {
maxNum = array.get(i);
}
}
arr.remove(maxNum);
Well,, you don't need any second loop.
Only one loop and two variables called, f.ex. MaxElementPosition and MaxElementValue, which are updated every time inside the loop if the number on this position is greater than the last MaxElementValue, update both value and position.
While the loop you do need the value for comparing. In the end you only need the position.
Your inner loop is irrelevant, you only have a 1D array, so it makes no sense to do any inner iteration.
If you insist on performing no sorting on the array, then you could do something like this:
public void deleteMax() {
// set value for comparison starting from the beginning of the array
int arrayMax = arr[0];
int maxIndex = 0;
for (int i = 0; i < nElems; i++) {
if (arr[i] > arrayMax) {
arrayMax = arr[i];
maxIndex = i;
}
}
arr.remove(maxIndex);
}
Once the for loop finishes, we remove the item at maxIndex
#Alex is on the right track, but there is no remove function that can be called on an array in java. All that you need is the variable maxIndex that he gets, which of course will be the first occurence of this maximum, so if you need to remove every occurence of the maximum, that would be a different issue. So once you use #Alex code:
int arrayMax = arr[0];
int maxIndex = 0;
for (int i = 0; i < nElems; i++) {
if (arr[i] > arrayMax) {
arrayMax = arr[i];
maxIndex = i;
}
}
This would be much easier if instead of an array, you were to use an ArrayList, in which case the code would look like:
int arrayMax = arr.get(0);
int maxIndex = 0;
for (int i = 0; i < nElems; i++) {
if (arr[i] > arrayMax) {
arrayMax = arr[i];
maxIndex = i;
}
}
arr.remove(maxIndex);
Otherwise you would have to create a temp array to remove the value:
int[] temp = new int[arr.length-1];
for(int i = 0, index = 0; index < nElems; i++, index++)
{
if(index == maxIndex) index++;
temp[i] = arr[index];
}
arr = temp;

Array in the reverse order [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have an array of n elements and these methods:
last() return the last int of the array
first() return the first int of the array
size() return the length of the array
replaceFirst(num) that add the int at the beginning and returns its position
remove(pos) that delete the int at the pos
I have to create a new method that gives me the array at the reverse order.
I need to use those method. Now, I can't understand why my method doesn't work.
so
for (int i = 1; i
The remove will remove the element at the position i, and return the number that it is in that position, and then with replaceFirst will move the number (returned by remove) of the array.
I made a try with a simple array with {2,4,6,8,10,12}
My output is: 12 12 12 8 6 10
so if I have an array with 1,2,3,4,5
for i = 1; I'm gonna have : 2,1,3,4,5
for i=2 >3,2,1,4,5
etc
But it doesn't seem to work.
Well, I'll give you hints. There are multiple ways to reverse an array.
The simplest and the most obvious way would be to loop through the array in the reverse order and assign the values to another array in the right order.
The previous method would require you to use an extra array, and if you do not want to do that, you could have two indices in a for loop, one from the first and next from the last and start swapping the values at those indices.
Your method also works, but since you insert the values into the front of the array, its going to be a bit more complex.
There is also a Collections.reverse method in the Collections class to reverse arrays of objects. You can read about it in this post
Here is an code that was put up on Stackoverflow by #unholysampler. You might want to start there: Java array order reversing
public static void reverse(int[] a)
{
int l = a.length;
for (int j = 0; j < l / 2; j++)
{
int temp = a[j]
a[j] = a[l - j - 1];
a[l - j - 1] = temp;
}
}
int[] reverse(int[] a) {
int len = a.length;
int[] result = new int[len];
for (int i = len; i > 0 ; i--)
result[len-i] = a[i-1];
return result;
}
for(int i = array.length; i >= 0; i--){
System.out.printf("%d\n",array[i]);
}
Try this.
If it is a Java array and not a complex type, the easiest and safest way is to use a library, e.g. Apache commons: ArrayUtils.reverse(array);
In Java for a random Array:
public static void reverse(){
int[] a = new int[4];
a[0] = 3;
a[1] = 2;
a[2] = 5;
a[3] = 1;
LinkedList<Integer> b = new LinkedList<Integer>();
for(int i = a.length-1; i >= 0; i--){
b.add(a[i]);
}
for(int i=0; i<b.size(); i++){
a[i] = b.get(i);
System.out.print(a[i] + ",");
}
}
Hope this helps.
Reversing an array is a relatively simple process. Let's start with thinking how you print an array normally.
int[] numbers = {1,2,3,4,5,6};
for(int x = 0; x < numbers.length; x++)
{
System.out.println(numbers[x]);
}
What does this do? Well it increments x while it is less than numbers.length, so what is actually happening is..
First run : X = 0
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[0]);
// Which resolves to..
System.out.println(1);
Second Run : X = 1
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[1]);
// Which resolves to..
System.out.println(2);
What you need to do is start with numbers.length - 1, and go back down to 0. To do this, you need to restructure your for loop, to match the following pseudocode..
for(x := numbers.length to 0) {
print numbers[x]
}
Now you've worked out how to print, it's time to move onto reversing the array. Using your for loop, you can cycle through each value in the array from start to finish. You'll also be needing a new array.
int[] revNumbers = new int[numbers.length];
for(int x = numbers.length - 1 to 0) {
revNumbers[(numbers.length - 1) - x] = numbers[x];
}
int[] noArray = {1,2,3,4,5,6};
int lenght = noArray.length - 1;
for(int x = lenght ; x >= 0; x--)
{
System.out.println(noArray[x]);
}
}
int[] numbers = {1,2,3,4,5};
int[] ReverseNumbers = new int[numbers.Length];
for(int a=0; a<numbers.Length; a++)
{
ReverseNumbers[a] = numbers.Length - a;
}
for(int a=0; a<ReverseNumbers.Length; a++)
Console.Write(" " + ReverseNumbers[a]);
int[] numbers = { 1, 2, 3, 4, 5, 6 };
reverse(numbers, 1); >2,1,3,4,5
reverse(numbers, 2); >3,2,1,4,5
public int[] reverse(int[] numbers, int value) {
int index = 0;
for (int i = 0; i < numbers.length; i++) {
int j = numbers[i];
if (j == value) {
index = i;
break;
}
}
int i = 0;
int[] result = new int[numbers.length];
int forIndex = index + 1;
for (int x = index + 2; x > 0; x--) {
result[i] = numbers[forIndex--];
++i;
}
for (int x = index + 2; x < numbers.length; x++) {
result[i] = numbers[x];
++i;
}
return result;
}

Java: Array with loop

I need to create an array with 100 numbers (1-100) and then calculate how much it all will be (1+2+3+4+..+100 = sum).
I don't want to enter these numbers into the arrays manually, 100 spots would take a while and cost more code.
I'm thinking something like using variable++ till 100 and then calculate the sum of it all. Not sure how exactly it would be written.
But it's in important that it's in arrays so I can also say later, "How much is array 55" and I can could easily see it.
Here's how:
// Create an array with room for 100 integers
int[] nums = new int[100];
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
nums[i] = i + 1; // +1 since we want 1-100 and not 0-99
// Compute sum
int sum = 0;
for (int n : nums)
sum += n;
// Print the result (5050)
System.out.println(sum);
If all you want to do is calculate the sum of 1,2,3... n then you could use :
int sum = (n * (n + 1)) / 2;
int count = 100;
int total = 0;
int[] numbers = new int[count];
for (int i=0; count>i; i++) {
numbers[i] = i+1;
total += i+1;
}
// done
I'm not sure what structure you want your resulting array in, but the following code will do what I think you're asking for:
int sum = 0;
int[] results = new int[100];
for (int i = 0; i < 100; i++) {
sum += (i+1);
results[i] = sum;
}
Gives you an array of the sum at each point in the loop [1, 3, 6, 10...]
To populate the array:
int[] numbers = new int[100];
for (int i = 0; i < 100; i++) {
numbers[i] = i+1;
}
and then to sum it:
int ans = 0;
for (int i = 0; i < numbers.length; i++) {
ans += numbers[i];
}
or in short, if you want the sum from 1 to n:
( n ( n +1) ) / 2
If your array of numbers always is starting with 1 and ending with X then you could use the following formula:
sum = x * (x+1) / 2
from 1 till 100 the sum would be 100 * 101 / 2 = 5050
this is actually the summation of an arithmatic progression with common difference as 1. So this is a special case of sum of natural numbers. Its easy can be done with a single line of code.
int i = 100;
// Implement the fomrulae n*(n+1)/2
int sum = (i*(i+1))/2;
System.out.println(sum);
int[] nums = new int[100];
int sum = 0;
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
{
nums[i] = i + 1;
sum += n;
}
System.out.println(sum);
The Array has declared without intializing the values and if you want to insert values by itterating the loop this code will work.
Public Class Program
{
public static void main(String args[])
{
//Array Intialization
int my[] = new int[6];
for(int i=0;i<=5;i++)
{
//Storing array values in array
my[i]= i;
//Printing array values
System.out.println(my[i]);
}
}
}

Categories

Resources