Reverse an Array

How to reverse the order of an array

Page 1 of 1

2 Replies - 2904 Views - Last Post: 13 November 2009 - 09:11 AM Rate Topic: -----

#1 Ibanez Gio  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 25-October 09

Reverse an Array

Posted 12 November 2009 - 10:57 PM

Ok so my assignment is to create a purse class and stuff and then have the methods in it called reverseOrder() and transfer(Purse other). Reverse will just take the the array and put themin opisite order (IE quarters, dimes, nickles, pennies turns into pennies, nickels, dimes, quarters)

The transfer will have purse a and b and say a has quarter, dime and purse b has nickel, penny then a.transfer(B) a is Purse[quarter,dime,nickel,penny]


any help??

here is the code
import java.util.ArrayList;

public class Purse
{
	ArrayList<String> coins;
	
	public Purse()
	{
		coins = new ArrayList<String>();
	}
	
	public void addCoins(String coinName)
	{
		coins.add(coinName);
	}
	
	public String toString()
	{
		String preamble = "Purse[";
		String body = "";
		String postamble = "]";
		
		for(int i = 0; i < coins.size(); i++)
		{
			body = body + coins.get(i);
			if (i < coins.size() -1)
			{
				body = body + ", ";
			}
		}
		
		return preamble + body + postamble;
	}
	
	 public String reverse()
	{
		String preamble = "Purse[";
		String body = "";
		String postamble = "]";
		
		for(int i = (coins.size() - 1); i >= 0; i--)
		{
			body = body + coins.get(i);
			if (i > 0)
			{
				body = body + ", ";
			}
		}
		
		return preamble + body + postamble;
	}
	
	public void transfer(Purse other)
	{
		
	}
	
	public void reverseCoins()
	{
		
	}
}



Is This A Good Question/Topic? 0
  • +

Replies To: Reverse an Array

#2 Dophert  Icon User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 60
  • Joined: 19-October 09

Re: Reverse an Array

Posted 13 November 2009 - 01:43 AM

Why not use the Collections.reverse(List<E>) method ? :)
Was This Post Helpful? 0
  • +
  • -

#3 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10778
  • View blog
  • Posts: 40,134
  • Joined: 27-December 08

Re: Reverse an Array

Posted 13 November 2009 - 09:11 AM

Because of the resizable nature of ArrayList vs. the static nature of an array, it might be easier to use the Collections.swap() method to write your own reverse() method. In this way, you can insure that your algorithm takes n/2 time, where n is the number of elements.

You can implement something like this:
0. ArrayList <-- get ArrayList
1. i <-- 0
2. k <-- ArrayList.size()
3. while i < k
4.   swap(i, k) //swap elems at i and k
   end while
end algorithm



This is easier and more efficient than moving n items to the end of the list.

Try implementing this solution and feel free to post if you need any more help. Good luck! :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1