1

I am working on a program where I take input from the user and I the enter 24 length String with numbers 0-5 and each number is repeated 4 times in the line. An example would be like this 000011112222333344445555. I realized when I am collecting the numbers for the user that I can't have them in a 2d int array of [6][4]. Which is what I want so what I want to do is take that string and put the each of the numbers in that array. So it would look like this [[0,0,0,0],[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4],[5,5,5,5]]. I am not sure how to get them into an array like this. I know that strings are immutable so I can't change the string but I did think I could take the string and turn it into char array and then insert each value into my desired int array. I don't know how to do this any help or guidance on how to approach this would be really appreciated. Thanks in advance

7
  • You're on the right track, try something and then post the code and we'll fix it. Commented Mar 2, 2017 at 3:04
  • Ok, I was thinking about what to right exactly because its something I have done in Java @DanAndrews Commented Mar 2, 2017 at 3:05
  • convert in to double , and then use divide and reminder using modulus,so that you can get each integer separately and put it into and 2darray Commented Mar 2, 2017 at 3:11
  • You can also iterate through the string and build the 2d array: stackoverflow.com/questions/196830/… Commented Mar 2, 2017 at 3:12
  • I'll give that a shot and write it up thanks for the suggestion :) @MonisMajeed Commented Mar 2, 2017 at 3:13

4 Answers 4

3

You can get your 2d array with a one liner:

int[][] numbers = Arrays.stream("000011112222333344445555".split("(?<=\\G.{4})")).map(s -> (Arrays.stream(s.split("(?<=\\G.{1})")).mapToInt(Integer::parseInt).toArray())).toArray(int[][]::new);
Sign up to request clarification or add additional context in comments.

2 Comments

This too does work out, awesome that you were able to do this all in one line, I don't know a lot of regex but it gets the job done :)
Very nice solution!
2

So its fairly easy thing to do.

lets assume your string is str;

char[] strArr = str.toCharArray();

// numbers is the range like 0 to 5 here.
// repeatCount is how many times its repeating like 4 here.

int arr[][] = new int[numbers][repeatCount];

for(int i = 0; i < numbers; i++){
    for(int j = 0; j < repeatCount; j++){
         arr[i][j] = strArr[i*repeatCount + j]-'0';
    }
}

Lastly a precaution, this function will work only if your numbers are single digit, as only one char is being picked.

9 Comments

I am not really concerned about making sure if the numbers are repeated 4 times and that they are 0-5 because they always are ensured to be. I am just wondering how to take that sting and turn it into that an array of [6][4]
Ok, let me explain it. 1) Covert the string to a char array using String class function toCharArray().
Buddy, then its just math.
Buddy, then its just math. Take a pen paper and write down the single char array in 2D form which you needed. Each point in a matrix has a different row and column value. Now flatten that 2D matrix row wise, I mean you put all the rows in a single line. Also write the row and column value on top of this flattened list. Now find the relationship between original position and the row and column numbers.
Ok here is what I have done but when I print it out I get 00004123244121533424123 not any form of an array finishedString = cubeString; System.out.println(finishedString); char [] cubeToArr = finishedString.toCharArray(); int [][] cube = new int [6][4]; for(int i = 0; i < 6; i++){ for(int j = 0; j < 4;j++){ cube[i][j] = cubeToArr[i * 4 + j]-'0'; } } System.out.println(cube.toString());
|
2

Tested on https://www.compilejava.net/ Also works if you have something different than:

I the enter 24 length String with numbers 0-5 and each number is repeated 4 times in the line

import java.util.ArrayList;
public class HelloWorld
{

  public static void main(String[] args)
  {
    String s = "00001111222233334444555599";
    ArrayList<ArrayList<Integer>> collection = new ArrayList<ArrayList<Integer>>();
    for (int i = 0; i <= 9; i++){
        collection.add(new ArrayList<Integer>());
    }

    for (int i = 0; i < s.length(); i++){
        int c = Character.getNumericValue(s.charAt(i));        
        collection.get(c).add(c);
    }

    for (int i = 0; i <= 9; i++){
        System.out.println(collection.get(i));
    }

    System.out.println(collection);
  }
}

Results:

[0, 0, 0, 0]
[1, 1, 1, 1]
[2, 2, 2, 2]
[3, 3, 3, 3]
[4, 4, 4, 4]
[5, 5, 5, 5]
[]
[]
[]
[9, 9]
[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5], [], [], [], [9, 9]]

2 Comments

what are the dimensions of int to complete the ReferenceType?
Its alright are you aware of NPE's ?The line ints[c].add(c) doesn't add any thing to to c
0

So you know your string must have 4 repeating elements, I assume after 4 repeats, a new value follows. So to me it seems like an N x 4 array.

Thus you can do, and I will do pseudocode for now to help guide you.

int[][] myArray = new int[str.length/4][4]

We divide by four since we know if we have "000011112222" our total length is 12. 12/4 is 3 and we would expect 3 columns. 4 is the amount of columns we have, and we know it will be only 4.

After that, and in here I assume you are entering the values one after the other, without any delimiter. We can do:

    int col = 0;
    int row = 0;
for(i from 0 to string length) {
    if((I+1) % 4 != 0) {
       //keep adding to myArray[row][col]
       //row++
      }
    } else { // so we now hit new numbers
       col++;
       row = 0;
      }
}

So in here I tried to stick to only one for-loop. I was thinking of doing it with a double for-loop, but wasn't sure on how I would approach it in this case since we are dealing with an empty array initially.

Quick edit, one thing you could do, btw. Is make a 2D List as so:

List<List<String>> strings = new ArrayList<List<String>>()

int index = 0;
while (index < text.length()) {
    String pattern = text.substring(index, Math.min(index + 4,text.length()));
   List<String> splitPattern = Arrays.asList(pattern.split(""));
   strings.add(splitPattern);
    index += 4;
}

So the logic here is we make a substring, split it on "" so nothing in otherwords it will just produce 0, 0, 0, 0 as the delimiter is nothing. and then we add it to our list of lists, and you would access by saying strings.get(I).get(j);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.