Google Answers Logo
View Question
 
Q: Java methods wanted ( Answered 5 out of 5 stars,   0 Comments )
Question  
Subject: Java methods wanted
Category: Computers > Programming
Asked by: meme123-ga
List Price: $25.00
Posted: 26 Nov 2004 01:46 PST
Expires: 26 Dec 2004 01:46 PST
Question ID: 434265
1. Write a Java method to calculate the 2 roots of a quadratic
equation: ax2 + bx + c = 0
Hint: There are 2 Solutions given by:

(-b + sqrt(b2 ? 4ac)) / (2a)

and 

(-b - sqrt(b2 ? 4ac)) / (2a)

2. Write a method binarySearchAllMatches() for the binary search
technique that finds and returns ALL matches in a sorted array of
integers. For example, in the array {1,2,3,4,5,5,5,5,6,6,7,8}
If we search for 1 we should get {0} for the indices array

If we search for 5 we should get {4, 5, 6, 7} for the indices array

If we search for 6 we should get {8, 9} for the indices array

If we search for 100 we should get {}, empty array, for the indices array

*** I want the answers to be as simple as possible ***
*** i need it Wednesday Dec 1st, after this date, it would be of no use to me***

Request for Question Clarification by endo-ga on 26 Nov 2004 03:05 PST
Hi,

These are basic Java exercises, have you attempted to do them?

If you're stuck with anything in particular, I could help.

Thanks.
endo

Clarification of Question by meme123-ga on 26 Nov 2004 06:19 PST
Umm...well i tried and im not very good at this, thats why im asking for help.
Answer  
Subject: Re: Java methods wanted
Answered By: leapinglizard-ga on 26 Nov 2004 08:38 PST
Rated:5 out of 5 stars
 
Dear meme123,

For each exercise, I shall first give the method together with a brief
explanation, followed by a full Java program that makes use of the
method.


1.

The following method presumes the existence of a quit(String) method
that prints the given error message and causes the program to cease
execution. Because we are not interested in complex solutions to the
equation, we verify that the figure under the square root is
non-negative before proceeding to apply the formula.

    double[] calculate(double a, double b, double c) {
        double sol[] = new double[2];
        if (b*b < 4*a*c)
            quit("no real solutions");
        sol[0] = (-b + Math.sqrt(b*b - 4*a*c))/(2*a);
        sol[1] = (-b - Math.sqrt(b*b - 4*a*c))/(2*a);
        return sol;
    }

The following is a program that makes use of the method.


import java.lang.*;
import java.util.*;
import java.io.*;

public class Quadratic {
    double[] calculate(double a, double b, double c) {
        double sol[] = new double[2];
        if (b*b < 4*a*c)
            quit("no real solutions");
        sol[0] = (-b + Math.sqrt(b*b - 4*a*c))/(2*a);
        sol[1] = (-b - Math.sqrt(b*b - 4*a*c))/(2*a);
        return sol;
    }

    void quit(String msg) {
        System.out.println(msg);
        System.exit(0);
    }

    void run(String[] abc_str) {
        if (abc_str.length != 3)
            quit("exactly three arguments required");
        double abc[] = new double[3];
        for (int i = 0; i < 3; i++)
            try {
                abc[i] = Double.parseDouble(abc_str[i]);
            } catch (NumberFormatException e) {
                quit(abc_str[i]+" is not valid");
            }
        double sol[] = calculate(abc[0], abc[1], abc[2]);
        if (sol[0] == sol[1])
            System.out.println("solution: x = "+sol[0]);
        else {
            System.out.println("solution 1: x = "+sol[0]);
            System.out.println("solution 2: x = "+sol[1]);
        }
    }

    public static void main(String[] argv) {
        new Quadratic().run(argv);
    }
}


Usage examples follow.


  > java Quadratic 2 1 -3
  solution 1: x = 1.0
  solution 2: x = -1.5

  > java Quadratic 1 0 9
  no real solutions

  > java Quadratic 1 -4 4
  solution: x = 2.0



2.

In the following method, we assume that arr[] is a sorted integer
array. We start by calling Java's binarySearch method to locate an
array element with the desired value. If there is such an element, we
store its index and search to the left and right until we either reach
a different value or run off the end of the array. We step back one
element in each case to find the lowest and highest indices of array
elements matching the target. Next, we allocate an array of suitable
size and copy the indices into it in ascending order.

    int[] binarySearchAllMatches(int[] arr, int target) {
        int lo, hi, mid = Arrays.binarySearch(arr, target);
        if (mid < 0)
            return new int[0];
        for (lo = mid-1; lo >= 0 && arr[lo] == arr[mid]; lo--);
        lo++;
        for (hi = mid+1; hi < arr.length && arr[hi] == arr[mid]; hi++);
        hi--;
        int indices[] = new int[hi-lo+1];
        for (int i = lo; i <= hi; i++)
            indices[i-lo] = i;
        return indices;
    }

This is not the most efficient way to solve the problem, but it is the
simplest. A faster approach would be to write a method that, after
finding an instance of the specified value through binary search,
calls itself recursively to find a further instance in the sub-array
to the left and the sub-array to the right. If you would prefer such a
solution, do let me know with a Clarification Request.

A full program using the current method follows. Note that the first
argument at execution should be the value sought, while the remaining
arguments are sorted integers.


import java.lang.*;
import java.util.*;
import java.io.*;

public class BinSearch {
    int[] binarySearchAllMatches(int[] arr, int target) {
        int lo, hi, mid = Arrays.binarySearch(arr, target);
        if (mid < 0)
            return new int[0];
        for (lo = mid-1; lo >= 0 && arr[lo] == arr[mid]; lo--);
        lo++;
        for (hi = mid+1; hi < arr.length && arr[hi] == arr[mid]; hi++);
        hi--;
        int indices[] = new int[hi-lo+1];
        for (int i = lo; i <= hi; i++)
            indices[i-lo] = i;
        return indices;
    }

    void quit(String msg) {
        System.out.println(msg);
        System.exit(0);
    }

    void run(String[] arr_str) {
        if (arr_str.length < 1)
            quit("at least one argument required");
        int target = -1, i = 0, arr[] = new int[arr_str.length-1];
        try {
            target = Integer.parseInt(arr_str[i]);
            for (i = 1; i < arr_str.length; i++)
                arr[i-1] = Integer.parseInt(arr_str[i]);
        } catch (NumberFormatException e) {
            quit(arr_str[i]+" is not valid");
        }
        for (i = 1; i < arr.length; i++)
            if (arr[i] < arr[i-1])
                quit(arr[i]+" should come before "+arr[i-1]);
        int indices[] = binarySearchAllMatches(arr, target);
        System.out.print("{");
        if (indices.length > 0)
            System.out.print(indices[0]);
        for (i = 1; i < indices.length; i++)
            System.out.print(", "+indices[i]);
        System.out.println("}");
    }

    public static void main(String[] argv) {
        new BinSearch().run(argv);
    }
}


And here are usage examples using the data you gave.


  > java BinSearch 1 1 2 3 4 5 5 5 5 6 6 7 8
  {0}

  > java BinSearch 5 1 2 3 4 5 5 5 5 6 6 7 8
  {4, 5, 6, 7}

  > java BinSearch 6 1 2 3 4 5 5 5 5 6 6 7 8
  {8, 9}

  > java BinSearch 100 1 2 3 4 5 5 5 5 6 6 7 8
  {}


If you have any trouble compiling these programs or if you desire
further explanation of any point, please let me know through a
Clarification Request so that I have a chance to fully meet your needs
before you assign a rating.

Regards,

leapinglizard
meme123-ga rated this answer:5 out of 5 stars
thanks for the answer....just what i needed :)

Comments  
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy