• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reverse an array in java

 
Michael Pickens
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am working on yet another homework assignment. This assignment is asking me to write a program which creates an array with its size determined by users and filled with random numbers between 1 and 100.

I must obtain the number of random numbers from the user through a GUI dialog box.
The 2 guidelines that my professor is requiring are:
1) My program should have at least two methods, "displayArray" and "reverse"
2) I am not allowed to create a new array within the method "reverse" to perform the task.

I have this code completely written, and I am having trouble reversing ALL the digits.

Output of my program: 7 random digits
myArray[0] = 5
myArray[1] = 14
myArray[2] = 88
myArray[3] = 18
myArray[4] = 20
myArray[5] = 8
myArray[6] = 46
myArray[7] = 100
After reversing the array
myArray[0] = 100
myArray[1] = 46
myArray[2] = 8
myArray[3] = 20
myArray[4] = 20
myArray[5] = 8
myArray[6] = 46
myArray[7] = 46

And since I am not allowed to simply make a new array, the code posted below is how I am handling the reverse.



Thanks again for the help.
 
Henry Wong
author
Marshal
Pie
Posts: 21015
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Michael Pickens wrote:I am working on yet another homework assignment. This assignment is asking me to write a program which creates an array with its size determined by users and filled with random numbers between 1 and 100.

I must obtain the number of random numbers from the user through a GUI dialog box.
The 2 guidelines that my professor is requiring are:
1) My program should have at least two methods, "displayArray" and "reverse"
2) I am not allowed to create a new array within the method "reverse" to perform the task.

I have this code completely written, and I am having trouble reversing ALL the digits.

Output of my program: 7 random digits
myArray[0] = 5
myArray[1] = 14
myArray[2] = 88
myArray[3] = 18
myArray[4] = 20
myArray[5] = 8
myArray[6] = 46
myArray[7] = 100
After reversing the array
myArray[0] = 100
myArray[1] = 46
myArray[2] = 8
myArray[3] = 20
myArray[4] = 20
myArray[5] = 8
myArray[6] = 46
myArray[7] = 46

And since I am not allowed to simply make a new array, the code posted below is how I am handling the reverse.



Thanks again for the help.


Take out some paper and a pen, and play compuiter -- follow your code, with some data, and you will quickly see what you are doing wrong.

Henry
 
Michael Pickens
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have run through this with pencil and paper several times. I am not catching the error. I thought that since I really only need to go through half of the array that I could do arrayOne.length / 2, but that of course only gives me half of the array, but chops off the non reversed section.

Thanks.
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If the intention is to copy a content using temp variable I will do like
A = temp;
A = B;
B = temp;
Is your B holder the same in both the places?
 
Michael Pickens
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I changed that code to match:

 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok what happened when you tried by length / 2 in the changed code? Can you show us what you tried?
 
Michael Pickens
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I changed the code to try to adjust the length. I see from doing a series of println statements .. that I am only switching the first and last statements, then switching them back.



What started out for me as a logical process has now turned into a big guessing game . when i added the /2 to the length, it only prints out like this:
myArray[0] = 36
myArray[1] = 91
myArray[2] = 56
myArray[3] = 22
myArray[4] = 14
myArray[5] = 37
myArray[6] = 49
After reversing the array
myArray[0] = 49
myArray[1] = 37
myArray[2] = 14

thus you can see I am missing 4 out of 7 indexes.. i suppose that is because arrayOne.length/2 = 3 (7/2=3).
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess you got the logic correct in reversing the array. The problem should be in the print statement within the for loop. It only prints as long as the loop checks the value of i.

Have the print statement as a separate and try to print all contents of the array & check.
 
Winston Gutkowski
Bartender
Pie
Posts: 10259
59
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Michael Pickens wrote:What started out for me as a logical process has now turned into a big guessing game . when i added the /2 to the length, it only prints out like this:

I suspect it's because you haven't "played computer" enough yet. You really do need to understand the problem before you can code it, so my advice to you is:
TURN YOUR COMPUTER OFF.
And, rather than writing Java code, try to describe the reversing process in English (or your native language).

What exactly are you doing inside the loop (ie, on each iteration)?
It might make it clearer if you actually put it into a separate method; and if you did, what would you call it?

thus you can see I am missing 4 out of 7 indexes.. i suppose that is because arrayOne.length/2 = 3 (7/2=3).

Again, I think you're getting a bit bogged down in the detail.
Tip: You are NOT restricted to only one index inside a for loop. It's quite permissible to do something like:
for (int i = 0, j = 10; {some condition}; i++, j++) { ...
(NOTE: The above is for illustration only)

HIH

Winston
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would also suggest you do it the object-oriented way, which is not to create new objects. Not in this instance. You write yourself a utility class, which has all static members. You give it a private constructor, so nobody can instantiate that class. You give it some methods. In this case you require two methods. You can add more methods as you find more uses for that class. This is what it looks like.You can overload those methods to take all 9 kinds of array as parameters.
Get the swapTwoElementsInArray method working first, then you can consider the reverseArray method. The reverseArray method will of course use the swap method.
Note you have the iffy design feature of output parameters. Rather than creating new objects, you are manipulating the object whose memory location is passed as an argument. Something you need to be careful about.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12100
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a method should do one thing, and one thing only, and should be named accordingly. So a method named "reverse" should not print anything. it should reverse something.

If you want to print an array, write a method called 'printArray'.

The idea is to write small, simple methods that can be tested into oblivion so that you are SURE they work...then you use them whenever you need to, however you need to.

If someone worked for me wrote a method that tried to both print and reverse an array, I'd delete it and tell them to start over.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fred rosenberger wrote:
The idea is to write small, simple methods that can be tested into oblivion so that you are SURE they work...then you use them whenever you need to, however you need to.


And, in case it's not clear, you test them independently of each other.

So you write your reverse() method, you fix the syntax errors so it compiles, then you write a tiny little main() method that does nothing but reverse a hard-coded array. You look at the results to make sure they are what they should be. Only when that works perfectly do you move on.

Totally independently of that, you write a printArray() method. You fix the syntax errors so it compiles. Then you write a tiny little main() method that does nothing but print a hard-coded array. You look at the results to make sure they are what they should be. Only when that works perfectly do you move on.

Then you combine those two methods. You write a tiny little main() that reverses a hardcoded array and then prints out the results. You compare those results to what you know they should be. Only when this part works, do you move on.

Maybe you have a requirement to generate a random array for reversal and printing, or take input from a user to put into an array for reversal an printing. Whatever this other requirement is, you follow the same procedure: Design, code, test, debug completely on its own, and then put it together with the other pieces that you know are already working.
 
Michael Pickens
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for all your help. I didnt turn on my computer, read the post on my phone, and started jamming on paper. Then it occurred to me.. why am I swapping, why don't i Just reverse it through a for loop..

I want to rewrite this later with a separate final print method, but I could not get it to work right.



here is my final snippet of code.

I appreciate the help, some of the help was above my understanding currently, but at least it gives me something to think about..

Cheers.



 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You haven’t reversed anything. You have simply displayed your array in reverse. Are you sure that is what you are supposed to do? The original post wasn’t at all clear on that point.
 
Michael Pickens
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is a good question..... I didn't realize that I was just doing that.. sigh.

and now that i look.. the indexes are also reversed..

myArray[0] = 40
myArray[1] = 37
myArray[2] = 62
myArray[3] = 60
myArray[4] = 3
myArray[5] = 79
myArray[6] = 43
myArray[7] = 65
After reversing the array
myArray [7] = 65
myArray [6] = 43
myArray [5] = 79
myArray [4] = 3
myArray [3] = 60
myArray [2] = 62
myArray [1] = 37
myArray [0] = 40

I dont know what to do. Pen and paper "playing computer" doesn't make sense to me. When I do it, i pretend that my array size is 5 and trace it through. I see that when I swap, that I end up swapping back with the third swap... I do not understand how to fix the problem. I have also made it so the last numbers will reverse, but it is either the first half of numbers or the 2nd half of numbers. I tried writing 2 methods.. one that would reverse the fist half and one that would reverse the 2nd half.. but of course, as you guessed, didn't compile and I did not no how to fix that. We have not studied objects as of yet.. that is the last chapter we are doing this semester. I have a mid term tomorrow in this class on loops, methods, and arrays (to give you an idea of where I am at.)
 
Winston Gutkowski
Bartender
Pie
Posts: 10259
59
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Michael Pickens wrote:I dont know what to do. Pen and paper "playing computer" doesn't make sense to me. When I do it, i pretend that my array size is 5 and trace it through. I see that when I swap, that I end up swapping back with the third swap... I do not understand how to fix the problem.

That's because you're fixated on doing it one particular way. As I said above you are NOT constrained to using just one index.

Think some more about it.

Winston
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12100
30
Chrome Java Linux
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about the problem in real world terms. I like to think of arrays as egg cartons, and the elements as eggs.

So, let's say you have an egg carton that can hold up to 12 eggs. The eggs, for whatever reason, have numbers written on them so you can identify them (but for the purpose of this exercise, the specific numbers don't matter). The slots in the carton are also numbered, so you can say "look at the egg in slot #4" or "look at the egg in slot #10 and read the number on it".

How would you, using your hands, reverse the order of the eggs? Note that a slot can only hold one egg. You can't put an egg into a slot that is already occupied, or else you will smash it, and loose that egg forever.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And I have already told you how you can use a swap method to reverse the whole thing.
 
Michael Pickens
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After thinking all day and jotting stuff down on paper I decided to add the second variable to the method and to create a separate method to print the reversed array.

There is an error that says j cannot be resolved or is not a field.. I don't understand what it means or wants me to do. Here is the code I came up with to swap these indexes.



they way I wrote this out on sever sheets of paper, i hope it works.

Thanks again for all the help. The egg carton example and realizing that i was indeed fixated on writing the code one way really helped. Though I did not know you could put 2 variables into a for loop with 2 sets of parameters, and 2 increments. I am obviously doing it wrong. Can i just separate the two for statements within the same method so I don't get the errors, using the first one to swap the first half of the indexes, and the 2nd one to swap the 2nd half of the indexes?
 
Michael Pickens
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
WOO again as I was typing the last reply, I found my answer!!



You guys are awesome. I love hanging out on the ranch!

Thanks again for all your help, sorry I am so frustrating to help!
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You got there in the end. There are some people who never seem to get there at all.

You have, however, I think managed to do it the hard way. You only need one loop. The first half of the loop reverses the array, and the second half reverses it again. Twice!
It is a very common problem, thinking that you use commas inside the () after for. You don’t; you use semicolons.

 
Winston Gutkowski
Bartender
Pie
Posts: 10259
59
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Michael Pickens wrote:WOO again as I was typing the last reply, I found my answer!!

Well done! And now that you've done it for yourself, here's the way to combine the two loops:See what I mean about using two indexes?

Also, as Campbell mentioned above, if you take out the body of the loop and put it in a swap() method, you don't have to repeat the code for your two loops.

Thanks again for all your help, sorry I am so frustrating to help!

Not at all. Glad you got there in the end.

Winston
 
Nazar Kani
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int AR5[] = new int[5];

AR5[0] = 5;
AR5[1] = 2;
AR5[2] = 1;
AR5[3] = 4;
AR5[4] = 3;

for(int i=AR5.length-1, j=0; i>=0;i--, j++)
{

System.out.println("My Array [" +j +"] =" +AR5[i]);

}
 
Les Morgan
Ranch Hand
Posts: 613
16
C++ Java Linux MySQL Database Netbeans IDE Oracle PHP Tomcat Server Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ever since CompSci-101 I liked using recursion for this type of problem. You needn't mess much with the array, as long as you have it visible, and you only have to worry about your stopping condition.
 
Winston Gutkowski
Bartender
Pie
Posts: 10259
59
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Les Morgan wrote:Ever since CompSci-101 I liked using recursion for this type of problem.

We should call you "Mr. Recursion".

And here I have to disagree. I see nothing about your method that makes it any easier to follow than mine; and furthermore, in Java (and many other languages) it could throw a Stack overflow error on a String as short as a thousand characters.

As a way of looking at the problem, or for a language that can unroll recursive methods automatically: I have no problem. But Java can't; so recursion (IMO) should be kept strictly for "divide and conquer" solutions, or ones that have a strict limit on the number of internal calls they can make.

Winston
 
Les Morgan
Ranch Hand
Posts: 613
16
C++ Java Linux MySQL Database Netbeans IDE Oracle PHP Tomcat Server Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote:
We should call you "Mr. Recursion".

Winston,

If you wish to call me that, it is fine, I have definitely been called worse.

I have not said that my way of doing things is better than yours, but it is my preference, as I stated. The problem given, as a homework assignment, was in the 80's and 90's a classic recursion problem in colleges. It is easily and straight forwardly solvable by using recursion, as such, it has been used as an example and still endures as such. Since the problem was a homework problem, I waited until a consensus had been reach and solution had been provided until mentioning it.

Do I advocate recursion in production code? With extreme rarity I will put a recursive algo into production over an iterative one, but due to the dangers of recursion it only happens where depth of recursion is small and convergence to an answer is guaranteed within an acceptable predefined maximum depth.

Les
 
Winston Gutkowski
Bartender
Pie
Posts: 10259
59
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Les Morgan wrote:I have not said that my way of doing things is better than yours, but it is my preference, as I stated...

I have to admit, I'm envious. I often wish I could "see" recursion the way you appear to, but I just can't. That's not to say I've never used it; and some of my favourite projects have involved it - perhaps because I find it challenging - but I'd still say it's not a "natural" way of programming unless you're a mathematician or used to functional languages.

My most recent "recursive adventure" was an ArrayInfo class that can parse and do a deepEquals() or deepCopy() on any array safely, even ones that contain "self-references" (ie, references to another element in the same array).

Just to let you know that I'm not a complete Luddite when it comes to recursion.

Winston
 
Hai Thompson
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:I would also suggest you do it the object-oriented way...

Hi Campbell, because the OP has figured out his own solution, so I think it is allowed that I post my code here, regard of your guild-line above.
I have finished and tested this code, which works, follow your advice.
What do you think about it? Please correct me if I have any wrongs in my code.
 
Les Morgan
Ranch Hand
Posts: 613
16
C++ Java Linux MySQL Database Netbeans IDE Oracle PHP Tomcat Server Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston,

Actually funny coincidence, my optional studies for my BS in CompSci was in Mathematics, and back in the day, most things were done in C, so functional programming was the main stay.

Probably what cemented recursion into my head the best was programming in LISP. I took a graduate level AI course and LISP was used. Literally everything we did was recursion, it has really stuck with me.

Les

BTW: I am also one that finds great delight in seeing small bits of code do a lot. After I make something that I consider "delightfully elegant", I have to play with it for a while. I do that when I see other people's code that is also "delightfully elegant" too. Yes, I am amused by simple things ;)

Winston Gutkowski wrote:
... - but I'd still say it's not a "natural" way of programming unless you're a mathematician or used to functional languages.
 
Winston Gutkowski
Bartender
Pie
Posts: 10259
59
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai Thompson wrote:What do you think about it? Please correct me if I have any wrongs in my code.

Nothing wrong, AFAICS; but a few minor points:

1. 'swapTwoElementsInArray' is a bit of a mouthful. What about just 'swap()'?

2. 'for(int i = 0; i <= (array.length/2 - 1); i++)' (line 15) involves recalculating a constant expression. Try:
  for(int i = 0, e = (array.length / 2) - 1; i < e; i++) instead.

Alternatively, use two index variables: one for the "left" and one for the "right", as I showed above.
Then the only operators you need are '++' and '--'

3. 'int temp = array[i];' (line 6) saves you a line of code.

4. Lines 23-26 can be replaced with
  Systen.out.println( Arrays.toString(ar) );
which will produce something very similar. Ditto for lines 28-30.
(Lesson: Don't re-invent the wheel )

5. In the context of your program, the check at line 5 is redundant; but for a public swap() method it's probably a very good idea.
So you might want to think about something like:because then you can use alwaysSwap(...) at line 16.

6. I really like all your throws clauses - very nice. I wish more people did it (including me ).

HIH

Winston
 
Winston Gutkowski
Bartender
Pie
Posts: 10259
59
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Les Morgan wrote:BTW: I am also one that finds great delight in seeing small bits of code do a lot.

Me too, but I try to avoid it in my programs. One example is the getc() (or possibly getchar()) macro in C - a piece of minimalist poetry in about 30 characters.
Trouble is: it took me about an hour to work out what it did the first time I looked at it (and probably would again now); and I'd never want to inflict that on anyone reading my code.

I'm still in awe of it's author though.

Winston
 
Hai Thompson
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote:
Nothing wrong, AFAICS; but a few minor points:
...

Thanks Winston, I got all things you mentioned
Winston Gutkowski wrote:
6. I really like all your throws clauses - very nice. I wish more people did it (including me ).

Actually it is Campbell who has told about that throws, in his original post. So I just followed that post, which is very clear.
 
Winston Gutkowski
Bartender
Pie
Posts: 10259
59
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai Thompson wrote:Thanks Winston, I got all things you mentioned

Great. You might want to consider putting things like swap() in a utility class, because I doubt this is the last time you'll want them. I call mine 'Arrayz'.

And just to elaborate on point 5, swapping and "setting" (ie, a method that works like List.set()) are very closely related, viz:and you may find 'set()' useful somewhere else (eg, line 16).

HIH

Winston
 
Winston Gutkowski
Bartender
Pie
Posts: 10259
59
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Les Morgan wrote:BTW: I am also one that finds great delight in seeing small bits of code do a lot...

You might like this one then. The set() method in my previous post can also be written:
But I wouldn't advise it.

Winston
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic