Monday, 9 January 2017

Write a Perl script that prints the numbers from 1 to 100, but for multiples of three print “Fast” instead of the number and for the multiples of seven print “Car”. For the numbers which are multiples of both three and seven print “FastCar”.

use warnings;
use strict;
my  $l=1;
for($l=1;$l<=100;$l++)
{
if( $l % 3 == 0 && $l % 7 == 0 ) {
                print "FastCar";
                print"\n";
               
              }
             elsif( $l % 3 == 0 && $l % 7 != 0 ) {
                    print "Fast";
                    print "\n";
                   
             }
             elsif( $l % 3 != 0 && $l % 7 == 0 ) {
                    print "Car";
                    print"\n";
                   
             }
             else {
                print $l;
                print "\n";
               
             }
}

Write a program in C++ that accepts a list of values as command line arguments and prints the sum of all the values. Make sure that the logic of the program contains a recursive method recurseAdd that accepts these list of values as the input to it and returns the sum of all the values.

#include <iostream>
#include <cstdlib>
using namespace std;

int recurseAdd(int *,int);
int main(int argc, char **argv)
{
   if (argc < 2) // the program's name is the first argument
   {
      std::cerr << "Not enough arguments!\n";
      return -1;
   }
 
   int *inArray = new int[argc-1];

   for(int i=0;i<argc-1;i++)
    inArray[i]=std::atoi(argv[i+1]);
   
   
   
    int result=recurseAdd(inArray,argc-1);
    cout<<result;  
   

   return 0;
}
int recurseAdd(int *arr, int size)
{
if(size==0)
return 0;
else
{
return (*(arr +0) + recurseAdd((arr+1),size-1));
}
}

Activity - Alumni Form You are helping your college build an alumni website. Build a HTML form that has the following fields: Name Email Gender - Male or Female - should show up as a radio control City - make it show a list of available options (atleast add 5 options to choose from) Company - current company where you are working

<html>
<head>
<title>XYZ Institute Of Engineering</title>
<h1 align="center">XYZ Institute Of Engineering</h1>
<hr/>
</head>
<body>
<table border="1" align="center">
<tr>
<td>Name</td>
<td><input type="text"/></td>
</tr>
<tr>
<td>Email</td>
<td><input type="email"/></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="g"/>Male &nbsp; <input type="radio" name="g"/>Female</td>
</tr>
<tr>
<td>City</td>
<td>
<select>
                <option value="-">--select--</option>
                <option value="Kolkata">Kolkata</option>
                <option value="Delhi">Delhi</option>
                <option value="Mumbai">Mumbai</option>
                <option value="Chennai">Chennai</option>
                <option value="Bangalore">Bangalore</option>
            </select>
</td>
</tr>
<tr>
<td>Company</td>
<td><input type="text"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"/></td>
</tr>

</table>
</body>
</html>

XML Processing in Java using JAXP

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
 * Efficient event based XML parsing using a SAX parser
 */
 class SaxRetrieval {
  /**
   * Parse specified file using Sax Parser.
   * @param fileName
   */
  public static void parseFile(String fileName) {
    try {
      // Instantiate Sax Parser.
      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser saxParser = factory.newSAXParser();
      // Setup handler for Sax Parser.
      DefaultHandler handler = new DefaultHandler() {
boolean employee = false;
        boolean name = false;
        boolean salary = false;
        // Invoked when the Sax Parser hits a start tag.
        public void startElement(String uri, String localName,String qName,
                     Attributes attributes) throws SAXException {
            if (qName.equalsIgnoreCase("EMPLOYEE") ) {
            employee = true;
          }        
          if (qName.equalsIgnoreCase("NAME") ) {
            name = true;
          }
          if (qName.equalsIgnoreCase("SALARY")) {
            salary = true;
          }

        }
       
       
        // Invoked for each text node in a tag.
        public void characters(char ch[], int start, int length) throws SAXException {
       
   if (name && employee) {
System.out.println("Name : " + new String(ch, start, length));
}
         
if (salary) {
System.out.println("Salary : " + new String(ch, start, length));
salary = false;
}
        }

        public void endElement(String uri, String localName,String qName) throws SAXException {
                      if(qName.equalsIgnoreCase("employee")){
                      employee = false;
                      }
if(qName.equalsIgnoreCase("name") ) {
name = false;
}



}
     
      };
     
      saxParser.parse(fileName, handler);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static void main(String argv[]) {
    SaxRetrieval.parseFile("activity.xml");


 }
}

Reflections in Java

public class Reflection  {
public static void runReflection(String packageName, String className) {
       try {
Class<?> c = Class.forName(className);
Point p=(Point)c.newInstance();
p.dynamicExecute();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {

e.printStackTrace();
} catch (IllegalAccessException e) {

e.printStackTrace();
}
   }
public static void main(String args[]){
Reflection r =new Reflection();
r.runReflection("Reflection", "Point");

}

}

Generics in Java

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class GenericsCollectionPrinter {
    public static void printCollection(Collection collection){
        Class c=collection.getClass();
        System.out.print("Collection "+c.getSimpleName()+": [ ");
        Iterator itr = collection.iterator();
        while(itr.hasNext()){
            Object o = itr.next();
            System.out.print(o+" ");
        }
        System.out.print("]");
        System.out.println();
}

    public static void main(String args[]){
List<Integer> x=new ArrayList<Integer>();
x.add(5);
x.add(8);
x.add(7);
List<String> y=new LinkedList<String>();
y.add("five");
y.add("eight");
GenericsCollectionPrinter.printCollection(x);
GenericsCollectionPrinter.printCollection(y);
}
}

Build a map function that takes a list as input and a function as input and returns a list of items where the function is applied to each item in the input list

function square(number) {
  return number * number;
}

function map(list[], function) {
result = [];
    foreach(number in list) {
        result.push(function(number));
    }
    return result;
}

map([1,2,3,4], square)

Write a calculator interface ICalculator having methods to add, subtract, divide and multiply 2 floats and an implementation of that interface Calculator. Ensure that the methods throws ArithmeticException's wherever the computation cannot be performed eg: when the denominator is zero.

import java.util.*;
import java.lang.*;
import java.io.*;
interface ICalculator {
public float add(float a,float b);
public float subtract(float a,float b);
public float multiply(float a,float b);
public float divide(float a,float b);
                      }
class Calculator implements ICalculator
{
public float add(float a,float b)
{
return (a+b);
}
public float subtract(float a,float b)
{
return (a-b);
}
public float multiply(float a,float b)
{
return (a*b);
    }
    public float divide(float a,float b)
    {
    if(b==0.000)
    {
    throw new ArithmeticException("You can't have denominator as zero");
    }
    else
    {
    return (a/b);
    }
    }
}  
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
double result=0;
 Scanner s=new Scanner(System.in);
        System.out.println("YOU HAVE FOLLOWING CHOICES : ");
        System.out.println("1. ADDITION");
        System.out.println("2. SUBTRACTION ");
        System.out.println("3. MULTIPLICATION ");
        System.out.println("4. DIVISION");
        System.out.println("ENTER YOUR CHOICE : ");
        int i=s.nextInt();
         
        System.out.println("ENTER FIRST NUMBER ");
        float a=s.nextFloat();
        System.out.println("ENTER SECOND NUMBER ");
        float b=s.nextFloat();
        Calculator x=new Calculator();
        System.out.println("The result is=");
            switch(i)
        {
            case 1:
            {
            result=x.add(a,b);
            System.out.println(result);
            }
                break;
            case 2:
                {
                result=x.subtract(a,b);
                System.out.println(result);
                }
                break;
            case 3:
                {
                result=x.multiply(a,b);
                System.out.println(result);
                }
                break;
            case 4:
                {
                   result=x.divide(a,b);
                    System.out.println(result);
                }
                break;
           
            default:
                System.out.println("YOU HAVE ENTERED A WRONG CHOICE");
           
        }
}
}

Create an interface Calculator which has the following methods - add, subtract, multiply, divide - The above methods take 2 parameters of double type and returns a value of double type. - Create 2 different types of calculator implementations – BasicCalculator and ScientificCalculator. - The BasicCalculator only has the implementations of methods defined in the Calculator interface - The ScientificCalculator also has power, square and squareRoot methods in addition to the methods in the BasicCalculator (show how this is achieved using interface extension). - power takes 2 parameters of double type and returns a value of double type. - square & squareRoot takes 1 parameter of double type and returns a value of double type. - Change the class definitions as appropriate (add extends/implements as required)

package calculator;
import java.io.*;
import java.util.*;
import java.lang.Math;
import java.util.Scanner;

interface Calculator
{
    public double add(double a,double b);
    public double subtract(double a,double b);
    public double multiply(double a,double b);
    public double divide(double a,double b);
}

class BasicCalculator implements Calculator
{
public double add(double a,double b){
   return (a+b);
}
public double subtract(double a,double b){
   return (a-b);
}
public double multiply(double a,double b){
   return (a*b);
}
public double divide(double a,double b){
   return (a/b);
}
}

class ScientificCalculator extends BasicCalculator
{
    public double add(double a,double b){
   return (a+b);
}
public double subtract(double a,double b){
   return (a-b);
}
public double multiply(double a,double b){
   return (a*b);
}
public double divide(double a,double b){
   return (a/b);
}
    public double power(double a,double b) {
        return (Math.pow(a,b));
    }
    public double square(double a) {
        return (a*a);
    }
    public double squareRoot(double a) {
        return (Math.sqrt(a));
    }
}
class cal {
    public static void main(String []args) {
   
    ScientificCalculator sc=new ScientificCalculator();
        Scanner scan=new Scanner(System.in);
        System.out.println("Enter two numbers :");
        double a=scan.nextDouble();
        double b=scan.nextDouble();
        int ch = scan.nextInt();
       
            System.out.println("1.Add 2.Subtract 3.Multiply 4.Divide 5.Power 6.Square 7.squareroot");
            System.out.println("\n Enter your choice ");
           
            switch(ch){
                case 1 : System.out.println(sc.add(a,b));
                            break;
                case 2 : System.out.println(sc.subtract(a,b));
                            break;
                case 3 : System.out.println(sc.multiply(a,b));
                            break;
case 4 : System.out.println(sc.divide(a,b));
break;
case 5 : System.out.println(sc.power(a,b));
break;
case 6 : System.out.println(sc.square(a));
break;
case 7 : System.out.println(sc.squareRoot(a));
break;
default : System.out.println("WRONG INPUT");

}
     
    }
}

LinkedIn is a social network for professionals. Here is a sample LinkedIn profile: http://www.linkedin.com/in/gauthampai Come up with the class design for the entities and relationship between these entities in the profile. In other words, just list down the classes, the fields in the class and the functions or methods in each class along with the return values of each method.

class Name{
 String First_Name;
 String Middle_Name;
 String Last_Name;
}

class DOB{
 int date();   // dd/mm/yy format
 int month;
 int year;
 }

class Skill_Sets{
 string skils;
 }
Class Id{
 string User_Name;
 }
class Password{
 int Pass_Word;
}
class Phonenumber{
 int land_number;
 int mobile_number;
}
class Projects{
 string project_Name;
 }
class Groups{
 string nameofGroups;
 string nameogMembers;

 }
class Petents{
 string project_Names;
 string project_duration;
 string team_members;
 string contents;
 }
class Interest{
 string interest;
 }
class Languages{
 string language_Names;
 }
 class  Photo{
  int size;
  }

class Experience{
 String company_Name;
 string post;
 }

class EducationQualification{
 string school_name;
 String university_name;
 String degree_name;
}
class LinkedIn {
public static void main(String[] args) {
EducationQualification education1=new EducationQualification();
ArrayList<EducationQualification> equal = new ArrayList<EducationQualification>();
equal.add(education1);
                Experience ex=new Experience();
                ArrayList<Experience> exp = new ArrayList<Experience>();
                exp.add(ex);
}
}

Implement Binary Search over an array of integers. A stub file has been given to you. The class Binary accepts an array of integers as input and a key to search and the binarySearch method returns the position of the number in the array. Note that if the number is found at the first position in the array, it should return 1 (and not 0). If the number is not found return -1. You can assume that the array supplied to the constructor is already sorted.

import java.util.*;
import java.lang.*;
import java.io.*;

class Binary
{
int []l;
int key;    
  public Binary(int[] l, int key) {
    this.l = l;
    this.key = key;
  }
  public int binarySearch() {
     
    int lb=0;
    int ub=l.length-1;
    if(key==l[0])
        return 1;
    while(lb<=ub)
             {
                int mid=((lb+ub)/2);
                if(key==l[mid])
                  return (mid+1);
                   
                    if(key<l[mid])
                     ub=mid-1;
                    else
                      lb=mid+1;
              }
                return -1;
             }
  }
 
class myclass {
    public static void main(String []args) {
        int a[]={1,2,3,4,5};
        int key=3;
        Binary b=new Binary(a,key);
        System.out.println(key+" is present at position "+(b.binarySearch()+1));
    }
}

Write a program in Java that finds the duplicate numbers (numbers that occur more than once) in a list. The function takes a list of integers as parameter and prints the duplicate numbers.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.Set;

 class Duplicate{
List<Integer> l=new ArrayList<Integer>();

    public void findDuplicate(List<Integer> l){
        Set duplicate = new HashSet();
        Set uniques = new HashSet();
       
        for (int i = 0; i < l.size(); i++)
      if (!uniques.add(l.get(i)))
        duplicate.add(l.get(i));
    uniques.removeAll(duplicate);
    Iterator iterator=duplicate.iterator();
    while (iterator.hasNext()){
    System.out.println(iterator.next() + " ");
    }
    }
}
class HuntDuplicate {
    public static void main(String[] args) {
    List<Integer> l=new ArrayList<Integer>();
l.add(1);
        l.add(2);
        l.add(2);
        l.add(4);
        l.add(5);
        l.add(4);
       
        Duplicate d=new Duplicate();
        d.findDuplicate(l);
    }
}

Modularity of Code in Java Activity - Recursive Adder Write a recursive method add in a class whose constructor accepts a list of integers as input and the add method returns sum of the list.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

class RecurseAdder {
    List<Integer> l=new ArrayList<Integer>();
    int index;
    int sum=0;
    public RecurseAdder(List<Integer> l) {
        this.l = l;
        this.index = 0;
    }
    public int add(){
        if(index<l.size()){
       sum=sum+l.get(index);
   index++;
   add();
        }
   return sum;
    }
}
class AddList{
    public static void main(String args[]){

List<Integer> l=new ArrayList<Integer>();
l.add(1);
        l.add(2);
        l.add(3);
        l.add(4);
        l.add(5);
RecurseAdder n=new RecurseAdder(l);
System.out.println(n.add());
    }
}

Basic Java Programming

public class FastCar {
 public static void main(String []args) {
     int i;
     for(i=1;i<=100;i++) {
         if(i%21==0) {
            System.out.println("FastCar"); }
        else if(i%3==0) {
            System.out.println("Fast"); }
        else if(i%7==0) {
            System.out.println("Car"); }
        else {
            System.out.println(i); }
     }
 }
}

There is a file containing one number in each line. The numbers are in the range from 1 to 1000. Write the pseudocode for a program that finds the non-duplicate numbers (numbers that occur exactly once) and duplicate numbers (numbers that occur more than once) in the file.

class FindDupsAndUnique {
  public static void main(String args[]) {
    Set uniques = new HashSet();
    Set dups = new HashSet();
    
    int[] values= {1,2,2,3,4,5,5};
    for (int i = 0; i < values.length; i++)
      if (!uniques.add(values[i]))
        dups.add(values[i]);

    uniques.removeAll(dups); 

    System.out.println("Unique words:    " + uniques);
    System.out.println("Duplicate words: " + dups);
  }
}