Showing posts with label Programing. Show all posts
Showing posts with label Programing. Show all posts

Tuesday, March 30, 2010

Bag Datastructure

An unordered collection of values that may have duplicates.

A bag has a single query function, numberIn(v), which tells how many copies of an element are in the bag, and two modifier functions, add(v) and remove(v).

numberIn(v) = returns no of element in Bag of type v;
add(v) = add a new element v in the bag;
remove(v) = removes all the element from the Bag of type v;
showBag() = prints all the element of the Bag;

Implementation of Bag in cpp(template).

#include < iostream >
#include < string.h >

using namespace std;

template < class Data >

class Bag
{
private:
struct node
{
Data data;
node *link;
}*ptr;
public:
Bag()
{
ptr = NULL;
}

void add(Data a)
{
if(ptr==NULL)
{
ptr = new node;
ptr- > data = a;
ptr- > link = NULL;
}
else
{
node *temp;
temp = new node;
temp- > data = a;
temp- > link = ptr;
ptr = temp;
}
}

void remove(Data data){
int present = 0;
if(ptr==NULL){
cout < < "Error !! Bag is empty" < < endl;
return;
}
else{
node *temp;
node *preTemp;
temp = ptr;
while(temp != NULL){
if(temp- > data == data){
if(temp == ptr){
ptr = ptr- > link;
delete temp;
temp = ptr;
}
else if(temp- > link!=NULL){
preTemp- > link = temp- > link;
delete temp;
temp = preTemp;
}
else if(temp- > link==NULL){
preTemp- > link = NULL;
delete temp;
}
}
else{
preTemp = temp;
temp = temp- > link;
}
}
}
}

int numberIn(Data data){
int count = 0;
if(ptr==NULL)
{
return count;
}
else
{
node *temp;
temp = ptr;
while(temp != NULL){
if(temp- > data == data){
count++;
}
temp = temp- > link;
}
}
return count;
}
void showBag(){
node *temp;
temp = ptr;
while(temp!=NULL){
cout < < " [" < < temp- > data < < "] " < < endl;
temp = temp- > link;
}
}
};



int main()
{
int input,remove;
Bag < int > intBag;

for(int i=0;i < 20;i++)
{
cin > > input;
intBag.add(input);
}
intBag.showBag();
cin > > remove;
cout < < "NumberIN = " < < intBag.numberIn(1) < < endl;
intBag.remove(remove);
cout < < "removed" < < endl;
intBag.showBag();
}

Thursday, December 3, 2009

Creating Own exception class in java.

Note: Exception class must be inherited


class OutOfRange extends Exception{
String message;
OutOfRange(){
message = new String("Please Enter No's between 0 and 100");
}
String toStr(){
return message;
}
}

public class MainCls{
public static void main(String args[]){
int input;
String inputStr;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

inputStr = br.readLine();
input = Integer.parseInt(inputStr);

try{
if(input < 0 || input > 100)
throw new OutOfRange();
}
catch(OutOfRange e){
System.out.println(e.toStr());
}
//Rest of code...
}
}

Thursday, September 10, 2009

trick to access a private member of class through its object


#include < iostream >

using namespace std;

class Base{
public: virtual void fun()=0;
};

class derived:private Base{
private: void fun(){
cout < < "accessing private method" < < endl;
}
};

int main(){
Base *base;
derived *dptr = new derived();
base = (Base *)dptr;
base- > fun();
return 0;
}

Thursday, May 21, 2009

Recursive Method to list all the file present in a Directory using cpp



#include < iostream >
#include < dirent.h >

using namespace std;

class recDir
{
private:
int fileCount;
public:
recDir()
{
fileCount = 0;
}
void showFileList(char *dirPath)
{
char *subDir="",*temp;
DIR *curDir;
struct dirent *entry;
if(curDir = opendir(dirPath))
{
while(entry = readdir(curDir))
{
if(strcmp(entry- > d_name,".") != 0 &&
strcmp(entry- > d_name,"..") != 0)
{
temp=strstr(entry- > d_name,".");
if(temp!=NULL
{
fileCount++;
cout << "File [" <<
fileCount << "] " <<
entry- > d_name << endl;
}
else
{
subDir = dirPath;
strcat(subDir,"/");
strcat(subDir,entry- > d_name);
showFileList(subDir);
}
}
}
closedir(curDir);
}
else
cout << "Error:Could not open directory/file\n";
}
int totalFiles()
{
return fileCount;
}
};


int main(int argc,char *argv[])
{
recDir obj;
obj.showFileList(argv[1]);
cout << endl << "Total Files =
" << obj.totalFiles() << endl;
}

Simple Example to extract data from xml file using expat............

takes an xml file and extract attributes into a file .rtf


#include "stdio.h"
#include "expat.h"
#include"string.h"
#define BUFFSIZE 8000



FILE *rtfFile;


static void startElement(void *cargo, const char *el,const char **attr)
{
}
static void endElement(void *cargo, const char *el)
{
}
static void characters(void *cargo, const char *ch, int len)
{
int i;
for (i=0; i putc(ch[i],rtfFile);
}

int main(int argc, char *argv[])
{
if(argc!=3)
{
printf("\nUsage : \n");
exit(0);
}
char Buff[BUFFSIZE];
FILE *fp;

fp = fopen(argv[1],"r");
rtfFile = fopen(strcat(argv[2],".rtf"),"w");

XML_Parser parser = XML_ParserCreate(NULL);
XML_SetElementHandler(parser, startElement, endElement);
XML_SetCharacterDataHandler(parser, characters);

for (;;)
{
int len = fread(Buff, 1, BUFFSIZE, fp);
int done = feof(fp);
if (! XML_Parse(parser, Buff, len, done))
exit(-1);
if (done) break;
}
fclose(fp);
printf("\n");
fclose(rtfFile);
return 0;
}


for Example we can use following content of a

< ?xml version="1.0"?>
< story>
< storyinfo>
< author>Ranjeet Kumar</author>
< datewritten>October 15,1985 </datewritten>
< keyword>Don</keyword>
< /storyinfo>
< body >
< headline > It's not gonna to help you < /headline >
< para > Don't be fool < /para >
< /body >
< /story >

Tuesday, May 19, 2009

Extracting data from the XML files Using expat on linux (XML parser)

1)Download .tar.gz files on from

http://webscripts.softpedia.com/script/Development-Scripts-js/XML-Tools/Expat--26466.html

2)extract into a folder
3) Move to this folder and run following well known commands

    ./configure
    make
    make install

4)now the times comes to check weather it is working or not.............
for this purpose expat people are very good as they have given two examples (too much i guess) in the folder expat.version/examples/. what you have have to do for checking, obviously copy a xml file from any where as you wish and run these programs.......
$>gcc examples.c -l expat
$>./a.out < xmlfile.xml

i hope you will see something which you need.

Tuesday, April 21, 2009

Mine Sweeper...........

//////////////////////////////////////////////////////////////////////////////////////////
The goal of the game is to find where all the mines are located within a M × N field.
The game shows a number in a square which tells you how many mines there are
adjacent to that square. Each square has at most eight adjacent squares. The 4 × 4 field
on the left contains two mines, each represented by a “*” character. If we represent the
same field by the hint numbers described above, we end up with the field on the right:
*... ===== *100
.... ===== 2210
.*.. ===== 1*10
.... ===== 1110
Input
The input will consist of an arbitrary number of fields. The first line of each field
contains two integers n and m (0 < n, m ≤ 100) which stand for the number of lines
and columns of the field, respectively. Each of the next n lines contains exactly m
characters, representing the field.
Safe squares are denoted by “.” and mine squares by “*,” both without the quotes.
The first field line where n = m = 0 represents the end of input and should not be
processed.
Output
For each field, print the message Field #x: on a line alone, where x stands for the
number of the field starting from 1. The next n lines should contain the field with the
“.” characters replaced by the number of mines adjacent to that square. There must
be an empty line between field outputs.
Sample Input ===== Sample Output
4 4 ===== Field #1:
*... ===== *100
.... ===== 2210
.*.. ===== 1*10
.... ===== 1110
3 5=====Field #2:
**... ===== **100
..... ======33200
.*...===== 1*100
0 0
////////////////////////////////////////////////////////////////////////////////////////////

//===============================================================================//
#include
#include

using namespace std;

int matrix[20][20];

void locate(int i,int j,int row,int column)
{
if(i-1 >=0 && i-1 < row && j-1 >=0 && j-1 < column && matrix[i-1][j-1] ==-1)
matrix[i][j] ++;
if(i-1 >=0 && i-1 < row && j >=0 && j < column && matrix[i-1][j] ==-1)
matrix[i][j]++;
if(i-1 >=0 && i-1 < row && j+1 >=0 && j+1 < column && matrix[i-1][j+1] ==-1)
matrix[i][j]++;
if(i >=0 && i < row && j-1 >=0 && j-1 < column && matrix[i][j-1] ==-1)
matrix[i][j]++;
if(i >=0 && i < row && j+1 >=0 && j+1 < column && matrix[i][j+1] ==-1)
matrix[i][j]++;
if(i+1 >=0 && i+1 < row && j-1 >=0 && j-1 < column && matrix[i+1][j-1] ==-1)
matrix[i][j]++;
if(i+1 >=0 && i+1 < row && j >=0 && j < column && matrix[i+1][j] ==-1)
matrix[i][j]++;
if(i+1 >=0 && i+1 < row && j+1 >=0 && j+1 < column && matrix[i+1][j+1] ==-1)
matrix[i][j]++;
}

void locatebombs(int row,int column)
{
for(int i=0;i < row;i++)
{
for(int j=0;j {
if(matrix[i][j] !=-1)
locate(i,j,row,column);
}
}
}

int main()
{
int row,column;
FILE *fp;
freopen("input.txt","r",stdin);
cin>>row>>column;
scanf("\n");
char m[20][20];
for(int i=0;i<=row;i++)
gets(m[i]);
cout< for(int i=0;i {
for(int j=0;j {
if(m[i][j] == '.')
matrix[i][j] = 0;
else
matrix[i][j] = -1;
}
cout< }
for(int i=0;i {
for(int j=0;j cout< cout< }

cout<<"\n"< locatebombs(row,column);
for(int i=0;i {
for(int j=0;j if(matrix[i][j] !=-1)
cout< else
cout<<"*\t";
cout< }
return 0;
}
//====================================================================================//

Thursday, April 16, 2009

Recursive Method to Find Total no of ways in which a positive number K can be written as sum of integers smaller than K

consider the a number 5. It can be represented as following sets {1+1+1+1+1},{1+1+1+2},{1+2+2},{1+1+3},{1+4},{2+3},{5+0} hence there are total seven.

recursive solution for finding total no of ways...

T(n) = Sigma (-1)^(m+1)*[ T(n-m*(3*m-1)/2) + T (n-m*(3*m+1)/2)]

where m = 1,2,3.........until (n-m*(3*m+1)/2) > 0;
Example:
T(5) = T(4) +T(3) - T(0)

//------------------------------------------------------------------------------------------------------------//
          int T(int n)
{
if(n < 0)
return 0;
else
{
if(n == 0)
return 1;
else
{
int temp = 1;
int tempr = 0;
int m = 0;
while(temp > 0)
{
m++;
temp = n-m*(3*m+1)/2;
tempr += pow(-1,m+1)*T(n-m*(3*m-1)/2) +
pow(-1,m+1)*T(n-m*(3*m+1)/2);
}
return tempr;
}
}
}

int main()
{
int number;
scanf("%d",number;);
printf("\nTotal ways = %d",T(number));
}

//------------------------------------------------------------------------------------------------------------//

Search Ranjeet's Blog