top of page
Caută
Poza scriitoruluioanaunciuleanu

Count the possible ways to construct buildings in JAVA

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.

29 afișări0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no...

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed...

Comments


bottom of page