-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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gabriela M
  • 605
  • 1
  • 10
  • 25
  • Have you at least tried to solve? Show us some code of what you tried. – Gianlucca Sep 22 '18 at 18:31
  • Look for list partitioning in java. Check this post: https://stackoverflow.com/questions/2895342/java-how-can-i-split-an-arraylist-in-multiple-small-arraylists – Beri Sep 22 '18 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. – MC Emperor Sep 22 '18 at 18:43

2 Answers2

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++];
  }
}
fnmps
  • 143
  • 6
  • `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] – RaffleBuffle Sep 22 '18 at 18:56
  • Thanks @SirRaffleBuffle, edited answer accordingly. – fnmps Sep 22 '18 at 19:00
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);
Coding Bad
  • 252
  • 1
  • 4
  • 12