Showing posts with label Java (programming language). Show all posts
Showing posts with label Java (programming language). Show all posts

Thursday, July 16, 2015

Memory Puzzle game in Java

Memory puzzle is a simple puzzle game of flipping and discovering pairs of similar cards. The player flips inverted cards one by one. If two cards flipped are same, they stay in that state, else they are flipped back to their original inverted state. The game ends when all the cards are flipped in pairs successfully.

Screenshot

[Image: memorypuzzle.png]

Source Code

Cards.java

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;


public class Cards {

private static BufferedImage card[] = new BufferedImage[9];
private static BufferedImage cardBack;

private static String cardFileName[] = {"1.jpg", "2.jpg", "3.jpg", "4.jpg",
"5.jpg", "6.jpg", "7.jpg", "8.jpg", "9.jpg"};
private static String cardBackName = "back.jpg";

static {
for(int i = 0; i < cardFileName.length; i++) {
try {
card[i] = ImageIO.read(Cards.class.getResourceAsStream(cardFileName[i]));
}
catch(Exception e) {
e.printStackTrace();
}
}

try {
cardBack = ImageIO.read(Cards.class.getResourceAsStream(cardBackName));
}
catch(Exception e) {
e.printStackTrace();
}
}

public static BufferedImage get(int v) {
return card[v];
}
public static BufferedImage getBack() {
return cardBack;
}
}

CardSlot.java

import java.awt.image.BufferedImage;


public class CardSlot {
private BufferedImage image;
private boolean visible, pairedUp;
private int value;

public CardSlot(int card) {
value = card;
image = Cards.get(card);
visible = false;
pairedUp = false;
}

public boolean isVisible() {
return visible;
}
public boolean flipCard() {
if(!pairedUp) {
visible = !visible;
return true;
}
return false;
}

public boolean isPairedUp() {
return pairedUp;
}
public void pairUp() {
pairedUp = true;
}

public BufferedImage getImage() {
if(isVisible())
return image;
else
return Cards.getBack();
}

public int getValue() {
return value;
}
}

Game.java

import java.awt.event.KeyEvent;
import java.util.Random;


public class Game {
private int width;
private int difficulty;
private int[][] board;
private int zX, zY;
private int forbidden;

public Game(int width, int difficulty) {
this.width = width;
this.difficulty = difficulty;

board = new int[width][width];

int ctr = 1;
for(int i = 0; i < width; i++) {
for(int j = 0; j < width; j++) {
board[j][i] = ctr++;
}
}
board[width - 1][width - 1] = 0;
zX = width - 1;
zY = width - 1;
forbidden = 2;

shuffle();
}

private void shuffle() {
Random random = new Random();
int i = 0;
while(i < difficulty) {
int v = random.nextInt(4);

switch(v) {
case 1:
if(up() && forbidden != 1) {
i++;
forbidden = 2;
}
break;
case 2:
if(down() && forbidden != 2) {
i++;
forbidden = 1;
}
break;
case 3:
if(left() && forbidden != 3) {
i++;
forbidden = 4;
}
break;
case 4:
if(right() && forbidden != 4) {
i++;
forbidden = 3;
}
break;
}
}
}

private boolean up() {
if(zY > 0) {
board[zX][zY] = board[zX][zY - 1];
board[zX][zY - 1] = 0;
zY--;
return true;
}
return false;
}
private boolean down() {
if(zY < width - 1) {
board[zX][zY] = board[zX][zY + 1];
board[zX][zY + 1] = 0;
zY++;
return true;
}
return false;
}
private boolean left() {
if(zX > 0) {
board[zX][zY] = board[zX - 1][zY];
board[zX - 1][zY] = 0;
zX--;
return true;
}
return false;
}
private boolean right() {
if(zX < width - 1) {
board[zX][zY] = board[zX + 1][zY];
board[zX + 1][zY] = 0;
zX++;
return true;
}
return false;
}

public boolean isCorrect() {
int ctr = 1;
for(int i = 0; i < width; i++) {
for(int j = 0; j < width; j++) {
if(board[j][i] == ctr++ || (i == width - 1 && j == width - 1))
continue;
else
return false;
}
}
return true;
}

public int getValueAt(int x, int y) {
if(x >= 0  && x <= width - 1 && y >= 0 && y <= width-1) {
return board[x][y];
}
return 0;
}

public void keyPressed(int key) {
switch(key) {
case KeyEvent.VK_UP:
up();
break;
case KeyEvent.VK_DOWN:
down();
break;
case KeyEvent.VK_LEFT:
left();
break;
case KeyEvent.VK_RIGHT:
right();
break;
}
}
}

SlidingPuzzlePanel.java

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class SlidingPuzzlePanel extends JPanel {

private static final long serialVersionUID = 4501938941435763747L;

private static final int SIDE = 4;
private static final int FONT_SIZE = 40;
private static int LEVEL = 10;

private Game game;
private Font font;
private Color background, foreground, borderColor;

private int slotWidth, slotHeight, slotXOffset, slotYOffset;

private int inX, inY, xOffset, yOffset;
private boolean dragged;

public SlidingPuzzlePanel() {
game = new Game(SIDE, LEVEL);
font = new Font(Font.SERIF, Font.BOLD, FONT_SIZE);

slotWidth = SlidingPuzzle.WIDTH / SIDE;
slotHeight = SlidingPuzzle.HEIGHT / SIDE;
slotXOffset = slotWidth / 2 - FONT_SIZE / 4;
slotYOffset = slotHeight / 2 + FONT_SIZE / 3;

background = new Color(123, 155, 232);
foreground = new Color(123, 255, 132);
borderColor = new Color(223, 255, 132);
dragged = false;

setFocusable(true);
requestFocus();

addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if(dragged) {
inX = e.getXOnScreen() - xOffset;
inY = e.getYOnScreen() - yOffset;
SlidingPuzzle.frame.setLocation(inX, inY);
}
else {
dragged = true;
xOffset = e.getX();
yOffset = e.getY();
}
}

@Override
public void mouseMoved(MouseEvent e) {
dragged = false;
}
});

addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch(key) {
case KeyEvent.VK_ESCAPE:
SlidingPuzzle.frame.dispose();
break;
default:
game.keyPressed(key);
repaint();
if(game.isCorrect()) {
JOptionPane.showMessageDialog(SlidingPuzzle.frame, "You Win!");
LEVEL += 10;
game = new Game(SIDE, LEVEL);
repaint();
}
}
}
});
}

@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setFont(font);
g2d.setColor(background);
g2d.fillRect(0, 0, getWidth(), getHeight());
drawBorders(g2d);

g2d.setColor(foreground);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(game.getValueAt(j, i) != 0)
g2d.drawString(""+game.getValueAt(j, i), slotXOffset + j * slotWidth,
slotYOffset + i * slotHeight);
}
}
}
private void drawBorders(Graphics2D g2d) {
g2d.setColor(borderColor);
for(int i = 0; i < 3; i++)
g2d.drawRect(i, i, SlidingPuzzle.WIDTH - 1 - 2 * i, SlidingPuzzle.HEIGHT - 1 - 2 * i);

for(int  i = 1; i < 4; i++) {
int level = i * slotHeight;
g2d.drawLine(0, level, SlidingPuzzle.WIDTH, level);
g2d.drawLine(0, level + 1, SlidingPuzzle.WIDTH, level + 1);
g2d.drawLine(0, level + 2, SlidingPuzzle.WIDTH, level + 2);

g2d.drawLine(level, 0, level, SlidingPuzzle.HEIGHT);
g2d.drawLine(level + 1, 0, level + 1, SlidingPuzzle.HEIGHT);
g2d.drawLine(level + 2, 0, level + 2, SlidingPuzzle.HEIGHT);
}
}
}

SlidingPuzzle.java

import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class SlidingPuzzle {
public static final int WIDTH = 512;
public static final int HEIGHT = 512;

public static JFrame frame;

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
frame = new JFrame("Sliding Puzzle");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setUndecorated(true);
frame.setSize(WIDTH, HEIGHT);

SlidingPuzzlePanel spp = new SlidingPuzzlePanel();
frame.add(spp);

frame.setVisible(true);
}
});
}
}


Download Runnable Jar:- Memory Puzzle 
Credits for Game:- Solixious

Continue Reading →

Wednesday, July 15, 2015

Space Warrior Game in Java

The game simply consists of a ship that travels through space encountering asteroids and villains in the way. The game ends when the final boss is destroyed. FYI, I myself could not complete this game, except in the testing stage where I manipulated code to call boss very early.

Screenshots:

[Image: sw1.png]

[Image: sw2.png] 

[Image: sw3.png] 

Runnable JAR : space_warrior.jar
Java 8 or higher is recommended for execution of the runnable JAR file.

Github Link : Space Warrior

Credits for the sprite images go to Ari Feldman.

Credits for this Game :- Solixious

 
Continue Reading →

Monday, June 29, 2015

Code for Damerau Lavenshtein Distance in Java

Earlier I had posted a tutorial on Fuzzy String Matching with Python Code. Here in this post I am sharing the Damerau Lavenshtein Algorithm Code in Java.

package com.codehackersblog.editdistance;

/**
*
* @author psychocoder
* @version 1.0
*/
public class DamerauLavenshtein {

    private String s1;
    private String s2;
    private int len_s1;
    private int len_s2;

    public DamerauLavenshtein() {
        s1 = null;
        s2 = null;
    }

    public DamerauLavenshtein(String s1, String s2) {
        this.s1 = s1.toLowerCase();
        this.s2 = s2.toLowerCase();
    }

    private void putValue(String m, String n) {
        s1 = m.toLowerCase();
        s2 = n.toLowerCase();
    }

    private int getMinimum(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }

    private int getDamerauLavenshtein() {

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        if (len_s1 == 0) {
            return len_s2;
        }

        if (len_s2 == 0) {
            return len_s1;
        }

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    cost = 0;
                } else {
                    cost = 1;
                }

                d[i][j] = getMinimum(
                        d[i - 1][j] + 1, /*Deletion*/
                        d[i][j - 1] + 1, /*Insertion*/
                        d[i - 1][j - 1] + cost /*Substitution*/
                );

                if (i > 1 && j > 1 && s1.charAt(i - 1) == s2.charAt(j - 1)
                        && s2.charAt(j - 1) == s1.charAt(i - 1)) {
                    d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);  /*transposition*/

                }
            }
        }

        return d[len_s1][len_s2];
    }

    private int getDamerauLavenshtein(String s1, String s2) {

        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    cost = 0;
                } else {
                    cost = 1;
                }

                d[i][j] = getMinimum(
                        d[i - 1][j] + 1, /*Deletion*/
                        d[i][j - 1] + 1, /*Insertion*/
                        d[i - 1][j - 1] + cost /*Substitution*/
                );

                if (i > 1 && j > 1 && s1.charAt(i - 1) == s2.charAt(j - 1)
                        && s2.charAt(j - 1) == s1.charAt(i - 1)) {
                    d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);  /*transposition*/

                }
            }
        }

        return d[len_s1][len_s2];

    }

    public static void main(String... args) {
        DamerauLavenshtein ob = new DamerauLavenshtein("Ludo", "lludo");
        System.out.println(ob.getDamerauLavenshtein());
        System.out.println(ob.getDamerauLavenshtein("Hello", "olhel"));
    }

}

Continue Reading →

Code for Wagner Fisher Algorithm in Java

Earlier I had posted a tutorial on Fuzzy String Matching with Python Code. Here in this post I am sharing the Wagner Fisher Algorithm Code in Java.

package com.codehackersblog.editdistance;

/**
*
* @author psychocoder
* @version 1.0
*/
public class WagnerFisher {

    private String s1;
    private String s2;
    private int len_s1;
    private int len_s2;

    public WagnerFisher() {
        s1 = null;
        s2 = null;
    }

    public WagnerFisher(String s1, String s2) {
        this.s1 = s1.toLowerCase();
        this.s2 = s2.toLowerCase();
    }

    private void putValue(String m, String n) {
        s1 = m.toLowerCase();
        s2 = n.toLowerCase();
    }

    private int getMinimum(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }

    private int getWagnerFisher() {

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    d[i][j] = d[i - 1][j - 1];
                } else {

                    d[i][j] = getMinimum(
                            d[i - 1][j] + 1, /*Deletion*/
                            d[i][j - 1] + 1, /*Insertion*/
                            d[i - 1][j - 1] + 1 /*Substitution*/
                    );
                }
            }
        }

        return d[len_s1][len_s2];
    }

    private int getWagnerFisher(String s1, String s2) {

        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    d[i][j] = d[i - 1][j - 1];
                } else {

                    d[i][j] = getMinimum(
                            d[i - 1][j] + 1, /*Deletion*/
                            d[i][j - 1] + 1, /*Insertion*/
                            d[i - 1][j - 1] + 1 /*Substitution*/
                    );
                }
            }
        }

        return d[len_s1][len_s2];

    }

    public static void main(String... args) {
        WagnerFisher ob = new WagnerFisher("loookes", "looks");
        System.out.println(ob.getWagnerFisher());
        ob.putValue("Hiya", "Hey");
        System.out.println(ob.getWagnerFisher());
        System.out.println(ob.getWagnerFisher("Hello", "Heoll"));
    }

}

Continue Reading →

Wednesday, June 24, 2015

PDF File Generation example in Java using iText Library

made an example where reports can be generated in PDF file format using iText library for Java. I made a swing app and we enter the data and then click the create pdf button to generate the pdf. Its not a tutorial but more like an example with a demo. Use the code, and I hope its readable enough.

[Image: 2Ssa87i.png]


Continue Reading →

Friday, June 19, 2015

Learning About the Stack Data Structure

Simple representation of a stack
Simple representation of a stack (Photo credit: Wikipedia)
Hello Everyone,

Today we will study about the data structure called Stack. But before roceeding with the tutorial I would like to read the following readers note.

Reader's Note :
Now we are good to start, So, Let's Begin.


Stack : A stack is a particular kind of abstract data type or collection in which the principal (or only) operations on the collection are the addition of an entity to the collection. The operations that are performed on the the stack are push which means to insert an element at the top of the stack and pop which means to remove the top element from the stack.
Stack follows LIFO (Last In First Out) Principle, that is the element which is inserted into a collection last is taken out first from the collection as well.
The concept of stack data structure is from from development point of view and it has found numerous applications, include system level design and making efficient processes.

Applications of Stack
 
1. Data Parsing
2. Compiler Designing.
3. Recursion
4. Solving numerous Classical problems like Tower of Hanoi.
5. System Memory Management.
6. Reversing String.
7. Mathematical Expression evaluation. (Converting them from infix to postfix and then manipulating evaluating them)
8. Backtracking.
etc...
 
Stack as an Abstract datatype


StackADT {

push(item) : insert the item into the stack


pop() : removes the top element.
size() : Returns the size of the stack.
isEmpty() : checks whether the stack is empty or not.
isFull() : checks whether the stack is full or not.
}
Now let us understand the concept of stack better by taking an example :-
 
Suppose we consider an array of the following elements :-

5 <--- Top element
6
7
8
9
 
Now we push another number onto the stack, say 34, then our stack has the following structure :-

34 <--- Top element.
5
6
7
8
9
 
So it is evident that the most recently inserted items are push onto the top of the stack following the LIFO principle. Again we push another number into the stack, say 2, just following the above concept we have the following :-

2 <--- Top element.
34
5
6
7
8
9
 
We have understood the push operation and so lets see how does pop works. Lets pop once from the above array and the array becomes :-

34 <--- Top element.
5
6
7
8
9
 
As you can see the top element was poped from the stack and the next element that is 34 becomes the top element. Okay so lets pop two more elements and then the stack has the following structure :-

6 <--- Top element.
7
8
9
 
What happened above ?
 
First 34 is poped and then 5 becomes the top element and then another element i.e. 5 is poped and 6 becomes the top element.
I hope you have understood the concept of stack. Since we have understood the concept of stack and so lets write some code now. I will use Java to write the code. We create an interface to understand the concept of our ADT.

StackInterface.java


JStackArray.java

A Visual or Animated Representation of Stack can be found here

Okay, We are now ready to study some applications of Stack. So lets begin.

Example of an Application of Stack

String Reverse.

A Stack can be used to reverse a list, integer, string etc. Lets Look at the following example to understand the concept better :-

Suppose we have a string variable NAME and a string value of "Firun" assigned to it.

String NAME = "Firun";

Now since Stack follows the LIFO principle so if we insert every character from NAME into the stack then we will have 'n' as the top element. Then we can pop the elements we will have our Strings reversed. Look at the following working :-

1. Insert 'F' into Stack. We have

'F' <--- Top

2. Insert 'i' into Stack. We have

'i' <--- Top
'F'

3. Subsequently we insert the remaining characters as well and we get the following Stack structure.

'n' <--- Top
'u'
'r'
'i'
'F'

Now we pop all the elements from the stack and we have the following sequence :-

'u' <--- Top
'r'
'i'
'F'

We get 'n'

'r' <--- Top
'i'
'F'

We get 'u'. Also initially we had 'n' and so now we add 'u' to it and we get "nu". Proceeding in a similar way we get the final string as "nuriF".

I hope you understood the logic. So lets peep at the function code :-

private String reverseString(){
       String m="";
       for(int i=0;i<str.length();i++){
           stack.push(str.charAt(i));
       }
       for(int i=0;i<str.length();i++){
          m=m+stack.pop();
       }
       return m;
   }

Algorithm

PROCEDURE REVERSE_STRING(M) {
    INITIALISE LEN = LENGTH(M)
    FOR I TO LEN:
        STACK.PUSH(M[I])
    FOR I TO LEN:        
        N = N + STACK.POP()
    RETURN N
}

If you are able to make it to this end then it probably means that you have read the tutorial. I hope you enjoyed it. If you have any questions or doubts then feel free to ask.

Stacks are very useful and they reduce your workload, but it solely depends on the programmer how efficiently he uses these concepts. More applications of Stack like Conversion to different notations and Tower of Hanoi will be covered separately.

Feedback would be appreciated. Comment in the comment section below.


Thank you,
Sincerely,
Psycho_Coder.
Continue Reading →

Tuesday, June 16, 2015

Visual Stack Application in Java

I made an application to graphically demonstrate the working of Stack. So, I made this application called Visual Stack which allows the users to interact and understand the working of Stack. In this post I have posted about VisualStack. Read ahead to get to know more about it.

Stack
Stack is a data structure that follows the LIFO (Last-In-First-Out) principle. Newly added elements are added to the top and the most recent inserted data are to be removed first as well.

Visual Stack
This applet is very simple and shows the working of a stack.

Video Demonstration


Screenshot

[Image: visualstack_zps5e183d58.png]

Description
We have a text area and you need to write certain commands for this to work. We need to know about the stack ADT first. A stack does the following operations :-

1. Push ; Pushes an element to the top.
2. Pop: Removes the top element
3. peek: Returns the top element.
4. size: returns the size of the stack.

We have 5 keywords here, namely - push, pop, top, size, and delay.

push and delay work as the following syntax :- 
<instruction> <single-space> <data>

push :- Push the data into the stack. Example : push you, push 2, push IAmDull etc
delays : delay the update of the stack and its visualization.

pop, top, size are single instructions.

pop : pops the top element.
top :
Shows the top element in logs.
size : Shows the size of the stack in logs.

Project on Github :- https://github.com/rawCoders/VisualStack


Related articles
Continue Reading →

Monday, June 15, 2015

Bag Data Structure Implementation in Java


A Bag is a collection where removing items is not supported. It purpose is to provide users with the ability to collect items and then to iterate through the collected items. At the end you have an option to empty the complete bag.

In this implementation you have an additional method to increase the Bag storage.

You can get the eclipse project and the project jar from here.

You can simply run the jar file from the terminal as :- 

java -jar Bag.jar

It will simply show you the output the sample test file for the Bag DS. I will provide the source for the test file which shows how to use it. Here's the code :-


Output  :- 

Initial Size of Bag (No of elements): 0
Capacity (No. of items the bag can hold) :5
Size of Bag after inserting items : 4
Capacity of Bag after extending the size :10
Size of Bag after inserting more items : 8
Elements present in the Bag :- 

12
212
1
123
142
12
19
131
No. of elements in the Bag (When used counter) :8
Size of Bag after clearing : 0


I hope you liked this post. Share it in your social networks.

Thank you.

Continue Reading →

Image to ASCII ART converter in Java

English: ascii art example. "Block" ...
English: ascii art example. "Block" or "High ASCII" style, cf. ANSI art. (Photo credit: Wikipedia)

ASCII art is a graphic design technique that uses computers for presentation and consists of pictures pieced together from the 95 printable (from a total of 128) characters defined by the ASCII Standard from 1963 and ASCII compliant character sets with proprietary extended characters (beyond the 128 characters of standard 7-bit ASCII). The term is also loosely used to refer to text based visual art in general.
-- From Wikipedia

Ascii Art is pretty cool and there are several online services available which allow you to use convert an image to its ASCII ART form. These are often used in image boards or online communities as Avatar images. So I made a little java program which takes an image and converts it to its ASCII form.

How to Use ?

This code doesn't takes command line input so you need to pass the image name with extension in the main function.

Example :-

obj.convertToAscii("Absolute_Path_To_Your_Image.jpg");

When you run the code a text file "asciiart.txt" is created which has the Ascii Art of the image you gave as input. For better vision of the converted image set the font size to 2 or 1. 
Source Code
Sample Run :-

The image I used is :-

[Image: 2YpkRjy.png]

The output is (See the text in notepad)

[Image: i0J2jdp.png]
Sample Demo 2
Input Image
 
Output
I hope you learned something new and will be using this code to make your own ASCII art from images. See you later :) 
Continue Reading →

Math Expression Parser in Java

Hello Everyone,

Today I am sharing a simple math expression parser that I made. This parser can parse and evaluate math expressions.

About the Parser
This parser supports many trigonometric functions and logarithmic and some general functions like exp, sqrt, abs etc. See the snapshots and everything will be clear. See the third screen shots for examples and their output

Description :

This parser is a simple math expression parser that parses and evaluates various mathematical functions.
Triginometric functions :  sin, cos, tan, arctan, arccos,arcsin, sec, cosec,cot
Logarithms :  ln is used for natural log, log10 is log base 10 and log2 is log base 2
Other functions : exp for exponentiation, abs for absolute value, sqrt for square root
Numbers like 45.3e-13 are also supported

This parser can also take functions of one variable like a math relation log10(x*sin(30*x)) with a variable x. Whenever such expressions are encountered you are asked to enter the value of x.

Please Note :

  1. Trigonometric functions work with radians and not degrees
  2. sin x is not valid but sin(x) or sin (x) is valid. Similarly its true for others too
  3. This parser also skips whitespaces and so it will work as long as parenthesis are in correct order

Type help, description, usage for assistence and exit to leave.

Usage : Type any mathematical expression with the functions stated above in the description example : sin(2*x)*cos(x)

 
Screenshots

[Image: mathparser1_zps115f779f.png]

[Image: mathparser2_zps03449d3d.png]

[Image: mathparser3_zpsddeb5dbb.png]
You must have Java 7. Open terminal and type :-

java -jar MathExpressionParser.jar

Note:- You must have set CLASSPATH and JAVA_HOME. If not then google for "how to set classpath in java".

Thank you,
Sincerely,
Psycho_Coder
Continue Reading →

L-Systems Dragon Curve Fractal in Java

I just love generative art and fractals. I made another fractal called Dragon Curve in Java. In this post I will share the code for the fractal.

Here's the code

Image generated

[Image: vpmPoOv.png] 

I simply modified it a bit again and got something like following :- 

[Image: jN1OGL7l.png] 

Code for the modified one is as follows :- 

Continue Reading →

Read Character Files line by line in Java version 6 or less

Duke, the Java Mascot, in the waving pose. Duk...
Duke, the Java Mascot, in the waving pose. Duke images are now Free Graphics see duke:Project Home Page for more details. (Photo credit: Wikipedia)

In this post I am sharing a code on how to read character files line by line for Java version 6 or less. The current java version being 8 and the way to read the files is a bit different, like we use Java NIO primarily. Still for the sake of knowledge this post will help you clear some concepts.

The following source shows you the way to read a file in Java version 6 or less (compatible with JDK 5 but not 4)

It covers most of the error handling cases possible and note that we should close BufferedReader when not in use. The following prints the time taken by the code to read the file and total number of the contents read (In this case I read a file containing all the words of a dictionary)



Related articles
Continue Reading →

Follow Me!

Followers

Visitor Map