Friday, April 27, 2018

Last man standing puzzle solution in Java by Ajit

This code is implemented and provided by Ajit from GNIOT college, Greater Noida

The Problem statement:   
   n number of people are standing in a circle. The person whose position is first,
    has a sword.
  
    He kills the next person who is standing next to him (whose position is second)
    and passes the sword to the person whose position is third.
  
    This process continues in the circular way till only one person remains alive.
    What will be the position of that person who remains alive at last?


 
The  Algorithm:
    
        Step 1 : Get the total number of people in the circle.
   
        Step 2 : We need to store them in a collection(I have used ArrayList).
      
        Step 3 : We need a Infinite loop which terminates when only
                 one person remains in the collection.
      
        Step 4 : Now we need to remove persons in a alternative way
             
            a. first get the last person in the circle before using the removable operation
             
            b. use a loop to remove persons in alternative way
               ( use i + 1, where i is the flow controller variable of inner loop)
             
            c. after one circulation get the last man in the collection.
             
            d. check that if last man before removal and last man after removable
               are same then the first person must be removed
               ( make i = -1, because we use (i + 1) to remove) else make i = 0.
       
         Step 5 : Now our code is ready to solve that problem...
       
         ########################################################
       
         For example if input is 100 then output will be 73.
       
         it means if there are 100 persons in a circle then position of the last man is 73.

        ########################################################

Note : Please save this class inside LastManStanding .java file in Eclipse IDE
import java.util.ArrayList;
import java.util.Scanner;

public class LastManStanding
{

    public static int getLastMan(int person)
    {
      
        ArrayList<Integer> list = new ArrayList<Integer>();
  
        for (int i = 1; i <= person; i++)
        {
            list.add(i);
        }
      
        int i = 0;
      
        int lastPerson = 0;
      
        int lastPersonAfterOneCirculation = 0;
      
        while (true)
        {
            lastPerson = list.get(list.size() - 1);
          
            while ((i + 1) < list.size())
            {
                System.out.println("Person number "+list.remove(i + 1)+" got killed");
          
                i++;
            }
          
            lastPersonAfterOneCirculation = list.get(list.size() - 1);
          
            if (lastPersonAfterOneCirculation == lastPerson)
            {
                i = -1;
            }
            else
            {
                i = 0;
            }
          
            if (list.size() == 1)
            {
                break;
            }

            System.out.print("Current status of remaining person "+list + "\n");
        }
      
        return list.get(0);
    }

    public static void main(String[] args)
    {

        Scanner s = new Scanner(System.in);
  
        System.out.print("Enter the total no of person : ");
        int person = s.nextInt();
      
        int lastMan = LastManStanding.getLastMan(person);
      
        System.out.println("Last Man : " + lastMan);
 
   } // end of main
} // end of class

        ########################################################

Output :

Enter the total no of person : 6
Person number 2 got killed
Person number 4 got killed
Person number 6 got killed
Current status of remaining person [1, 3, 5]
Person number 3 got killed
Current status of remaining person [1, 5]
Person number 1 got killed
Last Man : 5

Thursday, April 26, 2018

Program to show the need of startsWith() method of String class.

Program to show the need of startsWith() method of String class.

import java.util.Scanner;

public class StringAssignment01
{
    public static void main(String[] args)
    {
        try
        {
            // take a paragraph and store names saprated by comma
            // there shoud be no space before or after the comma
            String paragraph = "naman,manoj,kamal,rakesh,aman,nimesh,maniram"
                    + ",arif,raju,kunti,rajesh";
          
            System.out.println("Names["+paragraph+"]\n");
          
            // split the paragraph, jahan jahan bhi comma aaye
            String[] names = paragraph.split(",");
          
            Scanner sc = new Scanner(System.in);
          
            // agar flag ki value false hogi toh hum loop ko terminate kar denge
            boolean flag = true;
          
            // start infinite loop
            while(flag)
            {
            System.out.print("Enter a name (type .. to exit the loop) ->");
            String text = sc.next();
          
            // fetch all the names from the the array
            for(int i = 0;i < names.length; i++)
            {
                // check if ith element of array starts with given text
                if(names[i].startsWith(text))
                {
                    // print that element of array
                    System.out.println(names[i]);
                }
              
            }
          
            // agar input  dot dot (..) hai toh flag me false daal dou
            // jis se hum loop ke bahar ja saken
            if(text.equals(".."))
            {
                flag = false;
            }
          
            } // end of main
        }  // end of class
        catch (Exception e)
        {
            e.printStackTrace();
        }
      
        System.out.println("# end of application #");
    }
}

Tuesday, April 24, 2018

Agar kisi class ne comparable interface ko implement nahin kiya hai toh bhi hum uske objects ko TreeSet mai store kar sakte hain, or ye kaam hum Comparator interface ki help se kar sakte hai.

Comparator interface, java.util package ke andar hai. Is interface ka ek method hai jiska naam compare() hai.

declaration of compare() method inside Comparator interface ->

public abstract int compare(Object newObject,Object oldObject), newObject ka matlab woh object jo TreeSet mai store hona chahta hai, oldObject matlab woh object jo TreeSet mai pehle se stored hai.

baki, agar is method ne zero return kiya toh duplicacy mani jati hai, negative ke case mai newObject ko oldObject ke left mai, and positive ke case mai newObject ko oldObject ke right mai store kiya jata hai

----------------------------------------------------------------------------------

now, how to store an object of class inside TreeSet if it is doen implement not Comparable interface

## ye woh clas hai jiske objects ko hame TreeSet mai store karna hai
public class Person
{
    ## private data members of Person
    private int age;
   
    ## parameterized constructor of Person
    public Person(int age)
    {
    this.age = age;
    }
   
    ## setters and getters of Person, to store and fetch the data
    public void setAge(int age)
    {
    this.age = age;   
    }
   
    public int getAge()
    {
    return age;
    }
   
}

## ab hum ek class define karte hain jo ki Comparator interface ko implement karegi 
Person ke objects ko sorting logic provide karne ke liye, kyunki Person comparable nahin hai, or hame TreeSet ko person ke objects ko sort karne ka login batana hi padega

import java.util.*;
public class ImpComparator implements Comparator<Person> // Person hi woh class hai
// jiske objects ko sort karna hai, hai na
{
// ab hum Comparator interface ke compare() method ko override karenge
        public int compare(Person newObject,Person oldObject)
        {
        // agar mujhe person ko unki age se sort karna hai tok
        // ek kaam karte hai
        // person ke getter method ko call karke person ki age fetch karte hai
        // or newPerson ki age mai se oldPerson ki age subtract kar denge
        // or wohi result return kar denge
        // like this ------>
        return newPerson.getAge() - oldPerson.getAge();    
        // ## bus, ho gaya kaam
        }
}

------------------------------------------------------------------------------
## ab ek test application bana lete hain
## isme hum person ke kuch object bana kar TreeSet mai daal denge
## or haan, TreeSet ko ye batane ke liye ki person ko sort karne ka logic kisne diya hai
hum ek kaam karenge
## ImpComparator class ka ek object bana kar, us object ka naam (ref-var) hum TreeSet ke constructor ke andar paas kar denge

toh chalo banate hain..........................

import java.util.*;
public class Test
{
    public static void main(String[] args)
    {
    // create some person
    Person p1 = new Person(35);
    Person p2 = new Person(25);
    Person p3 = new Person(15);
   
    // create object of class that implements Comparator interface
    ImpComparator imp = new ImpComparator();
   
    // link TreeSet with ImpComparator by passing the object 'imp' inside the constructor
    TreeSet<Person> set = new TreeSet<Person>(imp);

    // store person object inside TreeSet
    set.add(p1);   
    set.add(p2);   
    set.add(p3);   
   
    // fetch the objects using for-each-loop
    for(Person p : set)
    {
    // fetch data of person using getter and show it
    Ssytem.out.println(p.getAge());
    }
    }
}














Friday, April 20, 2018

Print a Diamond pattern in Java using a single loop

This code is implemented and provided by Ajit Srivastava from GNIOT College, Greater Noida.
------------------------------------------------------------------
 Algorithm for this code is given below: 

 1. Make a condition for the loop
         it'll be the total no. of characters to be printed(count spaces also)
         a. count the total numbers of characters in each line
         b. count total no of lines
         c. multiply both to find the condition for the loop
   
 2. Find the if() condition for the next line(when we need to take println() method)
       a. divide the flow controlling variable(of loop) with the total number of character in each line
       b. compare it with zero
       c. if the condition becomes true print a next line using println() method

 3. At this stage we have the conditions for the loop and for the next line. Now we need to print the characters of the pattern
      a. in these conditions if we need to use those variables which are also used in loop condition, create a copy of those variable
      b. by creating copies of variables we can manipulate them and there will be no effect on main condition of loop
    
 4. Now use 'if', 'else if'(if required) and 'else' for making our pattern.

------------------------------------------------------------------
Special Note : Please save this class inside DiamondInSingleLoop.java file in Eclipse IDE.
import java.util.Scanner;
public class DiamondInSingleLoop
{
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);

        System.out.print("Input terms to print a Diamond: ");
        // take a term from keyboard
        int term = s.nextInt();
      
        // create a copy of term
        int copyOfterm = term;
      
        // variable for printing spaces
        int spaceCounter = 1;
      
        // loop starts
        for (int i = 1; i <= (2 * term - 1) * (term + 1); i++)
        {
            // check condition for spaces
            if (spaceCounter <= copyOfterm)
            {
                System.out.print(" ");
                spaceCounter++;
            }
            else
            {
                System.out.print("* ");
            }
          
            // check condition for next line
            if (i % (term + 1) == 0)
            {
                System.out.println();
                spaceCounter = 1;

                // check condition to get upper part of the diamond
                if(i < term *(term + 1))
                {  
                    copyOfterm--;
                }
                else
                {
                    copyOfterm++;
                }
            }
        }         // end of the loop  
      
        }         // end of main method  
  
} // end of class

------------------------------------------------------------------
Output of this code : Input terms to print a Diamond: 10
          *
         * *
        * * *
       * * * *
      * * * * *
     * * * * * *
    * * * * * * *
   * * * * * * * *
  * * * * * * * * *
 * * * * * * * * * *
  * * * * * * * * *
   * * * * * * * *
    * * * * * * *
     * * * * * *
      * * * * *
       * * * *
        * * *
         * *
          *
 

Friday, April 13, 2018

Mind blowing Permutations and Combinations in Java

This marvelous code is implemented and provided by "Riya Tyagi" from Galgotias College, Greater Noida. 


Note : Save this code inside Combinations.java file inside Eclipse IDE

import java.util.Scanner;

public class Combinations 
{
// method to find factorial of number
static int factorial(int num) 
{
if (num == 0)
return 1;
return num * factorial(num - 1);
}

// recursive method to find all permutations of given string
static String[] permutations(String x) 
{
String[] a;

// base case to stop the recursion
if (x.length() >= 1) 
               {
a = new String[factorial(x.length())];

int k = 0;

for (int i = 0; i < x.length(); i++) 
{
String[] b;

if (i > 0) 
{
                                       String t = x.substring(0, i).
                                                       concat(x.substring(i + 1, x.length()));

                                b = permutations(t); // call this method recursively 



else 
{
String t = x.substring(1, x.length());
b = permutations(t);
}

for (int j = 0; j < b.length; j++) 
{
a[k] = String.valueOf(x.charAt(i)).concat(b[j]);
k++;
}

}  // end of for loop

}  // end of if

else 
{
a = new String[1];
a[0] = "";
}

return a;
}

public static void main(String[] args) 
{

Scanner sc = new Scanner(System.in);

  System.out.println("Input a string for its combinations: ");
String x = sc.next();

System.out.println("# output #");

String[] a = Combinations.permutations(x);

for (int i = 0; i < a.length; i++) 
{
System.out.println((i + 1) + " : " + a[i]);
}

} // end of main method

} // end of class