views:

221

answers:

7

hello all.

I have an array:

int test[]={10212,10202,11000,11000,11010};

I want to split the inetger values to individual digits and place them in a new array as individual elements such that my array now is:

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

How would i go about doing that? I'm doing this in java.

Thank you.

A: 

You'd take each integer, divide by 10 and separate the fraction from the remainder. multiply the fraction by 10 to make it an integer again and put it into your new array. Repeat until you run out of digits. Repeate until you run out of integers in your input array.

High Performance Mark
Using mod 10 you can prevent floating point arithmatic.
rsp
Also, you'd end up with each number's digits reversed using this method or @Timmmm's... it would be simpler to use a String-based method I think (as Joachim pointed out, there's no indication that performance is a concern here).
Steven Mackenzie
A: 

Try something like this.

{
  int test[]={10212,10202,11000,11000,11010};
  int test2[] = new int[25];
  int i = 24;

  int temp;
  for(int n = test.size() - 1; n >= 0; n--){
    temp = test[n];
    while(temp > 0){
      test2[i--] = test % 10; // <= Gets remainder of division by 10.
      test /= 10; // <= Stores the integer result of the division.
    }
  }
}

I have not tested this code.

This code would ignore leading zeroes (Naturally) and backfill the array of integers. Getting the proper size for the array could be a problem.

zipcodeman
+5  A: 

You can go as suggested by Mark, or convert them to String to get the single digits:

int test[]={10212,10202,11000,11000,11010};
ArrayList<Integer> test2 = new ArrayList<Integer>();

for (int i : test)
{
  String str = String.valueOf(i);
  for (int j = 0; j < str.length(); ++j)
    test2.add((int)(str.charAt(j)-'0'));
}

As more memory efficient approach that still involves string would be to keep all the digits as just one string and calculate the int value on the fly:

class Digits
{
  String str;

  Digits(int[] nums)
  {
    StringBuilder sb = new StringBuilder();
    for (int i : nums)
      sb.append(String.valueOf(i));

    str = sb.toString();
  }

  int length()
  {
    return str.length();
  }

  int nth(int i)
  {
    return (int)(str.charAt(i)-'0');
  }
}

Mind that CheesePls solution is the right one because it uses math as it is intended to be used. Mine is just for noobs (and just to give another approach to the problem)..

Jack
Converting it back and forth from a string would be very inefficient.
zipcodeman
@zipcodeman: as would storing each digit in its own `int`. So what's your point?
Joachim Sauer
String does not need to be involved.
zipcodeman
we are not talking about efficiency I suppose, it was just to suggest an alternative way. Everyone should know that using modulo and division compared to generating strings is more efficient. But it wasn't the point.. the user isn't asking for an efficient way.. be creativ please, especially when talking about things that wouldn't affect efficiency unless working with millions of integers.
Jack
There is absolutely nothing wrong with using strings. Strings tend to make things a tad more complicated (and annoying) when it comes to actual coding and that's the only real reason to avoid this way of doing it.
CheesePls
There is really nothing wrong with using the existing classes (in this case `String`) in your language rather than rolling your own logic. Yes, `String` is slow and takes up more memory, but until that starts becoming a problem, there is no practical reason to avoid this solution IMHO.
MAK
A: 

This (untested):

int test[] = {10212,10202,11000,11000,11010};
ArrayList<Integer> test2 = new ArrayList<Integer>();

for (int i : test)
{
  int p = test2.size();
  while (i > 0)
  {
     test2.add(p, i % 10);
     i /= 10;
  }
}
Timmmm
A: 

Here's a way to do it with strings. Not particularly performant, but (I hope) easy to understand.

package playground.tests;

import junit.framework.TestCase;

public class SplitIntegerTest extends TestCase {

    public void testIntsFromOneInteger() throws Exception {
        assertEqualArrays(new int[] { 1, 0, 2, 1, 2 }, intsFrom(10212));
    }

    public void testIntsFromArray() throws Exception {
        int test[] = { 10212, 10202, 11000, 11000, 11010 };

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

        assertEqualArrays(test2, intsFrom(test));
    }

    private int[] intsFrom(int[] input) {
        int[][] list = new int[input.length][];
        for (int i = 0; i < input.length; i++)
            list[i] = intsFrom(input[i]);
        int n = 0;
        for (int[] array : list)
            n += array.length;
        int[] result = new int[n];
        int index = 0;
        for (int[] array : list)
            for (int i : array)
                result[index++] = i;
        return result;
    }

    private static int[] intsFrom(Integer n) {
        String s = n.toString();
        int[] result = new int[s.length()];
        for (int i = 0; i < result.length; i++)
            result[i] = intFrom(s.charAt(i));
        return result;
    }

    private static int intFrom(Character c) {
        return Integer.parseInt(c.toString());
    }

    private static void assertEqualArrays(int[] a, int[] b) {
        assertEquals(a.length, b.length);
        for (int i = 0; i < b.length; i++)
            assertEquals(a[i], b[i]);
    }

}
Carl Manaster
+6  A: 
int[] test={10212,10202,11000,11000,11010};
ArrayList<Integer> test2 = new ArrayList<Integer>();


for(int i = test.length -1; i >= 0; i--){
    int temp = test[i];
    while(temp>0){
        test2.add(0, temp%10);  //place low order digit in array
        temp = temp /10;        //remove low order digit from temp;
    }
}

This will do exactly what you want by placing the lowest order digit of an entry into the "front" of an arraylist, and therefore in front of the previous low order digits/entries.

If you need it to be in an Array, ArrayList has a toArray method.

CheesePls
This is more memory-efficient than Jack's solution, since no intermediate string is needed, but some developers might have a harder time understanding it. In most cases, I would go with Jack's, but I'm voting this one up.
Neil Whitaker
I don't understand whats so difficult about going through an array backwards or basic integer manipulation. It's as basic as a countdown or 5th grade math.-but yea, reading the for-statement could be tricky if you aren't used to it.
CheesePls
@neilwhitaker1: if developer have a problem understanding this basic piece of code then they are obviously not math oriented **at all** (because this is really basic) and maybe they should, well, start either learning or looking for another job ; )
Webinator
A: 

Almost one-liner (if we assume that there is an out of the box function for converting array of strings to array of integers):

int test[]={10212,10202,11000,11000,11010};
int result[] = strArray2IntArray (
                  Arrays.toString (test)
                 .replaceAll ("\\D", "")
                 .replaceAll ("(\\d)", "$1 ")
                 .split (" ")
               );

private static int[] strArray2IntArray (String[] array) {
    int[] result = new int[array.length];
    for (int i = 0; i < result.length; i++) {
        result[i] = Integer.parseInt (array[i]);
    }
    return result;
}
Roman