I have a problem as follows: One room can hold 13 people, one 9, and another 4. Rooms all start out empty 0 0 0 and can be filled to their capacity OR the contents of one room can be transferred into another. So, for a situation like 13 0 0, the 13 could fill the third room making it 9 0 4. And so on. I want to generate all different possibilities (follow each generation until I reach a END or a state I've already generated. I've already implemented this using LOTS of If Else statements... What is the most concise way I can generate this?
-
1Show us the code you've got, and based on the question wording, I also suggest http://codereview.stackexchange.com for broad code review. – MeetTitan Feb 09 '15 at 19:55
-
This sounds like a good case for recursion. – yshavit Feb 09 '15 at 19:56
1 Answers
You can define a class named State that contains a the state of the three rooms, for example you could do something like State st = new State(13, 0, 0). The construtor of state may also validate the state, in order to garntee that the first room can only hold 13 people, the second one 9 and the third one 4.
Then you can implement a function named expand, with the signature:
List<State> expand (State st)
This function receives a state and returns a list of states that can be generated from the received state.
To do the:
I want to generate all different possibilities (follow each generation until I reach a END or a state I've already generated
there are many ways to do this, it depends on what kind of data you want to get? Do you want the set of States tha lead you to the state you want? Or do you just want to know that the state is reachable?
EDIT: Ok, since you want to get all the reachable states, you can create another function like:
List<State> getReachableStates(State root)
Now you can implement this in a recursive way or in a iterative way. This is the iterative one: This method containt a list of expanded states and a list of to expand states initialy ontaining the root state that you receive as argument. Then while you hava a state to expand you call expand on the state you remove from the list of states to expand. After you call expand you add the expanded State to the processed states list and add the result of calling expand to the to process list. When you end, return the list of expanded States.

- 1,286
- 12
- 32
-
I want to generate all reachable states meaning that I have to account for all sorts of situations of transferring parts of rooms to another room, plus, anytime a room = 0, it can be changed to max (as a possible move) – jonbon Feb 09 '15 at 20:09