Share on Google+Share on Google+

Sonal jain
Java Program
2 Answer(s)      4 years and 8 months ago
Posted in : Java Beginners

Problem Statement You are required to write a program which, when given a sequence of integers, creates an equation. All but the last integer in the given sequence form an LHS (left-hand-side). The last integer forms an RHS. Operators are inserted between the integers in the LHS to form an expression. Like in any good equation, the LHS must equal the RHS. The operators allowed to be used are: {+, -, *}

You can use any operator at any place and any number of times. An operator can only be placed in between two integers and two integers can have only one operator between them. While evaluating the formed expression, the precedence of operators has to be observed. Note that the positions of integers given cannot be changed.

Thus, if 8, 5, 2, -2 are the integers given, then your program must create the expression: 8 - 5 * 2 = -2 Here, the integers 8, 5, 2 belong to the LHS and integer -2 forms the RHS. The LHS, with placeholders for operators is: 8 5 2. When - and * are inserted, they form an expression: 8 - 5 * 2. Using precedence rules, this evaluates to: 8 - 10, which works out to be equal to RHS.

NOTE:

It is guaranteed that there will be only one possible LHS which equals the RHS. Expression evaluation is done from left to right, thus expression 2-2+2 evaluates to 2 and not -2 Input Specification First line contains one integer K (3 < K < 7) indicating the number of integers The second line contains 'K' integers, each separated by a space Output Specification The operator sequence without any spaces between them terminated by a newline

Sample Test Cases Test Case 1 Input: 4 8 5 2 -2

Output: -*

Test Case 2 Input: 5 1 1 1 1 4

Output: +++

Test Case 3 Input: 5 7 5 3 2 29

Output: -

Ads

View Answers

July 24, 2012 at 1:27 PM


Here is a code that accepts the integers from the users and made an expression which in result satisfied the condition LHS=RHS.

import java.util.Scanner;

public class SequenceOfIntegers
{

    static int num;
    static int result;
    static int lhs[];
    static boolean stop = false;


    public static char getOperator(int num)
    {
        switch (num)
        {
            case 0:
                return '+';
            case 1:
                return '-';
            case 2:
                return '*';
        }
        return '.';
    }

   public static void evaluate(String operators)
    {
        int arr[] = (int[])lhs.clone();
        String answer = operators;

        while (operators.indexOf("-")!=-1)
        {
            int pos = operators.indexOf("-");
            arr[pos+1] = -arr[pos+1];
            operators = operators.substring(0,pos)+"+"+operators.substring(pos+1);
        }

        while (operators.indexOf("*")!=-1)
        {
            int pos=operators.indexOf("*");
            arr[pos+1] = arr[pos]*arr[pos+1];
            arr[pos]=0;
            operators = operators.substring(0,pos)+"+"+operators.substring(pos+1);
        }

        int sum = 0;
        for (int i=0; i<num; i++)
            sum += arr[i];

        if (sum==result)
            System.out.println("Output: "+answer);
    }


   public static void find(String operators)
    {
        if (operators.length() > num-2) 
        {
            evaluate(operators);
            return;
        }

        for (int i=0; i<3; i++)
            find(operators+getOperator(i));
    }

    public static void main(String []s)
    {
            Scanner input = new Scanner(System.in);
            System.out.print("Enter number of Integers: ");
            num = input.nextInt() - 1;
            lhs = new int[num];
            int i;
            System.out.println("Input: ");
            for(i=0; i<num ;i++)
                lhs[i] = input.nextInt();
                result = input.nextInt();

             find("");
    }
}


September 11, 2012 at 4:35 PM


Can u please explain me the concept in detail. I didn't get the concept.










Related Tutorials/Questions & Answers:
java program for
java program for   java program for printing documents,images and cards
Java Program
Java Program  A Java Program that print the data on the printer but buttons not to be printed
Advertisements
a Java program
a Java program    Write a Java program to print even numbers from 2 to 1024? Write a Java program to print ? My Name is Mirza? 100 times? Write a Java program to print Fibonacci Series? Write a Java program to reverse a number
java program
java program  write a program to print 1234 567 89 10
java program
java program  Write a java program to do matrix addition operation On two given matrices
java program
java program  Write a java program to find the number of Positive numbers in m* n matrix
java program
java program  Write a program to create an applet and display The message "welcome to java
java program
java program  java program to implement the reflection of a particular class details like constructor,methods and fields with its modifiers
Java Program
Java Program  java program to insert row in excel sheet after identifying an object
java program
java program  write a java program to display array list and calculate the average of given array
java program
java program  write a java program to display array list and calculate the average of given array
java program
java program  write java program for constructor,overriding,overriding,exception handling
java program
java program  how to write an addition program in java without using arithematic operator
java program
java program  hi friends how to make a java program for getting non prime odd numbers in a given series
java program
java program  Write a program to demonstrate the concept of various possible exceptions arising in a Java Program and the ways to handle them.  ... in Java
java program
java program  write a java program to compute area of a circle.square,rectangle.triangle,volume of a sphere ,cylinder and perimeter of cube using method over riding
java program
java program  write a java program to compute area of a circle.square,rectangle.triangle,volume of a sphere ,cylinder and perimeter of cube using method over riding
java program
java program  write a program to create text area and display the various mouse handling events
java program
java program   Write a program to find the difference between sum of the squares and the square of the sums of n numbers
program in java
program in java  write a reverse program in java using string buffer.the input and out put as follows. input- hi good mornig out put-ih doog ginrom
Java program
Java program  Write a program which performs to raise a number to a power and returns the value. Provide a behavior to the program so as to accept any type of numeric values and returns the results
java program
java program  . Write a program which performs to raise a number to a power and returns the value. Provide a behavior to the program so as to accept any type of numeric values and returns the results
java program
java program  . Develop the program calculatePipeArea. It computes the surface area of a pipe, which is an open cylinder. The program accpets three values: the pipes inner radius, its length, and the thickness of its wall
java program
java program  Develop the program calculatePipeArea. It computes the surface area of a pipe, which is an open cylinder. The program accpets three values: the pipes inner radius, its length, and the thickness of its wall
java program
java program   A B C D E F F E D C B A A B C D E E D C B A A B C D D C B A A B C C B A A B B A A A java program to display above triangle
java program
java program  write a program to create server and client such that server receives data from client using BuuferedReader and sends reply to client using PrintStream
java program
java program  write a program to read 10 numbers from user and store it in a array. display the maximum n minimum number in the array
java program
java program  i want a applet program that accepts two input strings using tag and concatenate the strings and display it in status window. please give mi he code for this in core java
java program
java program  i want a applet program that accepts two input strings using tag and concatenate the strings and display it in status window. please give mi he code for this in core java
java program
java program  i want a applet program that accepts two input strings using tag and concatenate the strings and display it in status window. please give mi he code for this in core java
Java Program
Java Program  I want to Write a program in JAVA to display to create a class called MATRIX using a two-dimensional array of integers. Perform the addition and subtraction of two matrices. Help me
Tutorials   
Java Spring Hibernate Struts Training What does core Java include? java What are some way to learn Java quickly? Is it required to learn Java before learning Java Script? Is it necessary to learn java script before learning PHP? Are HTML5 and Java Script boosts Java career? Is Java object oriented? Fingerprint application with Java Uninstall Oracle Virtual Box JSON to HashMap Free Java online Training I want example of Control Statement in Java ANSI Color Codes with Python Create a Program that Calculates Input What is difference between JDK,JRE and JVM? How to see ubuntu version on server? How to get Page Source in Selenium (WebDriver) using Java? The path to the driver executable must be set by the webdriver.gecko.driver system property parse data from a link in java Java Program Qns using BlueJ How to fix HAX Kernel Module Is Not Installed error? Installing Audacity Looking for code Logic to check track changes & Coments in MSWord, MSWordx, MSExcel, MSExcelx is ON/OFF Installing JDK on Mac SAX Parser exception ERROR 601 (42P00): Syntax error. Encountered Thread java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory How to install Ubuntu 16.04 LTS? HttpServletRequest cannot be resolved to a type in eclipse - Solved Unhandled event loop exception GC overhead limit exceeded Spring Data jpa with apache phoenix Caused by: java.lang.IllegalArgumentException: Not a host:port pair: PBUF o.a.h.h.z.RecoverableZooKeeper - Possibly transient ZooKeeper, quorum= com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager class not found com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager not found How to download and install Java 8 on Windows? How to uninstall JDK 7? How to install gtk-doc-tools package in Ubuntu? How to install Oracle JDK 8 on Ubuntu? ejabberd_ctl.beam not found - Solved How to convert date to UTC format in Java? How to install autoconf, automake and libtool in Ubuntu 15.10? How to convert current date to mm dd yyyy format in Java? How to convert current date to dd mm yyyy format in Java? How to stop window closing in "internalFrameClosing" event. How to find list of all index in Neo4j? neo4j-server.properties file location SASLError using PLAIN: not-authorized how to convert war file into .exe file using java code

Ads

 
Advertisement null

Ads