What am I doing wrong?
The median is always -0.5 result or 0.5, if ((m) + (m+1))/2;
public static double mediana(List<Double> liczby ){
Collections.sort(liczby);
int n = liczby.size()/2;
double m;
m = get(n);
if (liczby.size() % 2 == 0){
return ((m) + (m-1))/2;
}
else {
return m;
}
}
In your code, the problem is in this line.
return ((m) + (m-1))/2;
It should return the average of nth number and (n-1)th number as n = (size of the list)/2. You can try this.
public static double mediana(List<Double> liczby ){
Collections.sort(liczby);
int n = liczby.size()/2;
double m;
if (liczby.size() % 2 == 0)
m = (liczby.get(n) + liczby.get(n-1))/2;
else
m = liczby.get(n);
return m;
}
I believe the problem with it is the line return ((m) + (m-1))/2; You forget to retrieve the input of the next element in the list. Try:
l = get(n+1);
return (m + l)/2;
instead of:
return ((m) + (m-1))/2;
You need to be retrieving the n and n-1-th elements. You are currently subtracting 1 from the n-th value, which is not meaningful:
return (get(n) + get(n-1)) / 2;
I faced the same problem yesterday and I wrote a solution similar to sifho's one.
My method---implemented using Java generics---calculates the median value on every collection of Numbers. You can use the method with collections of Doubles, Integers, Floats and returns a double. Please consider that my method creates another collection in order to not alter the original one.
I provide also a test, have fun. ;-)
public static <T extends Number & Comparable<T>> double median(Collection<T> numbers){
if(numbers.isEmpty()){
throw new IllegalArgumentException("Cannot compute median on empty array of numbers");
}
List<T> numbersList = new ArrayList<>(numbers);
Collections.sort(numbersList);
int middle = numbersList.size()/2;
if(numbersList.size() % 2 == 0){
return 0.5 * (numbersList.get(middle).doubleValue() + numbersList.get(middle-1).doubleValue());
} else {
return numbersList.get(middle).doubleValue();
}
}
JUnit test code snippet:
/**
* Test of median method, of class Utils.
*/
#Test
public void testMedian() {
System.out.println("median");
Double expResult = 3.0;
Double result = Utils.median(Arrays.asList(3.0,2.0,1.0,9.0,13.0));
assertEquals(expResult, result);
expResult = 3.5;
result = Utils.median(Arrays.asList(3.0,2.0,1.0,9.0,4.0,13.0));
assertEquals(expResult, result);
}
Usage example (consider the class name is Utils):
List<Integer> intValues = ... //omitted init
Set<Float> floatValues = ... //omitted init
.....
double intListMedian = Utils.median(intValues);
double floatSetMedian = Utils.median(floatValues);
I do not know how to look method get(n).
It generates automatically.
The method can not return to zero.
private static double get(int n) {
// TODO Auto-generated method stub
return 0;
}
Related
I have to implement the following function in Java: public int stringToNumber(String input) without using Integer or any other class or method that parses the string. I have to loop over the characters of the string.
I attempted created a class that uses a loop to convert String to Integer.
Now, I am trying to figure out how I can return 0 if the string contains anything other than digits and an initial "-" for negative numbers.
Also I am trying to return 0 if the number is too large or too small for an int (Integer.MIN_SIZE to Integer.MAX_SIZE or -2^31 to 2^31 - 1).
Below is the code that I have so far.... Any help would be greatly appreciated
public class StringToNumber {
public static void main(String[] args) {
StringToNumber stn = new StringToNumber();
for (String arg : args) {
int number = stn.stringToNumber(arg);
System.out.format("Input number: %s, parsed number: %d %n", arg, number);
}
}
public int stringToNumber(String stn) {
int number = 0, factor = 1;
for (int n = stn.length()-1; n >= 0; n--) {
number += (stn.charAt(n) - '0') * factor;
factor *= 10;
}
return number;
}
}
Check if below code is working for you
public int stringToNumber(String stn) {
int number = 0, factor = 1;
int negative = 0;
if(stn.charAt(0)=='-') {
negative =1;
}
for (int n = negative; n < stn.length(); n++) {
int digit = stn.charAt(n)-'0';
if(digit<0 || digit>9)
return 0;
if((negative==0) && (Integer.MAX_VALUE-digit)/10 <number)
return 0;
else if ((negative==1) && (Integer.MAX_VALUE-digit+1)/10 <number)
return 0;
number = number*10+ (stn.charAt(n)-'0');
}
if(negative == 1) {
return -1*number;
}
return number;
}
Perhaps the best way to handle this would be to use Integer#parseInt(), which takes a string input and either returns an integer result or throws an exception if the input cannot be coerced to an integer:
public int stringToNumber(String stn) {
int result;
try {
result = Integer.parseInt(stn);
}
catch (NumberFormatException e) {
System.out.println("String input cannot be converted to integer: " + stn);
result = 0; // return 0 as the failure value
}
return result;
}
I need to create a method which must return the partial derivative of a function in the form of a term when passed the var you want to differentiate w respect to. This is my class the method is differentiate:
package poly;
import java.util.ArrayList;
import java.util.TreeSet;
import util.Vector;
/** Implements an individual term in a polynomial. If 5x^2 + 3xy is a polynomial,
* it has two terms 5x^2 and 2xy, each of which would be represented by a different
* instance of this class.
*
* #author ssanner#mie.utoronto.ca
*
*/
public class Term {
// For term 2.1*x^4*y*z^2, the data members would take values as follows:
public double _coef; // = 2.1
public ArrayList<String> _vars; // = ["x", "y", "z"]
public ArrayList<Integer> _pows; // = [4, 1, 2]
/** This constructor has been implemented for you.
*
* #param coef -- sets the _coef member
*/
public Term(double coef) {
_coef = coef;
_vars = new ArrayList<String>();
_pows = new ArrayList<Integer>();
}
/** This constructor has been implemented for you -- it parses a term
* representation from a String into the format required by this class.
* You need two understand the following code.
*
* #param s -- String to parse
* #throws PolyException if s is malformed
*/
public Term(String s) throws PolyException {
if (s == null || s.trim().equals(""))
throw new PolyException("Empty Term, cannot read");
// Initialize this term
_coef = 1.0d; // Will multiply any constants by this
_vars = new ArrayList<String>();
_pows = new ArrayList<Integer>();
// You need to understand all lines of the following code
String[] factors = s.split("\\*");
for (String factor : factors) {
factor = factor.trim(); // Get rid of leading and trailing whitespace
try {
// If successful, multiplies in a constant (multiple constants in a product allowed)
_coef *= Double.parseDouble(factor);
} catch (NumberFormatException e) {
// If not a coefficient, must be a factor "<var>^<pow>"
// Must be a variable to a power -- parse the factor and add to list
int pow = 1; // If no power, defaults to 1
String[] var_pow = factor.split("\\^");
String var = var_pow[0];
if (var_pow.length == 2) {
try { // Second part must be exponent
pow = Integer.parseInt(var_pow[1]);
} catch (NumberFormatException f) {
throw new PolyException("ERROR: could not parse " + factor);
}
} else if (var_pow.length > 2)
throw new PolyException("ERROR: could not parse " + factor);
// Successfully parsed variable and power, add to list
if (_vars.contains(var))
throw new PolyException("ERROR: " + var + " appears twice in " + s);
_vars.add(var);
_pows.add(pow);
}
}
}
/** Produce a re-parseable representation of this Term as a String. This
* has been done for you.
*
*/
public String toString() {
// Using "+" to append Strings involves a lot of String copies since Strings are
// immutable. StringBuilder is much more efficient for append.
StringBuilder sb = new StringBuilder();
sb.append(String.format("%01.3f", _coef));
for (int i = 0; i < _vars.size(); i++) {
String var = _vars.get(i);
int pow = _pows.get(i);
sb.append("*" + var + (pow == 1 ? "" : "^" + pow));
}
return sb.toString();
}
/** Returns all of the variables used in this Term as a sorted set (TreeSet).
* This has been implemented for you, but you need to understand how it works
* since you'll write a similar method in Polynomial that uses this method.
*
* #return
*/
public TreeSet<String> getAllVars() {
// TreeSets are like HashSets but sorted alphabetically (lookup and insertion are
// a little less efficient than HashSets, but this won't matter for our sizes).
return new TreeSet<String>(_vars);
}
///////////////////////////////////////////////////////////////////////////////
// TODO: Your methods here! You should add some helper methods that facilitate
// the implementation of the methods below.
///////////////////////////////////////////////////////////////////////////////
/** If Term defines a function f(x,y) = 2xy^2 and assignments is { x=2.0 y=3.0 }
* then this method returns 36.0, which is the evaluation of f(2.0,3.0).
*
* #param assignments
* #return
* #throws PolyException
*
*
*/
public double coef(){
return _coef;
}
public Double var(int i){
return Double.parseDouble(_vars.get(i));
}
public ArrayList power(){
return _pows;
}
public double evaluate(Vector assignments) throws PolyException {
double evaluated = 0;
double sum = 0;
for(int i = 0; i < _vars.size(); i++){
sum += Math.pow(var(i), _pows.get(i));
}
evaluated *= sum;
return evaluated;
}
/** If Term defines a function f(.) then this method returns the **symbolic**
* partial derivative (which you can verify from calculus is still a Term):
*
* partial f(1.0,2.0) / partial var.
*
* Specifically, if Term defines a function f(x,y) = 2xy^2 and var = "x"
* then this method returns a **new** Term 2y^2 and if var = "y" then it
* instead returns a **new** Term 4xy.
*
* #param var
* #return partial derivative of this w.r.t. var as a new Term
*/
public Term differentiate(String var) {
// TODO: Should not return null!
return null;
}
}
I'm unsure on how the differentiate method would be called but an example of the method to differentiate a relatively simple function could be done like the following...
Please note this method could use some fine-tuning (it returns a String not a Term value) and it doesn't take into consideration logs/trig functions etc but hopefully it's a helpful start.
public static void main(String args[]) {
String differentiated = differentiate("32x^2y^3", "x");
System.out.println(differentiated);
}
public static String differentiate(String function, String var) {
StringBuilder partialDerivative = new StringBuilder();
int indexOfVar = function.indexOf(var);
boolean coefficient = false;
String coefficientValue;
double coefficientAmount = 1;
StringBuilder powerValue = new StringBuilder();
StringBuilder variable = new StringBuilder();
double powerAmount;
StringBuilder otherVariables = new StringBuilder();
//ascertains whether a coefficient is present
int k = 0;
while (Character.isDigit(function.charAt(k))) {
coefficient = true;
if (k == 0) {
coefficientValue = Character.toString(function.charAt(k));
} else {
coefficientValue = function.substring(0, k+1);
}
coefficientAmount = Double.parseDouble(coefficientValue);
k++;
}
//checks for other variables that may also have polynomials
for (int i = 0; i <= function.length() - 1; i++) {
if (Character.isLetter(function.charAt(i)) && function.charAt(i) != var.charAt(0)) {
otherVariables.append(function.charAt(i));
if (i < function.length() - 1) {
if (function.charAt(i + 1) == '^') {
findPolynomial(function, i, otherVariables);
}
}
}
}
//works out if the var value has a polynomial and therefore times the coefficient by it and reduces it by one
if (function.charAt(indexOfVar + 1) == '^') {
findPolynomial(function, indexOfVar, powerValue);
powerAmount = Double.parseDouble(powerValue.toString().substring(1));
coefficientAmount *= powerAmount;
powerAmount -= 1;
powerValue.replace(1,powerValue.length(),Double.toString(powerAmount));
if(powerAmount != 1) {
variable.append(var).append(powerValue);
} else {
variable.append(var);
}
}
//include method for ln() or exponential functions
//include method for trig functions (sin() cos() etc)
if (coefficient) {
partialDerivative.append(coefficientAmount).append(otherVariables).append(variable);
} else {
partialDerivative.append(otherVariables).append(variable);
}
return partialDerivative.toString();
}
private static void findPolynomial(String function, int indexOfVar, StringBuilder powerValue) {
powerValue.append(function.charAt(indexOfVar + 1));
int j = indexOfVar + 2;
while (Character.isDigit(function.charAt(j))) {
powerValue.append(function.charAt(j));
if (j == function.length() - 1) {
break;
} else {
j++;
}
}
}
I've got 2 integer values, e.g. a = 10 and b = 20.
Now i want to substract them: a - b, but as a result i don't want to have negative values, so in this example i want the result 0 and a new integer variable with the rest (10 here).
Two more examples:
Input: a=40, b=20; Expected Output:20
input: a=25 b=50 Expected Output: 0 and a new int var = 25
How to do this in java without external libraries?
From what I understand, you want a variable to be holding the result if the result is greater than or equal to 0. Otherwise, that variable should hold 0 and another variable will hold a positive value of the result.
If this is the case, consider the following code snippet:
int result = a -b;
int otherVariable = 0;
if (result < 0) {
otherVariable = -result;
result = 0;
}
int aMinusB = a-b;
int output = Math.max(aMinusB,0);
int rest = aMinusB < 0 ? Math.abs(aMinusB) : 0;
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
There are two ways to solve this problem: -
First: -
If you don't want to create a method to return this value and only to display it, then you can do it by printing out the results of if-else block in the code below within the function itself.
Second: -
If you want to use the result somewhere else, go for an object based approach: -
// Main class
public class SubtractWithRest {
public static void main(String[] args) {
SubtractResultWithRest subtractResultWithRest = new SubtractResultWithRest();
subtraction(10, 20, subtractResultWithRest);
System.out.println("Result: " + subtractResultWithRest.getResult());
System.out.println("Rest: " + subtractResultWithRest.getRest());
}
private static void subtraction(int num1, int num2, SubtractResultWithRest subtractResultWithRest) {
if (num2 > num1) {
subtractResultWithRest.setResult(0);
subtractResultWithRest.setRest(num2 - num1);
} else {
subtractResultWithRest.setResult(num1 - num2);
}
}
}
// Object class
public class SubtractResultWithRest {
private int result;
private int rest = 0;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public int getRest() {
return rest;
}
public void setRest(int rest) {
this.rest = rest;
}
}
My Professor has created code that needs to be modified. The only problem is I don't understand his style at all on top of being a fairly new programmer myself. The parameters for the assignment are as follows:
• Modify setters so that they ignore inappropriate values (i.e., divide by zero)
• Implement the equals() method inherited from the top-level Object class
• Implement less than and greater than methods
• Implement add, subtract, and multiply methods
• Makes sure the equals method returns true for any two fractions that are arithmetically equal.
• Make sure that the equals method does not alter the values of the fractions being compared.
• The lessThan and greaterThan methods must each return a Boolean value, not a string.
• The provided reduce method returns a new (reduced) fraction object as its function value
I am completely lost about this assignment as I don't have the slightest clue where to even begin. Any and all help would be greatly appreciated!!!! I have the feeling that once I see it done, it will all make sense to me. I am just not used to this style of teaching at all.
public class Fraction {
private int numer;
private int denom;
public Fraction() { // no-arg constructor
numer = 0;
denom = 1;
}
public Fraction(int numer, int denom) {
this.numer = numer;
this.denom = denom;
}
public Fraction(Fraction frac) { // copy constructor
numer = frac.getNumer();
denom = frac.getDenom();
}
// getters and setters
public int getNumer() {
return numer;
}
public void setNumer(int x) {
numer = x;
}
public int getDenom() {
return denom;
}
public void setDenom(int x) {
denom = x;
}
// Special Methods
public String toString() {
return numer + "/" + denom;
}
// Other Methods
public Fraction reduce() {
Fraction temp = new Fraction();
int GCD = gcd(numer, denom);
temp.setNumer(numer / GCD);
temp.setDenom(denom / GCD);
return temp;
}
// Private Methods
private int gcd(int n1, int n2)
{
int M, N, R;
if (n1 < n2)
{
N = n1;
M = n2;
}
else
{
N = n2;
M = n1;
}
R = M % N;
while (R != 0)
{
M = N;
N = R;
R = M % N;
}
return N;
}
public static void main(String[] args) {
// test constructors
Fraction frac0 = new Fraction();
System.out.println("TESTING NO-ARG CONSTRUCTOR");
System.out.println("frac0: Result should be 0/1:");
System.out.println("Numer = " + frac0.getNumer());
System.out.println("Denom = " + frac0.getDenom());
System.out.println("TESTING int/int CONSTRUCTOR");
Fraction frac1 = new Fraction(2,4);
System.out.println("frac1: Result should be 2/4:");
System.out.println("Numer = " + frac1.getNumer());
System.out.println("Denom = " + frac1.getDenom());
System.out.println("TESTING Fraction CONSTRUCTOR");
Fraction frac2 = new Fraction(frac1);
System.out.println("frac2: Result should be 2/4:");
System.out.println("Numer = " + frac2.getNumer());
System.out.println("Denom = " + frac2.getDenom());
System.out.println("TESTING COPY CONSTRUCTOR frac1 frac2");
if (frac1.getNumer() == frac2.getNumer() &&
frac1.getDenom() == frac2.getDenom() &&
frac1 != frac2)
{
System.out.println("Copy constructor working");
}
else
System.out.println("PROBLEM with copy constructor");
// test equal method
System.out.println("TESTING EQUALITY OF frac1 and frac2 -");
System.out.println("SHOULD BE FOUND EQUAL:");
if (frac1.equals(frac2))
{
System.out.println("frac1 and frac2 found equal");
}
else
{
System.out.println("frac1 and frac2 NOT equal");
}
// test reduce method
System.out.println("TESTING reduce METHOD ON frac1");
Fraction reduced_frac1 = frac1.reduce();
System.out.println("Reduced frac1 = " + reduced_frac1);
// test getters and setters
frac2.setNumer(8);
frac2.setDenom(12);
System.out.println("Numer = " + frac2.getNumer());
System.out.println("Denom = " + frac2.getDenom());
// System.out.println("GCD of 2/4 = " + frac1.gcd(1,4));
}
//* TO BE COMPLETED *
}
There is nothing wrong with his teaching methods and with some further study I am sure you can figure it out. No one here is going to do it for you and I don't want to do your homework so I will ask the common question, what have you tried so far? I've given you one of the modified setters. Keep working, study your java better or you are going to have a hard time when it gets difficult.
//Here is where you start
public void setDenom(int x){
if(x > 0){
denom = x;
}else{
//throw an error
}
}
i wrote the following codes
my aim is to get the lowst value of doble[] absOfSub but it gives the following exception
at line compared= Double.compare(d2, d1);
Exception in thread "main" java.lang.StackOverflowError
why overflow and how to fix it?
EDIT
public class TestThe {
static double[] absOfSub = new double[5];
private static int index=0;
private static int compare(int currentIdx, int minIdx) {
if(index < absOfSub.length) {
if(absOfSub[currentIdx] < absOfSub[minIdx]) {
compare(currentIdx + 1, currentIdx);
} else {
compare(currentIdx + 1, minIdx);
}
}
return minIdx;
}
public static void main(String[] args) {
absOfSub[0]=1000;
absOfSub[1]=810;
absOfSub[2]=108;
absOfSub[3]=130;
absOfSub[4]=110;
double result;
int inndex= compare(0,1);
System.out.println(absOfSub[inndex]);
}
}
How about this simple and elegant solution?
static double min(double... ds) {
double min = Double.POSITIVE_INFINITY;
for (double d : ds) min = Math.min(min, d);
return min;
}
public static void main(String[] args) {
System.out.println(min(-5.2, 0, -10.1, 3));
}
Recursive solution (not recommended!):
static double minRecur(double... ds) {
return minRecur(ds, 0, Double.POSITIVE_INFINITY);
}
static double minRecur(double[] ds, int i, double runningMin) {
return (i < 0 || i >= ds.length)?
runningMin : minRecur(ds, i + 1, Math.min(runningMin, ds[i]));
}
You don't change the value of index inside your method. So this recursive method call won't stop at all.
You never manipulate the value of the index variable. You see another reason why people should try to limit the number of static variables they use. Let me try to help you:
public class TestThe {
private static double[] absOfSub = new double[5];
private static void compare(int currentIdx, int minIdx) {
if(currentIdx < absOfSub.length) {
if(absOfSub[currentIdx] < absOfSub[minIdx]) {
return compare(currentIdx + 1, currentIdx);
} else {
return compare(currentIdx + 1, minIdx);
}
} else {
return minIdx;
}
}
public static void main(String[] args) {
absOfSub[0] = 10;
absOfSub[1] = 810;
absOfSub[2] = 108;
absOfSub[3] = 130;
absOfSub[4] = 110;
System.out.println("The minimum value is: " + absOfSub[compare(0, 0)]);
}
}
EDIT Some more notes:
always specify the attribute accessor as private, when this is the intention
always format your code
when you write recursion, make sure you always change something for every consequent call and that it gets you closer to the ending condition.
double primitive type itself defines a comparison operator, no need to use Double.compare in your case.
You don't actually change the index variable, so the recursion will never end. But there is a lot more wrong with this.
An easy generic way to find the minimal value in an array, without using recursion:
int min = Integer.MAX_VALUE;
for( int i = 0; i < array.length; i++ ) {
// Math.min returns the lower value of the two arguments given
min = Math.min( min, array[i] );
}
return min;
This could be easily adapted to fit your needs.
Index in each routine is having either 0 or 1 or 2 as the value.