Thursday, 17 August 2017

SPY NUMBER


SPYNUMBER:
A spy number is a number where the sum of its digits equals the product of its digits. For example, 1124 is a spy number, the sum of its digits is 1+1+2+4=8 and the product of its digits is 1*1*2*4=8.

/* java program to find given number is spynumber or not*/

import java.util.*;
public class SpyNumber
{
    public static void main(String args[])
    {
        int no, pro, sum, digit;
        pro = 1;
        sum = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number to check spy number :");
        no = sc.nextInt();
        while(no != 0)
        {
            digit = no % 10;
            pro = pro * digit;
            sum = sum + digit;
            no = no / 10;
        }
        if(sum == pro)
        {
            System.out.println("Spy Number");
        }
        else
        {
            System.out.println("Not Spy Number");
        }
    }
}





OUTPUT:
Enter a number to check spy number:
1124
Spy Number
Enter a number to check spy number:
1254
Not Spy Number

FASCINATING NUMBER


 FASCINATING NUMBER :
When a number( 3 digit or more) is multiplied by 2 and 3 ,and when both these products are concatenated with the original number all digits from 1 to 9 are present exactly once, regardless of the number of zeroes.


Example:Joining 192 with its products by 2 and 3, the resultant number is 192384576. This number contains all digits from 1 to 9 and these digits appear exactly once in the result. Hence 192 is a fascinating number. Note : The number should be of at least 3 digits to qualify for fascinating number test

/* program to find whether it is fascinating number or not*/

import java.util.*;
class FascinatingNumber
{
    boolean isUnique(String q)
    {
        int A[] = {0,0,0,0,0,0,0,0,0,0}; //to store frequency of every digit from '0' to '9'
        int i, flag = 0;
        char ch;
        for(i=0; i<q.length(); i++)
        {
            ch = q.charAt(i);
            A[ch-48]++;
            /*  increasing A[5] if ch='5' as '5'-48 = 53-48=5
             *  (ASCII values of '0' to '9' are 48 to 57) */
        }

        for(i=1; i<10; i++)
        {
            //checking if every digit from '1' to '9' are present exactly once or not
            if(A[i]!=1)
            {
                flag = 1; //flag is set to 1 if frequency is not 1
                break;
            }
        }

        if(flag == 1)
            return false;
        else
            return true;
    }
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        FascinatingNumber ob = new FascinatingNumber();

        System.out.print("Enter a number : ");
        int n = sc.nextInt();
        String p = Integer.toString(n); //converting the number to String

        if(p.length()<3)
            System.out.println("Number should be of atleast 3 digits.");

        else
        {
            String s = Integer.toString(n*1) + Integer.toString(n*2) + Integer.toString(n*3);
            /*  Joining the first, second and third multiple of the number
             *  by converting them to Strings and concatenating them*/
            if(ob.isUnique(s))
                System.out.println(n+" is a Fascinating Number.");
            else
                System.out.println(n+" is not a Fascinating Number.");
        }    
    }
}






OUTPUT:

Enter a number : 192

192 is a Fascinating Number.

Enter a number : 152
152 is not a Fascinating Number.

Find it is PRONIC NUMBER or not

pronic number:
A pronic number is a number which is the product of two consecutive integers, that is, a number of the form n(n + 1). The study of these numbers dates back to Aristotle. They are also called oblong numbers, heteromecic numbers, or rectangular numbers; however, the "rectangular number" name has also been applied to the composite numbers.
The first few pronic numbers are:
0, 2, 6, 12, 20 30,42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462 



/* program to find given number is pronic number or  not*/

import java.util.*;
class PronicNumber
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
       
        System.out.print("Enter a number : ");
        int n = sc.nextInt();
        int flag = 0;
   
        for(int i=0; i<n; i++)
        {
            if(i*(i+1) == n)
            {
                flag = 1;
                break;
            }
        }
       
        if(flag == 1)
            System.out.println(n+" is a Pronic Number.");
        else
            System.out.println(n+" is not a Pronic Number.");    
    }
}


OUTPUT:

Enter a number : 420
420 is a Pronic Number.
 
Enter a number : 13
13 is not a Pronic Number.
 
Enter a number : 12
12 is a Pronic Number.
 
Enter a number : 21
21 is not a Pronic Number

Thursday, 10 August 2017

SampleGraph design

public class sampleGraph extends JPanel {

    private int width = 800;
    private int heigth = 400;
    private int padding = 25;
    private int labelPadding = 25;
    private Color lineColor = new Color(44, 102, 230, 180);
    private Color pointColor = new Color(100, 100, 100, 180);
    private Color gridColor = new Color(200, 200, 200, 200);
    private static final Stroke GRAPH_STROKE = new BasicStroke(2f);
    private int pointWidth = 4;
    private int numberYDivisions = 10;
    private List<Double> scores;

    public sampleGraph(List<Double> scores) {
        this.scores = scores;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        double xScale = ((double) getWidth() - (2 * padding) - labelPadding) / (scores.size() - 1);
        double yScale = ((double) getHeight() - 2 * padding - labelPadding) / (getMaxScore() - getMinScore());

        List<Point> graphPoints = new ArrayList<>();
        for (int i = 0; i < scores.size(); i++) {
            int x1 = (int) (i * xScale + padding + labelPadding);
            int y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + padding);
            graphPoints.add(new Point(x1, y1));
        }

        // draw white background
        g2.setColor(Color.WHITE);
        g2.fillRect(padding + labelPadding, padding, getWidth() - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding);
        g2.setColor(Color.BLACK);

        // create hatch marks and grid lines for y axis.
        for (int i = 0; i < numberYDivisions + 1; i++) {
            int x0 = padding + labelPadding;
            int x1 = pointWidth + padding + labelPadding;
            int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding);
            int y1 = y0;
            if (scores.size() > 0) {
                g2.setColor(gridColor);
                g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, getWidth() - padding, y1);
                g2.setColor(Color.BLACK);
                String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + "";
                FontMetrics metrics = g2.getFontMetrics();
                int labelWidth = metrics.stringWidth(yLabel);
                g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3);
            }
            g2.drawLine(x0, y0, x1, y1);
        }

        // and for x axis
        for (int i = 0; i < scores.size(); i++) {
            if (scores.size() > 1) {
                int x0 = i * (getWidth() - padding * 2 - labelPadding) / (scores.size() - 1) + padding + labelPadding;
                int x1 = x0;
                int y0 = getHeight() - padding - labelPadding;
                int y1 = y0 - pointWidth;
                if ((i % ((int) ((scores.size() / 20.0)) + 1)) == 0) {
                    g2.setColor(gridColor);
                    g2.drawLine(x0, getHeight() - padding - labelPadding - 1 - pointWidth, x1, padding);
                    g2.setColor(Color.BLACK);
                    String xLabel = i + "";
                    FontMetrics metrics = g2.getFontMetrics();
                    int labelWidth = metrics.stringWidth(xLabel);
                    g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3);
                }
                g2.drawLine(x0, y0, x1, y1);
            }
        }

        // create x and y axes
        g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding);
        g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth() - padding, getHeight() - padding - labelPadding);

        Stroke oldStroke = g2.getStroke();
        g2.setColor(lineColor);
        g2.setStroke(GRAPH_STROKE);
        for (int i = 0; i < graphPoints.size() - 1; i++) {
            int x1 = graphPoints.get(i).x;
            int y1 = graphPoints.get(i).y;
            int x2 = graphPoints.get(i + 1).x;
            int y2 = graphPoints.get(i + 1).y;
            g2.drawLine(x1, y1, x2, y2);
        }

        g2.setStroke(oldStroke);
        g2.setColor(pointColor);
        for (int i = 0; i < graphPoints.size(); i++) {
            int x = graphPoints.get(i).x - pointWidth / 2;
            int y = graphPoints.get(i).y - pointWidth / 2;
            int ovalW = pointWidth;
            int ovalH = pointWidth;
            g2.fillOval(x, y, ovalW, ovalH);
        }
    }

//    @Override
//    public Dimension getPreferredSize() {
//        return new Dimension(width, heigth);
//    }

    private double getMinScore() {
        double minScore = Double.MAX_VALUE;
        for (Double score : scores) {
            minScore = Math.min(minScore, score);
        }
        return minScore;
    }

    private double getMaxScore() {
        double maxScore = Double.MIN_VALUE;
        for (Double score : scores) {
            maxScore = Math.max(maxScore, score);
        }
        return maxScore;
    }

    public void setScores(List<Double> scores) {
        this.scores = scores;
        invalidate();
        this.repaint();
    }

    public List<Double> getScores() {
        return scores;
    }
   
    private static void createAndShowGui() {
        List<Double> scores = new ArrayList<>();
        Random random = new Random();
        int maxDataPoints = 40;
        int maxScore = 10;
        for (int i = 0; i < maxDataPoints; i++) {
            scores.add((double) random.nextDouble() * maxScore);
//            scores.add((double) i);
        }
        sampleGraph mainPanel = new sampleGraph(scores);
        mainPanel.setPreferredSize(new Dimension(800, 600));
        JFrame frame = new JFrame("DrawGraph");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
   
    public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }




OUTPUT:



Deadlock Program


package rakesh;
class Deadlock1
{
    // Deadlock1 class to sleep a thread
    static void sleep(long millis)
    {
        try
        {
            Thread.sleep(millis);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}

// This class is shared by both threads
class Shared
{
    // first synchronized method
    synchronized void task1(Shared s2)
    {
        System.out.println("task1 started");
        Deadlock1.sleep(1000);

        // taking object lock of s2 enters
        // into test2 method
        s2.task2(this);
        System.out.println("task1 ended");
    }

    // second synchronized method
    synchronized void task2(Shared s1)
    {
        System.out.println("task2 started");
        Deadlock1.sleep(1000);

        // taking object lock of s1 enters
        // into task1 method
        s1.task1(this);
        System.out.println("task2 ended");
    }
}


class Thread1 extends Thread
{
    private Shared s1;
    private Shared s2;

    // constructor to initialize fields
    public Thread1(Shared s1, Shared s2)
    {
        this.s1 = s1;
        this.s2 = s2;
    }

    // run method to start a thread
    @Override
    public void run()
    {
        // taking object lock of s1 enters
        // into test1 method
        s1.task1(s2);
    }
}


class Thread2 extends Thread
{
    private Shared s1;
    private Shared s2;

    // constructor to initialize fields
    public Thread2(Shared s1, Shared s2)
    {
        this.s1 = s1;
        this.s2 = s2;
    }

    // run method to start a thread
    @Override
    public void run()
    {
        // taking object lock of s2
        // enters into test2 method
        s2.task2(s1);
    }
}


public class Deadlock
{
    public static void main(String[] args)
    {
        // creating one object
        Shared s1 = new Shared();

        // creating second object
        Shared s2 = new Shared();

        // creating first thread and starting it
        Thread1 t1 = new Thread1(s1, s2);
        t1.start();

        // creating second thread and starting it
        Thread2 t2 = new Thread2(s1, s2);
        t2.start();

        // sleeping main thread
        Deadlock1.sleep(2000);
    }
}






OUTPUT:



task1 started
task2 started

Wednesday, 9 August 2017

To check two strings are anagram or not

import java.util.Scanner;

public class Anagram
{
    public static void main(String[] input)
    {
        String str1, str2;
        int len, len1, len2, i, j, found=0, not_found=0;
        Scanner scan = new Scanner(System.in);
       
        System.out.print("Enter First String : ");
        str1 = scan.nextLine();
        System.out.print("Enter Second String : ");
        str2 = scan.nextLine();
       
        len1 = str1.length();
        len2 = str2.length();

        if(len1 == len2)
        {
            len = len1;
            for(i=0; i<len; i++)
            {
                found = 0;
                for(j=0; j<len; j++)
                {
                    if(str1.charAt(i) == str2.charAt(j))
                    {
                        found = 1;
                        break;
                    }
                }
                if(found == 0)
                {
                    not_found = 1;
                    break;
                }
            }
            if(not_found == 1)
            {
                System.out.print("Strings are not Anagram to Each Other....");
            }
            else
            {
                System.out.print("Strings are Anagram");
            }
        }
        else
        {
            System.out.print("Both Strings Must have the same number of Character to be an Anagram");
        }
    }
}





OUTPUT:


Case#1
Enter First String : java
Enter Second String : aajv

Strings are Anagram

Case#2
Enter First String : java
Enter Second String : oracle
Both Strings Must have the same number of Character to be an Anagram


Case#3

Enter First String : hello
Enter Second String : given
Strings are not Anagram to Each Other..!!


Tuesday, 8 August 2017

Find IP-Address


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class IpAddress extends Frame implements ActionListener{
    JTextField tf; JLabel l; JButton b;
    IpAddress(){
        tf=new JTextField();
        tf.setBounds(50,50, 150,20);
        l=new JLabel();
        l.setBounds(20,100, 250,20);    
        b=new JButton("Find IP");
        b.setBounds(50,150,95,30);
        b.addActionListener(this);  
        add(b);add(tf);add(l);  
        setSize(400,400);
        setLayout(null);
        setVisible(true);
    }
    public void actionPerformed(ActionEvent e) {
        try{
        String host=tf.getText();
        String ip=java.net.InetAddress.getByName(host).getHostAddress();
        l.setText("IP of "+host+" is: "+ip);
        }catch(Exception ex){System.out.println(ex);}
    }
    public static void main(String[] args) {
        new IpAddress();
    } }





OUTPUT: