Adding elements of an Integer array in Java

I have an array, say

int a[]={2,0,1,0,1,1,0,2,1,1,1,0,1,0,1};

      

I need to add each of 5 adjacent elements and assign them to a new array b

with length=(a.length/5);

, and I want to add 5 adjacent elements so that I have: int b[]={20101,10211,10101};

I need to do this for different arrays of lengths, in most cases the length is a

greater than 15.

Any help would be greatly appreciated, I am programming in Java.

Thanks in advance.

+2


a source to share


5 answers


This is pretty weird:



// Assuming a.length % 5 == 0.
int[] b = new int[a.length / 5];
for (int i = 0; i < a.length; i += 5) {
    b[i/5] = a[i]*10000 + a[i+1]*1000 + a[i+2]*100 + a[i+3]*10 + a[i+4];
}

      

+4


a source


This sounds like a homemade question, so I won't give you a complete solution, but the main point is:

  •  
  • Calculate length of b: len = a.length / 5 
  • Create b with that many elements. 
  • Initialize subscript variable to point to first element in 
  • For each item from b:        
    •             
    • Construct the value for this element from [idx] ... a [idx + 4]            
    • Promote the index by 5.        
     


Also note that you may need to check that the input a is actually a multiple of 5 in length.

+2


a source


This works with (a.length % 5) != 0

and contains leading zeros (by storing digits in String

).

    int a[]={2,0,1,0,1,1,0,2,1,1,1,0,1,0,1,0,0,7};

    final int N = 5;
    String b[] = new String[(a.length + N - 1)/ N];
    StringBuilder sb = new StringBuilder(N);
    int x = 0;
    for (int i = 0; i < b.length; i++) {
        sb.setLength(0);
        for (int k = 0; k < N && x < a.length; k++) {
            sb.append(a[x++]);
        }
        b[i] = sb.toString();
    }
    System.out.println(java.util.Arrays.toString(b));
    // prints "[20101, 10211, 10101, 007]"

      


Alternatively, you can also use regex:

    String[] arr =
        java.util.Arrays.toString(a)
        .replaceAll("\\D", "")
        .split("(?<=\\G.{5})");
    System.out.println(java.util.Arrays.toString(arr));
    // prints "[20101, 10211, 10101, 007]"

      

It basically uses Arrays.toString(int[])

to append all digits to one long String

, then remove all non-digit characters \D

and then use \G

-anchored lookbehind to separate each.{5}

+1


a source


A naive approach.

import java.util.ArrayList;

/* Naive approach */
public class j2728476 {
    public static void main(String[] args) {
        int a[] = {2,0,1,0,1,1,0,2,1,1,1,0,1,0,1};
        ArrayList<String> al = new ArrayList<String>();
        String s = "";
        for (int i = 0; i < a.length; i++) {
            if (i % 5 == 0 && i != 0) {
                al.add(s);
                s = "" + a[i];
            } else {
                s += a[i];
            }
        }
        al.add(s);
        for (String t : al) {
            // convert values to ints ...
            System.out.println(t);
        }
    }
}

      

This will print:

20101
10211
10101

      

0


a source


import java.util.Arrays;

public class MainClass {
   public static void main(String args[]) throws Exception {
      int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 1);
      System.out.println("Didn't find 1 @ "
      + index);
      int newIndex = -index - 1;
      array = insertElement(array, 1, newIndex);
      printArray("With 1 added", array);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message
      + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if (i != 0){
            System.out.print(", ");
         }
         System.out.print(array[i]);         
      }
      System.out.println();
   }
   private static int[] insertElement(int original[],
   int element, int index) {
      int length = original.length;
      int destination[] = new int[length + 1];
      System.arraycopy(original, 0, destination, 0, index);
      destination[index] = element;
      System.arraycopy(original, index, destination, index
      + 1, length - index);
      return destination;
   }
}

      

It will print

Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Didn't find 1 @ -6
With 1 added: [length: 11]
-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8

      

0


a source







All Articles