how to print a list of numbers with a merged sum?

0

I have this list of 1 a 10 .

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Code:

List <Long> lista = new ArrayList();

for (long a = 1; a <= 10; a++) {
 lista.add(a);
 System.out.print(lista);
}

You would need a merged sum in this list, with a variable.

For example:

List <Long> lista = new ArrayList();

    long x,z=200;

for (long a = 1; a <= 10; a++) {

  x=z+a;
  lista.add(x);

        }
 System.out.print(lista);
    }
}

Instead of printing the normal list + 200 :

[201, 202, 203, 204, 205, 206, 207, 208, 209, 210]

I wanted the sum to be interleaved one yes another not ..

[1, 202, 3, 204, 5, 206, 7, 208, 9, 210]

And I also wanted to be able to change that distance from how many jumps to give the sum in the list could be from 2 to 2 or 5 to 5 ... from 30 to 30 . .. understands .. depending on the size of the list ... list from 1 to 100 from 1 to 10000 ...

Running on Repl: link

    
asked by anonymous 07.07.2018 / 01:32

3 answers

4

If you already have the list built, and want to apply a sum, by jumping from x to% with% elements, just a x with an increment of for in x that stops when it reaches the amount of list elements:

int avanco = 3;
int numSoma = 500;
for (int i = avanco - 1; i < lista.size(); i += avanco) {
    lista.set(i, lista.get(i) + numSoma);
}

System.out.println(lista);

For a list x the above code produces the following result:

[1, 2, 503, 4, 5, 506, 7, 8, 509, 10]

Confirm on Ideone

Replare that I changed the value of each element of the list with the method [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and got the previous value with set . The start of get had to be with for since arrays start in avanco - 1 .

However, a better solution would be to generate the list with the elements you want, thus avoiding unnecessary processing:

int avanco = 3;
int numSoma = 500;
List <Long> lista = new ArrayList<>();
for (long a = 1; a <= 10; ++a){
    lista.add(a % avanco == 0 ? a + numSoma: a);
}

System.out.println(lista); //[1, 2, 503, 4, 5, 506, 7, 8, 509, 10]

See this example on Ideone

Now add only the 0 in normal cases, and when the current number is a multiple of a add the sum of the two. So the list is all generated at once with the sums you want.

    
07.07.2018 / 02:26
0

This answer suits your problem.

List <Long> lista = new ArrayList();
long x=200;
long pulo = 3;
for (long a = 1; a <= 10; a++) {
 if((a % pulo) == 0){
  lista.add(x+a);
 }else{
   lista.add(a);
 }
}
System.out.print(lista);
    
07.07.2018 / 02:25
-2
int x,z = 10;
for (int a = 0; a <=10; a+=2) {
    x = z+a;
    System.out.print(a + ", " + x + ", ");
}
    
07.07.2018 / 01:42