Tuesday, December 21, 2010

15 game in Flash Actionscript3

Having implemented the 15-game in Java, I thought I would attempt the same with Flash + AS3. And the same was done swiftly and I have presented the output and the code here. This is the same as the applet version, you will have to use your arrow keys to play.




package{
 //----
 //IMPORT
 //
 import flash.display.*;
 import flash.events.*;
 import flash.text.*;
 import flash.ui.Keyboard;
 import flash.media.Sound;
 import flash.system.System;

 //Class creation
 public class Main extends MovieClip {
  
  private var SIZE:int;
  private var panelSize:int = 400;
  private var panelArray:Array = new Array(SIZE, SIZE);
  
  private var parentStage:Stage;
  private var baseClip:MovieClip;
  
  private var music:Sound = new BubbleSound();
  
  public function Main(stage, bClip, difficulty):void {
   SIZE = difficulty;
   parentStage = stage;
   baseClip = bClip;
   stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
   layout_in_grid();
   
   for(var i:int=0;i<SIZE*100;i++){//RANDOMIZE MOVES
    handleKeyPress(Math.floor(Math.random()*4) + 37);
   }
  }
  
  private function layout_in_grid():void{
   addChild(getGamePanel(SIZE));
  }
  
  private function keyPressed(e:KeyboardEvent):void{
   handleKeyPress(e.keyCode);
   music.play();
   if(areThingsInPlace()){
    baseClip.gotoAndStop(3,"Scene 1");
    stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
    this.parent.removeChild(this);
    var victory:Sound = new VictorySound();
    victory.play();
    return;
   }
  }
  
  private function handleKeyPress(keyCode:int):void{
   var emptyIndex:int = findEmptyIndex();
   var x:int = emptyIndex/SIZE;
   var y:int = emptyIndex%SIZE;
    
   switch (keyCode) {
    case Keyboard.LEFT://LEFT KEY
     if(y==SIZE-1) return;
     doSwap(x,y,x,y+1);
     break;
    case Keyboard.UP://UP KEY
     if(x==SIZE-1) return;
     doSwap(x,y,x+1,y);
     break;
    case Keyboard.RIGHT://RIGHT KEY
     if(y==0) return;
     doSwap(x,y,x,y-1);
     break;
    case Keyboard.DOWN://DOWN KEY
     if(x==0) return;
     doSwap(x,y,x-1,y);
     break;
   }
  }
  
  private function findEmptyIndex():int {
   for(var i:int=0;i<SIZE;i++){
    for (var j:int=0;j<SIZE;j++){
     if(panelArray[i][j].num_txt.text == '0'){
      return i*SIZE + j;
     }
    }
   }
   return 0;
  }
  
  private function doSwap(x:int, y:int, x1:int, y1:int):void{
   var temp:int;
   temp = panelArray[x][y].num_txt;
   panelArray[x][y].num_txt.text = panelArray[x1][y1].num_txt.text;
   panelArray[x1][y1].num_txt.text = temp;
   
   if(panelArray[x][y].num_txt.text == '0'){
    panelArray[x][y].alpha = 0;
    panelArray[x1][y1].alpha = 1;
   }else{
    panelArray[x][y].alpha = 1;
    panelArray[x1][y1].alpha = 0;
   }
    
  }
  
  private function getGamePanel(difficulty:int):MovieClip {
   var gridLayout:GridLayout = new GridLayout(SIZE, panelSize);
    
   var componentsList:Array = getRandomizedList(difficulty);
   var index:int = 0;
   for(var i:int=0;i<difficulty;i++){
    panelArray[i] = new Array(difficulty);
    for(var j:int=0;j<difficulty;j++){
     panelArray[i][j] = componentsList[index++];
     gridLayout.add(panelArray[i][j]);
    }
   }
   gridLayout.x = (parentStage.stageWidth / 2) - (gridLayout.width / 2);
     gridLayout.y = (parentStage.stageHeight / 2) - (gridLayout.height / 2);

   return gridLayout;
  }
  
  private function areThingsInPlace():Boolean{
   for(var i:int=0;i<SIZE*SIZE-1;i++){
    if(Number(panelArray[Math.floor(i/SIZE)][i%SIZE].num_txt.text) != (i+1)){
     return false;
    }
   }
   return true;
  }
  
  private function getRandomizedList(difficulty:int):Array  {
   var componentSet:Array = new Array(SIZE*SIZE);
   for(var i:int=0;i<difficulty*difficulty-1;i++){
    var square:SquareClip = new SquareClip();
    square.num_txt.text = (i+1).toString(10);
    componentSet[i] = square;
   }
   var emptyClip:SquareClip = new SquareClip();
   emptyClip.num_txt.text = (0).toString(10);
   componentSet[i] = emptyClip;
   return componentSet;
  }
 }
}

The Layout grid file which I wrote on my own to simulate an exact Grid Layout similar to the one in Java.

package{
 //----
 //IMPORT
 //
 import flash.display.*;
 import flash.events.*;
 import flash.text.*;
 
 //Class creation
 public class GridLayout extends MovieClip{
  
  private var _size:int;
  private var _size_of_grid:int;
  private var _gap:int;
  private var _itemCount:int;
  private var _totalFilled:int;
  
  public function GridLayout(size, size_of_grid):void {
   _size = size;
   _size_of_grid = size_of_grid;
   _totalFilled = 0;
  }
  
  public function add(object):int{
   if(_totalFilled == (_size*_size )){
       trace("GRID IS FULL");
     return 0;  
   }
   object.x = ( (_totalFilled % _size) ) * (_size_of_grid/_size)  ;
   object.y =  Math.floor(_totalFilled / _size) * (_size_of_grid/_size) ;
   _totalFilled++;
   addChild(object);
   return 1;
  }
  
 }
}

Cheers!!
Braga

Monday, December 20, 2010

Print % using printf in C

Problem:

How can you print % using the printf function? (Remember % is used as a format specifier!!!)
Very Simple, following cases are examples

#include <stdio.h>

int main()
{
    printf("\%\n"); // warning: unknown conversion type character 0xa in format - but prints
    printf("%%\n"); // correct statement
    printf("%\n");  // warning: unknown conversion type character 0xa in format
}

Cheers!!
Jack

Find Output for this C Program

Problem:

What would be the output of the following C program? (Is it a valid C program?)

#include <stdio.h>
int main()
{
    int i=43;
    printf("%d\n",printf("%d",printf("%d",i)));
    return 0;
}

Explanation:

This will produce output “4321”. The return type of printf is “int” which is the number of characters written to stdout.

printf("%d\n",printf("%d",printf("%d",i)));
printf("%d\n",printf("%d",printf("%d",43))); => 43
printf("%d\n",printf("%d",2)); => 2
printf("%d\n",1); => 1

Cheers!!
Jack

C - %n format specifier in printf

Well, what does the format specifier %n of printf function do?

Explanation:
Print nothing, but write number of characters successfully written so far into an integer pointer parameter.

Example:

#include <stdio.h>

int main()
{
    int val;
    printf("print the number of characters so far %n doesnt matter what you write here\n", &val);
    printf("val = %d\n", val);
    return 0;
}

Output:
blah blah
val = 38

Cheers!
Jack

C program to determine endian'ess

We shall see a small C program to determine whether a machine's type is little-endian or big-endian.

Definition:

BigEndian means that the higher order byte of the number is stored in memory at the lowest address, and the lower order byte at the highest address. The big end comes first.

eg: OAOBOCOD will be stored as OA(a) OB(a+1) OC(a+2) OD(a+3)


LittleEndian means that the lower order byte of the number is stored in memory at the lowest address, and the higher order byte is stored at the highest address i.e., the little
end comes first.

eg: OAOBOCOD will be stored as OD(a) OC(a+1) OB(a+2) OA(a+3)



Program:

#include <iostream>

using namespace std;

int main()
{
   int num = 1;
   if(*(char *)&num == 1)
      printf("Little-Endian\n");
   else // will be NULL
      printf("Big-Endian\n");

   return 0;
}

Cheers!!
Jack

Addition without using the + operator in C

Write a C function which does the addition of two integers without using the '+' operator. You can use only the bitwise operators.(Remember the good old method of implementing the full-adder circuit using the OR and XOR gates....)


Now, for the code implemented in C.
#include<stdio.h>
int main()
{
    int a = 12, b = 25;
    while (b)
    {
        int carry = a & b;
        a = a ^ b;
        b = carry << 1;
    }
    printf("%d\n",a);
}

Cheers!
Jack

CAT Brain Teaser

Well, this can be considered off-topic. A brain teaser in CAT. Only 2% students were able to solve this in the CAT Exam. They should have been really sick :) Enough build up, lets see what the problem is.

Given,

5+3+2 = 151022
9+2+4 = 183652
8+6+3 = 482466
5+4+5 = 202541

Then, 7+2+5 = ???


Solution:

5+3+2 = (5*3)(5*2)(5*3 + 5*2 - 3)
9+2+4 = (9*2)(9*4)(9*2 + 9*4 - 2)
8+6+3 = (8*6)(8*3)(8*6 + 8*3 - 6)
5+4+5 = (5*4)(5*5)(5*4 + 5*5 - 4)

Hence,

7+2+5 = (7*2)(7*5)(7*2 + 7*5 - 2) = 143547

Cheers!!
Jack

Thursday, December 16, 2010

"Offsetof" Macros in C : What it is and why it is

Problem:

The following is the offset macros which is used many a times. Lets figure out what is it trying to do and what is the advantage of using it.

#define offsetof(a,b) ((int)(&(((a*)(0))->b)))

Explanation:

offsetof tells you where in the memory allocation of the structure you will find a particular member.

Consider the example,

/* offsetof example */
#include <stdio.h>
#include <stddef.h>

struct mystruct
{
    char singlechar;
    char arraymember[10];
    char anotherchar;
};

int main ()
{
    printf ("offsetof(mystruct,singlechar) is %d\n",offsetof(mystruct,singlechar));
    printf ("offsetof(mystruct,arraymember) is %d\n",offsetof(mystruct,arraymember));
    printf ("offsetof(mystruct,anotherchar) is %d\n",offsetof(mystruct,anotherchar));

    return 0;
}

The structure defined takes up 12 bytes:

* byte 0: singlechar
* byte 1: arraymember[0]
* byte 2: arraymember[1]
* byte 3: arraymember[2]
* ...
* byte 10: arraymember[9]
* byte 11: anotherchar

The output will be:

offsetof(mystruct,singlechar) is 0
offsetof(mystruct,arraymember) is 1
offsetof(mystruct,anotherchar) is 11

If you allocate an object of type, and get a byte* to the start of the structure, you can use offsetof to find out where each member is. If you use that pointer offset, and convert it back to the correct type, it will give you a pointer to the member.

int main()
{
    mystruct s;
    s.anotherchar = 5;
    char* pBeginningOfS = (char*)(void*)(&s);
    char* pAnotherChar = pBeginningOfS + offsetof(mystruct, anotherchar);
    *pAnotherChar = 17;
    printf("anotherchar is %d", s.anotherchar);
    return 0;
}

The output will be:

anotherchar is 17

The reason you can't assume that each member will be a specific offset from the beginning of the struct is complicated, and compiler dependent. If you must do something like this (which is really low-level stuff which you should avoid unless you have to), then use a macro like offsetof, rather than trying to manually specify the offset yourself.

Hope you learnt something.

Cheers!!
Jack

How to find angle between hour and minute hands in an analog clock?

Given a simple clock, we have to find the angle between the hour and minute hands. Since this is a deliberate question, we should obviously be ignoring the thickness of the hands in the clock.


We need to understand the following things before we arrive at our solution.
  • The hour hand moves at the rate of 0.5 degrees per minute.
  • The minute hand moves at the rate of 6 degrees per minute.
The reason for the above statements are obvious if you think a layer deep. Now, for the code (works both for C++ and Java)

double angle(int h, int m)
{
     double hangle = 0.5D * (h*60 + m);
     double mangle = 6*m;
     angle = abs(hangle – mangle);
     angle = min(angle, 360-angle);
     return angle;
}

Cheers!!
Jack.

What is the difference between memcpy and memmove?

Answer:

With memcpy, the destination cannot overlap the source at all. With memmove copying takes place as if an intermediate buffer was used, allowing the destination and source to overlap. This means that memmove might be very slightly slower than memcpy, as it cannot make the same assumptions.

void * memcpy  ( void * destination, const void * source, size_t num );
void * memmove ( void * destination, const void * source, size_t num );

Cheers!!
Jack

Linked List : Given a pointer to any node, delete the node pointed by the pointer

Given a linked list like this,


Given a pointer to any node, delete the node pointed by the pointer. Note: no head pointer is given.

Solution:

Assume a pointer to p3, lets call it to 'p'. Since only pointer to current node is provided, there is no way to delete the current node from the list. But instead of deleting the current node, we can just move the next node data to current node and delete the next node. The algorithm can be explained simply as,
p->data = p->next->data;
t = p->next;
p->next = p->next->next;
delete t;

Cheers!!
Jack

Wednesday, December 15, 2010

C program to find fibonacci series using only one variable !!!

Problem:
Generating Fibonacci series using only one variable.

There are many ways to achieve this. I have given three ways to do this in the following methods.

Method #1:
We can have a simple function to do this.

F(n) = [(x^n) – ((1 – x)^n)]/ sqrt(5);
Where x = (1 + sqrt(5))/2 = 1.6180339887

Method #2:
The following recursive function would do the job.
int fib(n)
{
     return (n>2) ? n : fib(n-1)+fib(n-2);
}

Method #3:
The following one works great as well!
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
     unsigned long i = 1;
     printf ("0\n");
     while (((i & 0xffff0000) >> 16) + (i & 0xffff) <= 0xffff) {
          printf ("%d\n", i & 0xffff);    
          i = ((i & 0xffff) << 16) | ((i >> 16) + (i & 0xffff));
     }
     return 0;
}

Cheers!!
Jack