I have a text file called numbers.txt and its full of numbers. I need to find the mean median and mode of the numbers. I can read the file but I don't know any more than that.
import java.io.File;
import java.util.Scanner;
public class Terms {
public static void main(String[] args)throws Exception {
File file =
new File("C:\\Users\\coderva.org\\Documents\\numbers.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
According to the definitions of mean, median and mode:
public static void main(String[] args) {
File file = new File("C:\\Users\\coderva.org\\Documents\\numbers.txt");
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
return;
}
ArrayList<Float> list = new ArrayList<Float>();
while (sc.hasNextFloat())
list.add(sc.nextFloat());
int size = list.size();
if (size == 0) {
System.out.println("Empty list");
return;
}
Collections.sort(list);
for (int i = 0; i < size; i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
// mean value, classical way
float sum = 0;
for (float x : list) {
sum += x;
}
float mean = sum / size; // mean as integer
//median
float median;
if (size % 2 == 0) {
float x1 = list.get(size / 2 - 1);
float x2 = list.get(size / 2);
median = (x1 + x2) / 2;
} else {
median = list.get(size / 2);
}
//mode
Float mode = null;
int counter = 1;
for (int i = 0; i < size; i++) {
int freq = Collections.frequency(list, list.get(i));
if (freq > counter) {
mode = list.get(i);
counter = freq;
}
}
System.out.println("Mean=" + mean);
System.out.println("Median=" + median);
if (mode == null) {
System.out.println("No mode found");
} else {
System.out.println("Mode=" + mode);
}
}
You can create a list of numbers as such:
List<Integer> numberList = new ArrayList<>();
while (sc.hasNextInt())
numberList.add(sc.nextInt());
Or when you have doubles or floats:
List<Double> numberList = new ArrayList<>();
while (sc.hasNextDouble())
numberList.add(sc.nextDouble());
List<Float> numberList = new ArrayList<>();
while (sc.hasNextFloat())
numberList.add(sc.nextFloat());
From there you can calculate the mean as follows:
sum = numberList.stream().mapToInt(Integer::intValue).sum();
average = sum / numberList.size();
And so on for the other properties you need.
Note The types are of sum and average are depended on which types you read from the file.
Related
We had a lab in Comsci I couldn't figure out. I did a lot of research on this site and others for help but they were over my head. What threw me off were the arrays. Anyway, thanks in advance. I already got my grade, just want to know how to do this :D
PS: I got mean, I just couldn't find the even numbered median and by mode I just gave up.
import java.util.Arrays;
import java.util.Random;
public class TextLab06st
{
public static void main(String args[])
{
System.out.println("\nTextLab06\n");
System.out.print("Enter the quantity of random numbers ===>> ");
int listSize = Expo.enterInt();
System.out.println();
Statistics intList = new Statistics(listSize);
intList.randomize();
intList.computeMean();
intList.computeMedian();
intList.computeMode();
intList.displayStats();
System.out.println();
}
}
class Statistics
{
private int list[]; // the actual array of integers
private int size; // user-entered number of integers in the array
private double mean;
private double median;
private int mode;
public Statistics(int s)
{
size = s;
list = new int[size];
mean = median = mode = 0;
}
public void randomize()
{
Random rand = new Random(12345);
for (int k = 0; k < size; k++)
list[k] = rand.nextInt(31) + 1; // range of 1..31
}
public void computeMean()
{
double total=0;
for (int f = 0; f < size; f++)
{
total = total + list[f];
}
mean = total / size;
}
public void computeMedian()
{
int total2 = 0;
Arrays.sort(list);
if (size / 2 == 1)
{
// total2 =
}
else
{
total2 = size / 2;
median = list[total2];
}
}
public void computeMode()
{
// precondition: The list array has exactly 1 mode.
}
public void displayStats()
{
System.out.println(Arrays.toString(list));
System.out.println();
System.out.println("Mean: " + mean);
System.out.println("Median: " + median);
System.out.println("Mode: " + mode);
}
}
Here are two implementations for your median() and mode() methods:
public void computeMedian() {
Arrays.sort(list);
if ( (list.size & 1) == 0 ) {
// even: take the average of the two middle elements
median = (list[(size/2)-1] + list[(size/2)]) / 2;
} else {
// odd: take the middle element
median = list[size/2];
}
}
public void computeMode() {
// precondition: The list array has exactly 1 mode.
Map<Integer, Integer> values = new HashMap<Integer, Integer>();
for (int i=0; i < list.size; ++i) {
if (values.get(list[i]) == null) {
values.put(list[i], 1);
} else {
values.put(list[i], values.get(list[i])+1);
}
}
int greatestTotal = 0;
// iterate over the Map and find element with greatest occurrence
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
if (pair.getValue() > greatestTotal) {
mode = pair.getKey();
greatestTotal = pair.getValue();
}
it.remove();
}
}
I'm working on a program which sorts an array by dividing it into smaller max-heaps and extracting the max-integer out of each one, then deleting it from the heap and running again until every heap is empty, but I can't seem to figure it out.
From where I stand the code looks good, but I don't get the results which I am looking for. My input is created randomly, and makes an array of 512 integers. Here is what it prints for one example run -
Original Array -391 176 -380 -262 -474 327 -496 214 475 -255 50 -351 179 -385 -442 -227 465 127 -293 288
Sorted Array 475 465 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327
n = 20 k = 2
The number of comparisons is 243
Can anyone spot what's wrong with my code? I will be really gladful.
(1) Main Program
import java.io.File;
import java.util.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.IOException;
public class Project {
static final int n = 20;
static final int k = 2;
static int counter = 0;
private static Scanner scan;
public static void main(String[] args) throws IOException {
// Optional - reading from a file containing 512 integers.
InputCreator.main();
File f = new File("random.txt");
// File f = new File("increase.txt");
// File f = new File("decrease.txt");
try { scan = new Scanner(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
int [] L = new int[n];
System.out.print("Original Array ");
for (int i = 0; i < n ; i++)
{ counter++; L[i] = scan.nextInt(); System.out.print(" " + L[i]); }
Projectsort(L);
}
private static void Projectsort(int [] L) {
// int [][] Li = new int [k] [n-(n/k*(k-1))]; // The size of the rest of the integers (n-(n/k*(k-1)) will always be bigger than n/k
int [] temp = new int [n/k], extra = new int [n-(n/k)*(k-1)];
int extraIndex = 0, max, maxIndex = 0, r = 0;
ProjectMaxHeap [] Li = new ProjectMaxHeap [k];
// The following loop's time effiency is O(k) * O(N/k) = O(N)
for (int i=0; i<k-1; i++) { counter++; // copying all the integers from Array L into K-1 smaller arrays
for (int j=0; j<n/k ; j++)
{ counter++; temp [j] = L[i*(n/k)+j]; }
Li[i] = new ProjectMaxHeap (temp); }
for (int i=(n/k)*(k-1) ; i<n ; ++i) // The rest of the integers on array L
{ counter++; extra [extraIndex] = L[i]; extraIndex++; }
Li[k-1] = new ProjectMaxHeap(extra);
System.out.print("\nSorted Array ");
for (int i = n ; i > 0 ; i--) { counter++;
r = 0;
do{max = Li[r].extractMax(); r++; }while(Li[r].isEmpty() && r < k - 1);
for (int j = r; j < k; j++) // Time efficiency O(k)*O(N/k)
{ counter++;
if(!Li[j].isEmpty()) {
if (Li[j].extractMax() > max) {
counter++;
max = Li[j].extractMax();
maxIndex = j; }
}
System.out.print(max + " ");
Li[maxIndex].deleteMax(); } }
System.out.println("\nn = " + n + " k = " + k +"\nThe number of comparisons is " + counter);
}
}
(2) Max Heap Class
public class ProjectMaxHeap
{
private int [] _Heap;
private int _size;
public ProjectMaxHeap (int [] A){
_size = A.length;
_Heap = new int[A.length];
System.arraycopy(A, 0, _Heap, 0, A.length);
for (int i = _size / 2 ; i >=0 ; i--) {
Project.counter++;
maxHeapify(i); }
}
private int parent(int pos)
{ return pos / 2; }
private int leftChild(int pos)
{ return (2 * pos); }
private int rightChild(int pos)
{ return (2 * pos) + 1; }
private void swap(int fpos,int spos) {
int tmp;
tmp = _Heap[fpos];
_Heap[fpos] = _Heap[spos];
_Heap[spos] = tmp; }
private void maxHeapify (int i) {
int l = leftChild(i), r = rightChild(i), largest;
if(l < _size && _Heap[l] > _Heap[i]) {
Project.counter+=2;
largest = l; }
else largest = i;
if(r < _size && _Heap[r] > _Heap[largest]) {
largest = r;
Project.counter+=2; }
if (largest != i) {
Project.counter++;
swap(i, largest);
maxHeapify (largest); }
}
protected boolean isEmpty() { return _size == 0; }
protected void deleteMax() {
if (_size > 1) {
Project.counter++;
maxHeapify(0);
int max = _Heap[0];
_size--;
swap(0, _size);
maxHeapify(0); }
else _size = 0;
}
protected int extractMax() {
maxHeapify(0);
return _Heap[0];
}
}
(3) Input Creator
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.io.FileReader;
import java.io.BufferedReader;
public class InputCreator {
public static void main() {
randomizer();
decrease();
increase();
}
private static void randomizer() {
// The target file
File out = new File("random.txt");
FileWriter fw = null;
int n = 0;
// Try block: Most stream operations may throw IO exception
try {
// Create file writer object
fw = new FileWriter(out);
// Wrap thק writer with buffered streams
BufferedWriter writer = new BufferedWriter(fw);
int line;
Random random = new Random();
while (n < Project.n) {
// Randomize an integer and write it to the output file
line = random.nextInt(1000)-500;
writer.write(line + "\r\n");
n++;
}
// Close the stream
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
private static void increase() {
// The target file
File out = new File("increase.txt");
FileWriter fw = null;
int n = 0;
int temp = 0;
// Try block: Most stream operations may throw IO exception
try {
// Create file writer object
fw = new FileWriter(out);
// Wrap thק writer with buffered streams
BufferedWriter writer = new BufferedWriter(fw);
int line;
Random random = new Random();
while (n < Project.n) {
// Randomize an integer and write it to the output file
line = random.nextInt((n+1)*10);
if(line > temp) {
writer.write(line + "\r\n");
n++;
temp = line; }
}
// Close the stream
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
private static void decrease() {
// The target file
File out = new File("decrease.txt");
FileWriter fw = null;
int n = 0;
int temp = 10000;
// Try block: Most stream operations may throw IO exception
try {
// Create file writer object
fw = new FileWriter(out);
// Wrap thק writer with buffered streams
BufferedWriter writer = new BufferedWriter(fw);
int line;
Random random = new Random();
while (n < Project.n) {
// Randomize an integer and write it to the output file
line = 10000 - random.nextInt((n+1)*20);
if(line < temp) {
writer.write(line + "\r\n");
n++;
temp = line; }
}
// Close the stream
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
The problem is with max = Li[0].extractMax(); You are not checking if Li[0] might be empty.
Always check preconditions and fail fast. The problem would have become immediately obvious had you started extractMax and deleteMax with
if (_size == 0) {
throw new IllegalStateException("empty heap");
}
Here's the fixed final loop:
for (int i = 0; i < n; i++) {
int maxIndex = -1; // remove these variable declarations from top of method
int max = Integer.MIN_VALUE; // it's best to confine variables to narrow scope
for (int j = 0; j < k; j++) {
if (!Li[j].isEmpty()) {
int current = Li[j].extractMax();
if (maxIndex == -1 || current > max) {
maxIndex = j;
max = current;
}
}
}
assert maxIndex != -1;
Li[maxIndex].deleteMax();
System.out.print(max + " ");
}
I have the following piece of code used to calculate Heart Rate from an ECG Signal by detecting the QRS peaks:
public class Heart_Rate {
public static void main(String[] args) throws IOException{
// Read Text file
Path filePath = Paths.get("heartrate.txt");
Scanner scanner = new Scanner(filePath);
List<Double> rawData = new ArrayList<Double>();
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
rawData.add(scanner.nextDouble());
} else {
scanner.next();
}
}
System.out.println(rawData);
//Find Max value for Threshold Level
Double maximum = Collections.max(rawData);
Double threshold = 0.7*maximum;
System.out.println("Maximum = " + maximum);
System.out.println("Threshold = " + threshold);
//Calculate Heart Rate from list "Raw Data"
int upflag = 0;
int last = 1;
int p = 0;
int t = 0;
int count = 0;
//List<Double> heartRate = new ArrayList<Double>();
int heartRate2[] = new int[50];
for (int i = 0; i < rawData.size(); i++) {
if (rawData.get(i)> threshold){
if (upflag == 0){
if (last > 0){
t = i - last;
p = 100*60/t;
//100 is the sampling rate
heartRate2[count] = p;
count = count + 1;
//heartRate.add(p);
}
last = i;
}
upflag = 50;
}
else {
if (upflag > 0){
upflag = upflag -1;
}
}
}
System.out.println("Count = " + count);
System.out.println("Heart Rate = " + heartRate2);
System.out.println("Heart Rate = " + heartRate2);
}
}
When I add the heart rate values calculated(p) to my ArrayList (called HeartRate), I received a proper array of values.
However, I tried to change all my values to int and save my values in an integer array (called heartRate2) I get the following result:
Heart Rate = [I#dd1e765
I need my values to be integers since heart rate is calculated in beats per minute. I also tried converting the double values to int but ended up receiving a similar result as above.
Use Arrays.toString(arr) to get a meaningful String representation for some array arr.
I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?
I was wondering if the following code returns a sum of all the doubles in a text file. It seems to always appear as 0.0 when I test run it. What could be the problem? I
public double honorsCalculation() throws IOException {
Scanner test = new Scanner(new File("Calculus - Test.txt"));
while (test.hasNext()) {
ArrayList <Double> assignments = new ArrayList <Double> ();
double num = test.nextDouble();
assignments.add(num);
for (int i = 1; i < assignments.size() - 1; i++) {
sum = sum + assignments.get(i);
percentage = sum;
}
}
return percentage;
}
You don't need the ArrayList at all, and it's hard to see how a percentage can be equal to a sum, or where your variables are being initialized:
public double honorsCalculation() throws IOException {
double sum = 0;
Scanner test = new Scanner(new File("Calculus - Test.txt"));
while (test.hasNext()) {
sum += test.nextDouble();
}
return sum;
}
You are treating the information before reading all the data.
public double honorsCalculation() throws IOException {
Scanner test = new Scanner(new File("Calculus - Test.txt"));
ArrayList <Double> assignments = new ArrayList <Double> ();
while (test.hasNext()) {
double num = test.nextDouble();
assignments.add(num);
}
for (int i = 1; i < assignments.size() - 1; i++) {
sum = sum + assignments.get(i);
percentage = sum;
}
return percentage;
}
This should be the correct approach.