Calculate median [duplicate] - java

This question already has answers here:
Why double width = 50/110000; the output is 0.000000000000000?
(3 answers)
Closed 8 years ago.
I can't figure out what is wrong, why doesnt my median work ? Everything works except my median and i have been sitting here for a while and looking at it and still don't understand why it doesnt work.
import java.util.Arrays;
public class Stat{
private int[] värden = new int[100];
public int count = 0; // counter = 0
public int Värden(int värde){
värden[count++]=värde;
return värde;
}
public double medelv(){ //medelvärde
double medelv = 0;
int total = 0;
for(int x = 0; x < count; x++){
total += värden[x];
medelv = (total/count);
}
return medelv;
}
public double medianen(){
Arrays.sort(värden);
double medianen = 0;
for(int x = 0; x < count; x++){
if (värden.length % 2 == 0)
medianen = ((double)värden[värden.length/2] + (double)värden[värden.length/2 - 1])/2;
else
medianen = (double) värden[värden.length/2];

As #zouzou says in the comments, an int divided by another int equals an int. Cast one of them, and it will work.
medelv = ((double)total/count);

A much more concise way to calculate the median:
ArrayList<Integer> integers = new ArrayList<Integer>();
//TO DO: Add the integers to the array list
Collections.sort(integers);
double median;
if (integers.size() > 0) {
int x = integers.size() / 2;
else if (integers.size() % 2 == 0)
median = (integers.get(x - 1) + integers.get(x)) / 2.0;
else median = integers.get(x);
}

I don't see any issues with your logic . Other than finding it in loop . which is not required.
if (värden.length % 2 == 0) {
medianen = ((double)värden[värden.length/2] + (double)värden[värden.length/2 - 1])/2;
} else {
medianen = värden[värden.length/2];
}
If your array length is even then upper portion is double so no issues . If it is not even then you are picking middle ( 5/2 => 2.5 which would become 3 . it is median)
My question is , you declare the array length as 100. Are you filling all the 100 elements ? if not your logic will not work.

Related

Java Math.sqrt function rounding down to zero [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
How to divide 1 by 25(1/25) and get result .04 in java [duplicate]
(4 answers)
Closed 1 year ago.
I am trying to write a function to check a T score value and populate half of a 5x5 array.
public void calcTScores()
{
double temp = 0;
double tempSp = 0;
int n = 24;
this.tScores = new String [5][5];
for (int i = 0; i< this.Headers.length; i++){
for (int j = 0; j<this.Headers.length; j++)
{
if(i < j)
{
tempSp += (n-1)*this.SD[i] * this.SD[i] + (n-1)*this.SD[j] * this.SD[j];
tempSp = tempSp/(n+n-2);
tempSp = Math.sqrt(tempSp);
temp = tempSp * Math.sqrt(0.0833);
System.out.println(Math.sqrt(1/12));
temp = ((this.Mean[i] - this.Mean[j])/temp);
if(temp > 2.25 || temp< -2.25)
{
this.tScores[i][j] = "Y";
}
else
{
this.tScores[i][j] = "N";
}
temp = 0;
tempSp = 0;
}
}
}
}
Any idea why Math.sqrt(0.0833) and Math.sqrt(1/12) would evaluate to different values?
The T score when I add the 1/24 and 1/24 value and take the sqrt keeps evaluating to zero but when I plug in the actual decimal it gives me the answer I would expect
Any ideas why this is occuring?
1/12==0 as per integer division
There's nothing wrong with Math.sqrt. You're passing it the number zero.
Math.sqrt(1/12)
1/12 is a division operation on two integers (namely, 1 and 12), so it's going to produce an integer result. 12 goes into 1 zero times, so the integer result is zero. Thus, your expression is
Math.sqrt(0)
Consider
Math.sqrt(1.0/12.0)
Math.sqrt(1/12d)
Cast 1/12 to a double by casting one operand to a double.

Difference between while loop and for loop [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I'm new to Java.
If you want to know what I'm trying to solve, check this: http://codeforces.com/problemset/problem/200/B
The two versions of the code, solve the same problem:
1-(for loop) version
public static void method() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double sum = 0;
for (int i = 0; i < n; i++)
sum += (sc.nextInt() / 100.0);
System.out.println(sum * 100.0 / n);
}
2-(while loop) version
public static void method() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double sum = 0;
while (n-- > 0) {
sum += (sc.nextInt() / 100.0);
}
System.out.println((sum * 100.0) / n);
}
===================================================
Here is the input for each of them:
3
50 50 100
Here is the output of each of them:
1-(for loop): 66.66666666666667
2-(while loop): -200.0
===================================================
Why the output differs?
n-- this will change the value of n and it will make it -1 at end.
so your sum will devide by -1 and you get -200 but in first solution n does not change and at end 200/3 = 66.6
it looks like you are decrementing n and then evaluating which will allow n to become negative
-- X = decrement X then evaluate
X -- = evaluate X then decrement X

How to add together an array representation of an integer with different number of digits?

How would I add together two integers with different number of digits, using an array, without causing an out of bounds exception?
For example: 500 + 99
each digit is an element of the array
This is how I'm doing it right now:
int aIILength = infiniteInteger.length-1;
int bIILength = anInfiniteInteger.infiniteInteger.length-1;
for(int f = aIILength; f >0; f--){
int aTempNum = infiniteInteger[f];
int bTempNum = anInfiniteInteger.infiniteInteger[f];
result = aTempNum + bTempNum;
//array representation of sum
tempArray[f] = result;
}
Let the counter in the loop go from 1 and up, and use it to access the digits from the end of each array.
You need a carry to hold the overflow of adding each set of digits.
Loop until you run out of digits in both arrays, and carry is zero.
Check the range when you access the digits from the arrays, and use zero when you run out of digits.
int aIILength = infiniteInteger.length;
int bIILength = anInfiniteInteger.infiniteInteger.length;
int carry = 0;
for(int f = 1; f <= aIILength || f <= bIILength || carry > 0; f++){
int aTempNum;
if (f <= aIILength) {
aTempNum = infiniteInteger[aIILength - f];
} else {
aTempNum = 0;
}
int bTempNum;
if (f <= bIILength) {
bTempNum = anInfiniteInteger.infiniteInteger[bIILength - f];
} else {
bTempNum = 0;
}
result = aTempNum + bTempNum + carry;
tempArray[tempArray.length - f] = result % 10;
carry = result / 10;
}
Note: Make tempArray longer than both the operand arrays, so that it has place for a potential carry to the next digit.

Create my own BigInteger by using String in Java

I have to create a class MyBigInteger to calculate the operations: mod inverse and mod power with >very big integers ( about 60 digits in Decimals or more ). To solve this, I use String to store my >numbers and create some basic functions such as add, subtract, mod, div,... But the problem I got >here is that: while my add and subtract methods work right, my multiple functions only works with >small numbers, and if I use input with numbers 7, 8 or more digits, my program will not responds. I >think my idea to use String to store big numbers may be a bad idea and If i use array to store them, >will my class work more quickly, won't it?
Below is my code.The add and subtract method seem to work correctly so I will only post the method >multiple.
First is method a MyBigInteger multiply a integer. I use it to create my multipler between two >MyBigInteger:
public class MyBigInteger {
private String val;
public static final MyBigInteger ZERO = new MyBigInteger("0");
...
private MyBigInteger mutiple( int k){
MyBigInteger result = ZERO;
if( k == 0) return result;
for( int i = 1; i <= Math.abs(k); i++) result = result.add(this);
if( k > 0) return result;
else return result.getOpposite(); // result.add(result.getOpposite()) == ZERO
}
public MyBigInteger mutiple( MyBigInteger mbi){
MyBigInteger result = ZERO;
if( mbi.toString().charAt(0) != '-'){
for( int i = mbi.toString().length() - 1; i >= 0; i--){
result = result.add(this.mutiple(Integer.parseInt(mbi.toString().charAt(mbi.toString().length() - i -1) + "")).mutiple((int)Math.pow(10, i)));
}
} else{
for( int i = mbi.toString().length() - 1 ; i >= 1; i--){
result = result.add(this.mutiple(Integer.parseInt(mbi.toString().charAt(mbi.toString().length() - i) + "")).mutiple((int)Math.pow(10, i-1)));
}
result = result.getOpposite();
}
return result;
}
Many thanks for any help you may be able to provide
Sorry for this, but the Multiplication method was fixed and It works perfectly. But that it not the only problem in my Class. I created a mod method by using a subtraction method. And In my subtraction method, I use subAbs method which is a particular subtraction for two Positive MyBigNumber.
public MyBigInteger subAbs( MyBigInteger mBI){
String result = "";
int i = this.getLength();
int j = mBI.getLength();
int s = 0;
int r = 0;
String temp = "";
String val1 = this.toString();
String val2 = mBI.toString();
if( this.equalsTo(mBI) == true ) return ZERO;
else
if( this.greaterThan(mBI) == true){
for( int k = 0; k < i - j; k++) temp += "0";
val2 = temp + val2;
for( int k = i-1; k > 0; k-- ){
//And the statement right behind this comment is the wrong line (224) in the image
s = 10 + Integer.parseInt(val1.charAt(k) + "") - Integer.parseInt(val2.charAt(k) + "") - r;
if( s >= 10){
s = s - 10;
r = 0;
} else r = 1;
result = Integer.valueOf(s).toString() + result;
}
s = Integer.parseInt(val1.charAt(0) + "") - Integer.parseInt(val2.charAt(0)+"") - r;
if( s >= 0 ) result = s + result;
else result = Integer.valueOf(s).toString() + result;
return new MyBigInteger(result);
} else return new MyBigInteger("-" + mBI.subAbs(this).toString());
}
And if I put in a big number, I get a exception:
The problem may start from the method subAbs.
Your multiply method is simply adding over and over and over. This works fine for small numbers, but when you put in large numbers you are doing tons of calculations, the computer has to take a long time to figure it out.
How would you multiply 100x12345 by hand? Would you add 12345+12345, then take that and add 12345, then take that and add 12345, and repeat 100 times? That's what your alogirthm is doing now. You should try to implement your multiply algorithm in the same way you would multiply 100x12345.

Reversing an integer in Java using a for loop

This is a homework problem
How would I reverse an integer in Java with a for loop? The user will input the integer (I don't know how long it will be) and I need to reverse it. ie: If they enter 12345, my program returns 54321.
Here's the catch, you can't use String, StringBuffer, arrays, or other advanced structures in this problem.
I have a basic idea of what I need to do. My problem is...in the for loop, wouldn't the condition need to be x < the length of the integer (number of digits)? How would I do that without String?
Thanks for any input, and I'll add more information if requested.
EDIT:
Of course, after introspection, I realized I should use another for loop to do this. What I did was create a for loop that will count the digits by dividing by 10:
int input = scan.nextInt();
int n = input;
int a = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
EDIT 2:
This is what I have
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
for (int y = 0; y < n; y++) {
r = r + input%10;
input = input/10;
}
System.out.println(input);
When I run it, it isn't reversing it, it's only giving me back the numbers. ie: if I put in 1234, it returns 1234. This doesn't make any sense to me, because I'm adding the last digit to of the input to r, so why wouldn't it be 4321?
While your original number is nonzero, take your result, multiply it by 10, and add the remainder from dividing the original by 10.
For example, say your original number is 12345. Start with a result of 0.
Multiply result by 10 and add 5, giving you 5. (original is now 1234.)
Multiply result by 10 and add 4, giving you 54. (original is now 123.)
Multiply result by 10 and add 3, giving you 543. (original = 12.)
Multiply result blah blah 5432. (original = 1.)
Multiply, add, bam. 54321. And 1 / 10, in int math, is zero. We're done.
Your mission, should you choose to accept it, is to implement this in Java. :) (Hint: division and remainder are separate operations in Java. % is the remainder operator, and / is the division operator. Take the remainder separately, then divide the original by 10.)
You will need to use math to access each of the digits. Here's a few hints to get your started:
Use the % mod operator to extract the last digit of the number.
Use the / division operator to remove the last digit of the number.
Stop your loop when you have no more digits in the number.
This might not be the proper way but
public static int reverseMe(int i){
int output;
String ri = i + "";
char[] inputArray = ri.toCharArray();
char[] outputArray = new char[inputArray.length];
for(int m=0;m<inputArray.length;m++){
outputArray[inputArray.length-m-1]=inputArray[m];
}
String result = new String(outputArray);
output = Integer.parseInt(result);
return output;
}
public static void reverse2(int n){
int a;
for(int i = 0; i < n ; i ++){
a = n % 10;
System.out.print(a);
n = n / 10;
if( n < 10){
System.out.print(n);
n = 0;
}
}
}
here is the Answer With Correction of Your Code.
import static java.lang.Math.pow;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (; n > 0;){
n = n/10;
a = a + 1;
}
for (int y = 0; y < input;a--) {
r =(int)( r + input%10*pow(10,a-1));
input = input/10;
}
System.out.println(r);
}
}

Categories