Showing posts with label java lab programs. Show all posts
Showing posts with label java lab programs. Show all posts

April 28, 2022

Making entire row and column of matrix to zero if one element is zero | alternative approach


Given a matrix if an element in the matrix is 0 then you will have to set its entire column and row to 0 and then return the matrix.
 



/**
 * Given a matrix if an element in the matrix is 0 then you will have to set its entire column and row to 0 and then return the matrix.
 */
package com.striver.sde.practice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author apple
 *
 */
public class MatrixZero {

/**
* @param args
*/
public static void main(String[] args) {

int[][] input = { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 } };

MatrixZero m = new MatrixZero();
// m.findSolution(input);
m.findSolution2(input);

}

private void findSolution2(int[][] input) {
int len = input.length;

List rows = new ArrayList<>();
List cols = new ArrayList<>();

for (int row = 0; row < len; row++) {

for (int col = 0; col < len; col++) {

if (input[row][col] == 0) {
rows.add(row);
cols.add(col);
}

}

}
for (int row = 0; row < len; row++) {

for (int col = 0; col < len; col++) {

if(rows.contains(row)) {
input[row][col] =0;
}
if(cols.contains(col)) {
input[row][col] =0;
}

}

}
System.out.println(input);
}

private void findSolution(int[][] input) {

int[][] output = input.clone();

int len = input.length;

for (int row = 0; row < len; row++) {

for (int col = 0; col < len; col++) {

if (input[row][col] == 0) {

modifyMatrix(row, col, output, len);

}

}

}

}

private void modifyMatrix(int row, int col, int[][] output, int len) {

if (row == 0) {
int r = row;
while (r < len) {
output[r][col] = 0;
r = r + 1;
}

} else if (row == len) {
int r = row;
while (r >= 0) {
output[r][col] = 0;
r = r - 1;
}

} else {

}

}

}

December 14, 2019

Spiral unwinding a matrix interview question solved java source code

To unwind a matrix spirally to an array.

/**
 * Unwinding a matrix in java
 * Tested a 5 x 5 matrix
 */
package com.konzern.solution;

/**
 * @author Arjun Babu
 *
 */
public class Unwinding {

/**
* @param amazon
*/
public static void main(String[] hematcs) {
Unwinding unwindMatrix = new Unwinding();
int[][] matrix = unwindMatrix.getInput();
unwindMatrix.display(matrix);
int[] value = unwindMatrix.unwindMatix(matrix);
}

private void display(int[][] matrix) {
System.out.println("The Input Matrix \n");
int len = matrix.length;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}

}

private int[] unwindMatix(int[][] matrix) {
System.out.println("\nThe Output Array \n");
int len = matrix.length;
int loopCount = len * len;
int data[] = new int[loopCount];
int flag = 0;
int maxRow = len - 1;
int maxCol = len - 1;
int minRow = 0;
int minCol = 0;
int row = 0;
int col = 0;
for (int i = 0; i < loopCount; i++) {
data[i] = matrix[row][col];
System.out.print(data[i] + " ");
switch (flag) {
case 0:
col = col + 1;
if (col > maxCol) {
col = maxCol;
row = row + 1;
minRow++;
flag = 1;
}
break;
case 1:
row = row + 1;
if (row > maxRow) {
row = maxRow;
col--;
maxCol--;
flag = 2;
}
break;
case 2:
col = col - 1;
if (col < minCol) {
row = row - 1;
col = col + 1;
maxRow--;
flag = 3;
}
break;

case 3:
row = row - 1;
if (row < minRow) {
row = row + 1;
col = col + 1;
minCol++;
flag = 0;
}
break;
default:
break;
}
}
return data;
}

private int[][] getInput() {
int matrix[][] = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } };
return matrix;
}
}


The Input Matrix 

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

The Output Array 

1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13 


January 02, 2017

Traffic Light in java


Traffic Light program in java



Traffic light in java source code


package test;


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class TrafficLight extends JFrame implements ActionListener {
    JButton buttonRed, buttonYellow, buttonGreen;

      Signal green = new Signal(Color.green);
      Signal yellow = new Signal(Color.yellow);
      Signal red = new Signal(Color.red);

    public TrafficLight(){
        super("Java Traffic Light Program");
        getContentPane().setLayout(new GridLayout(2, 1));
        buttonRed = new JButton("Red");
        buttonYellow = new JButton("Yellow");
        buttonGreen = new JButton("Green");
        buttonRed.addActionListener(this);
        buttonYellow.addActionListener(this);
        buttonGreen.addActionListener(this);      

        green.turnOn(false);
        yellow.turnOn(false);
        red.turnOn(true);

        JPanel trafficPanel = new JPanel(new GridLayout(3,1));
        trafficPanel.add(red);
        trafficPanel.add(yellow);
        trafficPanel.add(green);
        JPanel lightPanel = new JPanel(new FlowLayout());
        lightPanel.add(buttonRed);
        lightPanel.add(buttonYellow);
        lightPanel.add(buttonGreen);

        getContentPane().add(trafficPanel);
        getContentPane().add(lightPanel);
        pack();
        }


    public static void main(String[] args){
        TrafficLight trafficLight = new TrafficLight();      
        trafficLight.setVisible(true);
    }  
    public void actionPerformed(ActionEvent e){      
        if (e.getSource() == buttonRed){
            green.turnOn(false);          
            yellow.turnOn(false);
            red.turnOn(true);
        } else if (e.getSource() == buttonYellow){
            yellow.turnOn(true);          
            green.turnOn(false);
            red.turnOn(false);
        } else if (e.getSource() == buttonGreen){
            red.turnOn(false);          
            yellow.turnOn(false);
            green.turnOn(true);
        }
    }
}  
class Signal extends JPanel{

    Color on;
    int radius = 40;
    int border = 10;
    boolean change;

    Signal(Color color){
        on = color;
        change = true;
    }

    public void turnOn(boolean a){
        change = a;
        repaint();      
    }

    public Dimension getPreferredSize(){
        int size = (radius+border)*2;
        return new Dimension( size, size );
    }

    public void paintComponent(Graphics graphics){
        graphics.setColor( Color.black );
        graphics.fillRect(0,0,getWidth(),getHeight());

        if (change){
            graphics.setColor( on );
        } else {
            graphics.setColor( on.darker().darker().darker() );
        }
        graphics.fillOval( border,border,2*radius,2*radius );
    }
}

http://javabelazy.blogspot.in/

December 25, 2013

Cryptography in java

Java Cryptography



 import javax.crypto.Cipher;
   import javax.crypto.BadPaddingException;
   import javax.crypto.IllegalBlockSizeException;
   import javax.crypto.KeyGenerator;
   import java.security.Key;
   import java.security.InvalidKeyException;

   public class LocalEncrypter {

        private static String algorithm = "DESede";
        private static Key key = null;
        private static Cipher cipher = null;

        private static void setUp() throws Exception {
            key = KeyGenerator.getInstance(algorithm).generateKey();
            cipher = Cipher.getInstance(algorithm);
        }

        public static void main(String[] args)
           throws Exception {
            setUp();
            if (args.length !=1) {
                System.out.println(
                  "USAGE: java LocalEncrypter " +
                                         "[String]");
                System.exit(1);
            }
            byte[] encryptionBytes = null;
            String input = args[0];
            System.out.println("Entered: " + input);
            encryptionBytes = encrypt(input);
            System.out.println(
              "Recovered: " + decrypt(encryptionBytes));
        }

        private static byte[] encrypt(String input)
            throws InvalidKeyException,
                   BadPaddingException,
                   IllegalBlockSizeException {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] inputBytes = input.getBytes();
            return cipher.doFinal(inputBytes);
        }

        private static String decrypt(byte[] encryptionBytes)
            throws InvalidKeyException,
                   BadPaddingException,
                   IllegalBlockSizeException {
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] recoveredBytes =
              cipher.doFinal(encryptionBytes);
            String recovered =
              new String(recoveredBytes);
            return recovered;
          }
   }

Merry Christmas and happy new year wishes to all visitors +belazy


Up helly aa fire festival

http://belazy.blog.com/

March 17, 2013

Find Prime Number in java

how to determine prime number in java


package prime Algorithm.Testing;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *java practical question
 * @author joseph
 */

/**
 * @author Samsung Galaxy S4
 *
 */
public class PrimeOrNot {

    /**
     * @param args
     */
      static int i,num,flag=0;
   
    public static void main(String[] Lumina) {
        // TODO Auto-generated method stub
   
        System.out.println(" To find prime number in java : enter the integer no:");
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       try {
         num=Integer.parseInt(br.readLine());
    } catch (NumberFormatException phpexp) {
        // TODO Auto-generated catch block
        phpexp.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       for(i=2;i           if(num%2==0)
           {
               flag=1;break;
           }
       }
       if(flag==1)
           System.out.println("Number is not prime");
       else
           System.out.println("Number is  prime"); 
    }

}
 




http://belazy.blog.com/

August 09, 2012

How to print matrix in java

Matrix Manipulation in java


Description : To print sum of all values of matrix in java


 import java.util.Scanner;

/**
* +belazy 
*/
/**
* @author BlackBery
*
*/
public class MatrixDiagonal {
private int [][]matrix = null;
private Scanner sc = null;
public MatrixDiagonal() {
matrix = new int[3][3];
}
public static void main(String[] args) {
MatrixDiagonal md = new MatrixDiagonal();
md.getMatrixValues();
md.showMatrix();
md.computeValue();
}
private void computeValue() {
int sum = 0;
for(int row = 0; row < 3 ; row ++){
for(int col =0; col col){
sum = sum + matrix[row][col];
}
}
}
System.out.println(sum);
}
private void showMatrix() {
for(int row = 0; row < 3 ; row ++){
for(int col =0; col < 3; col ++ ){
System.out.print(matrix[row][col]+"\t");
}
System.out.println();
}
}
private void getMatrixValues() {
sc = new Scanner(System.in);
System.out.println(" Enter values ");
for(int row = 0; row < 3 ; row ++){
for(int col =0; col < 3; col ++ ){
matrix[row][col] = sc.nextInt();
}
}
}
}

Facebook comments