Tuesday, March 22, 2016

Find Nth Element From Last of the LinkedList in Single Pass

package LinkedList;

public class NthLastElementFromLast {

Nod head;
int size;

NthLastElementFromLast()
{
head = null;
size = 0;
}

public static void main(String args[])
{
NthLastElementFromLast elementFromLast = new NthLastElementFromLast();
elementFromLast.add(1);
elementFromLast.add(2);
elementFromLast.add(3);
elementFromLast.add(4);
elementFromLast.add(5);
elementFromLast.display();
elementFromLast.findNthFromLast(3);
}

void add(int val)
{
size++;
if(head == null)
{
head = new Nod(val,null);
}
else
{
Nod temp = new Nod(val,head);
head = temp;
}
}

void display()
{
Nod temp = head;
while(temp != null)
{
System.out.println(temp.data);
temp = temp.link;
}
}

void findNthFromLast(int n)
{
if(n>size || n<0)
return;
Nod temp = head;
Nod temp1 = head;
for(int i=0;i<n;i++)
temp = temp.link;
while(temp != null)
{
temp = temp.link;
temp1 = temp1.link;
}
System.out.println(temp1.data);

}

}

class Nod {
int data;
Nod link;
Nod()
{
data =0;
link = null;
}
Nod(int data,Nod link)
{
this.data = data;
this.link = link;
}
}

Reverse a LinkedList using recursion

public void reverse()
{
Node newNode = null;
head = method(head,newNode);
}

private Node method(Node old,Node newNode)
{
if(old == null)
{
return null;
}
else
{
Node temp = method(old.getLink(),newNode);
if(temp == null)
{
newNode = old;
return newNode;
}
else
{
newNode = temp;
old.setLink(null);
while(temp.getLink() != null)
{
temp = temp.getLink();
}
temp.setLink(old);
return newNode;
}
}
}

Lexicographic Rank of a String

public class LexicographicRank
{
    public static void main(String args[])
    {
        String str = "dcba";
        int n = str.length();
        int rank = 0;
        for (int i = 0; i < n - 1; i++)
        {
            int x = 0;
            for (int j = i + 1; j < n; j++)
            {
                if (str.charAt(i) > str.charAt(j))
                    x++;
            }
            rank = rank + (x * (fact(n - i - 1)));
        }
        System.out.println(rank + 1);
    }
   
    private static int fact(int n)
    {
        int res = 1;
        if (n == 0)
            return 1;
        else
        {
            for (int i = 1; i <= n; i++)
            {
                res = res * i;
            }
        }
        return res;
    }
}

Saturday, March 19, 2016

Selection Sort in Java

import java.util.stream.IntStream;

public class SelectionSort
{
    public static void main(String args[])
    {
        int[] arr = new int[] {5, 12, 1, -5, 16};
        new SelectionSort().sort(arr);
        IntStream.of(arr).forEach(System.out::println);
    }
   
    private void sort(int[] arr)
    {
        int index = 0, smallEle;
        for (int i = 0; i < arr.length - 1; i++)
        {
            smallEle = arr[i];
            for (int j = i + 1; j < arr.length; j++)
            {
                if (arr[j] < smallEle)
                {
                    index = j;
                    smallEle = arr[j];
                }
            }
            smallEle = arr[i];
            arr[i] = arr[index];
            arr[index] = smallEle;
        }
    }
}

Buble Sort in Java

import java.util.stream.IntStream;

public class BubbleSort
{
   
    public static void main(String args[])
    {
        int[] arr = new int[] {5, 12, 1, -5, 16};
        new BubbleSort().sort(arr);
        IntStream.of(arr).forEach(System.out::println);
    }
   
    private void sort(int[] arr)
    {
        boolean loop = true;
        int temp = 0;
        while (loop)
        {
            loop = false;
            for (int i = 0; i < arr.length - 1; i++)
            {
                if (arr[i] > arr[i + 1])
                {
                    temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                    loop = true;
                }
            }
        }
    }
}

Java LinkedList Implementation

//Creating Node
public class Node
{
    private int data;
 
    private Node link;
 
    Node()
    {
        link = null;
        data = 0;
    }
 
    Node(int data, Node ref)
    {
        this.data = data;
        this.link = ref;
    }
 
    public int getData()
    {
        return data;
    }
 
    public void setData(int data)
    {
        this.data = data;
    }
 
    public Node getLink()
    {
        return link;
    }
 
    public void setLink(Node link)
    {
        this.link = link;
    }
}



//Creating LinkedList operations
public class LinkedList
{
    private Node head;
 
    private int size;
 
    LinkedList()
    {
        head = null;
        size = 0;
    }
 
    public boolean isEmpty()
    {
        return head == null;
    }
 
    public int getSize()
    {
        return size;
    }
 
    public void insertAtStart(int val)
    {
        Node temp = new Node(val, null);
        size++;
        if (head == null)
        {
            head = temp;
        }
        else
        {
            temp.setLink(head);
            head = temp;
        }
    }
 
    public void display()
    {
        System.out.println("\n----Singly Linked List----");
        if (size == 0)
        {
            System.out.println("Empty");
            return;
        }
        if (head.getLink() == null)
        {
            System.out.println(head.getData());
            return;
        }
        Node temp = head;
        while (temp.getLink() != null)
        {
            System.out.print(temp.getData() + "->");
            temp = temp.getLink();
        }
        System.out.print(temp.getData() + "\n");
     
    }
 
    public void insertAtEnd(int val)
    {
        Node insert = new Node(val, null);
        size++;
        if (head == null)
        {
            head = insert;
         
        }
        else
        {
            Node temp1 = head;
            while (temp1.getLink() != null)
            {
                temp1 = temp1.getLink();
            }
            temp1.setLink(insert);
        }
    }
 
    public void insertAtPos(int val, int pos)
    {
        Node insert = new Node(val, null);
        Node temp = head;
        pos = pos - 1;
        for (int i = 1; i < size; i++)
        {
            if (i == pos)
            {
                Node temp1 = temp.getLink();
                temp.setLink(insert);
                insert.setLink(temp1);
                break;
            }
            temp = temp.getLink();
        }
        size++;
    }
 
    public void deleteAtPos(int pos)
    {
        Node temp = head;
        if (pos > size)
        {
            System.out.println("Wrong number");
            return;
        }
        else if (pos == 1)
        {
            head = head.getLink();
            size--;
            return;
        }
     
        else if (pos == size)
        {
            while (temp.getLink().getLink() != null)
            {
                temp = temp.getLink();
            }
            temp.setLink(null);
            return;
        }
        else
        {
            pos -= 1;
            for (int i = 1; i < size; i++)
            {
                if (pos == i)
                {
                    Node del = temp.getLink();
                    temp.setLink(del.getLink());
                    break;
                }
                temp = temp.getLink();
            }
        }
    }

public void swap(int first, int second) {
Node firstSwap = null;
Node secondSwap = null;
if (first == second) {
return;
}
if (first > second && first > size && second > size && first < 0 && second < 1) {
System.out.println("The Entered Positions are wrong");
return;
}
if(first == 1)
{
firstSwap = new Node(head.getData(),null);
}

first -= 1;
second -= 1;
boolean set = true;
Node temp = head;
for (int i = 1; i < size; i++) {
if (i == first && secondSwap == null) {
firstSwap = new Node(temp.getLink().getData(), null);

}
if (i == first && secondSwap != null) {
secondSwap.setLink(temp.getLink().getLink());
temp.setLink(secondSwap);
break;
}
if (i == second && set) {
secondSwap = new Node(temp.getLink().getData(), null);
firstSwap.setLink(temp.getLink().getLink());
temp.setLink(firstSwap);

//i = ;
temp = head;

if(first ==0)
{

secondSwap.setLink(temp.getLink());
head = secondSwap;
}

}
temp = temp.getLink();
if(i == second && set)
{
set = false;
i = 0;
temp = head;
}
}

}
public void sort()
{
Node temp = null;
int smallEle =0;
int firstIndex=0;
int secondIndex=0;

for(int i=1;i<size;i++)
{
firstIndex =i;
temp = head;
smallEle = temp.getData();
for(int k=1;k<i;k++)
{
temp = temp.getLink();
smallEle = temp.getData();
}
for(int j=i+1;j<=size;j++)
{
temp = temp.getLink();
if(temp == null)
break;
if(smallEle > temp.getData())
{
secondIndex = j;
smallEle = temp.getData();
}
}
swap(firstIndex, secondIndex);
}
}
 public void reverse()
    {
        Node prev = head;
       
        Node cur = head;
        Node future = head.getLink();
        prev.setLink(null);
        while (future != null)
        {
            cur = future;
            future = future.getLink();
            cur.setLink(prev);
            prev = cur;
        }
        head = prev;
    }
}


//Executing class
public class SinglyLinkedList
{
    public static void main(String args[])
    {
        LinkedList linkedList = new LinkedList();
        System.out.println(linkedList.isEmpty());
        linkedList.insertAtStart(1);
        linkedList.insertAtStart(2);
        linkedList.insertAtStart(3);
        linkedList.insertAtStart(4);
        linkedList.insertAtEnd(9);
        linkedList.insertAtPos(10, 3);
        linkedList.display();
        linkedList.deleteAtPos(2);
        linkedList.display();
        //linkedList.swap(1, 5);
linkedList.sort();
        linkedList.display();
        System.out.println("\n" + linkedList.getSize());
    }
}

Java 8: IntStream

//Java8 IntStream Feature
//PrimitiveIterator is just introduced in java8
import java.util.PrimitiveIterator.OfInt;
//IntSupplier is just introduced in java8 and it is a functional interface
import java.util.function.IntSupplier;
import java.util.stream.IntStream;

public class IntStreamExample
{
    public static void main(String args[])
    {
        System.out.println("-------of() Example------");
        // of just takes the arbitrary numbers of int
        IntStream ofEx = IntStream.of(1, 2, 3);
        ofEx.forEach(x -> System.out.println(x));// It prints 1 2 3
     
        System.out.println("-------range() Example------");
        // range just prints the number within the range includes the starting number and excludes the ending number
        IntStream stream = IntStream.range(1, 3); // It prints 1 2
        // OfInt as a more performance replacement for Iterator<Integer>
        OfInt intList = stream.iterator();
        while (intList.hasNext())
        {
            System.out.println(intList.nextInt());
        }
     
        System.out.println("-------rangeClosed() Example------");
        // rangeClosed just prints the number within the range includes both starting and ending number
        IntStream.rangeClosed(1, 3).forEach(System.out::println); // It prints 1 2 3
        // IntStream.
     
        System.out.println("-------iterator() Example------");
        // iterator just iterate elements based on condition(x->x+1) and limit(Just count)
        IntStream.iterate(1, x -> x + 1).limit(5).forEach(System.out::println);// It prints 1 2 3 4 5
     
        System.out.println("-------generator() Example------");
        // generator simply takes an IntSupplier that will independently calculate the next int.
        // IntSupplier represents a supplier of int-valued results
        IntSupplier fib = new IntSupplier()
        {
            private int previous = 0;
         
            private int current = 1;
         
            public int getAsInt()
            {
                int nextValue = this.previous + this.current;
                this.previous = this.current;
                this.current = nextValue;
                return this.previous;
            }
        };
        IntStream.generate(fib).limit(10).forEach(System.out::println); // It prints fibonacci series
     
    }
}