Sunday, June 16, 2013
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock avoidance algorithm that tests for safety by simulating the allocation of predetermined maximum possible amount of all resources, and then makes a check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue. Here we have 3 input matrix where
max[][] - denotes maximum resources that will be required by processes
allocate[][] - denotes currently allocated resources to processes
avail[][] - denotes resources available in the system
We will calculate need matrix and then try to allocate. I f we can allocate safely then give a suitable message.
--------------------------------------------------------------------------------------------------------------------------
max[][] - denotes maximum resources that will be required by processes
allocate[][] - denotes currently allocated resources to processes
avail[][] - denotes resources available in the system
We will calculate need matrix and then try to allocate. I f we can allocate safely then give a suitable message.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.util.Scanner; public class Bankers{ private int need[][],allocate[][],max[][],avail[][],np,nr; private void input(){ Scanner sc=new Scanner(System.in); System.out.print("Enter no. of processes and resources : "); np=sc.nextInt(); //no. of process nr=sc.nextInt(); //no. of resources need=new int[np][nr]; //initializing arrays max=new int[np][nr]; allocate=new int[np][nr]; avail=new int[1][nr]; System.out.println("Enter allocation matrix -->"); for(int i=0;i<np;i++) for(int j=0;j<nr;j++) allocate[i][j]=sc.nextInt(); //allocation matrix System.out.println("Enter max matrix -->"); for(int i=0;i<np;i++) for(int j=0;j<nr;j++) max[i][j]=sc.nextInt(); //max matrix System.out.println("Enter available matrix -->"); for(int j=0;j<nr;j++) avail[0][j]=sc.nextInt(); //available matrix sc.close(); } private int[][] calc_need(){ for(int i=0;i<np;i++) for(int j=0;j<nr;j++) //calculating need matrix need[i][j]=max[i][j]-allocate[i][j]; return need; } private boolean check(int i){ //checking if all resources for ith process can be allocated for(int j=0;j<nr;j++) if(avail[0][j]<need[i][j]) return false; return true; } public void isSafe(){ input(); calc_need(); boolean done[]=new boolean[np]; int j=0; while(j<np){ //until all process allocated boolean allocated=false; for(int i=0;i<np;i++) if(!done[i] && check(i)){ //trying to allocate for(int k=0;k<nr;k++) avail[0][k]=avail[0][k]-need[i][k]+max[i][k]; System.out.println("Allocated process : "+i); allocated=done[i]=true; j++; } if(!allocated) break; //if no allocation } if(j==np) //if all processes are allocated System.out.println("\nSafely allocated"); else System.out.println("All proceess cant be allocated safely"); } public static void main(String[] args) { new Bankers().isSafe(); } }
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
Enter no. of processes and resources : 3 4
Enter allocation matrix -->
1 2 2 1
1 0 3 3
1 2 1 0
Enter max matrix -->
3 3 2 2
1 1 3 4
1 3 5 0
Enter available matrix -->
3 1 1 2
Allocated process : 0
Allocated process : 1
Allocated process : 2
Safely allocated
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Labels:Algorithms | 24
comments
Saturday, June 15, 2013
Today I will show you how to install Java on Ubuntu. New Linux users may find it difficult to install, so I will be sharing this post to help you people out. There are two procedures to do that. First is do it directly from terminal and the second is do it manually if you already have the binaries. We will show you the second procedure.
Step 1 : Download Java from Oracle Java SE Downloads . Download the appropriate version according to your platform architecture. [NOTE : The download link is subject to change. If dead please report it. ]
Step 2 ; Unpack the archive using the following command
tar xvzf <file-name> [ e.g. jdk-7u21-linux-x64.tar.gz ]
You will get a folder something named jdk1.7.0.
Step 3 : Next we will have to create a directory named jvm and copy the extracted folder into it with following command.
mkdir jvm
cp -r <extracted-folder-name> jvm [ e.g. cp -r jdk1.7.0 jvm ]
Now we will have to move this jvm folder to /usr/lib directory.
sudo mv jvm /usr/lib . Enter password when asked.
Step 4 : Since we have successfully copied the folder, now we will only have to tell the Linux system where your Java is installed.
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
-It will tell that JRE is available
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
-It will tell Java Compiler is available
Step 1 : Download Java from Oracle Java SE Downloads . Download the appropriate version according to your platform architecture. [NOTE : The download link is subject to change. If dead please report it. ]
Step 2 ; Unpack the archive using the following command
tar xvzf <file-name> [ e.g. jdk-7u21-linux-x64.tar.gz ]
You will get a folder something named jdk1.7.0.
Step 3 : Next we will have to create a directory named jvm and copy the extracted folder into it with following command.
mkdir jvm
cp -r <extracted-folder-name> jvm [ e.g. cp -r jdk1.7.0 jvm ]
Now we will have to move this jvm folder to /usr/lib directory.
sudo mv jvm /usr/lib . Enter password when asked.
Step 4 : Since we have successfully copied the folder, now we will only have to tell the Linux system where your Java is installed.
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
-It will tell that JRE is available
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
-It will tell Java Compiler is available
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 1
-It will tell Java Web Start is available
NOTE : There are many more executables that you may need to install like jar, javap, appletviewer and so on. Just perform the step 4 for installing any other features. We have just mentioned about java, javac and javaws. Also note that it is not mandatory to name the folder as jvm.
Hope this helps you. Keep coding :)
Labels:Java FAQs | 0
comments
Thursday, June 13, 2013
Today I am going to show you how you can perform edge detection on any image using Java. Here we will use the convolution operator to perform this. But for this we need a kernel to perform this operation. But before that we will first give a breif description about this.
ConvolveOp class : ConvolveOp is one of the most versatile image operators in the 2D API. It represents a spatial convolution, which is a fancy mathematical term that means that the color of each destination pixel is determined by combining the colors of the corresponding source pixel and its neighbors. A convolution operator can be used to blur or sharpen an image, among other things.
ConvolveOp class : ConvolveOp is one of the most versatile image operators in the 2D API. It represents a spatial convolution, which is a fancy mathematical term that means that the color of each destination pixel is determined by combining the colors of the corresponding source pixel and its neighbors. A convolution operator can be used to blur or sharpen an image, among other things.
Kernel class : The convolution operator uses a kernel to specify how a source pixel and its neighbors are combined. A kernel is simply a matrix, where the center of the matrix represents the source pixel and the other elements correspond to the neighboring source pixels. The destination color is calculated by multiplying each pixel color by its corresponding kernel coefficient and adding the results together.
How the operation will be performed - We will first read an image using read() method of ImageIO as BufferedImage. Next pass this to a function edgeDetect() where the operation will be carried out. Here we will first create a 3x3 array for kernel whose values add upto less than 1, which means that the image that will be produced will be darker. Next we will create the convolution operator creating ConvolveOp instance using the Kernel. Next we will call filter() method to perform the operation.
Screenshots of the images
Original Image |
Image after Edge Detection |
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import javax.imageio.ImageIO;
public class EdgeDetection {
public BufferedImage detectEdge(BufferedImage src){
//kernel for edge detection adding upto less than 1
float edgeArr[]={0,-1,0,-1,4,-1,0,-1,0};
//creating the convolution operator
ConvolveOp edgeOp=new ConvolveOp(new Kernel(3,3,edgeArr),ConvolveOp.EDGE_NO_OP,null);
return edgeOp.filter(src, null); //operating on image
}
public static void main(String[] args)throws Exception {
EdgeDetection obj=new EdgeDetection();
BufferedImage src=ImageIO.read(new File("src_edge.jpg")),
dest=obj.detectEdge(src); //edge detection
ImageIO.write(dest, "jpeg",new File("dest_edge.jpg"));
}
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Hope this helps. Keep coding :)
Labels:Graphics2D-Images | 0
comments
Tuesday, June 11, 2013
Today I will show you how you can flip an image vertically and horizontally. Flipping an image means reflecting an image along a miiror axis. Mathematically when we flip along horizontal axis x'=x and y'=-y whereas when flipped along vertical axis x'=-x and y'=y, where (x',y') is the transformed point and (x,y) is the original point. Here in our sample code we will first read the image from file as BufferedImage. Since there is no flip function available in Java so we will first perform scaling and then translation. We will use AffineTransformOp to transform the image and call filter() method that returns the transformed image.The transformation will be carried out in following way --->
Horizontal Flip : scale(1.0,-1.0) and translate(0,-image.getHeight())
Vertical Flip : scale(-1.0,1.0) and translate(-image.getWidth(),0)
Flip both ways : scale(-1.0,-1.0) and translate(-image.getWidth(),-image.getHeight())
AffineTransform class : It represents a 2D affine transform that performs a linear mapping from 2D coordinates to other 2D coordinates that preserves the "straightness" and "parallelness" of lines. Affine transformations can be constructed using sequences of translations, scales, flips, rotations, and shears.
AffineTransformOp class : This class uses an affine transform to perform a linear mapping from 2D coordinates in the source image or Raster to 2D coordinates in the destination image or Raster. The type of interpolation that is used is specified through a constructor, either by a RenderingHints object or by one of the integer interpolation types defined in this class.
Screenshots of the transformation
--------------------------------------------------------------------------------------------------------------------------
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class FlipImage {
public BufferedImage flipVertical(BufferedImage src){
AffineTransform tx=AffineTransform.getScaleInstance(-1.0,1.0); //scaling
tx.translate(-src.getWidth(),0); //translating
AffineTransformOp tr=new AffineTransformOp(tx,null); //transforming
return tr.filter(src, null); //filtering
}
public BufferedImage flipHorizontal(BufferedImage src){
AffineTransform tx=AffineTransform.getScaleInstance(1.0,-1.0); //scaling
tx.translate(0,-src.getHeight()); //translating
AffineTransformOp tr=new AffineTransformOp(tx,null); //transforming
return tr.filter(src, null); //filtering
}
public static void main(String[] args)throws Exception {
FlipImage obj=new FlipImage();
BufferedImage src=ImageIO.read(new File("src.jpeg")); //reading image
BufferedImage dest=obj.flipVertical(src); //flipping vertically
ImageIO.write(dest,"jpeg",new File("dest_flipVer.jpg"));
dest=obj.flipHorizontal(src); //flipping horizontally
ImageIO.write(dest,"jpeg",new File("dest_flipHor.jpg"));
dest=obj.flipVertical(dest); //flupping both ways
ImageIO.write(dest,"jpeg",new File("dest_flipBoth.jpg"));
}
}
Horizontal Flip : scale(1.0,-1.0) and translate(0,-image.getHeight())
Vertical Flip : scale(-1.0,1.0) and translate(-image.getWidth(),0)
Flip both ways : scale(-1.0,-1.0) and translate(-image.getWidth(),-image.getHeight())
AffineTransform class : It represents a 2D affine transform that performs a linear mapping from 2D coordinates to other 2D coordinates that preserves the "straightness" and "parallelness" of lines. Affine transformations can be constructed using sequences of translations, scales, flips, rotations, and shears.
AffineTransformOp class : This class uses an affine transform to perform a linear mapping from 2D coordinates in the source image or Raster to 2D coordinates in the destination image or Raster. The type of interpolation that is used is specified through a constructor, either by a RenderingHints object or by one of the integer interpolation types defined in this class.
Screenshots of the transformation
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class FlipImage {
public BufferedImage flipVertical(BufferedImage src){
AffineTransform tx=AffineTransform.getScaleInstance(-1.0,1.0); //scaling
tx.translate(-src.getWidth(),0); //translating
AffineTransformOp tr=new AffineTransformOp(tx,null); //transforming
return tr.filter(src, null); //filtering
}
public BufferedImage flipHorizontal(BufferedImage src){
AffineTransform tx=AffineTransform.getScaleInstance(1.0,-1.0); //scaling
tx.translate(0,-src.getHeight()); //translating
AffineTransformOp tr=new AffineTransformOp(tx,null); //transforming
return tr.filter(src, null); //filtering
}
public static void main(String[] args)throws Exception {
FlipImage obj=new FlipImage();
BufferedImage src=ImageIO.read(new File("src.jpeg")); //reading image
BufferedImage dest=obj.flipVertical(src); //flipping vertically
ImageIO.write(dest,"jpeg",new File("dest_flipVer.jpg"));
dest=obj.flipHorizontal(src); //flipping horizontally
ImageIO.write(dest,"jpeg",new File("dest_flipHor.jpg"));
dest=obj.flipVertical(dest); //flupping both ways
ImageIO.write(dest,"jpeg",new File("dest_flipBoth.jpg"));
}
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Labels:Graphics2D,Graphics2D-Images | 0
comments
Saturday, June 8, 2013
Today I will tell you how you can create shaped windows in Java. This is an extraordinary feature which was added in Java7. According to this feature you can create any shape and use that shape for your window. You can also create complex shapes and give your windows that shape. Different shapes like oval, round rectangle or complex like L-shape or I-shape. Here we will inherit the JFrame class and then add the ComponentListener to it. This is because when the window will be resized the shape will be calculated automatically. We will create a shape using Ellipse2D.Double and then call setShape() method to assign the shape to it. Below is a screenshot
--------------------------------------------------------------------------------------------------------------------------
import java.awt.Shape;
import java.awt.GridBagLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.geom.*;
public class OvalShapedWindow extends JFrame {
public OvalShapedWindow() {
super("Oval Window");
setLayout(new GridBagLayout()); //setting layout
addComponentListener(new ComponentAdapter() {
// If the window is resized, the shape is recalculated
@Override
public void componentResized(ComponentEvent e) {
Shape winShape=new Ellipse2D.Double(0,0,getWidth(),getHeight());
setShape(winShape); //giving shape
}
});
setUndecorated(true); //removing title-bar
setSize(350,250);
setLocationRelativeTo(null); //positioning at center
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JButton("Click Me")); //adding Button
}
public static void main(String[] args) {
// Creating UI on the event-dispatching thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
OvalShapedWindow sw = new OvalShapedWindow();
sw.setVisible(true); // Display the window
}
});
}
}
--------------------------------------------------------------------------------------------------------------------------
An oval-shaped window as seen on Ubuntu 12.04 |
Java Source Code
--------------------------------------------------------------------------------------------------------------------------import java.awt.Shape;
import java.awt.GridBagLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.geom.*;
public class OvalShapedWindow extends JFrame {
public OvalShapedWindow() {
super("Oval Window");
setLayout(new GridBagLayout()); //setting layout
addComponentListener(new ComponentAdapter() {
// If the window is resized, the shape is recalculated
@Override
public void componentResized(ComponentEvent e) {
Shape winShape=new Ellipse2D.Double(0,0,getWidth(),getHeight());
setShape(winShape); //giving shape
}
});
setUndecorated(true); //removing title-bar
setSize(350,250);
setLocationRelativeTo(null); //positioning at center
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JButton("Click Me")); //adding Button
}
public static void main(String[] args) {
// Creating UI on the event-dispatching thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
OvalShapedWindow sw = new OvalShapedWindow();
sw.setVisible(true); // Display the window
}
});
}
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Labels:Swing | 0
comments
Subscribe to:
Posts
(Atom)
Total Pageviews
Followers
Labels
- Algorithms (7)
- Annotation (3)
- Files (6)
- Generics (3)
- Graphics2D (5)
- Graphics2D-Images (7)
- Inheritance (2)
- J2EE (9)
- Java 8 (4)
- Java FAQs (19)
- JDBC (3)
- Networking (2)
- Packages (1)
- Reflection (4)
- Security (7)
- Sorting (2)
- Swing (3)
- Threads (3)
- Utils (3)
Popular Posts
-
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock a...
-
------------------------- UPDATE ------------------------- I have updated the code on request of some followers so that they can directly...
-
Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post here we ...
-
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important applicat...
-
--------------------UPDATE------------------- I have updated my post so that now it can detect IE 11. This modification was necessary as t...
-
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turin...
-
Today I am going to post a program that will be able to produce all the mColorings of a given graph G. What is mColoring : The problem st...
-
Today in this article I will show you how to create or develop a Tower of Hanoi game in Java. The Tower of Hanoi is a famous problem tha...