java - Store values from pyramid in jagged array -


here's code:

arraylist<arraylist<integer>> nums = new arraylist<>();     int index = 0;     for(int = 0; < 15; i++){         nums.add(new arraylist<integer>());         int j = 0;         while(!(j > i)){             if(character.isdigit(pyramid.charat(index))){                 string s = "" + pyramid.charat(index) + pyramid.charat(index + 1);                 int c = integer.parseint(s);                 nums.get(i).add(c);                 j++;                 index++;             }             index++;         }     } 

'pyramid' string contains fifteen-row pyramid of numbers (top row has 1 number, next row has 2 numbers, etc.). doing way, jagged arraylist.

my question how accomplish array? way can think of numbers in own array make 2d array 15 arrays long 15 spots in each array. bit of waste since won't using every index of every array (i use every index last one). ideas?

if want initialize 2d jagged array this:

 public static void main( string [] args){    int [][] jaggedarray = new int [15][];    (int i=0; i<15; i++){      jaggedarray[i] = new int[i+1];  }  

however, in question looks you're checking @ runtime if characters in string numbers , adding them dynamically. problem arraylists vs arrays former lets change size dynamically whereas latter doesn't. either have to:

  • know static size ahead of time , intialize way above
  • go through string , determine static size others have said , initialize it
  • otherwise, need use data structure allows dynamic resizing

also, i'm not sure of application, if you're guaranteed thing won't bigger 15x15, wouldn't worry tiny bit of over-allocation.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -