Archive for June, 2008

Draw a Circle in Java, the fundamental “pixels” way !

The following code draws a circle of particular diameter by setting the PIXELS falling inside the circle to a different RGB value. It involves simple co-ordinate geometry fundas. There are some approximations being taken.


import java.awt.image.*;
import javax.swing.*;
import javax.swing.JComponent.*;

public class circles extends JFrame {
public static void main(String args[]) {
double d=Double.parseDouble(args[0]);
int diameter= (int)d;

circles ca= new circles();
ca.drawCircle(diameter);
}
public void drawCircle(int diameter) {
int x=0,y=0,radius;
JFrame frame=new JFrame();
JLabel lab;
BufferedImage bi=new BufferedImage (diameter,diameter,BufferedImage.TYPE_BYTE_GRAY );
WritableRaster raster=bi.getRaster();
double [] iPix=new double [diameter*diameter];
if(diameter%2 == 1) {
diameter-=1;
}
radius=diameter/2;
for(int i=0;i
(radius)){
y=y%(radius);
}
else
{
y-=radius;
y=-y;
}
if((x*x+y*y)<=((radius)*(radius))) { iPix[i]=255; } else { iPix[i]=0; } }
raster.setPixels(0,0,diameter,diameter,iPix); lab=new JLabel(new ImageIcon(bi)); frame.add(lab);

frame.setVisible(true); frame.setSize(600,600);
}
}

compile the program as javac circles.java

run as java circles diameter_value

e.g. java circles 500

Swap two numbers without a ‘=’ operator

Came across an interesting problem of swapping two numbers without using ‘=’ operator. I thought of this approach. It’s little lengthy and can be modified I guess.
____________________________________________________________________________
____________________________________________________________________________

#include
static int counter;
int main()
{
int a,b;
printf(”Enter two numbers”);
scanf(”%d%d”,&a,&b);

if(a>b)
{
switch ((a-b)%2)
{
case 0 :while((a-b))
{
counter++;
a–;
b++;
}
while (counter >0)
{
counter–;
a–;
b++;
}
printf(”\nThe swapped set : %d\t%d”,a,b);
break;
case 1 :while((a-b-1))
{
counter++;
a–;
b++;
}
counter++;
while (counter >0)
{
counter–;
a–;
b++;
}
printf(”\nThe swapped set : %d\t%d”,a,b);
break;
}
}

else
{
switch ((b-a)%2)
{
case 0 :while((b-a))
{
counter++;
a++;
b–;
}
while (counter >0)
{
counter–;
a++;
b–;
}
printf(”\nThe swapped set : %d\t%d”,a,b);
break;
case 1 :while((b-a-1))
{
counter++;
a++;
b–;
}
counter++;
while (counter >0)
{
counter–;
a++;
b–;
}
printf(”\nThe swapped set : %d\t%d”,a,b);
break;
}
}
return 0;
}

____________________________________________________________________________
____________________________________________________________________________