Tuesday, December 2, 2014

Binary Search in an Array

Input is an sorted array and an element which need to be searched in the array. The module will return the possition of the element in the given array.

public class BinarySearchArray {
    private final static int Default = -999; //default value
   
    public int BinarySearch(ArrayList<Integer> input, int element)    {
        if(input.size() == 0)
            return Default;
        return BinarySearchRecursive(input, element, 0, input.size());
    }
   
    private int BinarySearchRecursive(ArrayList<Integer> input, int element, int min, int max)    {
        int possition = Default;
        int check_possition = min+((max-min)/2);
        if(input.get(check_possition) == element)
            possition = check_possition;
        else if(max <= min)
            return Default;    //element not found
        else if(element > input.get(check_possition))    {
            int difference = (max-min)/2;
            if(difference == 0) difference = 1;
            min = min + (difference);
            possition = BinarySearchRecursive(input, element, min, max);
        }    else    {
            max = check_possition-1;
            possition = BinarySearchRecursive(input, element, min, max);
        }
        return possition;
    }
}
-----------------------------------------------------------------------------------------------------------
Recursion costs more memory. To be more memory efficient we can use a loop instead of recursion.

public class BinarySearchInLoop {
    private final static int Default = -999; //default value
    public int BinarySearch(ArrayList<Integer> input, int element)    {
        if(input.size() == 0)
            return Default;
        else {
        int min = 0;
        int max = input.size();
        while(min <= max) {
            int check_possition = min+((max-min)/2);
            if(input.get(check_possition) == element) {
            return check_possition;
            } else if(element > input.get(check_possition))    {
            int difference = (max-min)/2;
                    if(difference == 0) difference = 1;
                    min = min + (difference);
            } else {
            max = check_possition-1;
            }
            }
        return Default;
        }
    }
}

Saturday, November 15, 2014

Converting 2D NxN Array into a List in Spiral Order

Given a 2D NxN array. Print the array into a lost in spiral order.

Example:
If the input array if the following:
00     01     02     03
10     11     12     13
20     21     22     23
30     31     32     33
Then the output will be:
00     01     02     03     13     23     33     32     31     30     20     10     11     12     22     21

The following is a program using Java.

public ArrayList<Character> getSpiralArrayList(char[][] input) {
int size = input.length;
ArrayList<Character> output = new ArrayList<Character>();
if(input[0].length != size) {
System.out.println("Error: Not a NxN Matrix");
return output;
} else {
int top, bottom, left, right;
top = left = 0;
bottom = right = size-1;
for(int layer=0;layer<(size-1); layer++) {
for(int row=left;row<=right;row++)
output.add(input[top][row]);
top++;
for(int column=top; column<=bottom; column++)
output.add(input[column][right]);
right--;
for(int row=right; row>=left; row--)
output.add(input[bottom][row]);
bottom--;
for(int column=bottom; column>=top; column--)
output.add(input[column][left]);
left++;
}
return output;
}
}

Example input = {{'q','w','e'},{'r','t','y'},{'u','i','o'}};

Wednesday, November 5, 2014

App Store: Installing Older Versions of Apps

I got an iPod Touch 4th Generation from my uncle. He was using it for few years and before I got it. It was made to factory reset and hence it got erased all data and app from the device.

I created a new icloud account and started to configure it.

It had iOS 6 preinstalled in it. But current version of iOS is 8. Many apps like Facebook, Skype which we use daily supports only iOS 7 and above.

The App Store contained only latest apps and hence whenever I try to install, it throwed an error,
"This application requires iOS 7.0 or later" - Dismiss

I tried several times and asked few friends but nothing worked out. I found something here: http://support.apple.com/en-us/ht5919 but that too did not work. I went to my Purchased screen and found it empty. There was nowhere I was not able to find the option which provides a download. Some friends even suggested for jail breaking which I wasn't willing to.

Then I tried this which worked.
Just Follow the steps:
  1. I had a Windows 8.1 PC. I installed iTunes there and logedin using my newly created account. In that there is an App Store where I downloaded these apps. 
  2. As soon as I download these apps using WinPC iTunes, I can see the apps are showing in my iPod Purchase Screen. 
  3. The Purchase Screen is in the updates area of the App Store in iOS. 
  4. Go there and download the app again, it will download and install. Now you can follow this link: http://support.apple.com/en-us/ht5919 Everything will come to place

Wednesday, September 3, 2014

Check if char in a string are unique


public class StringUniqueChar {
final static int TotalChar = 128; //Total Number of ASCII
public boolean isUnique(String s) {
if(s.length()>TotalChar) return false;
else {
boolean[] hash = new boolean[TotalChar];
for(int i=0; i<s.length(); i++) {
int possition = s.charAt(i);
if(hash[possition]==true) return false;
else hash[possition] = true;
}
return true;
}
}
}

Simple Linked List Using Java

public class List {
List next;
int data;

List(int d) {
data = d;
next = null;
}

void appendData(int d) {
List l = new List(d);
List n = this;
while(n.next != null) {
n = n.next; 
}
n.next = l;
}

void printData() {
List n = this;
for(; n.next != null; n = n.next)
System.out.println(n.data);
System.out.println(n.data);
System.out.println("-END-");
}

void appendMiddle(int d, int position) {
List n = this;
for(int i=1; i<position; i++)
n=n.next;
List l = new List(d);
l.next = n.next;
n.next = l;
}

void deleteEnd() {
List n = this;
for(; n.next.next!=null; n=n.next) {}
n.next = null;
}

void deleteMiddle(int possition) {
List n = this;
for(int i=1; i<possition; i++)
n=n.next;
List a = n.next;
n.next = n.next.next;
a = null;
}
}

Tuesday, July 8, 2014

Random number generation using C

#include<stdio.h>
int main()
{
int range, random_number;
printf("Enter range 1 - ? :");
scanf("%d",&range);
random_number = rand(range);
printf("%d\n",random_number);
}
int rand(int range)
{
int temp = (int)&temp;
int random_number = temp % range;
temp = (int)NULL;
if(random_number<0)
random_number = random_number * -1;
return random_number;
}

Tuesday, May 13, 2014

Simulation: Comparison between Classical Computer and Quantum Computer using C

This is a program which gives you an idea about what a Quantum Computer is and how is it different from a Classical Computer. It can be compiled using CC or GCC compilers.

#include<stdio.h>
#include<stdlib.h>
#include<curses.h>
#include<time.h> 
void classic();
void quantum();
void delay_sec( int seconds );
int main() {
int c;
while(1) {
printf("\n\n1. Classical\n2. Quantum\n3. Exit\n(Please do not enter non-integer here)\nEnter the case: ");
scanf("%d",&c);
switch (c) {
case 1: {
classic();
break;
}
case 2: {
quantum();
break;
}
case 3: {
exit(0);
}
default: {
printf("Wrong Case!\nTry again");
break;
}
}
}
}
void delay_sec( int seconds ) {
    clock_t endwait;
    endwait = clock () + seconds * CLOCKS_PER_SEC;
    while (clock() < endwait) {}
}
void classic() {
system("clear");
printf("ONLY ONE SCHEMA AT A TIME\n");
printf("Classical\n");
printf("Data1 -> \nData2 -> \nData3 -> \nData4 -> \nData5 -> \nData6 -> \nData7 ->\n");
delay_sec(1);
system("clear");
printf("ONLY ONE SCHEMA AT A TIME\n");
printf("Classical\nData1 -> Schema1\nData2 -> \nData3 -> \nData4 -> \nData5 -> \nData6 -> \nData7 ->\n");
delay_sec(1);
system("clear");
printf("ONLY ONE SCHEMA AT A TIME\n");
printf("Classical\nData1 -> Schema1\nData2 -> Schema2\nData3 -> \nData4 -> \nData5 -> \nData6 -> \nData7 ->\n");
delay_sec(1);
system("clear");
printf("ONLY ONE SCHEMA AT A TIME\n");
printf("Classical\nData1 -> Schema1\nData2 -> Schema2\nData3 -> Schema3");
printf("\nData4 -> \nData5 -> \nData6 -> \nData7 ->\n");
delay_sec(1);
system("clear");
printf("ONLY ONE SCHEMA AT A TIME\n");
printf("Classical\nData1 -> Schema1\nData2 -> Schema2\nData3 -> Schema3");
printf("\nData4 -> Schema4\nData5 -> \nData6 -> \nData7 ->\n");
delay_sec(1);
system("clear");
printf("ONLY ONE SCHEMA AT A TIME\n");
printf("Classical\nData1 -> Schema1\nData2 -> Schema2\nData3 -> Schema3");
printf("\nData4 -> Schema4\nData5 -> Schema5\nData6 -> \nData7 ->\n");
delay_sec(1);
system("clear");
printf("ONLY ONE SCHEMA AT A TIME\n");
printf("Classical\nData1 -> Schema1\nData2 -> Schema2\nData3 -> Schema3");
printf("\nData4 -> Schema4\nData5 -> Schema5\nData6 -> Schema6\nData7 ->\n");
delay_sec(1);
system("clear");
printf("ONLY ONE SCHEMA AT A TIME\n");
printf("Classical\nData1 -> Schema1\nData2 -> Schema2\nData3 -> Schema3");
printf("\nData4 -> Schema4\nData5 -> Schema5\nData6 -> Schema6\nData7 -> Schema7\n");
delay_sec(1);
printf("\nTOTAL TIME TAKEN = 7 Units (1 Unit per schema)");
}
void quantum() {
system("clear");
printf("MULTIPLE OR EVERY POSSIBLE SCHEMA AT THE SAME TIME\n");
printf("Quantum\n");
printf("Data1 -> Schema1\nData2 -> Schema2\nData3 -> Schema3");
printf("\nData4 -> Schema4\nData5 -> Schema5\nData6 -> Schema6\nData7 -> Schema7\n");
printf("\nTOTAL TIME TAKEN = 1 Units (1 Unit per schema)");
}

Local Network Multichat UDP Application using Java without Server

This is a Multichat application inside a Local Network without any centralized Server. It uses MulticastSocket protocol which is UDP based. It transfer data through network as UDP packets. 

I am using PORT 8880 and 224.2.2.3 as IP. Make sure you this Port is available in the network. If not please compile the program with new PORT number. Also make sure the IP address you compile is a MulticastSocket address (Range between 224.0.0.1 and 239.255.255.254).

Run the same program in two different computer in the same network. Any number of system can be connected and you will be able to sent and receive data from all systems. 

Note :
  • Use ##Bye for exit the program
  • Do not use same username for two different systems.
Filename: Multicast.java

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Multicast
{
public static void main(String args[])
{
Login a = new Login();
String un = a.User();
un=un.concat("#><#");
System.out.println("name :"+un);
new Sender(un);
String[] parts = un.split("#><#", 2);
un=parts[0];
System.out.println("Type the word '##Bye' to exit the program");

MulticastSocket socket = null;
DatagramPacket inPacket = null;
byte[] inBuf = new byte[256];
try
{
try
{
//Prepare to join multicast group
//Recever End
socket = new MulticastSocket(8880);
InetAddress address = InetAddress.getByName("224.2.2.3");
//Range between 224.0.0.1 and 239.255.255.254
socket.joinGroup(address);

while (true)
{
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
String msg = new String(inBuf, 0, inPacket.getLength());
parts = msg.split("#><#", 2);
String SendersUN = parts[0];
msg = parts[1];
if(SendersUN.equals(un))
{
continue;
}
else
{
System.out.println("From : "+SendersUN+ "IP Address : " +inPacket.getAddress()+ "\n Message :"+msg);
}
}
}
catch (IOException ioe)
{
System.out.println(ioe);
}
Thread.sleep(100);
          }
catch (InterruptedException e)
{
System.out.println("Main Reciever thread interrupted.");
}
}
}
class Sender implements Runnable
{
Thread t;
String un;
Sender(String un)
{
t = new Thread(this,"Sender Thread");
t.start();
this.un=un;
}
public void run()
{
try
{
DatagramSocket socket = null;
DatagramPacket outPacket = null;
byte[] outBuf;
final int PORT = 8880;
Scanner in = new Scanner(System.in);
socket = new DatagramSocket();
String msg;
while (true)
{
InetAddress address = InetAddress.getByName("224.2.2.3");
//Range between 224.0.0.1 and 239.255.255.254
msg = in.nextLine();
if(msg.equals("##Bye"))
{
msg="Good Bye";
msg=un.concat(msg);
outBuf = msg.getBytes();
outPacket = new DatagramPacket(outBuf, outBuf.length, address, PORT);
socket.send(outPacket);
socket.close();
System.exit(0);
}
msg=un.concat(msg);
outBuf = msg.getBytes();
outPacket = new DatagramPacket(outBuf, outBuf.length, address, PORT);
socket.send(outPacket);
try
{
Thread.sleep(500);
}
catch (InterruptedException ie)
{
}
}
}
catch (IOException ioe)
{
System.out.println(ioe);
}
}
}
class Login
{
String User()
{
Scanner in = new Scanner(System.in);
String name;
System.out.println("Enter your user name");
name = in.nextLine();
return name;
}
}
UA-39217154-2