Tuesday, 8 November 2016

Hackerrank , Project Euler #5: Smallest multiple

Project Euler #5: Smallest multiple


from fractions import gcd
def lcm(numbers):
    return reduce(lambda x, y: (x*y)/gcd(x,y), numbers)
t=input()
for i in range(0,t):
    print lcm(range(1,input()+1))

Hackerrank , Project Euler #4: Largest palindrome product

Project Euler #4: Largest palindrome product


# Enter your code here. Read input from STDIN. Print output to STDOUT
t=input()
for i in range(0,t):
    no=input()
    for k in range(no-1,101100,-1):
        if str(k)==str(k)[::-1]:
            lst = [k for e in range(100,999) if k%e==0 and len(str(k/e))==3]
            if lst :
                print max(lst)
                break

Hckerrank , Project Euler #3: Largest prime factor

Project Euler #3: Largest prime factor


# Enter your code here. Read input from STDIN. Print output to STDOUT
t=input()
def largest_prime_factor(n):
    i = 2
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
    return n

for j in range(0,t):
    n=input()
    print largest_prime_factor(n)

Friday, 28 October 2016

Check for pair in A[] with sum as x

Given an array A[] and a number x, check for pair in A[] with sum as x 


##include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
@author Anurag
*/
int main() {
  // create a vector to store int
  int myints[] = {32,71,12,45,26,80,53,38};
  vector < int > vec(myints, myints + 8);
  sort(vec.begin(), vec.begin() + 8);
  vector < int > ::iterator f = vec.begin();
  vector < int > ::iterator l = vec.begin() + 7;
  int x = 50;
  while (f != vec.end()) {
    if (( * f) + ( * l) > x) {
      l--;
    } else if (( * f) + ( * l) < x) {
      f++;
    } else {
      cout << * f << "," << * l;
      break;
    }
  }
  return 0;
}}

Sunday, 17 July 2016

Factorial of a No. using Dynamic Programming

 Following program show how to find out the factorial of a No. using Dynamic Programming.

Factorial of No.   :
 
class Factorial
{
  public static void main(String[] args) {
    int n=8;
    long arr[] = new long[n+1];
    for(int i=0 ;i<n+1;i++)
      arr[i]=0L;
    System.out.println("Factorial is :: "+fact(n,arr));
  }
  static long fact(int n, long arr[])
  {
    if (n==0 || n==1)
      return 1;
    else if(arr[n]!=0)
      return arr[n];
    else
      {
        arr[n]=fact(n-1, arr)*n;
        return arr[n];
      }
  }
}

Friday, 15 July 2016

Counting Sort

Following code show counting sort implementation in Java .

Counting Sort :   

class CountingSort
{
  public static void main(String[] args) {
    char arr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'};
    sort(arr);
    System.out.print("Sorted character array is ");
        for (int i=0; i<arr.length; ++i)
            System.out.print(arr[i]);
  }
  static void sort(char arr[])
  {
    int n = arr.length;
    int count[] = new int[256];
    for (int i=0; i<256; ++i)
        count[i] = 0;
    for (int i=0; i<n; ++i)
        ++count[arr[i]];
    for (int i = 0,j=0; i<n;j++)
      {  while(count[j]>0)
         {
           arr[i] = (char)j;
           --count[j];
           i++;
         }
      }
  }

}
 

Thursday, 14 July 2016

Hackerrank , Project Euler #1: Multiples of 3 and 5

Here you can find solutions for  the famous Euler Project's Problems . Questions can find on following link https://www.hackerrank.com/contests/projecteuler/challenges.

 Project Euler #1: Multiples of 3 and 5     :

# Enter your code here. Read input from STDIN. Print output to STDOUT
t= input()
for i in range(0,t):
    no=input()
    n=(no-1)/3
    sum_3=(n*(2*3+3*(n-1))/2)
    n=(no-1)/5
    sum_5=(n*(2*5+5*(n-1))/2)
    n=(no-1)/15
    sum_15=(n*(2*15+15*(n-1))/2)
    print sum_3+sum_5-sum_15

Wednesday, 13 July 2016

Selection Sort

Selection sort is a simple sorting algorithm.Smallest element is selected from the unsorted array and swapped with the leftmost element and that element becomes part of sorted array. This process continues moving unsorted array boundary by one element to the right.

 This algorithm is not suitable for large data sets as its average and worst case complexity are of O(n2) where n are no. of items.

Following  program shows selection sort algorithm in JAVA.

Selection Sort : 
public class SelectionSort {

    public static void main(String args[]) {
        int array[] = { 5, 2, 7, 4, 9, 0 };
        array = selectionSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
        }
    }

    private static int[] selectionSort(int array[]) {
        for (int i = 0; i < array.length; i++) {
            for (int j = i; j < array.length; j++) {
                if (array[i] > array[j]) {
                    int temp;
                    temp = array[j];
                    array[j] = array[i];
                    array[i] = temp;

                }
            }
        }
        return array;
    }

}

Tuesday, 12 July 2016

BubbleSort

This Java bubble sort example shows how to sort an array of int using bubble sort algorithm. Bubble sort is the simplest sorting algorithm.

BubbleSort  :

package sorting;

public class BubbleSort {

    public static void main(String args[]) {
        int array[] = { 5, 2, 7, 4, 9, 0 };
        array = bubbleSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
        }
    }

    private static int[] bubbleSort(int array[]) {
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    int temp;
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;

                }
            }
        }
        return array;
    }

}
 

QuickSort

Following program show Quicksort Algorithm in Java.

QuickSort:

public class QuickSort {
    public static void main(String args[]) {
        int array[]={9,2,5,1,7,1,2,9,5,4};
        quickSort(array,0,array.length-1);
        for(int e : array)
        {
            System.out.println(""+e);
        }
    }

    static void quickSort(int [] arr , int left ,int right)
    {
        if(left<right)
        {
        int p = partition(arr,left,right);
        quickSort(arr,left,p-1);
        quickSort(arr,p+1,right);
        }
    }

static int partition(int [] arr,int l, int h)
{
    int pivot=arr[h];
    int i=l-1;
    for(int j=l;j<h;j++)
    {
        if(arr[j]<=pivot)
        {
            swap(arr,i+1,j);
            i++;
        }
    }
swap(arr,i+1,h);
return i+1;
}
static void swap(int arr[] ,int i , int j)
{
    int temp= arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
}

}

Monday, 11 July 2016

Tower of Hanoi

Following Java program shows  demo of famous "Tower of Hanoi" Problem.

Tower of Hanoi     :

import java.util.*;
class TowerOfHonaoi
{

  public static void main(String[] args) {
    System.out.println("Enter No. of discs");
    Scanner sc = new Scanner(System.in);
    int no = sc.nextInt();
    move(no,"A","B","C");
  }

  public static void move(int n , String src, String inter, String dest)
  {
    if(n==1)
    {
        System.out.println(src+" -> "+dest);
    }else{
      move(n-1,src,dest,inter);
      System.out.println(src+" -> "+dest);
      move(n-1,inter,src,dest);
    }
  }

}

Wednesday, 6 July 2016

Hackerrank , 30 Days of Code Challenges ( Day 28 & 29 Solution)

Day 28: RegEx, Patterns, and Intro to Databases  :

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        for(int a0 = 0; a0 < N; a0++){
            String firstName = in.next();
            String emailID = in.next();
        }
    }
}

Day 29: Bitwise AND  :

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

        int T = sc.nextInt();
        for (int tc = 0; tc < T; tc++) {
            int N = sc.nextInt();
            int K = sc.nextInt();

            System.out.println(solve(N, K));
        }

        sc.close();
    }

    static int solve(int N, int K) {
        int result = 0;
        for (int A = 1; A <= N; A++) {
            for (int B = A + 1; B <= N; B++) {
                int current = A & B;
                if (current > result && current < K) {
                    result = current;
                }
            }
        }
        return result;
    }
}

Hackerrank , 30 Days of Code Challenges ( Day 26th & 27th Solution)

 Day 26: Nested Logic :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int actualDay = sc.nextInt();
        int actualMonth = sc.nextInt();
        int actualYear = sc.nextInt();
        int expectedDay = sc.nextInt();
        int expectedMonth = sc.nextInt();
        int expectedYear = sc.nextInt();

        int fine;
        if (actualYear > expectedYear) {
            fine = 10000;
        } else if (actualMonth > expectedMonth && (actualYear >= expectedYear)) {
            fine = 500 * (actualMonth - expectedMonth);
        } else if (actualDay > expectedDay && (actualMonth >= expectedMonth) && (actualYear >= expectedYear)) {
            fine = 15 * (actualDay - expectedDay);
        } else {
            fine = 0;
        }
        System.out.println(fine);

        sc.close();
    }
}

Day 27: Testing :

print "5"
print "4 3"
print "-1 0 4 2"
print "5 3"
print "0 1 -2 -6 9"
print "6 4"
print "1 0 -3 4 5 7"
print "7 5"
print "0 -3 -2 -1 6 -8 9"
print "8 6"
print "2 -4 5 1 3 7 6 0"

Hackerrank , 30 Days of Code Challenges ( Day 24 & 25 Solutions)

Day 24: More Linked Lists   :

public static Node removeDuplicates(Node head) {
     //Write your code here
       Node currentNode = head;
       while(currentNode!=null && currentNode.next!=null)
           {
           Node node = currentNode;
           while(node.next!=null)
               {
               if(node.next.data==currentNode.data)
                   {
                   Node next = node.next.next;
                   Node temp= node.next;
                   node.next=next;
                   temp=null;

               }
               else{
               node=node.next;
               }
           }
           currentNode=currentNode.next;
       }
       return head;
   }

Day 25: Running Time and Complexity  :

# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
t=input()
def isPrime(data):
    if data < 2:
        return False
    v=int(math.sqrt(data))
    for i in range(2,v+1):
        if data%i==0:
            return False;
    return True;
for i in range(t):
    if isPrime(input()):
        print "Prime"
    else:
        print "Not prime"

   

Hackerrank , 30 Days of Code Challenges ( Day 21 - 23 Solutions)

Day 21: Generics  :
//Write your code here

static <E>  void printArray( E[] inputArray)
{
for( E e : inputArray)
    {
    System.out.println(""+e);
}

}

Day 22: Binary Search Trees  :

public static int getHeight(Node root){
    //Write your code here
      if(root ==null)
          return -1;
      int left=getHeight(root.left);
      int right=getHeight(root.right);
      return Math.max(left, right) + 1;
  }

Day 23: BST Level-Order Traversal   :

    static void levelOrder(Node root){
      //Write your code here
        Queue<Node> queue = new LinkedList<Node>();
        queue.add(root);
        while(queue.peek()!=null)
            {
            Node node =queue.remove();
            System.out.print(""+node.data+" ");
            if(node.left!=null)
                queue.add(node.left);
            if(node.right!=null)
                queue.add(node.right);
        }
    }

Thursday, 30 June 2016

Convert InFix Expression to PostFix Expression using stacks

InFix Expression to PostFix Expression using stacks   :

import java.util.Scanner;
import java.util.Stack;

public class InfixToPostFix {
    public static void main(String args[]) {
        Stack<Character> stack = new Stack<Character>();
        Scanner sc = new Scanner(System.in);
        // Read InFix String
        char inFixArray[] = sc.next().toCharArray();
        String postFixString = "";
        for (char e : inFixArray) {
            // check for operand
            if (e >= 'A' && e <= 'Z') {
                postFixString = postFixString + e;
            } else if (e >= 'a' && e <= 'z') {
                postFixString = postFixString + e;
            } else if (e == '(') {
                stack.push(e);
            } else if (e == ')') {
                while (!stack.isEmpty() && stack.peek() != '(') {
                    postFixString = postFixString + stack.pop();
                }
                stack.pop();
            } else {
                // check for operator
                while (!stack.isEmpty() && Prec(stack.peek()) >= Prec(e)) {
                    postFixString = postFixString + stack.pop();
                }
                stack.push(e);

            }
        }
        while (stack.isEmpty()) {
            postFixString = postFixString + stack.pop();
        }
        System.out.println(postFixString);

    }

    static int Prec(char e) {
        switch (e) {
        case '+':
        case '-':
            return 1;
        case '*':
        case '/':
            return 2;

        case '^':
            return 3;

        }
        return -1;
    }
}

Wednesday, 29 June 2016

Evaluate PostFix Expression using stack

Evaluate PostFix Expression using stack   :

import java.util.Scanner;
import java.util.Stack;

public class EvalPostFix {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        Stack<Integer> stack = new Stack<Integer>();
        char exp[] = sc.next().toCharArray();
        for (char e : exp) {
            if (Character.isDigit(e)) {
                stack.push(Character.getNumericValue(e));
            } else {
                int var1 = stack.pop();
                int var2 = stack.pop();
                switch (e) {
                case '+':
                    stack.push((var1 + var2));
                    break;
                case '-':
                    stack.push((var1 - var2));
                    break;
                case '*':
                    stack.push((var1 * var2));
                    break;
                case '/':
                    stack.push((var1 / var2));
                    break;
                }

            }
        }
        System.out.println("" + stack.peek());

    }

}
 

Reverse String using Stack Data Structure

 Reverse a String using Stack Data Structure in Java  :


import java.util.Stack;

public class ReverseString {
    public static void main(String args[]) {
        Stack<Character> stack = new Stack<Character>();
        String result="My name is Anurag Goel.";
        char exp[] = obj.next().toCharArray();
        for (char e : exp) {
            stack.push(e);
        }
        while (!stack.isEmpty()) {
            result=result+stack.pop().toString();
        }
        System.out.println(result);
    }

}

Stack Implementation using LinkedList

Stack Implementation using LinkedList in Java     :

import java.util.*;

public class DynamicStack {
 static class Node {
  int data;
  Node next;
  Node(int e) {
   this.data = e;
   this.next = null;
  }
 }
 LinkedList < Node > list;
 DynamicStack() {
  this.list = new LinkedList < Node > ();
 }
 public void push(int data) {
  list.add(new Node(data));
 }
 public int pop() {
  if (list.size() < 1)
   return -1;
  return list.remove().data;
 }
 public int Top() {
  return list.getLast().data;
 }
 public boolean isEmpty() {
  return list.size() < 1 ? true : false;
 }
 public static void main(String[] args) {
  DynamicStack stack = new DynamicStack();
  stack.push(1);
  stack.push(2);
  stack.push(3);
  stack.push(4);
  stack.push(5);
  while (!stack.isEmpty()) {
   System.out.println(stack.pop());
  }

 }
}

Stack Implementation

Stack Implementation in Java :
Following example shows how to implement stack in Java .

/**
 *
 * @author Anurag
 *
 *
 */
public class ArrayStack{

    private int array[];
    private int top;
    private int capacity;

ArrayStack(int capacity)
{
    this.capacity=capacity;
    this.array=new int[capacity];
    top=-1;
}
public boolean isEmpty()
{
    return top==-1?true:false;
}
public boolean isFull()
{
    return top==capacity-1?true:false;
}
public int Top()
{
    if (top==-1)
    {
        System.out.println("Stack is Empty");
    return -1;
}
    return array[top];
}

public void push(int e)
{
    if (top==capacity-1)
    {
        System.out.println("Stack is Full !");
        return;
    }
    array[++top]=e;
    return;
}

public int pop()
{
    if (top==-1)
    {
        System.out.println("Stack is Empty !");
        return -1;
    }
    return array[top--];
}
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        stack.push(1);stack.push(2);stack.push(3);stack.push(4);stack.push(5);stack.push(6);
        System.out.println("Stack is Full :: "+stack.isFull());
        while(!stack.isEmpty())
        {
            System.out.println(""+stack.pop());
        }
        System.out.println("Stack is Empty :: "+stack.isEmpty());

    }
}

Hackerrank , 30 Days of Code Challenges ( Day 19 Solution)


 Day 19: Interfaces   :


//Write your code here
class Calculator implements AdvancedArithmetic
    {

    public int divisorSum(int n)
        {
        int sum=0;
        for(int i=1 ; i<=n;i++)
            {
            if(n%i==0)
                sum+=i;
        }
        return sum;
    }
}

Hackerrank , 30 Days of Code Challenges ( Day 20 Solution)

Day 20: Sorting   :

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int a[] = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }


         int numberOfSwaps=0;
        for (int i = 0; i < n; i++) {

            for (int j = 0; j < n - 1; j++) {
                 if (a[j] > a[j + 1]) {
                   int temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                    numberOfSwaps++;
                }
            }
            if (numberOfSwaps == 0) {
                break;
            }
        }

        System.out.println("Array is sorted in "+numberOfSwaps+" swaps.");
        System.out.println("First Element: "+a[0]);
        System.out.println("Last Element: "+a[a.length-1]);
    }


}

Tuesday, 28 June 2016

Hackerrank , 30 Days of Code Challenges ( Day 18 Solution)

 Day 18: Queues and Stacks   :

public class Solution {
    // Write your code here.
    Stack<Character> stack = new Stack<Character>();
    Queue<Character> queue = new LinkedList<Character>();
    void pushCharacter(char ch)
        {
        stack.push(ch);
    }
     void enqueueCharacter(char ch){
        queue.add(ch);
     }
    char popCharacter() {
        return stack.pop();
    }

    char dequeueCharacter()
        {
        return queue.remove();
    }

Hackerrank , 30 Days of Code Challenges ( Day 16 & Day 17 Solutions)

Day 16: Exceptions - String to Integer    :
 import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        try{
        String S = in.next();
            System.out.println(""+Integer.parseInt(S));
    }catch(Exception e)
            {
            System.out.println("Bad String");
        }
    }
}

Day 17: More Exceptions   :
class Calculator :
    def power(self, a, b):
        if a>= 0 and b>=0:
            return a**b
        else:
            return "n and p should be non-negative"
 

Hackerrank , 30 Days of Code Challenges ( Day 13 - 15 Solutions)

Day 13: Abstract Classes   :
 
//Write MyBook Class
class MyBook extends Book
    {
    int price;
    MyBook(String t , String a , int p)
        {
        super(t,a);
        this.price =p;
    }
    void display()
        {
        System.out.println("Title: "+title);
        System.out.println("Author: "+author);
        System.out.println("Price: "+price);
    }
}

Day 14: Scope   :

    # Add your code here
    def computeDifference(self):
        self.maximumDifference =  max(a)-min(a)


Day 15: Linked List   :
 class MyBook extends Book
    {
    int price;
    MyBook(String t , String a , int p)
        {
        super(t,a);
        this.price =p;
    }
    void display()
        {
        System.out.println("Title: "+title);
        System.out.println("Author: "+author);
        System.out.println("Price: "+price);
    }
}

Hackerrank , 30 Days of Code Challenges ( Day 12 Solution)

 Day 12: Inheritance    :

class Student extends Person{
    private int[] testScores;
    Student(String firstName, String lastName, int identification , int [] scores)
        {
        super(firstName,lastName,identification );
        this.testScores=scores;
    }

    public String calculate()
        {
        int sum =0;
        for(int i : this.testScores)
            {
            sum+=i;
        }
        double avg= sum/testScores.length;
        if (avg<=100 && avg>=90)
            {
            return "O";
        }else if(avg<90 && avg>=80)
            {
             return "E";
        }
        else if(avg<80 && avg>=70)
            {
             return "A";
        }
        else if(avg<70 && avg>=55)
            {
             return "P";
        }
         else if(avg<55 && avg>=40)
            {
             return "D";
        }
        else{
             return "T";
        }
    }

}

Hackerrank , 30 Days of Code Challenges ( Day 10 & Day 11 Solutions)

Day 10: Binary Numbers    :

import sys
n = int(raw_input().strip())
string = '{0:b}'.format(n)
array=string.split('0')
array.sort()
print len(array[len(array)-1])

Day 11: 2D-Arrays    :
arr = []
max=-999
for arr_i in xrange(6):
   arr_temp = map(int,raw_input().strip().split(' '))
   arr.append(arr_temp)

for i in xrange(4):
    for j in xrange(4):
        temp=arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]
    if temp > max:
        max=temp

print max

Friday, 24 June 2016

Hackerrank , 30 Days of Code Challenges ( Day 6-9 Solutions)

Day 6: Let's Review  :
# Enter your code here. Read input from STDIN. Print output to STDOUT
t=input()
for i in range(0,t):
    string =raw_input()
    print ''.join([string[i] for i in range(0,len(string),2)])+" "+''.join([string[i] for i in range(1,len(string),2)])

Day 7: Arrays   :
#!/bin/python
import sys
n = int(raw_input().strip())
arr = map(int,raw_input().strip().split(' '))
arr.reverse()
print " ".join(str(i) for i in arr)

Day 8: Dictionaries and Maps     :
# Enter your code here. Read input from STDIN. Print output to STDOUT
t=input()
data=dict()
index=[]
for i in range(0,t):
    array=raw_input().split(" ")
    data[array[0]]=array[1]
for k in range(0,t):
    inp= raw_input()
    if data.has_key(inp):
        print inp+"="+data[inp]
    else:
        print "Not found"

Day 9: Recursion    :
n= input()
def factorial(n):
    if n ==0 or n==1 :
        return 1
    else:
        return n*factorial(n-1)
print factorial(n)





Saturday, 18 June 2016

Hackerrank , 30 Days of Code Challenges ( Day 0-5 Solutions)

Hackerrank , 30 Days of Code Challenges  =>

Day 0: Hello, World (Python) :

inputString = raw_input() # get a line of input from stdin and save it to our variable

# Your first line of output goes here
print 'Hello, World.'

# Write the second line of output
print inputString

Day 1: Data Types (C#) :

// Declare second integer, double, and String variables.
        int i2;
        double d2;
        string s2;
       
        // Read and save an integer, double, and String to your variables.
        i2=int.Parse(Console.ReadLine());
        d2= double.Parse(Console.ReadLine());
        s2 = Console.ReadLine();
       
        // Print the sum of both integer variables on a new line.
        Console.WriteLine("{0:#.#}",i2+i);
       
        // Print the sum of the double variables on a new line.
        Console.WriteLine("{0:0.0}",d+d2);
        // Concatenate and print the String variables on a new line
        // The 's' variable above should be printed first.
        Console.WriteLine(s+s2);

Day 2: Operators (Python) :

a=raw_input()
b=raw_input()
c=raw_input()
print "The total meal cost is "+str(int(round(float(a)+(float(b)*float(a)/100)+(float(c)*float(a)/100))))+" dollars."


Day 3: Intro to Conditional Statements (Python) :

 #!/bin/python

import sys


N = int(raw_input().strip())

if N%2!=0:
    print "Weird"
elif N>=2 and N<=5 :
    print "Not Weird"
elif N>=6 and N<=20 :
    print "Weird"
else:
    print "Not Weird"
    

Day 4: Class vs. Instance (Java) :

public class Person {
    private int age;   
 
    public Person(int initialAge) {
          // Add some more code to run some checks on initialAge
        this.age=initialAge;
    }

    public void amIOld() {
          // Write code determining if this person's age is old and print the correct statement:
        if(this.age<0)
          { System.out.println("Age is not valid, setting age to 0.");
           this.age=0;
           amIOld();
          }
        else if(this.age<13)
            System.out.println("You are young.");
        else if(this.age<18)
            System.out.println("You are a teenager.");
        else if(this.age>=18)
            System.out.println("You are old.");
    }

    public void yearPasses() {
          // Increment this person's age.
        this.age+=1;
    }

Day 5: Loops (Python) :

#!/bin/python

import sys


N = int(raw_input().strip())
for i in xrange(1,11):
    print str(N)+" x "+str(i)+" = "+str(N*i)

Friday, 17 June 2016

Merge two sorted Linked List

 Merge 2 Sorted LinkedList :

class MergeLinkedList
{
  static class Node
  {
    int data;
    Node next;
  }
  public static void main(String[] args) {
    Node head1 = new Node();
    Node head2=  new Node();
    Node head3=  new Node();
    head3=null;
    head1.data=0;
    head2.data=1;
    head1=insert(insert(insert(insert(insert(insert(head1,2),5),7),8),9),11);
    head2=insert(insert(insert(insert(insert(head2,2),6),8),11),13);
    while(true)
    {
      if(head1==null && head2==null)
      {
        break;
      }
      else if(head1==null)
      {
        head3=insert(head3,head2.data);
        head2=head2.next;
      }
      else if(head2==null)
      {
        head3=insert(head3,head1.data);
        head1=head1.next;
      }
      else if(head1.data<=head2.data)
      {
        head3=insert(head3,head1.data);
          head1=head1.next;
      }
      else{
        head3=insert(head3,head2.data);
          head2=head2.next;
      }
    }
    printList(head3);
  }

  public static Node insert(Node head, int data) {
   Node node = new Node();
   node.data = data;
   node.next = null;
      if(head==null)
      return node;
 Node currentNode= head;
 while(currentNode.next!=null)
 {
     currentNode=currentNode.next;
     }

   currentNode.next=node;
   return head;
  }

 /**
  * Print All Elements of Linked List
  *
  * @param      node  The node
  */
  public static void printList(Node node) {
   Node currentNode = node;
   while (currentNode != null) {
    System.out.println(currentNode.data);
    currentNode = currentNode.next;
   }

}
}

Thursday, 16 June 2016

Delete Nth Node From Linked List

Delete Nth Node  From Linked List : 

class DeleteNthNode
{
  static class Node {
   int data;
   Node next;
  }
  /**
  @main Method
  **/
  public static void main(String[] args) {
  Node head = insert(insert(insert(insert(null, 1), 2), 3),4);
  head= delete(head,0);
  head= delete(head,2);
  printList(head);

  }
  /**
   * Delete Node At Nth Position of Linked List
   *
   * @param      head  The head
   *
   * @param      Nth Position
   * @return     return head of Linked List
   */
  public static Node delete(Node head,int pos) {
   if (head == null) {
    return head;
   }
   if(pos==0)
   {
     Node next = head.next;
     return next;
   }
   else{
     Node currentNode=head;
     while((pos-1)>0)
     {
       currentNode=currentNode.next;
       pos--;
     }
    Node next = currentNode.next.next;
    currentNode.next=next;
    return head;
   }

  }

  /**
   * Insert Node at End
   *
   * @param      head  The head node
   * @param      data  The data
   *
   * @return     { description_of_the_return_value }
   */
   public static Node insert(Node head, int data) {
    Node node = new Node();
    node.data = data;
    node.next = null;
       if(head==null)
       return node;
  Node currentNode= head;
  while(currentNode.next!=null)
  {
      currentNode=currentNode.next;
      }

    currentNode.next=node;
    return head;
   }
 /**
  * Print All Elements of Linked List
  *
  * @param      Head of Linked List
  */
  public static void printList(Node node) {
   Node currentNode = node;
   while (currentNode != null) {
    System.out.println(currentNode.data);
    currentNode = currentNode.next;
   }


  }
}

Detect and Remove Loop in a Linked List

Detect & Remove Loop  From Linked List :
class DetectAndRemoveLoop
{
  static class Node {
   int data;
   Node next;
  }

  public static void main(String[] args) {
    Node node1 = new Node();
     node1.data = 1;
     Node node2 = new Node();
     node2.data = 2;
     Node node3 = new Node();
     node3.data = 3;
     Node node4 = new Node();
      node4.data = 4;
      Node node5 = new Node();
      node5.data = 5;
      Node node6 = new Node();
      node6.data = 6;
      Node node7 = new Node();
      node7.data = 7;
     node1.next = node2;
     node2.next = node3;
     node3.next = node4;
     node4.next=node5;
     node5.next=node6;
     node6.next=node7;
     node7.next=node3;
    if (detectAndRemove(node1) == true)
    {  printList(node1);  }
    else
    {System.out.println("No Loop Found"); }
  }
public  static boolean detectAndRemove(Node head)
  {
    Node slow=head;
    Node fast=head.next;
    while(fast!=null && fast.next!=null)
    {
      if(slow==fast)
      {
        break;
      }
    slow=slow.next;
    fast=fast.next.next;
  }
    if(slow==fast)
    {  slow=head;
        while(fast.next!=slow)
        {
          slow=slow.next;
          fast=fast.next;
        }
        fast.next=null;
        System.out.println("Loop Removed");
        return true;
    }

    return false;
  }

  public static void printList(Node node) {
   Node currentNode = node;
   while (currentNode != null) {
    System.out.println(currentNode.data);
    currentNode = currentNode.next;
   }
}
}