2 in 1

I am back.
Here’s a clean and plain Java program that fills an array in spiral form.Not clever very simple.
like if you enter 4 then output:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7


import java.io.*;

class Spiral{
	
	static int a[][];
	static int i,j,k;
	
	static void fill(int l,int t){
		
		while(j<l){
        a[i][j]=k++;
        j++;
    }
    i++;j--;

    while(i<l){
        a[i][j]=k++;
        i++;
    }
    i--;j--;

    while(j>=t){
        a[i][j]=k++;
        j--;
    }
    i--;j++;

    while(i>=t+1){
        a[i][j]=k++;
        i--;
    }
    i++;j++;
		
	}
	
	static void print(){
		
		int i,j;
		for(i=0;i<a.length;i++){
		   for(j=0;j<a[0].length;j++)
		      System.out.print(a[i][j] + " ");
		   System.out.println();
		   }
		      
	}
	
	public static void main(String args[]){
		
		int l,t,n;
		k=1;
		i=j=0;
		n=t=0;
		
		System.out.print("Enter n:");
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		try{
		n=Integer.parseInt(br.readLine());
		}catch(IOException e){}
		
		a=new int[n][n];
		l=n;
		
		while(k<=n*n){
			fill(l,t);
			l--;
			t++;
		}
		
		print();
		
		
	}
	
}

Here’s the other one.This one from the classic C book “The C Programming Language”.

Question:

Write a function expand(s1,s2) that expands shorthand notations like a-z in the string s1 into the equivalent complete list abc…xyz in s2 . Allow for letters of either case and digits, and be prepared to handle cases like a-b-c and a-z0-9 and -a-z . Arrange that a leading or trailing – is taken literally.

In the “The C Answer book” the solution is such krx303
Thats EYE straining and complex!

I tried to do it my way and in less lines and maybe i was successful..?
Anyways here is my solution…


#include <stdio.h>

int main()
{
    char c,prev;
    char tab[256];
    int state=0,i=0,cnt;
    prev=0;

    for(i=0;i<256;i++)
       tab[i]=i;

    while((c=getchar())!=EOF){
        switch(state){
            case 0:
            putchar(c);
            if(c!='-' && c!='\n'){
                prev=c;
                state=1;
            }
            break;

            case 1:
            if(c=='-'){
                cnt=1;
                while((c=getchar())=='-')cnt++;
                if(c!='\n')cnt--;   /*Its not a leading or trailing '-'*/
                for(i=0;i<cnt;i++)
                   putchar('-');
                if(c!='\n'){             /*It was not a leading or trailing '-' so expand.Note string like "abc---f" is converted "abc--def" .I was just adding some new flavors....its redundant though */
                    for(i=prev+1;i<=c;i++)
                       putchar(tab[i]);
                }
                state=0;
            }
            else{
                prev=c;
                putchar(c);
            }
            break;
        }
    }

    return 0;
}

I am busy…

Hello friends,
If you are a regular visitor to my blog then you would have noticed that i have not made any post from more then a couple of months.It is because i am busy sorting out other things,i think it will take another month.But as soon as i am done with my work..i will be back again!
Have a nice time!

Python:Insertion sort

Though it’s a simple insertion sort program but it’s written in python.Recently i have started learning this language and it’s fantastic…i can’t resist myself from posting the programs. 🙂

a=[]
print "Enter 10 integers"
for i in range(10):
    x=int(raw_input(""))
    a.append(x)
for i in range(1,10):
    tmp=a[i]
    j=i-1;
    while tmp<a[j] and j>=0:
        a[j+1]=a[j]
        j=j-1
    a[j+1]=tmp

print "The sorted array is"
for i in range(10):
    print a[i]

Expression Parser

This is a simple mathematical expression parser.It can parse +,-,*,/,%,().You enter the mathematical expression and it will display the result.I was quick coded so not much of error checking.As always i am lazy enough to not comment the code.

expr.h

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

#define NUM   256
#define NONE  257
#define END   258


char token[20];
int lookahead;
char buffer[100];
char *pbuf;
double value;

int lexan();
int isdelim(char);
void error(char *);
void match(int);
void parse(double *);
void expr(double *);
void term(double *);
void rest(double *);
void factor(double *);

expr.c

#include "expr.h"

static int state;

int lexan()
{
    char *tmp=token;
    char c;
    *tmp=0;

    while(isspace(*pbuf))pbuf++;

    if(*pbuf==0)
        return END;

    state=0;
    while(c=*pbuf){
        switch(state)
        {
            case 0:
              if(isdigit(c))
                  state=1;
              else if(c=='.')
                  state=2;
              else c=0;
              break;
            case 1:
              if(c=='.')
                  state=2;
              else if(c=='E' || c=='e')
                  state=3;
              else if(!isdigit(c))
                  c=0;
              break;
            case 2:
              if(c=='E' || c=='e')
                  state=3;
              else if(!isdigit(c))
                  c=0;
              break;
            case 3:
              if(!isdigit(c))
                  c=0;
              break;
        }
        if(c==0)
          break;
        pbuf++;
        *tmp++=c;
    }

    if(tmp!=token){
        *tmp=0;
        return NUM;
    }

    if(strchr("+-/*%()",*pbuf)){
        *tmp++=*pbuf++;
        *tmp=0;
        return *(tmp-1);
    }
    return NONE;
}


void error(char *e)
{
    fputs(e,stdout);
    exit(1);
}


void match(int t)
{
    if(lookahead==t)
       lookahead=lexan();
    else
       error("Syntax error\n");
}


void parse(double *val)
{
    *val=0;
    lookahead=lexan();
    if(lookahead!=END)
       expr(val);
    else
       error("No character in stream\n");
}


void expr(double *val)
{
    double t;
    term(val);

    while(1){
         switch(lookahead)
        {
            case '+':
                match('+');term(&t);*val+=t;
                break;
            case '-':
                match('-');term(&t);*val-=t;
                break;
            default:
                return;
        }
    }
}


void term(double *val)
{
    double t;
    rest(val);

    while(1){
         switch(lookahead)
         {
             case '*':
                 match('*');rest(&t);*val*=t;
                 break;
             case '/':
                 match('/');rest(&t);*val/=t;
                 break;
             case '%':
                 match('%');rest(&t);*val=(int)*val%(int)t;
                 break;
             default:
                 return;
         }
    }
}

void rest(double *val)
{
    char op=0;
    if(lookahead=='+' || lookahead=='-'){
        op=lookahead;
        match(lookahead);
    }
    factor(val);
    if(op=='-')
        *val=-(*val);
}


void factor(double *val)
{
    switch(lookahead)
    {
        case '(':
             match('(');expr(val);match(')');
             break;
        case NUM:
             sscanf(token,"%lf",val);match(NUM);
             break;
        default:
             return;
    }
}


int main()
{
    fputs("Enter expression:",stdout);
    pbuf=buffer;
    fgets(pbuf,sizeof(buffer),stdin);
    parse(&value);
    printf("Value:%.2lf\n",value);
    return 0;
}

KeyComb

KeyComb is a small tool that matches a given key combination from what is being typed on the keyboard.All the inputs to the program are given in interactive mode(not from the command line).

The first input is the key combination which will be matched with what is typed at the keyboard.
By key combination it means that a sequence of keystrokes like:- “abcd ”
Now whenever these four characters(“abcd”) are typed in succession it will be matched and the actions can be taken as provided in the further inputs.
KeyComb also tries to emulate backspace key so:-
abcd=abcp[BACKSPACE]d ;where [BACKSPACE] is the pressing of the backspace key.

You have option to display a message box with a message(which you can give at input) if the combination is typed at the keyboard.However,it’s optional.You can enter a newline(Empty line) to display no message box.

You have option to run a program(by giving its path) if the combination is typed from the keyboard.However,it’s optional.You can enter a newline(Empty line) for no program to run.

Uses:-
Well many it depends,you can freak out someone or you can warn someone on typing the bad words(you know which words!)

Download:-
http://flashcore.110mb.com/files/KeyComb.zip

Reference:-
http://flashcore-hq.blogspot.com

Print Upside Down

From one of the forums i was reading i got the idea of creating this program.Inputs some line of text and prints them as it was traversed from up to down when arranged in a row-column like structure.

Sample Input:-

ABCD
BMNF

Output:-

ABBMCNDF

#include <stdio.h>
#include <string.h>
#define BYTES 512

void pud(char *p,int o)
{
    if(!*p)return;
    int len=strlen(p);
    if(len>o)
        putchar(*(p+o));
    while(*p++);        /*points to first character of the next line*/
    pud(p,o);
}

int main()
{
    char str[BYTES];
    int i,max=0x0,j=0x0,t,size;
    
    size=fread(str,1,BYTES - 0x1,stdin);
    str[size]='\x00';
    
    for(i=0x0;i<size;i++){
         if(str[i]=='\n'){
             str[i]='\x00'; /*to make it usable by strlen*/
             t=strlen(&str[j]);
             if(t>max)
                 max=t;
             j=i + 0x1;
             }
    }

    for(i=0x0;i<max;i++)
        pud(str,i);
        
    return 0x0;
}

Cat

Another minimal implementation of cat.The gnu cat implementation read the file in the dynamically allocated buffer by using the formula (OUTSIZE – 1 + INSIZE * 4 + LINE_COUNTER_BUF_LEN).As you can see the buffer allocated is very large when compared to file.If the file is hugeeee then it can create problem on a low memory machine.So i thought i should create a cat implementation which reads the file in chunks in a fixed size buffer rather than whole file at once.At the first sight it looked easy but it had to care of previous and upcoming states to determine its output!
Here is my mini cat.Supported command options:-
-n //number all output lines
-b //number non-blank output lines
-t //display tabs as ^I
-e //display end-of-line characters as $

Mini Cat:-

#include <stdio.h>
#include <string.h>
#define  ISFTAB(x) x=='\t' || x=='\n'                 /*Non-printable characters format tags*/

enum{OPT_N=0x8,OPT_E=0x4,OPT_B=0x2,OPT_T=0x1};
enum{NEWF,TABF};                                      /*You can add more format tags(for non-print chars) here*/
int lcount=1;

/*Get's the next line from the input stream*/
int getline(char *buff,int max,FILE *fp)
{
    if(fgets(buff,max,fp)==0)
      return 0;
    return strlen(buff);
}

/*Returns the format tag for the non printable character*,it is extensible*/
char *fnonprint(char *f,char c)
{
    static char ftab[][5]={"$\n","^I"};
    int t=-1;
    if(c=='\n')
      t=NEWF;
    else if(c=='\t')
      t=TABF;
    return strcpy(f,ftab[t]);
}

void cat(const char *in,int opt)
{
    const char *p=in;
    char fc[10];
    if(*p=='\n'){
        if(opt&OPT_N)
          fprintf(stdout,"%d.",lcount++);
        if(opt&OPT_E)
          fprintf(stdout,"%s",fnonprint(fc,'\n'));
        else
          putchar('\n');
        return;                     /*The line is empty so no need of further processing and return*/
    }
    if(opt&OPT_N || opt&OPT_B)
      fprintf(stdout,"%d.",lcount++);       /*-b and -n option is to print line number for non-blank and all lines,both of which is
                                    true here because non empty line has been checked before*/

    while(*p){
        if(ISFTAB(*p)){
          if(opt&OPT_E || opt&OPT_T)
            fprintf(stdout,"%s",fnonprint(fc,*p));
          else
            putchar(*p);
        }
          else
            putchar(*p);
        p++;
    }
}

int main(int argc,char *argv[])
{
    int nfiles=0;
    int opt=0,i=0;
    FILE *fp;
    char in[512],c;

    while((++argv)[0] && argv[0][0]=='-'){
        while(c=*++argv[0])
            switch(c){
                case 'e':
                 opt|=OPT_E;
                 break;
                case 'b':
                 opt|=OPT_B;
                 break;
                case 't':
                 opt|=OPT_T;
                 break;
                case 'n':
                 opt|=OPT_N;
                 break;
                default:
                 fprintf(stderr,"cat:Unknown option %c",c);
                 return 1;
            }
    }

    while(argv[0]){
        nfiles++;
        fp=fopen(argv[0],"r");
        if(!fp){
          fprintf(stderr,"cat:Unable to open file %s",argv[0]);
          return 1;
        }
        while(i=getline(in,sizeof in,fp))
             cat(in,opt);

        fclose(fp);
        argv++;
    }
      /*take input from stdin*/
     if(nfiles==0){
        fp=stdin;
        while(i=getline(in,sizeof in,fp))
             cat(in,opt);
    }
    return 0;
}

String Replace

This  program removes all occurence of argv[1] by argv[2] in the file argv[3].

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>

/* Return the length of the file.Paramter is the file descriptor of the file */
off_t filelength(int fildes)
{
 off_t filesize;
 filesize=lseek(fildes,0,SEEK_END);
 lseek(fildes,0,SEEK_SET);
 return filesize;
}

/* Finds needle in p and if found skips needle string and print replace */
void match(char *p,const char *needle,const char *replace,size_t size)
{
 char *t;
 char *begin;
 char *c;
 int  needle_len;
 t=p ;    /* t is the current position of the buffer */
 begin=p; /* begin always point to the character from where printing starts */
 needle_len=strlen(needle);
 for(;(t-p)!=size;){

 t=strstr(t,needle);
 if(t){
 for(c=begin;c!=t;c++)/* t contains the address of needle so skip it */
 putchar(*c);
 printf("%s",replace);/* Prints replace in place of the needle string */
 t+=needle_len;       /* t now pints to the string after the match */
 begin=t;             /* Update begin to print from the charatcers after the match */
 }
 else break;
 }
 /* Prints the remaining character in the buffer which has no match with needle */
 for(c=begin;(c-p)!=size;c++)
 putchar(*c);
 //putchar('\n');
}

int main(int argc,char *argv[])
{
 if(argc!=4 && argc){
 fprintf(stderr,"Illegal number of parameters\n");
 return 1;
 }
 else
 if(argc==1){
 printf("Usage %s <string_to_replace> <string_to_replace_by>\n",argv[0]);
 return 1;
 }

 int fd;
 off_t size;
 char *chunk;
 char *needle;
 char *replace;

 needle=argv[1];  /*String to replace */
 replace=argv[2]; /*String to replace needle by */

 if((fd=open(argv[3],O_RDONLY))==-1){
 fputs("Error in opening file",stderr);
 return 1;
 }
 size=filelength(fd);
 chunk=(char*)malloc(size+1);
 if(!chunk){
 fputs("Memory intialization failure",stderr);
 return 1;
 }

 if(read(fd,chunk,size)==size)
 match(chunk,needle,replace,size);
 else {
 fputs("Error in reading file\n",stderr);
 return 1;
 }
 return 0;
}

Word Sort

This C program sorts all the word in the file supplied as argument lexicographically.The getword() function gets the next word and the bst_insert() function inserts it in the tree.The approach here used is that of Binary Search Tree.After this all it traverses the tree in inorder method and prints it to the console,each word in a new line.Suppose that if the word is there in the file more tahn 1 time then it is displayed that much time on the line each time separated by spaces.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char *pos;               /*position of the pointer in the buffer*/
char *word;             /*pointer to word scanned by getword()*/
int str_val;

struct pWord
{
char *pw;                  /*pointer to the word */
size_t w_count;         /*count of the word in the file */
struct pWord *left;
struct pWord *right;
};

/*Get's the next word from the buffer*/

void getword()
{
char *w=pos;
word=w;
if(!isalnum(*w)){
if(*w!=EOF){
*w='\x00';
pos++;
}
return;
}

 while(isalnum(*w=*pos++))w++;
*w='\x00';
pos=w+1;
}

struct pWord * bst_insert(struct pWord * wp,char *str)
{
if(wp=='\x00'){
wp=(struct pWord*)malloc(sizeof(struct pWord));
wp->pw=str;
wp->left=wp->right='\x00';
wp->w_count=1;
return wp;
}

 str_val=strcmp(str,wp->pw);
if(str_val < 0)         wp->left=bst_insert(wp->left,str);
else if(str_val> 0)
wp->right=bst_insert(wp->right,str);
else
wp->w_count++;
return wp;
}

void print_word(struct pWord * wp)
{
while(wp->w_count--){
fputs(wp->pw,stdout);
putchar(wp->w_count==0 ? '\n' : ' ');
}
}

void inorder(struct pWord *wp)
{
if(wp!='\x00'){
inorder(wp->left);
print_word(wp);
inorder(wp->right);
}
}

long int filelength(FILE *fp)
{
long int size;
fseek(fp,0,SEEK_END);
size=ftell(fp);
rewind(fp);
return size;
}

int main(int argc,char *argv[])
{
if(argc!=2){
fputs("Invalid arguments\n",stderr);
exit(1);
}

FILE *fp=fopen(argv[1],"r");
long int size=filelength(fp);

 if(size==-1){
fputs("Error in initializing:Calculating file length\n",stderr);
exit(2);
}

char *buff=(char*)malloc(size+1);
if(buff=='\x00'){
fputs("Error in memory allocation:Memory maybe low\n",stderr);
exit(3);
}

 if(fread(buff,1,size,fp)!=size){
fputs("Error in reading file:File may be in use by other process\n",stderr);
free(buff);
exit(4);
}

buff[size]=EOF;
pos=buff;

struct pWord *wp='\x00';
getword();
while(*word!=EOF){
if(*word!='\x00')
wp=bst_insert(wp,word);
getword();
}
inorder(wp);
free(buff);
return EXIT_SUCCESS;
}