Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Convert array to array of arrays  RSS feed

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My program takes from the user the upper bound (of the primes to be displayed finally) to be the size of the array. The isPrime(int[]) method is called by passing the array containing the primes and non-primes. The method
Original code:

prints out the primes from this array as shown in the output.
Output:


Continuing with the above example, I modified the program to display the results as an array of arrays (row * col matrix i.e 5 * 5 as the count of primes below 100 is 25). Array of arrays hereafter called 2d array and the array 'array1d' as 1d array for the sake of brevity. The modifications include:
  • the program takes from the user the number of rows and columns for displaying the primes in 5 * 5 matrix, besides the upper bound
  • the isPrime method takes in two additional parameters defining the rows and columns i.e isPrime(int[], int, int)
  • within the method, creating a 2d array 'array2d' of appropriate size
  • assign each element of the 1d array (containing the prime) to the 2d array by looping thru the same and print the result


  • The isPrime method modified


    and its (wrong) output

    Whereas my objective is to print them as

    Could the problem be

  • my looping structure vis-a-vis 1d array to 2d array and / or
  • ternary operator in line no.32 of the modified code (I'm aware that java has boolean true or false values only and does not support implicit casting to int values like 1 or 0)


  • Could any of the forum expert(s) help in resolving this.

    Thanks,

    Sudhir

     
    Ranch Hand
    Posts: 375
    1
    Java Python Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    **** Nested Loop upto 4 levels??? [DANGER]

    The code that assigns the prime number to your 2-D array is inside the nested for-loop for iterating the array...
    If your :-
    is inside your loop: -

    You will get the same value for all the cells..

    *PS: - Your one method isPrime() is doing so many of task..
    1). It is iterating over the array,
    2). It is finding which number are primes among them,
    3). plus it is creating new 2D array for those prime numbers
    4). Finally it is printing the array..

    Ideally a single method should do a single job...

    Try to separate your task this way.. Life would be comparatively easy..

    * Advice : - Before getting onto writing a code on the computer, you should first spend few minutes with pencil and paper..
    Bullet down the things you need to do, in a particular order.. And also write how would you do it generally out of the code..
    Them, convert those steps into program one step at a time..
     
    Bartender
    Posts: 10575
    66
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:Whereas my objective is to print them as
    ...
    Could the problem be...


    Actually, the basic problem is that you don't need to convert the array in order to print it out the way you want. So I guess the next question is:
    Do you want to know how to convert a simple array to a matrix, or do you simply want to print it out like one?

    BTW, could you please edit your post to remove all those enormous lines? It makes your Thread very hard to read; and it's also bad coding practise.
    I'd do it for you, but there are tons of them.

    I suggest you re-read the UseCodeTags (←click) page. Thoroughly.

    Winston
     
    R. Jain
    Ranch Hand
    Posts: 375
    1
    Java Python Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Did you read my last post in this topic?? I think I have stated the problem with your code there..

    Still, I'll try to help you again.. Look at your 4 level nested for loop..
    1). The 2 outer loop is iterating over rows and columns (Generally done to access each cell of a matrix)
    2). The inner two for loops is iterating over a 1-D array to find out what numbers are prime..

    Problem # 1: - You are running Step#2 completely for each cell.. So, every time you do step#2, you will get the same value.. (The last prime number in your array)
    Problem # 2: - Every time you find a Prime number in step#2, you are assigning it to the current cell in the matrix : - array2D[x][y]
    But, ultimately, only the last value will be stored in the cell (Since you are running this loop completely for each cell)

    What exactly is happening here: - For each cell, you are iterating over the 1D array, and assigning the last prime number to that cell (So, the same value 97).



    Now, try to simplify your approach (Preferably, reduce the level of nesting you have for that loop)..
    Try to come up with some modification, then see how it works..
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    At the outset, thank you for your response and suggestions.

    R. Jain wrote:The code that assigns the prime number to your 2-D array is inside the nested for-loop for iterating the array...
    If your :-
    is inside your loop: -

    You will get the same value for all the cells..



    I'm not sure I understand. I need to assign each array element (containing the prime)

    to the 2d array and print the same in the matrix. Without the nested for loop how do I traverse the columns within each row and
    populate with values? Please explain with sample code.

    R. Jain wrote:
    *PS: - Your one method isPrime() is doing so many of task..
    1). It is iterating over the array,
    2). It is finding which number are primes among them,
    3). plus it is creating new 2D array for those prime numbers
    4). Finally it is printing the array..

    Ideally a single method should do a single job...

    Try to separate your task this way.. Life would be comparatively easy..



    You are right. I did do the separation of concerns -

  • One method to determine whether the number is a prime(from the array of primes and non-primes)
  • Another method to iterate through the array, call the boolean method with each number
    (from the source array) and print the values for which the method returns true

  • - initially as the code below depicts

    and its successful output(without the matrix).

    I was stuck in the line of code (line no.8)where the boolean method isPrimeNum is called (from the isPrime method), and
    not sure how to go about printing the boolean 'true' values as primes in the matrix. So, ended up combining
    the lot and net result
    How can this be resolved? Much appreciate your suggestions in this regard.
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    R. Jain wrote:Did you read my last post in this topic?? I think I have stated the problem with your code there..

    Still, I'll try to help you again..


    I was busy replying to your earlier post and with slow internet connection got to see your current post only after I uploaded my response. Will certainly work around my original code as suggested and get back to you.

    Many Thanks,

    Sudhir
     
    R. Jain
    Ranch Hand
    Posts: 375
    1
    Java Python Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:

  • One method to determine whether the number is a prime(from the array of primes and non-primes)


  • Why you need to pass array the again into the method whose sole purpose is to find whether the passed number is prime or not??

    Sudhir Srinivasan wrote:

    So, ended up combining the lot and net result


    You should call your isPrimeNum() method with only one argument (i.e. the number itself which your checking for Prime)..
    What you are doing is, iterating over the array (in isPrime() method) and for each number, you are calling the isPrimeNum() method,
    and there also, I don't know why, you are iterating over the passed array again..

    Your isPrimeNum() should look like this: -

    And call this method from your isPrime() like this: -
     
    R. Jain
    Ranch Hand
    Posts: 375
    1
    Java Python Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Winston Gutkowski wrote:

    Sudhir Srinivasan wrote:Whereas my objective is to print them as
    ...
    Could the problem be...


    So I guess the next question is:
    Do you want to know how to convert a simple array to a matrix, or do you simply want to print it out like one?
    Winston


    Also Sudhir, consider answering the question earlier asked by Winston..
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Winston Gutkowski wrote:
    Actually, the basic problem is that you don't need to convert the array in order to print it out the way you want. So I guess the next question is:
    Do you want to know how to convert a simple array to a matrix, or do you simply want to print it out like one?



    It would be of great help if you could explain both concepts.

    Winston Gutkowski wrote:
    BTW, could you please edit your post to remove all those enormous lines? It makes your Thread very hard to read; and it's also bad coding practise.
    I'd do it for you, but there are tons of them.

    I suggest you re-read the UseCodeTags (←click) page. Thoroughly.

    Winston



    I'd uploaded in a hurry and therefore my post ended up with long lines. Sorry. I've trimmed the same and posted again. Hope this enhances the readability for other forum members.

    Thanks,
    Sudhir
     
    Marshal
    Posts: 61741
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote: . . . Sorry. I've trimmed the same and posted again. Hope this enhances the readability for other forum members.

    Thanks,
    Sudhir

    Apologoies accepted (). I am afraid reposting does not enhance readability, and reposting different code inside quote tags simply causes confusion. People expect what is in quote tags to be exactly what was posted before.

    I think, to recognise your effort, I shall tidy up the code. I shall delete the unnecessary duplications and go back and edit your code to what it ought to have looked like.
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    R. Jain wrote:
    You should call your isPrimeNum() method with only one argument (i.e. the number itself which your checking for Prime)..


    While you are right about passing just each number, your suggested code vis-a-vis isPrimeNum(int n) method

    R. Jain wrote:


    returns

    where, as you're aware, the nos. 0,1,9,15......etc. to name a few are not primes
    This could be due to

    a) Array passed to isPrime(int[], int, int) contains array elements & their values sequentially i.e from 0 to upperbound-1
    b) isPrimeNum(int) when called then checks and returns true for those values that are prime
    c) In the for loop i is evaluated against 1st array element value 0. As the condiiton is false, straightaway exits the for loop and
    returns true. This is the same when evaluated against 2nd array element value 1.
    d) In the case of other array element values, the if construct checks for their divisibility by 2 only (which requires an inner
    for loop to check for divisibility by numbers between 2 and arraysize-1......as provided for in my original code).

    R. Jain wrote:
    Still, I'll try to help you again..
    ---
    ---


    Now, try to simplify your approach (Preferably, reduce the level of nesting you have for that loop)..
    Try to come up with some modification, then see how it works..


    I'm working on modifying the problem area as suggested and get back to you once resolved OR where I'm stuck.

    Thank you for your time and patience.

    Sudhir

     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:

    Winston Gutkowski wrote:
    Actually, the basic problem is that you don't need to convert the array in order to print it out the way you want. So I guess the next question is:
    Do you want to know how to convert a simple array to a matrix, or do you simply want to print it out like one?



    It would be of great help if you could explain both concepts.



    Winston - Could you please show how to convert a simple array to a matrix.

    Thanks,
    Sudhir
     
    R. Jain
    Ranch Hand
    Posts: 375
    1
    Java Python Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:
    0 1 2 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
    where, as you're aware, the nos. 0,1,9,15......etc. to name a few are not primes


    Ah!! I'm sorry..
    Change the (number % 2 == 0) to (number % i == 0) in the for loop.. Then it would work..
     
    Campbell Ritchie
    Marshal
    Posts: 61741
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Have you come across the Sieve of Eratosthenes for finding prime numbers?
     
    R. Jain
    Ranch Hand
    Posts: 375
    1
    Java Python Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:Have you come across the Sieve of Eratosthenes for finding prime numbers?


    That was something worth knowing... thanks Campbell
     
    Campbell Ritchie
    Marshal
    Posts: 61741
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You’re welcome The Sieve is in many of the basic programming books.
     
    Sudhir Srinivasan
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:

    R. Jain wrote:
    What exactly is happening here: - For each cell, you are iterating over the 1D array, and assigning the last prime
    number to that cell (So, the same value 97).


    arrayPrime[(x * row) + y] = arrayPrime[i];
    array2d[x][y] = arrayPrime[(x * row) + y]; /* This is the PROBLEM */ /* It should not be inside your innermost for loop.. */



    Now, try to simplify your approach (Preferably, reduce the level of nesting you have for that loop)..
    Try to come up with some modification, then see how it works..


    I'm working on modifying the problem area as suggested and get back to you once resolved.......



    Success! I've got the desired output by using the

  • isPrimeNum(int) method to determine the number is prime........refer my previous post
  • isPrime(int[], int, int) method to iterate over the source array, call the boolean method with each number
    (from the source array)........refer my previous post
  • and
  • assign the next element, for which the method returns true, to each cell of the matrix.

  • [sidebar]break the innermost loop after primality is established. Each element to be stored as 1d array
    elements of the 2d array within the outer nested loop[/sidebar]

  • Finally, use the outer nested loop (the loop used to iterate over the rows and columns) again to initialize each
    2d array element by the 1d array elements (of the 2d array) and print the primes stored thereof........by setting the
    loop structure properly, the results can be displayed for 'n' rows * columns and not restricted to the 5 * 5 I had
    started out with.


  • I know the last 2 points seem confusing given the level of nesting but can be overcome [by modifying the loop
    structure thru trial & error as I'd done and] as shown by the sample outputs


    Regards,

    Sudhir
     
    R. Jain
    Ranch Hand
    Posts: 375
    1
    Java Python Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    That's good.. Nice to see that you were working on that code for so long..
    Normally I forget about a code that old..

     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!