You receive as an input a number representing sections. Each section is composed of two plots, on either side of the road. You must find all possible ways to construct buildings in the plots, considering that there has to be a space between any two buildings.
Input: int sections = 3; Output: 25 Explanation: For one side the possible ways are Building-Space-Space, Building-Space-Building, Space-Space-Space, Space-Building-Space and Space-Space-Building. In total there are 25 ways to construct buildings because a way to place on one side can correspond to any of 5 ways on the other side. |
Solution:
1. static int countWaysToConstructBuildings(int sections) { 2. if (sections == 1) { 3. return 4; 4. } 5. 6. int countBuildingAtEnd = 1; 7. int countSpaceAtEnd = 1; 8. int previousCountBuilding; 9. int previousCountSpace; 10. 11. for (int i = 2; i <= sections; i++) { 12. previousCountBuilding = countBuildingAtEnd; 13. previousCountSpace = countSpaceAtEnd; 14. 15. countSpaceAtEnd = previousCountBuilding + previousCountSpace; 16. countBuildingAtEnd = previousCountSpace; 17. } 18. 19. int result = countSpaceAtEnd + countBuildingAtEnd; 20. 21. return (result * result); 22. } 23.
Comments