I need to sum of x element together in order from an array and insert the result in new array.
For example,
int x = 3;
int [ ]array = {1,2,5,8,4,9,4,2,9,7,5}; //we have 11 element here
int [ ]newarray= new int [Math.round(array.length/x)]; // the size will be round(11/3)= 4
The size of newarray will be 4
int sum = 0 ; // this will hold the sum of the array element
I need loop into array and sum the first **(x)**three elements and insert the summation in the first newarray index and empty sum variable
then loop again in the array starting from the next three element and insert the summation in the second index of the newarray and so on..
the last index of the new array will be summation of the last two element from array because there is only two element in the array
we get the some and insert it to the last index of the array the array should look like that
for (int i=0; i< newarray.length;++i){
System.out.println(newarray[i]);
Expected output should be
newarray [ 0 ]= 1+2+5 = 8
newarray [ 1 ]= 8+4+9 = 21
newarray [ 2 ]= 8+4+9 = 15
newarray [ 3 ]= 7+5 = 12
Need a solution.
First you need to cast the x to double, because int/int will result in int so you will never get the space last for holding the partial sum. Use the ceil() function not the round(). Because round() converts the input to the closest integer, where as you need closet upper integer.
int []newarray= new int [(int) Math.ceil(array.length / (double)x)];
Use two loops and put the sum in array. First, iterates over the sum result array (where you are storing the sum) and second to fetch the element from the source array.
When the source array does not have element in the multiples of x make sure you don't access the extra unavailable elements, otherwise exception will be thrown.
for (int i=0; i<newarray.length; i++) {
int sum = 0;
for(int j=0; j<x && x*i+j < array.length; j++) {
sum += array[x*i+j];
}
newarray[i] = sum;
}
// print the results
for (int xx : newarray) {
System.out.println(xx);
}
Try folowing code:
It can be done with reduced complexity having just the one loop:
int x=3;
int [ ]array = {1,2,5,8,4,9,4,2,9,7,5};
int [ ]newarray= new int [(int) Math.ceil(array.length / (double)x)];
int sum=array[0],k=0;
for (int i=1; i< array.length;i++){
sum=sum+array[i];
if((i+1)%3==0){
newarray[k]=sum;
System.err.println(newarray[k]);
sum=0;
k++;
}else if(i+1==array.length){
newarray[k]=sum;
System.err.println(newarray[k]);
}
}
Output:
8
21
15
12
Here is the solution you want,
int ind = 0, sum;
for (int i = 0; i < array.length; i += 3)
{
sum = 0;
for(int j = 0; j < 3 && i + j < array.length; j++)
{
sum = sum + array[i + j];
}
newarray[ind++] = sum;
}
Now newarray contains what you want.
Related
I have a set of 1d arrays that are being pulled from a method (tableMethod) - i want to grab those 1d arrays, then sum all the elements in each 1d array. How can I do that?
I have two loops
one that can sum a 1d array by itself
another that can display all the 1d arrays
I'm having difficulty combining the for loops so that it can grab each 1d array, sum it, then move on to the next 1d array, sum it, and so forth
the result should look something like:
total: 391
total: 393
total: 3903
total: 39104
total: 39031
... and so forth
int sum = 0;
int w = 0;
int[] arrayOne = tableMethod(table, w);
for (int k = 0; k < arrayOne.length; k++) {
sum = sum + arrayOne[k];
}
for (int i = 0; i < arrayOne.length; i++) {
System.out.println(Arrays.toString(tableMethod(table, i)));
}
System.out.println(sum);
}
Something like this would work,
import java.util.stream.IntStream;
int n = <max value of w>
int sum = 0;
for (int i = 0; i < n; i++) {
int[] array = tableMethod(table, i);
int arr_sum = IntStream.of(array).sum();
System.out.println(arr_sum); //single array sum
sum += arr_sum;
}
System.out.println(sum); //total sum
The code should be simply using nested loops (inner loop to calculate a sum may be replaced with stream):
int n = ... ; // a number of 1d arrays
int total = 0;
for (int i = 0; i < n; i++) {
int[] arr = tableMethod(table, i);
int sum = Arrays.stream(arr).sum();
System.out.println(sum);
total += sum;
}
System.out.println(total);
New to java and am trying to create a program/method that will take an int array, and return another int array but it replaces the values of the indexes with the value of the elements. (Example {2,1,3} will return {0,0,1,2,2,2}
public static void main(String[] args) {
int[] pracArray = {2, 1, 3};
int sum = 0;
for (int i = 0; i < pracArray.length; i++)
{
sum = sum + pracArray[i];
}
System.out.println("Amount of array indexes: " + sum);
int[] newArray = new int[sum];
System.out.println(Arrays.toString(pracArray));
for (int i = 0; i < pracArray.length; i++)
{
for (int j = 0; j < pracArray[i]; j++)
{
newArray[j] = i;
}
}
System.out.println(Arrays.toString(newArray));
}
}
Currently I am getting [2,2,2,0,0,0]. I have tried changing the how many times each for loop iterates with no avail. I have also tried to make the elements of newArray equal to a counter ( int count = 0; and having count++ in the for loop) since the values of the new array will always be 0 - however many runs.
Given the length of your array is 3, your outer 'i' loop is iterating through the values 0,1,2. That means your inner 'j' loop never writes to index 3,4,5 (hence why they are 0 in the output), and why the first 3 indexes are set to '2' (2 is the last indexed processed in the 'i' loop). Try this instead...
int h = 0;
for (int i = 0; i < pracArray.length; i++)
{
for (int j = 0; j < pracArray[i]; j++)
{
newArray[h] = i;
h++;
}
}
Hi so the question is: if array1 is smaller than array2 replace the missing values with number 1, so that array1 missing values can be multiplied by array2 as if they were the number 1?
Here is my idea of how one could go about it... help with the correct syntax? Best way to go about it?
public addMissingNumber(int[] array1, int[] array2){
for (int 1 = array1.length; i > 0; i--)
for(int j = array2.length; j > 0; j--){
if(array1[i] < array2[j]) {
array1[i].[j] = 1;
/*what I want to say here is that the empty position of the array1[i] that is equivalent to the position of array2[j] that contains a number should become the number 1. How can this be done?*
}
}
}
Here is the original exam question, the second part is what I'm having trouble with:
Write a method called add that takes two arrays v, w of type double as its parameters. The method should return a new array of double formed by adding the corresponding elements of the input arrays. That is to say, element i of the output array should be equal to v[i]+w[i].
If the lengths of v and w are different, the output array should have as length the maximum of (v.length, w.length).
The missing elements of the shorter array should be assumed to be one in the calculation of the output.
Try this:
public double[] addMissingNumber(double[] array1, double[] array2){
double[] arraynew = new double[max(array1.length,array2.length)];
int i = 0;
int j = 0;
int k = 0;
while ( i < array1.length && j < array2.length) {
arraynew[k] = array1[i] + array2[j];
i++;
j++;
k++
}
while(i < array1.length) {
arraynew[k] = array1[i]+1;
i++;
k++;
}
while(j < array2.length){
arraynew[k] = array2[j]+1;
j++;
k++;
}
return arraynew;
}
You don't need to put 1 into the array. Just traverse through both the arrays till they are equal and store the sum . After that the longer array is traversed and 1 is added to it everytime.
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;
}
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]);
}
}
}