Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 22 of 22

Thread: Need help on how to tackle this Java Project.

  1. #1
    Junior Member
    Join Date
    Apr 2014
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Need help on how to tackle this Java Project.

    Hey Java people!

    I am currently learning Java at Uni, and i have given myself a project to work on, i figured this would really test my skills. (so dw, your not helping me with a Uni assignment)

    I do want to try and do it myself, i just need to know what area of Java i would be working with, since i am still a Noob.

    The Project/Calculator;

    It is a sort of Game/Calculation, in which the End goal is to get a number to 0.
    Imagine you walk into a shop that has its own currency, say 'Rubies'. You spend real money to convert to rubies;

    $5 = 600 Rubies
    $10 = 1200 Rubies
    $20 = 2700 Rubies
    $50 = 6500 Rubies
    $100 = 17,000 Rubies
    (note: rubies are whole numbers, and do not use decimals)

    Now with those Rubies, you can buy varies products at the following price points;
    260, 390, 520, 750, 975, 1350, 1820, 3250

    Everything should be simple up to this point. The next part is what i'm getting stuck on, i tried using lots of loops but i cant seem to get it to work the way i want it.

    Say a user has 50 Rubies left over, they input '50' into the calculator, and it tells them the most efficient way for them to get to 0 Rubies. Now remember, they can only purchase items from the price points listed above.

    What would be the best way to get my calculator to output something like this (numbers are incorrect, just an example):
    "To get from 50 Rubies to 0, you must purchase 2x$10 Rubie Packages and 1x$50 Rubie package. Then spend your rubies on 6x1820 products, 1x750 product and 1x260 product."

    At the moment, all i am able to do is the following 'Check to see how many $5 packages i have to buy, to get my 50 Rubies to 0 by spending it only on the 260 package" and then comparing it to the same equation, just with the different price points to see what is the most efficient way, but this does not really help me much since its not trying to use different combinations.

    I am going to guess its something similiar to how Chess Algorithms work, in terms of 'tree branching' the possibilities.

    Any help on trying to solve this would be appreciated, i don't want code on how to do it exactly, but rather what areas of Java/Programming in general i should be looking into. If i still cant solve it in a few weeks, i will check back for more help.

    Ps: it's 2am for me, so sorry if i didn't explain myself properly, i will check back in the Morning to any replies. Thanks


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Need help on how to tackle this Java Project.

    Welcome to the Forum! Please read this topic to learn how to post code correctly and other useful tips for newcomers.

    and it tells them the most efficient way for them to get to 0 Rubies
    Once you define "most efficient," you should be able to create rules to achieve that efficiency and then program them. Without knowing what you mean by "most efficient," I'm not sure how to help.

  3. #3
    Member
    Join Date
    Apr 2012
    Posts
    160
    Thanks
    0
    Thanked 27 Times in 27 Posts

    Default Re: Need help on how to tackle this Java Project.

    Well just having some code to look at would help us point you in the right direction.

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Need help on how to tackle this Java Project.

    I would imagine there is some sort of mathematical formula for doing this. Possibly with convergence or limits. It's an interesting puzzle.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Euphoraz (April 22nd, 2014)

  6. #5
    Junior Member
    Join Date
    Apr 2014
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Need help on how to tackle this Java Project.

    Quote Originally Posted by GregBrannon View Post
    Welcome to the Forum! Please read this topic to learn how to post code correctly and other useful tips for newcomers.


    Once you define "most efficient," you should be able to create rules to achieve that efficiency and then program them. Without knowing what you mean by "most efficient," I'm not sure how to help.
    Quote Originally Posted by Parranoia View Post
    Well just having some code to look at would help us point you in the right direction.
    By 'Most Efficient' i mean using the lowest amount of real world money as possible. So lets say (numbers are wrong, just using as example) you have 50 Rubies left. You could purchase 10 Rubie packs of 17,000 rubies for $1,000 and then purchase X amount of whatever, but its cheaper and more efficient if you just purchase 2x$10 packs for $20.
    This part i think i could work out, assigning a counter to each loop, then multiplying the counter by the Price, then comparing.

    The real issue that i am stumped on, is comparing all the different price points at the same time. I will show you some code now but please be warned, you may want to Exit the browser, vomit, laugh, murder me, ect.. after witnessing this terrible code.


    import java.util.Scanner;
     
    public class RPCalc {
        public static void main(String[] args) {
     
            Scanner input = new Scanner(System.in);
     
            // Get Rubies amount from user
            System.out.println("Enter your Rubies: ");
            String Rubiesinput = input.nextLine();
     
            // Check to see if Rubies amount is a multiple of 5
            int intRubiesinput = Integer.parseInt(Rubiesinput);
            int Rubiescheck = intRubiesinput % 5;
     
            if (Rubiescheck == 0) {
                System.out.println("Multiple of 5 check complete");
            } else {
                System.exit(0);
            }
     
            int Seed = intRubiesinput / 5;
            int PriceA = Seed;
            int Acounter, Bcounter;
                Acounter = Bcounter = 0;
            int purchaseRubies;
            int packs;    
     
            //The 5th Function
     
            int test = PriceA % 52;
     
            while (test != 0 && Acounter < 10000) {
                test = test + 120;
                test = test % 52;        
                Acounter++;
            } 
     
           if (Acounter < 10000) { 
           purchaseRubies = Acounter * 120; 
           packs = (intRubiesinput + (Acounter * 600))/260;
           System.out.println("You need to purchase " + Acounter + " 600Rubie packs, and then purchase " + packs + " 260Rubie Products.");
           } else {
        	   System.out.println("Rubies Cant be used");
           }
     
     
          test = PriceA % 78;
     
           while (test != 0 && Bcounter < 10000) {
               test = test + 120;
               test = test % 78;        
               Bcounter++;
           } 
     
          if (Bcounter < 10000) { 
          purchaseRubies = Bcounter * 120; 
          packs = (intRubiesinput + (Bcounter * 600))/390;
          System.out.println("You need to purchase " + Bcounter + " 600Rubie packs, and then purchase " + packs + " 390Rubie Products.");
          } else {
       	   System.out.println("Rubies Cant be used");
          }  
     
        }
    }
    I didn't really create the code at the time for anyone to read over it, so i will have to change it up a bit. This was just a very basic proof of concept i was working on until i had a proper idea on how to tackle it. At first i figured i would be able to do this with just loops, but im not to sure anymore.

    Note: The reason im checking to see if its a multiple of 5, is because in my original draft up of the project, i had different pricepoints that included the possibility of having a non 5 multiplier. For now, i am just working with multiples of 5.

    Note: I found it easier if i divided all the numbers by 5, and worked with that instead of the whole number. At the time it helped.

    If you are brave enough to execute the code, you will see that if you type in '700' it will say 'You need to purchase 1 600Rubie packs, and then purchase 5 260Rubie Products.'
    This is all well and good, but i dont know to make the loops go through every single possibility, so it comes up with something like 'You need to purchase 1 600Rubie packs, and then purchase 1 1300Rubie Products.'

    Im still not sure if i have explained myself correctly, and i will try again using Real World currency.

    Say you have $5, and you want $0. But the products cost $10, $25 $75 $120. You can borrow some money from a friend, but he only has $30, $50, $150 notes.

    my program would find out that if you borrow 4x$30 notes from a friend, giving you $125, you could purchase 5x$25 products to get to 0.
    but this is not the most efficient way, you just borrow $120, when in reality you could of done the following
    Borrow 1x$30 note, giving you a total of $35, in which you could buy a $10 product and a $25 product.

    Quote Originally Posted by aussiemcgr View Post
    I would imagine there is some sort of mathematical formula for doing this. Possibly with convergence or limits. It's an interesting puzzle.
    I figured something that Chess Simulators would use, since as far as i am aware, the use some sort of branching algorithm to calculate all the possibilities, then compare to see what is the best way to move. I feel like something similar could be applied to this.

  7. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Need help on how to tackle this Java Project.

    I really don't think I'm getting it, and that's okay, but as I read your descriptions I'm thinking of "shortest path algorithms" to decide the solution.

  8. #7
    Junior Member
    Join Date
    Apr 2014
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Need help on how to tackle this Java Project.

    Had a quick look into Shortest path Algorithms, seems like it will be a challenge applying it to what im doing, but its definitely a good start in the right direction. Thanks
    Last edited by Euphoraz; April 12th, 2014 at 08:43 AM.

  9. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Need help on how to tackle this Java Project.

    Considering that all the rubie purchase amounts are divisible by 100, I would say your first step would buy whatever products would make your remaining about divisible by 100.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  10. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Euphoraz (April 22nd, 2014)

  11. #9
    Member
    Join Date
    Apr 2012
    Posts
    160
    Thanks
    0
    Thanked 27 Times in 27 Posts

    Default Re: Need help on how to tackle this Java Project.

    You could always brute force it and calculate each possibility and find out which one is the best solution

  12. #10
    Junior Member
    Join Date
    Apr 2014
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Need help on how to tackle this Java Project.

    Would you have any idea how i could go about doing this?

    I tried to come up with a few concepts over the last few days but had no luck. I will keep at it though.

    Thanks everyone for your help

  13. #11
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Need help on how to tackle this Java Project.

    I would brute force it with recursion, but I think that would require a limiter, which means it would be possible to not reach a solution. I wonder if there is a way to run recursion concurrently... Let me think about this.

    EDIT: I figured out a solution by doing concurrent recursion (it is an ugly thing to program), but I don't know if it is the "shortest" solution. Rather, it is a "whoever is fastest to the finish line" solution. I'm sure additional logic could be added to find multiple solutions and compare them.
    By "concurrent" I don't mean on separate threads. Instead of fully completing a recursive call, I instead effectively queued up recursions and cycled through them, completing a single recursive call during each visit. So the lengths of the recursive branches should all be around the same, but it still doesn't guarantee the "shortest" solution.
    For your example of 50, it found: buy 1 600 rubie convertion package, and buy 1 390 rubie product and 1 260 rubie product.
    This is probably the shortest solution for *this* example, but I don't know about all possible examples.
    Last edited by aussiemcgr; April 15th, 2014 at 11:52 AM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  14. The Following 2 Users Say Thank You to aussiemcgr For This Useful Post:

    Euphoraz (April 16th, 2014), GregBrannon (April 15th, 2014)

  15. #12
    Junior Member
    Join Date
    Apr 2014
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Need help on how to tackle this Java Project.

    Quote Originally Posted by aussiemcgr View Post
    I would brute force it with recursion, but I think that would require a limiter, which means it would be possible to not reach a solution. I wonder if there is a way to run recursion concurrently... Let me think about this.

    EDIT: I figured out a solution by doing concurrent recursion (it is an ugly thing to program), but I don't know if it is the "shortest" solution. Rather, it is a "whoever is fastest to the finish line" solution. I'm sure additional logic could be added to find multiple solutions and compare them.
    By "concurrent" I don't mean on separate threads. Instead of fully completing a recursive call, I instead effectively queued up recursions and cycled through them, completing a single recursive call during each visit. So the lengths of the recursive branches should all be around the same, but it still doesn't guarantee the "shortest" solution.
    For your example of 50, it found: buy 1 600 rubie convertion package, and buy 1 390 rubie product and 1 260 rubie product.
    This is probably the shortest solution for *this* example, but I don't know about all possible examples.
    This is probably going to be the best way to go about it, so thank-you very much.

    In doing some researching into your suggestion, i found something 'similar' in terms of a 'Greedy Algorithm' that could also be applied. I will mix the two together and will report my results after the easter break. Thanks again!

  16. #13
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Need help on how to tackle this Java Project.

    A little bit of fine-tuning has led me to reach what I believe is the shortest solution most of the time. Tell me how your solution goes.
    I know you want to do this on your own, so I won't provide my solution unless you ask for it.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  17. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Euphoraz (April 22nd, 2014)

  18. #14
    Junior Member
    Join Date
    Apr 2014
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Need help on how to tackle this Java Project.

    Quote Originally Posted by aussiemcgr View Post
    A little bit of fine-tuning has led me to reach what I believe is the shortest solution most of the time. Tell me how your solution goes.
    I know you want to do this on your own, so I won't provide my solution unless you ask for it.
    I have tried to do it but still not much luck . Would i be able to look at your solution?

  19. #15
    Junior Member
    Join Date
    Mar 2014
    Posts
    21
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Need help on how to tackle this Java Project.

    haha actually I got confused there... but he does have on e where the price is higher for a bigger payment. anyways...

    does creating functions such as "y = 600x + [rupies owned]" (algebra) help?
    a loop with a condition that stops IF (y % 260 = 0) IF ( y % 390 = 0) etc.. then taking the best deal into account?
    but then that would only be for $5 packages...

    ill keep working on it :P this is a really good problem

    oh and x is an increasing number in case you didn't get that
    Last edited by Tea.EarlGrey.Hot.; April 21st, 2014 at 06:19 AM.

  20. #16
    Junior Member
    Join Date
    Apr 2014
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Need help on how to tackle this Java Project.

    sorry if I missed the point, but don't you usually give a discount for the more they buy? Like you have with the 100$ deal 170 rubies/dollar, and at the 5$ deal its 120 rubies/dollar...
    if you change the prices to where you get a bigger discount for buying bulk (like normal) things would be a lot easier.

    wait.. are they buying the packages or the products?

    Don't get your head wrapped around the actual problem. Its not exactly a real world problem, just something i came up with to try and solve as a test. I learn from doing more then just studying, so to speak.

    i do understand what you mean though, but no matter the prices, the solution should be the same

  21. #17
    Junior Member
    Join Date
    Mar 2014
    Posts
    21
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Need help on how to tackle this Java Project.

    so sorry aout that I was editing my question when you replied XD

  22. #18
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Need help on how to tackle this Java Project.

    Quote Originally Posted by Euphoraz View Post
    I have tried to do it but still not much luck . Would i be able to look at your solution?
    Sure. I commented the code to make it easier to understand. This is fairly complicated code. Tell me how much of it makes sense. Feel free to ask any questions. This is a learning exercise, after all.
    /**
     * RubieRecursion.java
     *
     * Apr 15, 2014
     */
     
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
     
    /**
     * @author aussiemcgr
     * 
     * The class which does the recursion.
     */
    public class RubieRecursion {
    	/**
    	 * The list of rubies which can be bought for exchange. Note: ascending order for greedy algorithm.
    	 */
    	public static int[] buyRubies = new int[]{600,1200,2700,6500,17000};
    	/**
    	 * The list of rubie packages which can be bought. Note: descending order for greedy algorithm.
    	 */
    	public static int[] packages = new int[]{3250,1820,1350,975,750,520,390,260};
    	/**
    	 * The bounds threshold so the recursive numbers do not grow too large. This is set to twice the largest 
    	 * package.
    	 */
    	public static int bound_threshold = (int)(packages[0]*2.0);
    	/**
    	 * A map of numbers which have already been visited by recursions. This exists so we can prevent recursing 
    	 * with numbers we already have. It is assumed that the first item to be mapped to a number is the shortest
    	 * path to that number. 
    	 */
    	public static Map<Integer,RubieRecursion> mappedValues = new HashMap<Integer,RubieRecursion>();
     
    	/**
    	 * The rubie value for the recursion.
    	 */
    	private int value;
    	/**
    	 * A list of rubie conversions made for this recursion.
    	 */
    	private List<Integer> rubiesPurchased;
    	/**
    	 * A list of rubie packages purchased for this recursion.
    	 */
    	private List<Integer> packagesPurchased;
    	/**
    	 * A list of all sub-recursions for this recursion.
    	 */
    	private List<RubieRecursion> recursions;
    	/**
    	 * <b>true</b> if the sub-recursions have already been built, <b>false</b> otherwise.
    	 */
    	private boolean recursionsBuilt = false;
    	/**
    	 * The parent recursion to this sub-recursion. <b>null</b> if this is the 
    	 * recursion called from the main.
    	 */
    	private RubieRecursion parent;
    	/**
    	 * A sub-recursion which should be removed because it has reached a dead end. 
    	 */
    	private RubieRecursion triggerRemoveChild;
     
    	/**
    	 * Creates a new RubieRecursion. The parent is set to null.
    	 * 
    	 * @param val the initial rubie value for the recursion
    	 */
    	public RubieRecursion(int val) {
    		/* According to the conversions and packages available, the initial value must be 
    		 * divisible by 5. If it is not divisible by 5, no solution can be found
    		 */
    		if(val%5!=0)
    			throw new RuntimeException("Invalid input: "+val+". Value must be divisible by 5.");
    		this.value = val;
    		this.rubiesPurchased = new ArrayList<>();
    		this.packagesPurchased = new ArrayList<>();
    		this.recursions = new ArrayList<>();
    	}
     
    	/**
    	 * Creates a new RubieRecursion with the initial value and parent recursion.
    	 * 
    	 * @param val the initial rubie value for the recursion
    	 * @param par the parent recursion
    	 */
    	public RubieRecursion(int val, RubieRecursion par) {
    		this(val);
    		this.parent = par;
    	}
     
    	/**
    	 * @return the list of rubies conversions for this recursion
    	 */
    	public List<Integer> getRubiesPurchased() {
    		return this.rubiesPurchased;
    	}
     
    	/**
    	 * @return the list of rubie packages purchased for this recursion
    	 */
    	public List<Integer> getPackagesPurchased() {
    		return this.packagesPurchased;
    	}
     
    	/**
    	 * Adds a new rubies conversion to the list.
    	 * 
    	 * @param amount the conversion value to add 
    	 */
    	@SuppressWarnings("boxing")
    	public void addRubiesPurchase(int amount) {
    		this.rubiesPurchased.add(amount);
    	}
     
    	/**
    	 * Adds a new rubies purchase package to the list.
    	 * 
    	 * @param amount the package value to add 
    	 */
    	@SuppressWarnings("boxing")
    	public void addPackagePurchase(int amount) {
    		this.packagesPurchased.add(amount);
    	}
     
    	/**
    	 * @return the value of this recursion
    	 */
    	public int getValue() {
    		return this.value;
    	}
     
    	/**
    	 * Adds a recursion to the sub-recursions. If the value for this recursion is already found
    	 * in the map, the value is not added, because a shorter path to it has already been discovered
    	 * and is already being recursed.
    	 * 
    	 * @param toAdd the recursion to add 
    	 */
    	public void addToRecursions(RubieRecursion toAdd) {
    		Object existing = RubieRecursion.mappedValues.get(Integer.valueOf(toAdd.value));
    		if(existing==null) {
    			RubieRecursion.mappedValues.put(Integer.valueOf(toAdd.value), toAdd);
    			this.recursions.add(toAdd);
    		}
    		else {
    			//System.out.println("Already existing: "+toAdd.value);
    			//System.out.println("Existing: "+existing+", Adding: "+toAdd);
    		}
    	}
     
    	/**
    	 * Runs the recursion. This is called only from the main.
    	 * 
    	 * @return the shortest recursion to the goal 
    	 */
    	public RubieRecursion run() {
    		// value is 0, we can cleanup the recursion and return this as the fastest result
    		if(this.value==0) {
    			while(cleanUp()) {/*do nothing*/}
    			return this;
    		}
    		// build the sub-recursions
    		RubieRecursion check = buildRecursions();
    		// if check is not null, a successful result was found, so we should clean it and return it
    		if(check!=null) {
    			this.packagesPurchased.addAll(check.packagesPurchased);
    			this.rubiesPurchased.addAll(check.rubiesPurchased);
    			while(cleanUp()) {/*do nothing*/}
    			return this;
    		}
    		// max iterations of 50, just to be safe that the program doesn't run forever. 
    		// 50 should be more than big enough.
    		int iterations = 50;
    		for(int its=0;its<iterations;its++) {
    			System.out.println("its: "+its+", size: "+this.recursions.size());
    			// iterate over the sub-recursions and recurse each one
    			for(int i=0;i<this.recursions.size();i++) {
    				RubieRecursion temp = this.recursions.get(i);
    				RubieRecursion result = recurse(temp);
    				// if result is not null, a sub-recursion was successful, so we should return it
    				if(result!=null) {
    					this.packagesPurchased.addAll(result.packagesPurchased);
    					this.rubiesPurchased.addAll(result.rubiesPurchased);
    					while(cleanUp()) {/*do nothing*/}
    					return this;
    				}
    				// if a child has been set to remove, we remove it and continue with the rest of the list
    				if(this.triggerRemoveChild!=null) {
    					this.recursions.remove(this.triggerRemoveChild);
    					this.triggerRemoveChild = null;
    					i--;
    				}
    			}
    		}
    		// no successful recursion was found
    		return null;
    	}
     
    	/**
    	 * Attempts to shorten the recursion by combining purchases and conversions.
    	 * 
    	 * @return <b>true</b> if a change occurred and a cleanup should be ran again, 
    	 * <b>false</b> if there was nothing to clean up. 
    	 */
    	@SuppressWarnings("boxing")
    	public boolean cleanUp() {
    		boolean change = false;
    		for(int x=0;x<this.rubiesPurchased.size();x++) {
    			int tempValue = this.rubiesPurchased.get(x);
    			OUTER:
    			for(int y=x+1;y<this.rubiesPurchased.size();y++) {
    				int value2 = this.rubiesPurchased.get(y);
    				for(int option : RubieRecursion.buyRubies) {
    					if(tempValue+value2==option) {
    						this.rubiesPurchased.remove(x);
    						this.rubiesPurchased.remove(y);
    						this.rubiesPurchased.add(option);
    						x--;
    						change = true;
    						break OUTER;
    					}
    				}
    			}
    		}
    		for(int x=0;x<this.packagesPurchased.size();x++) {
    			int tempValue = this.packagesPurchased.get(x);
    			OUTER:
    			for(int y=x+1;y<this.packagesPurchased.size();y++) {
    				int value2 = this.packagesPurchased.get(y);
    				for(int option : RubieRecursion.packages) {
    					if(tempValue+value2==option) {
    						this.packagesPurchased.remove(x);
    						this.packagesPurchased.remove(y);
    						this.packagesPurchased.add(option);
    						x--;
    						change = true;
    						break OUTER;
    					}
    				}
    			}
    		}
    		return change;
    	}
     
    	/**
    	 * The recursive call to check the sent recursion and build sub-recursions.
    	 * 
    	 * @param check the recursion to build off of
    	 * @return a successful recursion, or <b>null</b> if the recursion was not finished
    	 */
    	public RubieRecursion recurse(RubieRecursion check) {
    		// if the value is 0, we have a successful recursion, so we return it
    		if(check.getValue()==0) {
    			return check;
    		}
    		System.out.println(check.toString()+", recursions: "+check.recursions.size()+", "+check.recursionsBuilt);
    		// if the sub-recursion size is 0...
    		if(check.recursions.size()==0) {
    			// ... and if the recursions have already been built, it means we have exhausted all the children, so
    			// this recursion can be removed from its parent
    			if(check.recursionsBuilt) {
    				System.out.println("Already built");
    				check.parent.triggerRemoveChild = check;
    				return null;
    			}
    			//... we build the sub-recursions
    			RubieRecursion temp = check.buildRecursions();
    			check.recursionsBuilt = true;
    			if(temp!=null) {
    				return check;
    			}
    			// return null pause this recursion and cycle to the next recursive call
    			return null;
    		}
    		// recurse each sub-recursion
    		for(int i=0;i<check.recursions.size();i++) {
    			RubieRecursion result = check.recurse(check.recursions.get(i));
    			if(result!=null) {
    				check.rubiesPurchased.addAll(result.rubiesPurchased);
    				check.packagesPurchased.addAll(result.packagesPurchased);
    				return check;
    			}
    			if(check.triggerRemoveChild!=null) {
    				check.recursions.remove(check.triggerRemoveChild);
    				check.triggerRemoveChild = null;
    				i--;
    			}
    		}
    		// a solution has not been found yet, return null to pause this recursion and cycle to the next
    		return null;
    	}
     
    	/**
    	 * Builds the sub-recursions for this recursion.
    	 * 
    	 * @return a successful recursion, or <b>null</b> if the recursion is not finished
    	 */
    	@SuppressWarnings("boxing")
    	public RubieRecursion buildRecursions() {
    		System.out.println("Value: "+this.toString());
    		// the value of 0, so we can return this recursion as successful
    		if(this.value==0) {
    			return this;
    		}
    		// iterate over the package options
    		for(int pack : RubieRecursion.packages) {
    			// if the value is smaller than the package size, there is no point in try to do any math with it
    			if(this.value<pack)
    				continue;
    			/* if the value is divisible by the package size, we know a direct path is just purchasing x number
    			 * of these packages. However, just purchasing x number of packages may not be the shortest path, so
    			 * we just recurse with one package for now, and exit the loop to conserve our greedy-algorithm design.
    			 */ 
    			if(this.value%pack==0) {
    				RubieRecursion temp = new RubieRecursion(this.value-pack,this);
    				temp.packagesPurchased.add(pack);
    				addToRecursions(temp);
    				break;
    			}
    			// add a recursion where one of these packages have been purchased
    			RubieRecursion temp = new RubieRecursion(this.value-pack,this);
    			temp.addPackagePurchase(pack);
    			addToRecursions(temp);
    		}
    		// if the bounds threshold has been reached, return null to indicate the recursion has hit a dead end. 
    		// It will automatically be cleaned up from its parent later.
    		if(this.value>RubieRecursion.bound_threshold) {
    			System.out.println("Bound hit - "+this.recursions.size());
    			return null;
    		}
    		// loop through the conversion options for the rubies and build a recursion off of each one
    		for(int buy : RubieRecursion.buyRubies) {
    			RubieRecursion temp = new RubieRecursion(this.value+buy,this);
    			temp.addRubiesPurchase(buy);
    			addToRecursions(temp);
    			// loop through the packages and build a recursion of each purchase package off of each conversion option
    			for(int pack : RubieRecursion.packages) {
    				if(temp.getValue()<pack) {
    					continue;
    				}
    				RubieRecursion newTemp = new RubieRecursion(temp.getValue()-pack,this);
    				newTemp.addRubiesPurchase(buy);
    				newTemp.addPackagePurchase(pack);
    				addToRecursions(newTemp);
    			}
    		}
    		// return null to pause the current recursion (and all sub-recursions) and cycle to the next recursion call
    		return null;
    	}
     
    	@Override
    	public String toString() {
    		String result = ""+this.value;
    		if(this.parent!=null) {
    			result = this.parent.toString()+"->"+result;
    		}
    		return result;
    	}
    }

    Executable class:
    /**
     * Main.java
     *
     * Apr 15, 2014
     */
     
    import java.util.Arrays;
     
    /**
     * @author aussiemcgr
     *
     * The main executing class.
     */
    public class Main {
     
    	/**
    	 * The constructor for this class.
    	 */
    	public Main() {
    		RubieRecursion first = new RubieRecursion(50);
    		RubieRecursion result = first.run();
    		if(result!=null) {
    			System.out.println("Results Found: ");
    			System.out.println("Rubies: "+Arrays.toString(result.getRubiesPurchased().toArray()));
    			System.out.println("Packages: "+Arrays.toString(result.getPackagesPurchased().toArray()));
    		}
    		else {
    			System.out.println("No result");
    		}
    	}
     
    	/**
    	 * @param args the arguments passed to the main
    	 */
    	@SuppressWarnings("unused")
    	public static void main(String[] args) {
    		// A call to a new version of this class so we don't have to work with static content if we don't want to.
    		new Main();
    	}
    }
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  23. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Euphoraz (April 22nd, 2014)

  24. #19
    Junior Member
    Join Date
    Apr 2014
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Need help on how to tackle this Java Project.

    Whoa, that's some heavy code above my level of knowledge, im going to try and break it down over the next few days and see if i can understand it properly.

    Thanks for the help man, i ave learnt lots already!

  25. #20
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Need help on how to tackle this Java Project.

    Most of it is just looping and recursion. I think I put in enough print statements for you to be able to get an idea of the program flow when you run it. So try to run it while you are breaking it down.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  26. #21
    Junior Member
    Join Date
    Apr 2014
    Posts
    12
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Need help on how to tackle this Java Project.

    Quote Originally Posted by aussiemcgr View Post
    Most of it is just looping and recursion. I think I put in enough print statements for you to be able to get an idea of the program flow when you run it. So try to run it while you are breaking it down.
    Do you find it hard reading other peoples code? I always struggle a little bit at the start, even if i have some idea on what is going on.
    Thanks heaps for adding the comments, you went out of your way a lot to help me and i appreciate it a lot.

  27. #22
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Need help on how to tackle this Java Project.

    Quote Originally Posted by Euphoraz View Post
    Do you find it hard reading other peoples code? I always struggle a little bit at the start, even if i have some idea on what is going on.
    Thanks heaps for adding the comments, you went out of your way a lot to help me and i appreciate it a lot.
    Only a bit. I've done it enough that I've gotten used to it. With that being said, the code above isn't exactly simple to read. I'm sure the run() and recurse() methods can be merged someway to simplify it, but I couldn't bother to try to figure out how. With the exception of that, I tried to simply the code as much as possible, but the algorithm is pretty complex, so I could only do so much. I didn't mind trying to figure it out. It was a very interesting problem, lol.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. Replies: 1
    Last Post: April 6th, 2014, 05:16 PM
  2. Java School Project Help; Project #2, In Danger of Failing.....
    By john++ in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 2nd, 2014, 02:35 AM
  3. Replies: 0
    Last Post: August 30th, 2010, 07:34 AM
  4. Replies: 2
    Last Post: August 1st, 2010, 06:29 AM