Sunday, 20 August 2017

Program For Single Columnar Transposition

Program:

import java.util.*;
class simpleColumnar{
      public static void main(String sap[]){
Scanner sc = new Scanner(System.in);

System.out.print("\nEnter plaintext(enter in lower case): ");
String message = sc.next();
System.out.print("\nEnter key in numbers: ");
String key = sc.next();

/* columnCount would keep track of columns */
int columnCount = key.length();

/* rowCount will keep of track of rows...no of rows = (plaintextlength + keylength) / keylength */
int rowCount = (message.length()+columnCount)/columnCount;

/*plainText and cipherText would be array containing ASCII values for respective alphabets */
int plainText[][] = new int[rowCount][columnCount];
int cipherText[][] = new int[rowCount][columnCount];

/*Encryption Process*/
System.out.print("\n-----Encryption-----\n");
cipherText = encrypt(plainText, cipherText, message, rowCount, columnCount, key);

// prepare final string
String ct = "";
for(int i=0; i<columnCount; i++)
{
for(int j=0; j<rowCount; j++)
{
if(cipherText[j][i] == 0)
ct = ct + 'x';
else{
ct = ct + (char)cipherText[j][i];
}
}
}
System.out.print("\nCipher Text: " + ct);

/*Decryption Process*/
System.out.print("\n\n\n-----Decryption-----\n");

plainText = decrypt(plainText, cipherText, ct, rowCount, columnCount, key);

// prepare final string
String pt = "";
for(int i=0; i<rowCount; i++)
{
for(int j=0; j<columnCount; j++)
{
if(plainText[i][j] == 0)
pt = pt + "";
else{
pt = pt + (char)plainText[i][j];
}
}
}
System.out.print("\nPlain Text: " + pt);

System.out.println();
}

static int[][] encrypt(int plainText[][], int cipherText[][], String message, int rowCount, int                                                                                                           columnCount, String key){
int i,j;
int k=0;

/* here array would be filled row by row  */
for(i=0; i<rowCount; i++)
{
for(j=0; j<columnCount; j++)
{
/* terminating condition...as string length can be smaller than 2-D array */
if(k < message.length())
{
/* respective ASCII characters would be placed */
plainText[i][j] = (int)message.charAt(k);
k++;
}
else
{
break;
}
}
}

/* here array would be filled according to the key column by column */
for(i=0; i<columnCount; i++)
{
/* currentCol would have current column number i.e. to be read...as there would be ASCII value stored in key so we would subtract it by 48 so that we can get the original number...and -1 would be subtract as array position starts from 0*/
int currentCol= ( (int)key.charAt(i) - 48 ) -1;
for(j=0; j<rowCount; j++)
{
cipherText[j][i] = plainText[j][currentCol];
}

}

System.out.print("Cipher Array(read column by column): \n");
for(i=0;i<rowCount;i++){
for(j=0;j<columnCount;j++){
System.out.print((char)cipherText[i][j]+"\t");
}
System.out.println();
}

return cipherText;
     }

static int[][] decrypt(int plainText[][], int cipherText[][], String message, int rowCount, int                                                                                                          columnCount, String key){
int i,j;
int k=0;

for(i=0; i<columnCount; i++)
{
int currentCol= ( (int)key.charAt(i) - 48 ) -1;
for(j=0; j<rowCount; j++)
{
plainText[j][currentCol] = cipherText[j][i];
}
}

System.out.print("Plain Array(read row by row): \n");
for(i=0;i<rowCount;i++){
for(j=0;j<columnCount;j++){
System.out.print((char)plainText[i][j]+"\t");
}
System.out.println();
}

return plainText;
}
}

Output: 

Enter plaintext(enter in lower case): networksecurity

Enter key in numbers: 31452

-----Encryption-----
Cipher Array(read column by column):
t       n       w       o       e
s       r       e       c       k
i       u       t       y       r

Cipher Text: tsixnruxwetxocyxekrx


-----Decryption-----
Plain Array(read row by row):
n       e       t       w       o
r       k       s       e       c
u       r       i       t       y

Plain Text: networksecurity

Wednesday, 19 July 2017

WaterJug Problem in Java: Artificial Intelligence

Problem Statement: There are two jugs (suppose capacity of 3 and 5) and we need to fill the jug in such a way that 5 litres capacity jug should contain 4 litres of water.


import java.util.*;
class WaterJug{
public static void main(String sap[]){
Scanner sc = new Scanner(System.in);

// j1 is capacity of small tank
System.out.print("\nEnter odd capacity of small tank: ");
int j1 = sc.nextInt();

// j2 is capacity of large tank
System.out.print("\nEnter odd capacity of large tank: ");
int j2 = sc.nextInt();

// count takes care of number of iterations
int count = j1 + j2;

/* jug1 array would hold the values for smaller tank and jug2 array would hold the values for larger     tank */
int jug1[] = new int[count];
int jug2[] = new int[count];

int i=0;

// initialzing jug1 and jug2 array
jug1[i] = j1;
jug2[i] = 0;
i++;

jug1[i] = 0;
jug2[i] = j1;
i++;

while(i < count){
if(jug1[i-1] > 0){
// if jug1 has any amount of water i.e. it is not empty
jug1[i] = jug1[i-1];
jug2[i] = 0;
}
else{
// jug1 is fully empty
jug1[i] = j1;
jug2[i] = jug2[i-1];
}
i++;

if(jug2[i-1] > 0){
// if jug2 has any amount of water i.e. it is not empty
if(jug1[i-1] + jug2[i-1] < j2){
// final result obtained
jug2[i] = jug1[i-1] + jug2[i-1];
jug1[i] = 0;
}
else{
int temp = jug2[i-1];
temp = j2 - temp;
jug2[i] = temp + jug2[i-1];
jug1[i] = jug1[i-1] - temp;
}
}
else{
// jug2 is fully empty
jug2[i] = jug1[i-1];
jug1[i] = 0; 
}
i++;
}

// display final result
for(i=0; i<count; i++){
System.out.print("\nJUG1: "+jug1[i]+"\tJUG2: "+jug2[i]);
}

System.out.println();
}
}

Output: 

Enter odd capacity of small tank: 3

Enter odd capacity of large tank: 5

JUG1: 3 JUG2: 0
JUG1: 0 JUG2: 3
JUG1: 3 JUG2: 3
JUG1: 1 JUG2: 5
JUG1: 1 JUG2: 0
JUG1: 0 JUG2: 1
JUG1: 3 JUG2: 1
JUG1: 0 JUG2: 4

Saturday, 25 March 2017

Program For Hundred Year Calender


Step1 - Firstly, select a year and then we need to find out the respective alphabet associated with it (Suppose we are selecting a year '2010' then the alphabet we would be getting is 'E')

Step2 - Secondly, the alphabet obtained from phase1 would act as your row index and the month you are looking would be your column index (now selecting month as 'march' then the column we are looking would be column3 and the row we are looking would be row5 as alphabet 'E' is at 5th row now the output of phase2 would be the intersection of column3 and row5 i.e. '1')

Step3 - Lastly, the number obtained from phase2 would act as a column index and then we need to traverse that column for the date we are looking for (the output from phase2 is '1' so we would be looking column1 and we are selecting date as '10' then we need to traverse column1 for date 10 and the day we would be getting would be 'Wednesday' i.e. final result)



Program -
import java.util.*;
class HundredYearCalender{
public static void main(String sap[]){
Scanner sc = new Scanner(System.in);
int i;
StringBuilder final_date = new StringBuilder();

/*
Phase1 - For phase input would be year and output would be the alphabet associated with that             year
*/
char alpha_28[] =                 {'A','B','C','K','F','G','A','I','D','E','F','N','B','C','D','L','G','A','B','J','E','F','G','H','C','D','E','M'};

//array for 100 years alphabets
char years[] = new char[100];
//variable 'k' keeps track of array alpha_28
int k = 0;
for(i=1;i<100;i++){
years[i] = alpha_28[k];
k++;
k = k % 28;
}

//taking input year
System.out.print("\nEnter the year(2001-2099): ");
int input_year = sc.nextInt();
final_date = final_date.append(input_year + "-");
input_year = input_year - 2000;

//setting the alphabet w.r.t specific year
char final_year = years[input_year];

/*
Phase2 - input would be the alphabet obtained from phase1 and the month you are searching                for and output would be the intersecting number
*/
//setting column values
int months[] = {1,4,4,7,2,5,7,3,6,1,4,6};

/*here subtracting the alphabet getting from phase1 with 64 to get the respective row to opt for*/
int row = (int)final_year - 64;

//taking input month
System.out.print("\nEnter the month: ");
int input_month = sc.nextInt();
final_date = final_date.append(input_month + "-");

input_month = input_month-1;
int initial_value = months[input_month];

int final_month=0;
for(i=0;i<row;i++){
final_month = initial_value;
initial_value++;
initial_value = initial_value % 7;
}

/*
Phase3 - number obtained from phase2 and the date would be input for phase3 and the output              would be the day we are looking for
*/
String weekdays[] =       {"Monday","Tuesday","Wednesday","Thrusday","Friday","Saturday","Sunday"};
System.out.print("\nEnter date: ");
int input_date = sc.nextInt();
final_date = final_date.append(input_date + "");

input_date = input_date + final_month - 1;
int result = -1;
for(i=0;i<input_date;i++){
result++;
result = result % 7;
}

//final result
System.out.print("\nDate(YYYY-MM-DD): "+ final_date + "\nDay: " + weekdays[result]);
}
}

Output -

Enter the year(2001-2099): 2017

Enter the month: 03

Enter date: 25

Date(YYYY-MM-DD): 2017-3-25
Day: Saturday

Wednesday, 2 November 2016

Cyclic Redundancy Check (CRC)

Program:

import java.util.*;
class CRC{
public static void main(String sap[])
{
Scanner sc = new Scanner(System.in);
int i,j,flag=0;

//string input of dividend...
System.out.print("\nEnter dividend: ");
String dividend = sc.next();

//string input for divisor...
System.out.print("\nEnter divisor: ");
String divisor = sc.next();

//length of dividend and divisor...
int dividend_length = dividend.length();
int divisor_length = divisor.length();

//array for dividend, divisor and send _array...
int dividend_array[] = new int[dividend_length + divisor_length - 1];
int send_arr[] = new int[dividend_length + divisor_length - 1];
int divisor_array[] = new int[divisor_length];

//loading dividend values into dividend array...
for(i=0;i<dividend_length;i++)
{
dividend_array[i] = Integer.parseInt(""+dividend.charAt(i));
send_arr[i] = dividend_array[i];
}

//padding '0' to dividend array...
for(i=dividend_length;i<dividend_array.length;i++)
{
dividend_array[i] = 0;
}

//loading divisor values into divisor array...
for(i=0;i<divisor_length;i++)
{
divisor_array[i] = Integer.parseInt(""+divisor.charAt(i));
}

//temp array would hold temp dividend...
int temp[] = new int[divisor_length];
for(i=0;i<dividend_array.length;i++)
{
/*it would work only for '1' and for '0' it would do nothing just increment the index...*/
if(dividend_array[i] == 1)
{
//loading temp dividend to temp array...
for(j=0;j<divisor_length;j++)
{
if(i+j>dividend_array.length-1)
{
//flag = 1 dividend < divisor
flag=1;
break;
}
else
{
temp[j] = dividend_array[i+j];
}
}

//flag = 0 means divison is possible...
if(flag==0)
{
for(j=0;j<divisor_length;j++)
{
if(temp[j] == divisor_array[j])
{
dividend_array[i+j] = 0;
}
else
{
dividend_array[i+j] = 1;
}
}
}
}
  }

//loading send_arr with value generated...
for(i=dividend_length;i<dividend_array.length;i++)
{
send_arr[i] = dividend_array[i];
}

//displaying message to be transmitted...
System.out.print("\nMessage to be transmitted is: ");
for(i=0;i<send_arr.length;i++)
{
System.out.print(send_arr[i]);
}
}
}

Output:

Enter dividend: 1101011011

Enter divisor: 10011

Message to be transmitted is: 11010110111110

Sunday, 18 September 2016

Hamming Code: N-bit

Program for N-bit Hamming Code:
import java.util.*;
class hamming{
  public static void main(String sap[]){
    System.out.print("\nNOTE: Example - Format for 7-bit Hamming Code - P1 P2 D3 P4 D5 D6 D7");
    int i,j,k;
    Scanner sc = new Scanner(System.in);

    /*taking no of data bits...*/
    System.out.print("\nEnter no of bits: ");
    int no_of_data_bits = sc.nextInt();

    /*creating parity positions array as per no of data bits...here parity_pos[] array size would be no_of_data_bits and indexing would be from 0 to (no_of_data_bits - 1)...*/
    int parity_pos[] = new int[no_of_data_bits];
    int no_of_parity_bits=0;
    while(no_of_data_bits>Math.pow(2,no_of_parity_bits)){
      parity_pos[no_of_parity_bits] = (int)Math.pow(2,no_of_parity_bits);
      no_of_parity_bits++;
    }
    parity_pos[no_of_parity_bits] = (int)Math.pow(2,no_of_parity_bits);
    no_of_parity_bits++;

    /*creating a sending array of size (no_of_data_bits + no_of_parity_bits + 1)...here send_arr[] indexing would be from 1 to ((no_of_data_bits + no_of_parity_bits + 1) - 1)...index '0' of send_arr[] is not used...*/
    int send_arr[] = new int[no_of_data_bits+no_of_parity_bits+1];

    /*creating a variable 'k' which would be used to bypass the parity positions in send_arr[] by referring parity_pos[]...*/
    k=0;
    System.out.print("\nEnter "+no_of_data_bits+" Data Bits: \n");
    for(j=1;j<send_arr.length;j++){
      if(parity_pos[k]==j){
        k++;
      }
      else{
        /*taking data_bits and storing in send_arr[]...*/
        send_arr[j] = sc.nextInt();
      }
    }

    int result,distance,count;
    /*creating a parity value array as per no_of_data_bits...here indexing of parity_value[] would be from 0 to (no_of_data_bits - 1)...*/
    int parity_value[] = new int[no_of_data_bits];

    /*here variable 'i' would take care of no of parity values to be generated...*/
    i=0;
    while(i<parity_pos.length && parity_pos[i]!=0){
      /*result variable would contain the parity value generated...*/
      result = 0;

      /*here distance and count variable would contain the distance...
      distance would be like...suppose distance = 2 then we would take first 2 values from send_arr[] and skip next 2 values from send_arr[] and repeat the procedure till the end of the send_arr[]...*/
      distance=count=parity_pos[i];

      /*j variable would take care of generating parity as per distance in the send_arr[]...*/
      j=1;
      while(j<send_arr.length){
        /*for this while loop the values of send_arr[] would be considered for generating parity value...and we are not taking care of parity bits as initially parity bits in send_arr[] would be '0'...*/
        while(count<=distance && count>0 && j<send_arr.length){
          result = result + send_arr[j];
          count--;
          j++;
        }

        /*for this while loop the values of send_arr[] would not be responsible for generating parity value...*/
        while(count<distance){
          count++;
          j++;
        }
      }

      /*at the end of every iteration of above while loop...parity value would be generated...and value of parity would be stored in parity_value[]...*/
      parity_value[i] = result%2;
      i++;
    }

    /*merging the send_arr[] and parity_value[]...*/
    j=0;
    for(i=1;i<send_arr.length;i++){
      /*as per parity_pos[] array the values would be inserted respectively in send_arr[]...*/
      if(i==parity_pos[j]){
        send_arr[i] = parity_value[j];
        j++;
      }
    }

    /*Displaying the data to be transmitted...*/
    System.out.print("\nData to be transmitted: ");
    for(i=1;i<send_arr.length;i++){
      System.out.print(send_arr[i]);
    }
    System.out.println();
  }
}

Output:

NOTE: Example - Format for 7-bit Hamming Code - P1 P2 D3 P4 D5 D6 D7
Enter no of bits: 8

Enter 8 Data Bits:
1
0
0
1
1
0
1
0

Data to be transmitted: 011100101010

Saturday, 30 July 2016

Super ASCII String Checker

Problem Statement: 

In the Byteland country a string "S" is said to super ascii string if and only if count of each character in the string is equal to its ascii value.

In the Byteland country ascii code of 'a' is 1, 'b' is 2 ...'z' is 26.

For eg1 - String "bba" is super ascii string
Explanation:- .String "bba" 
The count of character 'b' is 2. Ascii value of 'b' is also 2.
The count of character 'a' is 1. Ascii value of 'a' is also 1.
Hence string "bba" is super ascii string.

For eg2 - String "acc" is not super ascii string
Explanation:- String "acc"
The count of character 'a' is 1. Ascii value of 'a' is also 1
The count of character 'c' is 2. But the ascii value of 'c' is 3
Hence string "acc" is not super ascii string.

Program: 

import java.util.*;
class PS
{
  public static void main(String sap[])
  {
    int i,j;
    Scanner sc = new Scanner(System.in);

    //taking input string
    System.out.print("\nEnter String: ");
    String str = sc.next();

    //character array for retriving the value of respective character
    char char_arr[] = new char[27];

    //loading the character array
    int char_count=97;
    for(i=1;i<27;i++)
    {
      char_arr[i] = (char)(char_count++);
    }

    //it would act like a hash table
    int result_arr[] = new int[27];

    //initially loading result array with 0
    for(i=1;i<27;i++)
      result_arr[i]=0;

    //loading result array i.e hash table
    for(i=0;i<str.length();i++)
    {
      for(j=1;j<27;j++)
      {
        if(char_arr[j]==str.charAt(i))
        {
          int temp = result_arr[j];
          result_arr[j]=temp+1;
          break;
        }
      }
    }

    //comparing result array with its index if yes then accept else break
    for(i=1;i<27;i++)
    {
      if(result_arr[i]>0)
      {
        if(result_arr[i]!=i)
        {
            break;
        }
      }
    }

    //if value of 'i' would be less then 27 then string is rejected...
    if(i<27)
      System.out.print("\n"+str+" not a super ascii string...");
    else
      System.out.print("\n"+str+" is super ascii string...");
  }
}

Output:

1. Enter String: bab
    bab is super ascii string...

2. Enter String: ccdddd
    ccdddd not a super ascii string...

Tuesday, 21 June 2016

Problem Statement - II


Problem Statement:-

                              N x N board is given for 'N' queen. We want to place 'N' queen on the board in non-attacking position.

Note: Queen can attack horizontally, vertically and diagonally.

For this use 1-D array-X where Kth element of array-X will give column of Kth queen.

Example:











Constraint on array-X:
1. Every value stored in array-X should be unique
2. Every value stored in array-X should be between 1 to 'N'


Program:
#include<stdio.h>
#include<math.h>
#define MAXSIZE 10

int x[MAXSIZE];
int n;

void printsolution()
{
    int i, k;
    static int solno=1;

    printf("\nSolution %d: ", solno++);
    for(i=1;i<=n;i++)
    {
        printf("%d ",x[i]);
    }
}

int place(int k, int i)
{
    int j;

    for(j=1; j<k; j++)
    {
        if( (x[j] == i) || (abs(x[j]-i) == abs(j-k)) )
            return 0;
    }
    return 1;
}

void nqueen(int k)
{
    int i;

    for(i=1; i<=n; i++)
    {
        if(place(k,i))
        {
            x[k] = i;
            if(k == n)
                printsolution();
            else
                nqueen(k+1);
        }
    }
}

void main()
{
    printf("\nEnter board size: ");
    scanf("%d",&n);
    if(n>MAXSIZE)
    {
        exit(1);
    }
    nqueen(1);
}

Output:

Enter board size: 4

Solution 1: 2 4 1 3
Solution 2: 3 1 4 2

Monday, 29 February 2016

Problem Statement - I

Problem Statement:
              You have been given a gold prices for n days. You Need to find out max benefit in best time to buy and sell.

import java.util.*;
class Demo
{
  public static void main(String s[])
  {
  Scanner sc = new Scanner(System.in);
       int day[]=new int[100];
        int i,j,res,a=0,b=0,fres=0;
       System.out.println("\nEnter no of days: ");
  int n=sc.nextInt();

  System.out.print("\nEnter "+n+" gold prices: ");
  for(i=0;i<n;i++)
  {
    day[i]=sc.nextInt();
  }
  for(i=0;i<n;i++)
  {
    for(j=i;j<n;j++)
    {
    res=day[j]-day[i];
    System.out.print("Purchase Day: "+(i+1)+" Sell Day: "+(j+1)+" Profit: "+res);
    if(res>=fres)
    {
      a=i;
      b=j;
      fres=res;
    }
    System.out.println();
    }
  }

    System.out.print("\nBest Purchase:\nPurchase Day: "+(a+1)+" Sell Day: "+(b+1)+" Profit: "+fres);
  }
}

Output:
Enter no of days:
5

Enter 5 gold prices: 
100
60
400
500
30

Purchase Day: 1 Sell Day: 1 Profit: 0
Purchase Day: 1 Sell Day: 2 Profit: -40
Purchase Day: 1 Sell Day: 3 Profit: 300
Purchase Day: 1 Sell Day: 4 Profit: 400
Purchase Day: 1 Sell Day: 5 Profit: -70
Purchase Day: 2 Sell Day: 2 Profit: 0
Purchase Day: 2 Sell Day: 3 Profit: 340
Purchase Day: 2 Sell Day: 4 Profit: 440
Purchase Day: 2 Sell Day: 5 Profit: -30
Purchase Day: 3 Sell Day: 3 Profit: 0
Purchase Day: 3 Sell Day: 4 Profit: 100
Purchase Day: 3 Sell Day: 5 Profit: -370
Purchase Day: 4 Sell Day: 4 Profit: 0
Purchase Day: 4 Sell Day: 5 Profit: -470
Purchase Day: 5 Sell Day: 5 Profit: 0

Best Purchase:
Purchase Day: 2 Sell Day: 4 Profit: 440

Saturday, 23 January 2016

PatternDemo in Java - II


class PatternDemo
{
public static void main(String s[])
{
int n = 5;
for(int i=1;i<=n;i++)
{
for(int j=0;j<i;j++)
{
System.out.print((i+j)%2+"\t");
}
System.out.print("\n");
}
}
}

Output:
1
0       1
1       0       1
0       1       0       1
1       0       1       0       1



class PatternDemo
{
public static void main(String s[])
{
int n = 4,k=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
System.out.print((k++)+"\t");
}
System.out.print("\n");
}
}
}

Output:
0
1       2
3       4       5
6       7       8       9

Tuesday, 22 December 2015

PatternDemo in Java - I

import java.util.*;
class PatternDemo
{
    public static void main(String args[])
    {
        char ch='A';
     
        Scanner sc = new Scanner(System.in);
        System.out.print("\nEnter value for n: ");
        int n = sc.nextInt();
     
        for(int i=1;i<=n;i++)
        {
           for(int j=n;j>=i;j--)
           {
              System.out.print(" ");
           }
             
           for(int k=1;k<=i;k++)
           {
               System.out.print(ch++);
           }
           ch--;
         
           for(int m=1;m<i;m++)
           {
              System.out.print(--ch);
           }
           System.out.print("\n");
        }
    }
}
Output2:
Enter value for n: 5
           A
        ABA
      ABCBA
    ABCDCBA
 ABCDEDCBA



import java.util.*;
class PatternDemo
{
    public static void main(String args[])
    {
        char ch='A';

        Scanner sc = new Scanner(System.in);
        System.out.print("\nEnter value for n: ");
        int n = sc.nextInt();
     
        for(int i=0;i<=(n-1);i++)
        {
            for(int j=0;j<=i;j++)
            {
               System.out.print(ch++);
            }
            System.out.print("\n");
        }
    }
}

Output1:
Enter value for n: 4
A
BC
DEF
GHIJ