-2

I can sequentially retrieve the following list of elements in Java and I need to insert them in an AxB dimension matrix. How can I put these elements in their order to the matrix?

Element: rainy
Element: hot
Element: high
Element: false
Element: No
Element: rainy
Element: cold
Element: normal
Element: true
Element: yes

My desired output is this:

array = [[rainy, hot, high, false, No],[rainy, cold, normal, true, yes]]

How to begin?

3
  • Have you at least tried to solve? Show us some code of what you tried. Commented Sep 22, 2018 at 18:31
  • Look for list partitioning in java. Check this post: stackoverflow.com/questions/2895342/… Commented Sep 22, 2018 at 18:34
  • But I suggest you create a class holding related data. You could create, for instance, a class Weather or something, with fields like precipitation, temperature, et cetera. Commented Sep 22, 2018 at 18:43

2 Answers 2

0

The question is not very clear for me, but since I cannot comment yet here goes an answer:

I am going to assume that you have your data in an array (like so String [] dataset) and want to convert it in a bidimensional array so here are the steps.

First initialize the bidimensional array with your AxB size:

int a = dataset.length/5; // the size of your dataset divided by the chuncks
int b = 5; // the size of your chunck
String[][] processedDataset = new String[a][b];

Then you want to fill in the bidimensional array with your dataset. This can be done with a basic for loop:

int k = 0;
for(int i = 0; i < processedDataset.length; i++){
  for(int j = 0; j < processedDataset[i].length; j++){
    processedDataset[i][j] = dataset[k++];
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

dataset[i+j] should be dataset[i*processedDataset[i].length+j]. Another option is to use a third loop variable, k, initialized to 0 in the outer for loop and incremented in the inner for loop, then access dataset[k]
Thanks @SirRaffleBuffle, edited answer accordingly.
0

You can use the guava library for partitioning Guava list partition

List<String> element= //...
List<List<String>> smallerLists = Lists.partition(element, # of partition you want);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.