First Java assignment[Part II]

This is part II of my first Java Assignment.
1.Generating 1000 Random Integer Number
We have to ‘find a way’ to generate 1000 Random Number and save to text file name “array.txt” (that said we have to dig into java standard written code, not to actually code it)

I did find a way to generate Random Number at : http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Random.html

The general syntax is like this :

 Random generator = new Random();  //new random object

generator.nextInt();               //generate a random Number using computer time clock
//milliseconds as seed number
//OR
generator.nextInt(seed);           //using your seed

//make sure you have something to assign to when generating random number



So for generating 1000 number, we just need to make it a for loop that run 1000 times, like this:

//generating 1000 integer number
for (int i = 0; i < 1000; ++i){
randval = generator.nextInt(seed);
//save it to file
//... continue the cycle
}


2.Do some general task that is usually asked for array of numbers.
That is :
a.Find the smallest Number.
b.Find the largest Number.
c.Find the Average.
d.Find the mode.
e.Find the median.
f.Sort the array

Let’s shoot one at a time.
a.b.f.Sort + Largest Number + Smallest number.
It is better to sort the array first so then you automatically know the smallest number(first number : arr[0]) and last number to be the largest number(arr[arr.length-1]).

I use the simple and easy kind of sort : BUBBLE SORT. This sorting scheme is easy but performance suffer from it. Basically, starting from the beginning element, you compare it to the second element, swap the two if it is smaller, then compare first element to the third, the fourth,……nth. Then we do it again starting from second element until you start off with the nth-1 element. In general the number of comparison is $(n-1)^2$, in which n is the number of element in the array, which is bad in performance.

You would think that computer is so fast that we can still do it provided it is easy. In reality, it is not like that. Say for example, you would not want your computer to wasting your time in business world. You have to be fast. Say for example, if 1 comparison takes 1 millisecond then the whole BUBBLE SORT would takes $((n-1)^2)*1$ milliseconds to sort. For example if n = 10,000 , it would take $(10,000 - 1)^2 = 99980001$ milliseconds or 27.7722225 hour or roughly a day and 3 hour to sort just 10,000 number. Can you take this seriously now? Thus, for this assignment, bubble sort is used just for showing, not for doing seriously. Therefore, in a function that generate 1000 random number, I would pass in howMany to generate, just for checking, because if it works for 20 numbers, it would work for 1000 or 10,000. By the way, using this scheme, sorting 1000 numbers would just needs 30 minutes – not bad.

/**
* Sort the array using BUBBLE SORT.
* @param arr - array of number.
*/
public static void sort(int[]arr){

//implement simple and easy 'BUBBLE SORT'
//reimplement using C code MATH201
int tmp = 0;
for (int i = 0; i < arr.length; ++i){
for (int j = i + 1; j < arr.length;++j){
//comparing 2 consecutive number
if (arr[i] >= arr[j]){     //change this to '<=' for descending order
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}


Oh and I would let the user choose their seed value also, because they would not want to wait when I prints off 1000 numbers on the screen and check for everyone of them. Anyhow, by entering this seed value, it helps me do the mode later on.

System.out.print("Please enter your seed number : ");
Scanner sc = new Scanner(System.in);
userSeed = sc.nextInt(); //pass in howManyRandomNumber to generate.
//pass in seed value --> helpful at later time.
generateRandom(howManyRandomNumber, userSeed);


After that, in the main program I just need to write out simple lines :

smallestNumber = Arr[0];
biggestNumber = Arr[Arr.length - 1];

System.out.println("The smallest number is : " + smallestNumber);
System.out.println("The biggest number is : " + biggestNumber);


c.e.AVG + Median
Finding average is easy : $Average = \frac{array[o] + array[1] + ... + array[length-1]}{array.length}$.
Thus all you have to do is loop through the array to find the total number value and divide by array.length.

/**
* Find the average from the records of number
* @param arr - the number array
* @return    - avg the average number
*/
public static int findAvg(int[]arr){
int tmpAvg = 0;

for (int i = 0; i < arr.length; ++i){
tmpAvg += arr[i];
}

tmpAvg /= arr.length;

return tmpAvg;
}


Median is the middle number that divides the array number into 2 halves: the left half and the right half. If the array length is odds, the median is just array[array.length/2]. If the array length is even, the median would be (array[array.length/2] + array[(array.length/2)-1])/2 – the average of the last number of first half and first number of second half.

So, here is code :

/**
* Find the median of the numbers
* @param arr -array of int numbers
* @return  -median numbers
*/

public static int findMedian(int[]arr){

//even case
if ((arr.length % 2) == 0)
return (arr[arr.length/2] + arr[(arr.length/2)-1])/2;

//odd case
else return arr[arr.length/2];

}



d.Find the mode
That is the numbers that appear the most in the sequence, having the greatest frequency. This is when seedNumber helps me.
To count the mode, we would have to count every number and get the number that appear the most. Thus, when generating random numbers, user would enter a seed number so that no matter what how big the array size is, the biggest number cannot get pass seed-1(because it will generate the number in the range 0 – seed – 1). Therefore, I create an array name frequency, whose size is seed to count the mode.
Having done that, all you have to is when you get the number from the input file, increment the value of frequency at that number index or frequency[array[i]]++; so you have a records of all number(which is frequency index)’s mode.

/**
* Get all the number from text to array
* @param arr  -the number array
* @param freg  -the frequency array to count the mode
*/
public static void TextToArray(int[]arr, int []freg){

try{
BufferedReader br = new BufferedReader(
new FileReader("E:\\PortableApps\\eclipse\\workspace\\Hw1\\src\\array.txt"));

String line = br.readLine();
int i = 0;

//reading through the list
while(line != null){
//have to parse the Integer using object
arr[i] = Integer.parseInt(line);

//frequency.. ehhhh..
freg[arr[i]]++;
i++;
line = br.readLine();
}
br.close();
}catch(Exception e){}
}


After that, just loop through frequency array to find the mode, which you have to loop 2 times, the first to find the largest mode, the second time to find numbers that have the same mode:


/**
* Find the mode of the numbers
* @param freg - the frequency array that stores the records of 'howMany'
*       numbers and theirs occurence.
*/
public static void findMode(int[]freg){
int appear_the_most = freg[0];
int noMode = 0;

//finding the number that appear the mode
for (int i = 0; i < freg.length-1; ++i){
if (freg[i] > appear_the_most)
appear_the_most = freg[i];
}

//rescanning for the same-mode number
System.out.print("The mode numbers are[null means none] :");

for (int i = 0; i < freg.length; ++i){
if ((freg[i] == appear_the_most) && (freg[i] > 1))
{
System.out.print(i + " ");
}
else noMode++;
}

if (noMode == freg.length)
System.out.print("null");
System.out.print("\n");
}


Well… Every task done … This is the full code :

/**
* Name   : Duc Ho.
* Class  : MATH410.
* Prof.  : Lonnie Bowe.
* Obj.   :   +Generate 1000 Random Number and save to text file name "array.txt"
*            +Sort the array
*            +Find the Smallest Number
*            +Find the Largest Number
*            +Find the Average
*            +Find the mode
*            +Find the median
*             ?NOTE : User has to enter the seed value to generate in the range (0,seed_number)
* IDE    : Eclipse
* Compiler : Java SE 1.7.0.
* Date  : 02/05/2012.
*/
import java.util.*;
import java.io.*;

public class DucHoA1P2 {

/**
* Generate 'howMany' random number with seed
* @param howMany - howMany random number to generate
* @param seed  - seed value to generate from 0 - seed - 1
*/
public static void generateRandom(int howMany, int seed){

try{
//create a file to save number
//whoever use this file should rewrite the directory to the file
BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\PortableApps\\eclipse\\workspace\\Hw1\\src\\array.txt"));
Random generator = new Random();  //new random object
int randVal;       //take the random value

if (seed > 1000) seed = 1000;
//generate the random Numbers

for (int i = 0; i < howMany; ++i){

randVal = generator.nextInt(seed);  //random val from 0...seed

while (randVal < 0)
randVal = generator.nextInt(seed);

//write out the String representation of Integer
bw.write(String.valueOf(randVal));
bw.newLine();
}

//close the file
bw.close();
}catch(Exception e){}

}

/**
* Get all the number from text to array
* @param arr  -the number array
* @param freg  -the frequency array to count the mode
*/
public static void TextToArray(int[]arr, int []freg){

try{
BufferedReader br = new BufferedReader(
new FileReader("E:\\PortableApps\\eclipse\\workspace\\Hw1\\src\\array.txt"));
String line = br.readLine();
int i = 0;

//reading through the list
while(line != null){
//have to parse the Integer using object
arr[i] = Integer.parseInt(line);
//frequency.. ehhhh..
freg[arr[i]]++;
i++;
line = br.readLine();
}

br.close();
}catch(Exception e){}
}

/**
* Sort the array using BUBBLE SORT.
* @param arr - array of number.
*/
public static void sort(int[]arr){

//implement simple and easy 'BUBBLE SORT'
//reimplement using C code MATH201
int tmp = 0;

for (int i = 0; i < arr.length; ++i){
for (int j = i + 1; j < arr.length;++j){
//comparing 2 consecutive number
if (arr[i] >= arr[j]){
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}

}

/**
* Find the average from the records of number
* @param arr - the number array
* @return    - avg the average number
*/
public static int findAvg(int[]arr){

int tmpAvg = 0;
for (int i = 0; i < arr.length; ++i){
tmpAvg += arr[i];
}

tmpAvg /= arr.length;

return tmpAvg;
}

/**
* Find the median of the numbers
* @param arr -array of int numbers
* @return  -median numbers
*/
public static int findMedian(int[]arr){

//even case
if ((arr.length % 2) == 0)
return (arr[arr.length/2] + arr[(arr.length/2)-1])/2;

//odd case
else return arr[arr.length/2];
}

/**
* Find the mode of the numbers
* @param freg - the frequency array that stores the records of 'howMany'
*       numbers and theirs occurence.
*/
public static void findMode(int[]freg){
int appear_the_most = freg[0];
int noMode = 0;

//finding the number that appear the mode
for (int i = 0; i < freg.length-1; ++i){ if (freg[i] > appear_the_most)
appear_the_most = freg[i];
}

//rescanning for the same-mode number
System.out.print("The mode numbers are[null means none] :");
for (int i = 0; i < freg.length; ++i){
if ((freg[i] == appear_the_most) && (freg[i] > 1)){
System.out.print(i + " ");
}
else noMode++;
}

if (noMode == freg.length)
System.out.print("null");
System.out.print("\n");
}

/**
* Main methods
* Ask user to input seed value
* Allocate the 2 array : numbers and frequency
* Get the value from text and count the frequency
* Sort the Array
* Output the smallest, largest, median, mode numbers.
* @param args - the string array of arguments.
*/
public static void main(String[] args){

//generating random number and save to "array.txt"
//change it to howmany you want
final int howManyRandomNumber = 10;
double biggestNumber = 0;
double smallestNumber = 0;
int avg = 0;          //huuuhhhh AVG
int median = 0;
int userSeed;
System.out.print("Please enter your seed number : ");

Scanner sc = new Scanner(System.in);
userSeed = sc.nextInt();

//allocate the array of 'howManyRandomNumber' size
int[] Arr = new int[howManyRandomNumber];

//frequency array to .... count the frequency
int[] freg = new int[userSeed];

//generate randomNumber function
generateRandom(howManyRandomNumber, userSeed);

TextToArray(Arr,freg);

sort(Arr);

System.out.println("After sort the array becomes:");
for (int i = 0; i < Arr.length; ++i){
System.out.println(Arr[i]);
}

smallestNumber = Arr[0];
biggestNumber = Arr[Arr.length - 1];

System.out.println("The smallest number is : " + smallestNumber);
System.out.println("The biggest number is : " + biggestNumber);

avg = findAvg(Arr);

System.out.println("After scanning AVG, it finds itself: " + avg);

median = findMedian(Arr);

System.out.println("The median is : " + median);

findMode(freg);
}
}



Phew…. Sample run :

Please enter your seed number : 20
After sort the array becomes:
2
2
9
9
10
14
16
17
18
19
The smallest number is : 2.0
The biggest number is : 19.0
After scanning AVG, it finds itself: 11
The median is : 12
The mode numbers are[null means none] :2 9

Advertisements