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;
}