How to sum an ArrayList in Java element by element - java

I have a double ArrayList that has this numbers:
2, 4, 10, 14, 20, 33...
And I want to create a new ArrayList with the sum of the first ArrayList, but the sum result must to be:
2, 6, 16, 30, 50, 83...
The operations inside must to be:
position 0: 2 without operations
position 1: 2 + 4 = 6
position 2: 10 + 6 = 16
position 3: 14 + 16 = 30
position 4: 20 + 30 = 50
position 5: 33 + 50 = 83
...
At the moment i have this:
ArrayList <Double> velocidad = new ArrayList();
ArrayList <Double> velocidad_acum = new ArrayList();
double prevVel = 0;
double vel_acum = 0;
velocidad.add(vel);
for (double i : velocidad){
int currentIndex = velocidad.indexOf(i);
int prevIndex = velocidad.indexOf(i) - 1;
if (currentIndex > 0){
prevVel = velocidad.get(prevIndex);
vel_acum = prevVel + i;
}
}
velocidad_acum.add(vel_acum);
"vel" is a variable that update its value each second, and each second the ArrayList "velocidad" acumulates a new number inside.
This code mades with the example above:
2, 6, 14, 24, 34, 53...
position 0: 2 without operations
position 1: 2 + 4 = 6
position 2: 10 + 4 = 14
position 3: 14 + 10 = 24
position 4: 20 + 14 = 34
position 5: 20 + 33 = 53
...

List<Double> one = Arrays.asList(2.0, 4.0, 10.0, 14.0, 20.0, 33.0);
List<Double> two = new ArrayList<>();
double sum = 0;
for (double d: one) {
sum += d;
two.add(sum);
}
System.out.println(two);
// [2.0, 6.0, 16.0, 30.0, 50.0, 83.0]
Start sum with 0 and keep adding intermediate sum values to the List.

We're not going to do your homework for you, but here is a basic pseudo code solution:
public static List<Double> sum(List<Double> src) {
//Create a List<> to hold your sums
List<Double> sumList = new ArrayList<>();
//loop through your src list
for (Double item : src) {
//If the sumList is empty, add the item to your sumList
//other wise, grab the value at the end of your sumList
//add it to the item, and add that value to your sumList
}
return sumList;
}

Related

Maximum difference between final and initial sum

I am new to programming and having trouble solving one task. I have several input example. First line contains two numbers m (number of digits on paper, 1<m<1000) and h (limit on the number of operations, 1<h<1000). I have the opportunity, no more than h times, to take any number from a piece of paper (means m), then paint over one of the old digits, and write a new arbitrary digit in its place. By what maximum value can I be able to increase the sum of all the numbers on the piece of paper?
First example:
Input:
5 2 //m and h
1 3 1 4 5 //m = 5, so I can add 5 arbitrary numbers and h=2, so I can change 2 numbers
Output:
16 // cause I changed 1 and 1 to 9 and 9, so the difference 8 and 8 and the sum is 16
Second example:
Input:
3 1
99 5 85
Output:
10 //85 to 95, so the difference is 10
Third example:
Input:
1 10
9999
Output:
0 // nothing to be change
What I have for now:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int m = sc.nextInt();
int h = sc.nextInt();
System.out.println("Entered: " + m);
System.out.println("Entered: " + h);
int[] numbers = new int[m];
for(int i = 0; i < m; ++i) {
numbers[i] = sc.nextInt();
}
Arrays.sort(numbers);
//here is my logic: I am changing 1 to 9
for (int i = 0; i < h; i++) {
if (numbers[i] < 10) {
numbers[i] = 9;
}
else if (numbers[i] > 9 and numbers[i] < 100) {
numbers[i] = 99;
}
}
sc.close();
My logic can work for the first example, but for the second example it won't work. Can you assist me if I am using right logic or is there any easier way to solve this? Thanks in advance.
I quickly came up with below solution
public static void calculateMax(int m,int h, int[] arr){
int sum = 0;
ArrayList<Integer> al = new ArrayList<>();
for(int i=0;i<arr.length;i++){
String stringNum = Integer.toString(arr[i]);
int num = Integer.parseInt(stringNum.substring(0, 1));
if(num!=9){
al.add(Integer.parseInt(("9"+stringNum.substring(1)))-arr[i]);
continue;
}
al.add(0);
}
Collections.sort(al);
int j = al.size()-1;
for(int i=0;i<h && j>0;i++){
sum+=al.get(j--);
}
System.out.println(sum);
}
Here what I am doing is basically, calculating for each number what we can get as maximum by removing one digit and replacing by 9. And I am storing them in a list. Then we can sort that list and get 'h' largest numbers from stored list, and essentially getting the sum of them and printing it.
Break each input number into its digits times the appropriate power of 10. Sort these by powers of 10 descending, digits ascending. Apply your operation in this order.
E.g., 876, 12, 42 -> 800, 70, 6, 10, 2, 40, 2 -> 800, 10, 40, 70, 2, 2, 6.

Is there a way to reverse specific arrays in a multidimensional array in java?

I know how to generally manipulate and create a multidimensional array but I don't know all the utils and features that arrays have. I want to know is if I have a 2D array the size of [5][4], can I print it where the first line is in order, second is in reverse, and the third is in order... and so on.
For example:
[1 2 3 4] //in order
[8 7 6 5] //reverse
[9 10 11 12] //in order
[16 15 14 13] //reverse
[17 18 19 20] //in order
as my teacher stated "Define a two-dimensional array of size m × n. Write a method to initialize this array with numbers from 1 to m × n in the way as below: the first row, initialize the elements from left to right; the second row, initialize from right to left; then switch order. For example, if m=5; and n = 4; the array should be initialized to:"
I’m not sure if it should be done using a temp method or some other loop method.
You cannot reverse it directly. But you can have a loop and reverse the alternative rows:
void reverseArray() {
Integer[][] arr = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16},
{17, 18, 19, 20}};
for (int i = 1; i < arr.length; i += 2) {
Collections.reverse(Arrays.asList(arr[i]));
}
}
if I have a 2D array the size of [5][4], can I print it where the
first line is in order, second is in reverse, and the third is in
order... and so on.
It's unclear how you want to use the output, but here is a literal way to do it:
public static void main(String[] args) {
int[][] values = new int[][]{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
for (int r = 0; r < values.length; r++) {
if (r % 2 == 0) {
// forwards
for (int c = 0; c < (values[r].length - 1); c++) {
System.out.print(values[r][c] + " ");
}
System.out.println(values[r][values[r].length - 1]);
} else {
// backwards
for (int c = (values[r].length - 1); c > 0; c--) {
System.out.print(values[r][c] + " ");
}
System.out.println(values[r][0]);
}
}
}
Output:
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
int[][] arr = new int[][]{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
AtomicInteger counter = new AtomicInteger(0);
Arrays.stream(arr).forEach(ints -> {
System.out.println(Arrays.stream(ints)
.mapToObj(String::valueOf)
.reduce((a, b) ->
counter.get() % 2 == 0 ? a + " " + b : b + " " + a).get());
counter.incrementAndGet();
});
This code uses the Stream API to iterate over an array. The first stream iterates over single-level arrays, the second - their elements, and then forms a string. Also, according to the counter value, items are combined from left to right or from right to left.
You can create such an array with a "snake order" without sorting at all, using a stream in a stream or a loop in a loop:
int m = 5;
int n = 4;
int[][] arr = IntStream
// create rows of array
.range(0, m).mapToObj(row -> IntStream
// for each row create cells where
// values are numbers from 1 to [m * n]
.range(0, n).map(cell -> {
int val = row * n;
if (row % 2 == 0)
// even rows:
// straight order
val += cell + 1;
else
// odd rows:
// reverse order
val += n - cell;
return val;
})
// return int[] array
.toArray())
// return int[][] 2d array
.toArray(int[][]::new);
int m = 5;
int n = 4;
int[][] arr = new int[m][n];
// create rows of array
for (int row = 0; row < m; row++) {
// for each row create cells where
// values are numbers from 1 to [m * n]
for (int cell = 0; cell < n; cell++) {
int val = row * n;
if (row % 2 == 0)
// even rows:
// straight order
val += cell + 1;
else
// odd rows:
// reverse order
val += n - cell;
arr[row][cell] = val;
}
}
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
// [1, 2, 3, 4]
// [8, 7, 6, 5]
// [9, 10, 11, 12]
// [16, 15, 14, 13]
// [17, 18, 19, 20]
See also:
• How do I rotate a matrix 90 degrees counterclockwise in java?
• Is there any other way to remove all whitespaces in a string?
Not as efficient as nested loops, one can simply iterator from 1 to 20 and determine row i and column j.
final int M = 5;
final int N = 4;
int[][] matrix = new int[M][N];
IntStream.range(0, M*N)
.forEach(no -> { // no = 0, 1, 2, ... , M*N-1
int i = no / N; // Row.
int j = no % N; // Increasing column (for even row).
if (i % 2 == 1) { // Odd row.
j = N - 1 - j; // Decreasing column.
}
matrix[i][j] = no + 1;
});
i % 2 is the modulo 2, rest by division of 2, hence 0 for even, 1 for odd.
Or use a bit more language features:
IntStream.range(0, N)
.forEach(i -> {
int no = N * i;
IntUnaryOperator jToValue = i % 2 == 0
? j -> no + 1 + j
: j -> no + N - 1 -j;
Arrays.setAll(matrix[i], jToValue);
});
Here Arrays.setAll(int[], (int index) -> int) fills the array based on the index.
About the question of there being some nice function:
You probably saw List.reverse; there does not exist an Arrays.reverse, hence Arrays.setAll seems to be best. In this case where the values are increasing one theoretically could also sort all odd rows reversed. But only with a trick, and sorting costs.
It is interesting that there are so many solutions. Instead of waggling the dog's tail one can take the tail and waggle the dog.

Add the consecutive digits of a birthdate recursively till it reaches to a single digit

I am developing a numerology application which has to provide a result which is similar to the following,
1 5 0 8 1 9 9 4
6 5 8 9 1 1 1
1 1 1 1 2 2
2 2 2 3 4
4 4 5 7
8 9 1
1 1
2
It has to add the consecutive digits and retain the first digit if the sum is of 2 digits.
I am missing something. Adding a while loop for the length of intList doesn't seem to work.
int date;
List<Integer> sumList = new ArrayList<Integer>();
Scanner s = new Scanner(System.in);
System.out.println("Enter the date");
date = s.nextInt();
int len = Integer.toString(date).length();
int[] convertarray = new int[len];
for (int index = 0; index < len; index++) {
convertarray[index] = date % 10;
date /= 10;
}
List<Integer> intList = new ArrayList<Integer>();
for (int i : convertarray) {
intList.add(i);
}
Collections.reverse(intList);
System.out.println(intList);
int sum = 0;
int size = intList.size();
for (int i = 0; i < intList.size() - 1; i++) {
sum = intList.get(i) + intList.get(i + 1);
int length = (int) (Math.log10(sum) + 1);
if (length > 1) {
int firstDigit = Integer.parseInt(Integer.toString(sum).substring(0, 1));
sum = firstDigit;
}
System.out.print(sum + " ");
sumList.add(sum);
}
System.out.println("\n");
intList.clear();
intList = sumList;
My output is something like,
1 5 0 8 1 9 9 4
6 5 8 9 1 1 1
A simple recursive solution:
public static void main(String[] args) throws Exception {
String birthday = "01091995";
int[] digits = Arrays.stream(birthday.split("")).mapToInt(Integer::parseInt).toArray();
recursiveFunction(digits);
}
private static void recursiveFunction(int[] digits) {
if(digits.length == 1) {
// Base Case
System.out.println(digits[0]);
} else {
// Recursive Case
System.out.println(Arrays.toString(digits));
int[] digitsProcessed = new int[digits.length -1];
for (int i = 0; i < digits.length - 1; i++) {
digitsProcessed[i] = digits[i] + digits[i+1]; // Logic
}
recursiveFunction(digitsProcessed);
}
}
This produces:
[0, 1, 0, 9, 1, 9, 9, 5] // 8 numbers
[1, 1, 9, 10, 10, 18, 14] // 7 numbers
[2, 10, 19, 20, 28, 32] // 6 numbers
[12, 29, 39, 48, 60] // 5 numbers
[41, 68, 87, 108] // 4 numbers
[109, 155, 195] // 3 numbers
[264, 350] // 2 numbers
614 // 1 number
Adding a while loop for the length of intList doesn't seem to work.
Well it can be done with loops, but it would be harder and messier.
An algorithm with recursion would be the following:
Init the array of integers.
Call the recursive function "F" with the array.
From now, the recursive function behaviour:
Check if the recieved array's length is 1.
If it is, print the element and terminate.
If it is not:
Print the recieved array.
Make a new array.
Put in this new array the result of processing the recieved one adding as intended.
Call the recursive function "F" with this new array.

Subtract elements in an array

I have an array with this values 80 82 84 90 94 is it possible to subtract the values so the output could be 0 2 2 6 4?
I´ve edited the question:Now I want to use this in an android cursor adapter but I´m getting index out of bounds when it reaches the calculation of the difference.
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
double weight = cursor.getDouble(cursor
.getColumnIndex(DbHelper.ENTRY_USER_WEIGHT));
int count=cursor.getCount();
Double[] input = new Double[count];
// Obtaining the number of records
System.out.println("number of records "+input.length);
// Array for storing differences
double[] difference= new double[count ];
difference [0] = 0; // First record difference is 0 only
int i;
// Looping number of records times
for( i=0; i<count-1 ;i++)
{
input[i]=weight;
System.out.println("i value"+i);
System. out.println(""+input[i]);
// Difference = next record - current record
difference [i]= input [i+1] - input[i];
// System.out.println ("Difference between "+input [i+1]+ " and "+input[i] + " is : " +difference[i]);
}
// Setting the input array.
int input[]= {80, 82, 84, 90, 94};
// Obtaining the number of records
int noOfRecords = input.length;
// Array for storing differences
double[] difference= new double[noOfRecords ];
difference [0] = 0; // First record difference is 0 only
// Looping number of records times
for( int i=0; i < noOfRecords -1 ;i++)
{
// Difference = next record - current record
difference [i+1]= input [i+1] - input[i];
System.out.println ("Difference between "+input [i+1]+ " and "+input[i] + " is : " +difference[i+1]);
}
System.out.println("My final difference array Output is : "+java.util.Arrays.toString( difference ));
OUTPUT:
Difference between 82 and 80 is : 2.0
Difference between 84 and 82 is : 2.0
Difference between 90 and 84 is : 6.0
Difference between 94 and 90 is : 4.0
My final difference array Output is : [0.0, 2.0, 2.0, 6.0, 4.0]
If you replace double[] difference = new double[noOfRecords ]; by
int [] difference = new int [noOfRecords];
You get an output exactly as you wanted :
Difference between 82 and 80 is : 2
Difference between 84 and 82 is : 2
Difference between 90 and 84 is : 6
Difference between 94 and 90 is : 4
My difference array Output is : [0, 2, 2, 6, 4]
Logic:
for array Arr[] = {80 82 84 90 94}
Required output = {0,2,2,6,4}
Sol:
output[0] = 0;
for( i=1;i<cursor.getCount();i++)
{
output[i] = Arr[i]-Arr[i-1];
}
Note that the output array elements are obtained by subtracting current index element with the element at previous index.
Example 82-80 =2, 84-82=2, 90-84=6 and 94-90=4
You can subtract a number from its next number.
int[] numbers={80, 82, 84, 90, 94};
for (int i = 0; i < numbers.length; i++) {
if(i < numbers.length - 1)
System.out.println(numbers[i + 1] - numbers[i]);
}
}
Output-
2
2
6
4

Algorithm design: inserting bags into containers with a limited size

I have to create an algorithm which requires adds a n number of luggage bags, each with a varying weight, into n containers each of which can hold 50kg. Each bag is loaded into a container in order.
An example string of luggage bags' weight is as follows (each number representing the weight of a bag):
16 24 25 3 20 18 7 17 4 15 13 22 2 12 10 5 8 1 11 21 19 6 23 9 14
There are two rules for filling a container with luggage:
A container can carry no more than 50 (kg) of baggage
If the next (unloaded) bag will cause the container to be overweight, place it in the next container
My final goal is to print the list of bags weight of each container. The example output for the example string of luggage bags would be:
Container 1: 16 24
Container 2: 25 3 20
Container 3: 18 7 17 4
Container 4: 15 13 22
Container 5: 2 12 10 5 8 1 11
Container 6: 21 19 6
Container 7: 23 9 14
My current code fails to create the containers, and I am now looking for a better way to do this.
public static void insertBagsContainer() {
ArrayList<ArrayList<Integer>> containerArray = new ArrayList<ArrayList<Integer>>();
int tempSum = 0;
int x=0;
for(int i=0; i<bags.size()-1; i++){
tempSum = 0;
ArrayList<Integer> innerBags = new ArrayList<Integer>();
while (tempSum<= containerWeight){
tempSum+= bags.get(x);
innerBags.add(bags.get(x));
x++;
}
containerArray.add(innerBags);
}
}
Classic example of using an iterator.
public static void main(String[] args) {
int maxWeight = 50;
ArrayList<Integer> containerWeights = new ArrayList<Integer>();
Integer[] weights = new Integer[] { 16, 24, 25, 3, 20, 18, 7, 17, 4, 15, 13, 22, 2, 12, 10, 5, 8, 1, 11, 21, 19, 6, 23, 9, 14 };
Iterator<Integer> itr = Arrays.asList(weights).iterator();
int current = itr.next(); //Get the first weight
int containerWeight = 0;
while(itr.hasNext()) {
if(containerWeight + current > maxWeight) {
containerWeights.add(containerWeight);
containerWeight = current;
} else {
containerWeight += current;
}
current = itr.next();
}
containerWeights.add(current);
System.out.println(Arrays.deepToString(containerWeights.toArray()));
}
Prints:
[40, 48, 46, 50, 49, 46, 14]
I would recommend creating a Container class that has two fields: List<Integer> container and int currentWeight, then a boolean add(Integer luggage) that returns a boolean value accordingly if the luggage was inserted or not. Then, you can have a List<Container> containers that will grow accordingly based if the luggage could be inserted or not.
In code:
class Container {
private static final int MAX_SIZE = 50;
private List<Integer> container;
private int currentWeight;
//luggage should be of type Luggage as well, just using Integer for sample purposes
public boolean add(Integer luggage) {
//implement it accordingly...
}
}
class Bags {
List<Container> containerList;
//again, it should be List<Luggage>, just for sample purposes
public void process(List<Integer> luggage) {
//implement accordingly...
}
}
The implementation details are up to you.
Just consider each innerbags list a container.
To print out container 1 you would print out the list of bags in containerArray.get(0).
Sounds like homework, so see if that gets you started...

Categories