Stack and Recursive Program to Convert Arithmetic Expressions

//In the name of Allah
/*
Using the Stack and Recursive concept, develop a program to convert arithmetic expressions. The program should be able to:

- Convert from infix to postfix
- Convert infix to prefix

The program must prompt user input an arithmetic infix expression for conversion to either prefix or postfix. The conversion option is wholly dependent to the user; either to postfix or prefix.
---
Infix -> Postfix Rules:
R1: Object operatorStack is empty
R2: if operator, loop until the operator has been pushed onto the operatorStack
-if the operatorStack is empty, or operator have higher precedence than the operator on top of the operatorStack,
-push operator onto operatorStack
-else
-Pop the operatorStack and append that popped operator to the postfix string.
R3: Once reach the end of input string
-loop until operatorStack is empty
-pop the operatorStack object and append that popped operator to the postfix string

**Parentheses:
if leftParentheses "(",
pushed onto the operatorStack
but precedence is lower than any other binary operator
else if rightParenthese ")" is found
operator object is repeatedly popped
popped element appended to postfix string
until operator on top is leftParentheses "("
then that operator "(" is popped but not appended
continue scanning the infix string

Infix -> Prefix Rules:
iNew algorithm
1: Reverse the input string
2: Examine the next element in the input
3. If it is operand, add it into the output string
4. If it is closing parenthesis, push it on stack
5. If it is an operator, then
a. If stack.isEmpty, push operation on stack
b. if the top of the stack is ")", push operator on stack
c. if it has same or higher priority than the top of the stack, push it
d. else pop the operator & add it to output string, repeat 5
6. If it is "(" pop operator and add them to string s until a ")" is encountered . POP and discard ")"
7. If there is more input go to step 2
8. If there is no more input, unstack the remaining operators and add them
9. Reverse the output string
New algorithm
1. if operand push into operand stack
2. if operator
a. if stack is empty or ch="(", push into operator stack
b. if ")", CASE3 until reach "("
c. else, CASE3
3. if endofexpression, CASE3 until operator stack empty
4. return the only operand in operandStack


*Compile: javac 2009147897.java
*Run: java PostfixPrefixApp
Problems still arises1. Can't deal with expression with spaces in it E.g. [a + b]. Must use [a+b]
2. Program are too redundant at certain part: i++; and toPostfix(exp)
3. Thinking that this is more of the brute way rather than
the inteligent way. Maybe can be simplified
4. Operators limited to * / + - %
5. Looping of the program cause unexpected result
6. toPrefix() is not correct.
e.g: Didn't work for (a+b)+c+d, a+(c-h)/(b*d)
*/
import java.util.*;
class PostfixPrefixApp{
/**Global Variables**************************************/
private static Stack operatorStack= new Stack();
private static Stack operandStack= new Stack();
private static String postfix="";
private static String prefix="";
private static String temp="";
private static int i=0; //use i to iterate through infix string [exp.charAt(i)]
private static int menu=0;
public static void main (String [] args){
/**Local Variables***************************************/
Scanner scan = new Scanner(System.in);
String infix;
/**Menu**************************************************/
System.out.println ("\nChanging from infix to postfix or prefix notation.");
System.out.println ("----------");
System.out.println ("Menu");
System.out.println ("----------");
System.out.println ("1. Postfix");
System.out.println ("2. Prefix");
menu = scan.nextInt();

/**Postfix***********************************************/
if ( menu == 1){
System.out.println ("Infix to Postfix");
System.out.print ("Enter infix expression: ");
infix = scan.next();
postfix = toPostfix(infix);
System.out.println("Postfix: "+ postfix);
System.out.println ("----------");
}
/**Prefix************************************************/
else if ( menu == 2){
System.out.println ("Infix to Prefix");
System.out.print ("Enter infix expression: ");
infix = scan.next();// Storing the infix string
infix=reverse(toPrefix(reverse(infix)));
System.out.println("Prefix: "+infix);//display prefix string
}
/**Wrong input*******************************************/
else {
System.out.println ("Wrong input.");
System.out.println ("----------");
}

System.exit(0);
}
/**toPostfix*********************************************/
public static String toPostfix(String exp){
if (exp.length()==i){
/*
for when the infix has finished being processed
because iterate i for the usage of exp.charAt(i)
*/
while (! operatorStack.isEmpty()){
String temp = (String)operatorStack.peek();
if (temp.charAt(0)!='(')//if there is "(" in the operatorStack
postfix+=(String)operatorStack.pop();//pop all element into postfix string
else
operatorStack.pop();//removing "("
}
return postfix; //the last process of the recursion
}
else { //if the infix still being processed
String ch = exp.substring(i,i+1);
if (ch.charAt(0)==')'){//if opening parentheses "(", push it into stack
operatorStack.push(ch);
return redundantFunction(exp);// there are same processes that were simplified in this method instead. Refer "Problems arises"
// or refer the method redundantFunction() below
}
else if (ch.charAt(0)=='('){
/*
if found closing parentheses ')'
loop until reach '('
append poped element of operatorStack into postfix string
remove '(' from operatorStack
*/
String topOfoperatorStack = (String)operatorStack.peek();
while (! topOfoperatorStack.equals("(")){
//String a=(String)operatorStack.pop();
//System.out.println(a); //for testing process
postfix+=operatorStack.pop();
topOfoperatorStack = (String) operatorStack.peek();
}
operatorStack.pop();
//String c= (String) operatorStack.pop();
//System.out.println("c: "+c); //for testing if we correctly removing (
return redundantFunction(exp);
}
else if (isOperand(ch)){
/*
if an operand a-zA-Z atau digit \\d
directly appened to infix
*/
postfix+=ch;
return redundantFunction(exp);
}
else if (isOperator(ch)){
/*
if operators
if empty
directly push into operatorStack
else
see top of operatorStack
if higher precendence
directly push into operatorStack
else
pop topOfoperatorStack
append it to postfix string
push current operator into operatorStack
*/
if (operatorStack.isEmpty()){
operatorStack.push(ch);
return redundantFunction(exp);
}
else {
String topOfoperatorStack = (String)operatorStack.peek();
if (precendence(ch) > precendence(topOfoperatorStack)){
operatorStack.push(ch);
return redundantFunction(exp);
}
else {
postfix+=(String)operatorStack.pop();
operatorStack.push(ch);
return redundantFunction(exp);
}
}
}
else{
//catching all other possible situation supposedly
return redundantFunction(exp);
}
}
}
/**toPrefix**********************************************/
private static String toPrefix(String exp){
temp="";
if (iprecendence( (String) operatorStack.peek() )) ){
operatorStack.push(ch);
}
else{
temp=CASE3();
operandStack.push(temp);
}
}
//System.out.println(ch);//testing
return redundantFunction(exp);
}
else{
while(! operatorStack.isEmpty()){
temp=CASE3();
operandStack.push(temp);
}
//System.out.println("Who is it? : "+operandStack.peek());//testing
/*if (operandStack.isEmpty())//testing
return "operandStack.isEmpty()";
else*/
return (String) operandStack.pop();
}
}
/**isOperator********************************************/
private static boolean isOperator(String ch){//method to check operator
String operators = "*/%+-";
if (operators.indexOf(ch) != -1)
return true;
else
return false;
}
/**isOperand********************************************/
private static boolean isOperand(String ch){//check if it is alphanumeric - method taken from outside sources
if (ch.matches("[a-zA-Z]|\\d"))
return true;
else
return false;
}
/**precedence********************************************/
private static int precendence(String ch){//method that check the precendence of operator and return it

//value 1 or 2
String precendence2 = "*/%";
String precendence1 = "+-";
if (precendence2.indexOf(ch) != -1)
return 2;
else if (precendence1.indexOf(ch) != -1)
return 1;
else
return 0;
}
/**redundantFunction********************************************/
private static String redundantFunction(String exp){
/*redundant processes
need i to iterate through infix string while using recursion technique
*/
i++;
if (menu==1)
return toPostfix(exp); //the recursion part
else
return toPrefix(exp); //the recursion part
}
/**reverse********************************************/
private static String reverse(String exp){
Stack tempString = new Stack();
for (int index=0;index tempString.push( exp.charAt(index) );
}
exp="";
while (! tempString.isEmpty() ){
exp+= tempString.pop();
}
return exp;
}
private static String CASE3(){
String opt="",oprn1="",oprn2="";
opt += operatorStack.pop();
oprn1 += operandStack.pop();
if (operandStack.isEmpty())
oprn2+="";
else
oprn2 += operandStack.pop();
temp=opt+oprn2+oprn1;
//System.out.println("Temp:"+temp);
return temp;
}
}

Create a program that simulates a slot machine

/* Create a program that simulates a slot machine. When the program runs, it should do the
following:
• Asks the user to enter the amount of money he or she wants to enter into the slot
machine.
• Instead of displaying images, the program will randomly select a word from the
following list: Cherries, Oranges, Plums, Bells, Melons, Bars. To select a word, the
program can generate a random number in the range of 0 through 5. If the number is 0,
the selected word is Cherries; if the number is 1, the selected word is Oranges; and so
forth. The program should randomly select a word from this list three times and display
all three of the words.
• If none of the random selected words match, the program will inform the user that he
or she has won $0. If two of the words match, the program will inform the user that he
or she has won two times the amount entered. If three of the words match, the
program will inform the user that he or she has won three times the amount entered.
• The program will ask whether the user wants to play again. If so, these steps are
repeated. If not, the program displays the total amount of money entered into the slot
machine and the total amount won.*/

public static void main(String[] args) {
       //define var
        //String Cherries, Oranges, Plums, Bells, Melons, Bars;
        int one,two,three,four,five,num,count;
        double bet;
        Random rand = new Random();
     
       
        Scanner keyboard = new Scanner (System.in); //New scanner class
   
        System.out.print("How much would you like to bet? ");//get's user input and bet
        bet = keyboard.nextDouble();
       
        for (count=1; count<=3;count++)
        {
     
         int picked = rand.nextInt(6);
           
         switch (picked){
               case 0:
                    System.out.print("Bells ");word=1;
                    break;
               case 1:
                    System.out.print("Cherries "); word=1;
                    break;
               case 2:
                    System.out.print("Orange "); word=1;
                    break;
               case 3:
                    System.out.print("Plums "); word=1;
                    break;
               case 4:
                    System.out.print("Melons "); word=1;
                    break;
              case 5:
                    System.out.print("Bars "); word=1;
                    break;
         
            }

     
        }
}
//I can get the code to print the 3 words at random but I need to save the output to a different variable each time the for loop runs any suggestions?

Simple Commission Calculation Program

Java Simple Commission Calculation Program


import java.util.Scanner ;

public class CommissionCalculator3
{
    public static void main(String[] args)
   {
   // define variables & initialize them
   double salary = 50000.00 ;   // Salesperson fixed salary $50000
   double rate = .05 ;         // Salesperson commission rate 5%
   double annual;       // Inputted annual sales
   double compensation;    // Annual compensation
   double target= 120000;   // Target sales
   double acceleration = .015; // Acceleration factor for sales over $120,000
   double rate2 = .08;  // Sales incentive starts when 80% of sales target is met.
   
   // Output message for user to input annual sales
   System.out.println("Please input annual sales: ") ;
   Scanner input = new Scanner(System.in) ;
   annual = input.nextDouble() ;
   compensation = annual * rate + salary ;

   // Output information for user to receive annual compensation information
   System.out.println("Your annual compensation is: " + compensation) ;
 
   // Output information for displaying the table of potential total annual
   // compensation.
   System.out.println("Total Sales\t\tTotal Compensation");
   System.out.println("------------------------------------");

   {
       if(annual <=80.0*target/100.0)
        compensation = 0;
       else if(annual <=target)
         
        if(annual = 25.0*target/100.0);
        else compensation = 25.0*annual/100+
                rate2*annual;
   }
   }
   
}
   


The company has recently changed its total annual compensation policy to improve sales.

A salesperson will continue to earn a fixed salary of $50,000. The current sales target for every salesperson is  $120,000.

The sales incentive will only start when 80% of the sales target is met. The current commission is 5% of total sales.

If a salesperson exceeds the sales target, the commission will increase based on an acceleration factor. The acceleration factor is 1.5.

The application should ask the user to enter annual sales, and it should display the total annual compensation.

The application should also display a table of potential total annual compensation that the salesperson could have earned, in $5000 increments above the salesperson’s annual sales, until it reaches 50% above the salesperson’s annual sales.

Sample Table: Assuming a total annual sales of $100,000, the table would look like this:

Total Sales Total Compensation
100,000 <<Program calculated value>>
105,000 <<Program calculated value>>
110,000 <<Program calculated value>>
115,000 <<Program calculated value>>
120,000 <<Program calculated value>>
125,000 <<Program calculated value>>
130,000 <<Program calculated value>>
135,000 <<Program calculated value>>
140,000 <<Program calculated value>>
145,000 <<Program calculated value>>
150,000 <<Program calculated value>>

The Java™ application should also meet these technical requirements:

The application should have at least one class, in addition to the application’s controlling class.
The source code must demonstrate the use of conditional and looping structures.
There should be proper documentation in the source code.

Use Sqoop in Java Program

How to use Sqoop in Java Program?

final int ret = Sqoop.runTool(new String[] { ... });
if (ret != 0) {
  throw new RuntimeException("Sqoop failed - return code " + Integer.toString(ret));
}

Bit Sort Program in Java

How to write bit sort program in Java?

#include <stdio.h>
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000
int a[1 + N/BITSPERWORD];

void set(int i) {
    a[i>>SHIFT] |=  (1<<(i & MASK));
}

void clr(int i) {
    a[i>>SHIFT] &= ~(1<<(i & MASK));
}
int  test(int i){
    return a[i>>SHIFT] &   (1<<(i & MASK));
}

int main()
{   int i;
    for (i = 0; i < N; i++)
        clr(i);
/*  Replace above 2 lines with below 3 for word-parallel init
    int top = 1 + N/BITSPERWORD;
    for (i = 0; i < top; i++)
        a[i] = 0;
 */
    while (scanf("%d", &i) != EOF)
        set(i);
    for (i = 0; i < N; i++)
        if (test(i))
            printf("%dn", i);
    return 0;
}

int a[1 + N/BITSPERWORD]; // allocates BitSet of N size

Java NIO Example

Simple Echo Server - Binds to both TCP and UDP ports 5050, and 5051 and will echo all data received to all other connections. It will treat all data as a String so use "telnet localhost 5050" or if you have netcat you can use "nc -u localhost 5050" to send udp packets to the server.

Solution:
/*
Simple Echo Server
Binds to both TCP and UDP ports 5050, and 5051
and will echo all data received to all other
connections. It will treat all data as a String
so use "telnet localhost 5050" or if you have
netcat you can use "nc -u localhost 5050" to
send udp packets to the server.
*/
package nioexample;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.TimeUnit;

public class NioExample implements Runnable{
   
    final private Thread nioThread;
    final private Selector selector;
   
    final private Queue<Runnable> runnableQueue = new LinkedList<Runnable>();
   
    final private List<Attachment> attachments = new ArrayList<Attachment>();
   
    public NioExample() throws IOException{
        selector = Selector.open();
        nioThread = new Thread(this);
        nioThread.setName("NioExample");
    }
   
    public void start(){
        if(!nioThread.isAlive()) nioThread.start();
    }
   
    @Override
    public void run() {
        ByteBuffer reusableBuffer = ByteBuffer.allocate(0x4000);
        while(selector.isOpen()){
            if(!runnableQueue.isEmpty()) handleQueue();
            try{
                handleSelect(reusableBuffer);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
   
    public void runOnNioThread(Runnable runnable){
        synchronized(runnableQueue){
            runnableQueue.add(runnable);
            selector.wakeup();
        }
    }
   
    private void handleQueue(){
        synchronized(runnableQueue){
            Runnable runnable;
            while((runnable = runnableQueue.poll()) != null) runnable.run();
        }
    }
   
    private void handleSelect(ByteBuffer buffer) throws IOException{
        int totalKeys = selector.select();
        Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
        while(selectedKeys.hasNext()){
            buffer.clear();
            SelectionKey key = selectedKeys.next();
            SelectableChannel channel = key.channel();
            Attachment attachment = (Attachment)key.attachment();
            try{
                if(key.isValid()){
                    if(key.isReadable()){
                        if(channel instanceof DatagramChannel){
                            DatagramChannel dChannel = (DatagramChannel)channel;
                            SocketAddress remote = dChannel.receive(buffer);
                            if(remote != null){
                                buffer.flip();
                                attachment.onReceiveData(buffer, remote);
                            }else{
                               
                            }
                        }else if(channel instanceof SocketChannel){
                            SocketChannel sChannel = (SocketChannel)channel;
                            int bytesRead = sChannel.read(buffer);
                            buffer.flip();
                            if(bytesRead == -1){
                                key.cancel();
                                attachment.onClosed();
                            }else{
                                attachment.onReceiveData(buffer);
                            }
                        }
                    }else if(key.isAcceptable()){
                        ServerSocketChannel ssChannel = (ServerSocketChannel)channel;
                        SocketChannel sChannel = ssChannel.accept();
                        sChannel.configureBlocking(false);
                        Attachment sAttachment = new Attachment();
                        sAttachment.channel = sChannel;
                        sChannel.register(selector, SelectionKey.OP_READ, sAttachment);
                        sAttachment.onStart();
                    }
                }else{ //INVALID KEY
                   
                }
            }catch(Exception e){
                key.cancel();
                attachment.onClosed();
                e.printStackTrace();
            }finally{
                selectedKeys.remove();
            }
        }
    }
   
    public Attachment createServerSocket(final SocketAddress address){
        final Attachment attachment = new Attachment();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    ServerSocketChannel ssChannel = ServerSocketChannel.open();
                    attachment.channel = ssChannel;
                    ssChannel.configureBlocking(false);
                    ssChannel.socket().bind(address);
                    ssChannel.register(selector, SelectionKey.OP_ACCEPT, attachment);
                    attachment.onStart();
                } catch (IOException e) {
                    attachment.onClosed();
                    e.printStackTrace();
                }
            }
        };
        runOnNioThread(runnable);
        return attachment;
    }
   
    public Attachment createDatagramSocket(final SocketAddress address){
        final Attachment attachment = new Attachment();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    DatagramChannel dChannel = DatagramChannel.open();
                    attachment.channel = dChannel;
                    dChannel.configureBlocking(false);
                    dChannel.socket().bind(address);
                    dChannel.register(selector, SelectionKey.OP_READ, attachment);
                    attachment.onStart();
                } catch (IOException e) {
                    attachment.onClosed();
                    e.printStackTrace();
                }
            }
        };
        runOnNioThread(runnable);
        return attachment;
    }
   
    public void sendToAll(ByteBuffer buffer){
        for(Attachment a:attachments){
            try {
                if(a.channel instanceof SocketChannel){
                    a.send(buffer);
                    buffer.flip();
                }else if(a.channel instanceof DatagramChannel){
                    a.sendToAll(buffer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
   
    public static void main(String[] args) throws IOException {
        NioExample nio = new NioExample();
        nio.start();
        nio.createServerSocket(new InetSocketAddress(5050));
        nio.createServerSocket(new InetSocketAddress(5051));
        nio.createDatagramSocket(new InetSocketAddress(5050));
        nio.createDatagramSocket(new InetSocketAddress(5051));
    }
   
    public class Attachment{
        SelectableChannel channel;
        Map<SocketAddress, Long> remoteAddresses = new HashMap<SocketAddress, Long>();
        void onStart(){
            attachments.add(this);
            System.out.println("Started Listening " + channel);
        }
        void onReceiveData(ByteBuffer buffer){
            System.out.printf("Received TCP(%s): %s\n",
                    ((SocketChannel)channel).socket().getRemoteSocketAddress(),
                    new String(buffer.array(), buffer.position(), buffer.limit()));
            NioExample.this.sendToAll(buffer);
        }
        void onReceiveData(ByteBuffer buffer, SocketAddress remote){
            remoteAddresses.put(remote, System.currentTimeMillis());
            System.out.printf("Received UDP(%s): %s\n",
                    remote, new String(buffer.array(), buffer.position(), buffer.limit()));
            NioExample.this.sendToAll(buffer);
        }
        void onClosed(){
            attachments.remove(this);
            System.out.println("Closed " + channel);
        }
       
        public synchronized void send(ByteBuffer data) throws IOException{
            SocketChannel sChannel = (SocketChannel)channel;
            sChannel.write(data);
        }
       
        public synchronized void sendTo(ByteBuffer data, SocketAddress remote) throws IOException{
            if((System.currentTimeMillis() - remoteAddresses.get(remote)) > (TimeUnit.MINUTES.toMillis(5))){
                remoteAddresses.remove(remote);
                System.out.println("Deleted Entry " + remote);
                return;
            }
            DatagramChannel dChannel = (DatagramChannel)channel;
            dChannel.send(data, remote);
        }
       
        public void sendToAll(ByteBuffer data) throws IOException{
            Iterator<SocketAddress> addresses = remoteAddresses.keySet().iterator();
            while(addresses.hasNext()){
                sendTo(data, addresses.next());
                data.flip();
            }
        }
    }
}