Friday 5 February 2016

Blocks world (Programming Assignment)

Write a program which does the following:
There are 3 tables in a room. Every table can hold any number of blocks stacked on each other with only one block touching the table. No two blocks are of the same size. At any point of time, the blocks must be placed in ALL tables in such a way that no smaller sized block will have a larger sized block on top of it. Initially all the blocks are placed on table number 1 in the correct fashion (biggest block at bottom and smallest block at the top). Our aim is to move all the blocks from table number 1 to table number 3 such that at every step all the constraints are satisfied and the final order in table 3 is: smallest block must be at the top and the largest at the bottom and all the other blocks in between in increasing size. Tables 2 and 1 should not have any blocks on them at the end of the process. You are allowed to move only one block at a time from any table to any other table.
Write a program which takes number of blocks as input and outputs the number of moves required to do so.


Input: a single integer indicating number of blocks
Output:a single integer indicating the number of moves required
Constraints:  You can assume that the number of blocks will be atmost 20.


Solution -:
#include<stdio.h> int table();int b=0; int main() {int n; scanf("%d",&n); table(n); printf("%d",b); return 0; } int table(int a) {b++; if(a==1) return; table(a-1); table(a-1); }

7 comments:

  1. could you send logic... cdntocgate@gmail.com

    ReplyDelete
    Replies
    1. the logic is pretty simple like the tower of hanoi..use recursion to solve it.

      Delete
  2. #include
    int TOH(int,char,char,char);
    int main()
    {
    int n;

    scanf("%d",&n);
    int c = TOH(n,'A','C','B');
    printf("%ld", c);
    return 0;
    }
    int TOH(int n,char first,char third,char second)
    {
    int count=0;
    if(n>0){
    count=TOH(n-1, first, second, third);
    count++;
    count+= TOH(n-1, second, third, first);
    }
    return count;
    }

    ReplyDelete
    Replies
    1. please don't write solution here , you can only use logic

      Delete
    2. please don't write solution here , you can only use logic

      Delete
  3. #include
    int TOH(int,char,char,char);
    int main()
    {
    int n;

    scanf("%d",&n);
    int c = TOH(n,'A','C','B');
    printf("%ld", c);
    return 0;
    }
    int TOH(int n,char first,char third,char second)
    {
    int count=0;
    if(n>0){
    count=TOH(n-1, first, second, third);
    count++;
    count+= TOH(n-1, second, third, first);
    }
    return count;
    }

    ReplyDelete
  4. formula is (2power n)-1 ..we can directly print that right?

    ReplyDelete