How do I place my values horizontally below a header? - java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
class TestDive
{
private static void displayDifficultyScore(ArrayList<TestDive> alist, double[] dArray)
{
// Create a Random class
Random rand = new Random();
double[] difficulty = new double[5];
for (int i = 0; i < difficulty.length; i++) {
difficulty[i] = 2.0 + rand.nextDouble() * 3.0;
}
for (int i = 0; i < difficulty.length; i++) {
System.out.printf("D %-5d", i+1, difficulty[i]);
System.out.printf("%-5.1f", difficulty[i]);
}
}
public static void main(String[] args)
{
double[] difficulty = new double[1];
ArrayList<TestDive> alist = new ArrayList<TestDive>();
for (int i = 0; i < difficulty.length; i++) {
displayDifficultyScore(alist, difficulty);
}
}
}
This is my current code above. And my current output is this:
D 1 4.5 D 2 4.3 D 3 2.9 D 4 2.5 D 5 4.4
But I want it to look like this:
D 1 D 2 D 3 D 4 D 5
4.5 4.3 2.9 2.5 4.4
Just to mention that I am randomly generating these score values & I'm also making use of Array List to freely print how many D (no.) I want.

Related

How do I generate more values in each column?

I need help to see what I'm doing wrong.
I'm trying to generate 10 random values in 3 columns, but so far I can only generate one.
private static void displayDifficultyScore(ArrayList<TestDive> alist, double[] dArray)
{
// Create a Random class
Random rand = new Random();
double[] diffScores = new double[10];
double[] diffArray = new double[3];
// Print next line
System.out.println();
// Loop for Difficulty Scores
for (int j = 0; j < diffScores.length; j++) {
diffScores[j] = 2.0 + rand.nextDouble() * 3.0;
System.out.printf("%-7.1f%n", diffScores[j]);
}
}
public static void main(String[] args)
{
double[] diffScores = new double[1];
ArrayList<TestDive> alist = new ArrayList<TestDive>();
for (int j = 0; j < diffScores.length; j++) {
displayDifficultyScore(alist, diffScores);
}
}
}
Currently it's only printing out in 1 column:
2.9
4.4
4.9
3.7
4.3
3.1
4.2
4.5
4.2
2.9
Output that I want to achieve:
2.9 3.0 2.2
4.4 3.4 4.7
4.9 2.5 3.0
3.7 4.7 3.3
4.3 4.4 3.8
3.1 3.0 4.9
4.2 2.1 2.9
4.5 5.0 2.2
4.2 4.8 3.6
2.9 2.6 3.1
You can try generating a 2D array (or matrix) first and then printing it
Something like this
public class Hello {
private static double[][] generateDifficultyScores(int matrixLength, int matrixWidth) {
// Create a Random class
Random rand = new Random();
double[][] diffScores = new double[matrixLength][matrixWidth];
// Loop for Difficulty Scores
for (int i = 0; i < matrixLength; i++) {
for (int j = 0; j < matrixWidth; j++) {
diffScores[i][j] = 2.0 + rand.nextDouble() * 3.0;
}
}
return diffScores;
}
public static void main(String[] args) {
// generate random difficulty scores (stores it in a 2D array or matrix of values)
double[][] diffScores = generateDifficultyScores(10, 3);
// print out each array in matrix (line by line)
for (int j = 0; j < diffScores.length; j++) {
// print each element of the array separated by a tab `\t` and formatted to one decimal point
System.out.printf("%7.1f\t%7.1f\t%7.1f", diffScores[j][0], diffScores[j][1], diffScores[j][2]);
// add a newline for next iteration
System.out.println();
}
}
}

How to sort the array in ascending order?

I cannot figure out why the r array will not sort into ascending order. I have tried Array.sort and manually sorting the array.
import java.lang.*;
import java.lang.Object;
import java.lang.Integer;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Gaussian {
public static int seed;
public static final int n = 100;
public static void main(String argv[]) {
double r[] = new double[100];
// Initiate the seed from the current time
GregorianCalendar t = new GregorianCalendar();
int t1 = t.get(Calendar.SECOND);
int t2 = t.get(Calendar.MINUTE);
int t3 = t.get(Calendar.HOUR_OF_DAY);
int t4 = t.get(Calendar.DAY_OF_MONTH);
int t5 = t.get(Calendar.MONTH);
int t6 = t.get(Calendar.YEAR);
seed = t6 + 65*(t5+12*(t4+31*(t3+24*(t2+60*t1))));
if ((seed%2) == 0) seed = seed-1;
**************This is the section giving me trouble*****************
// Put the Gaussian random numbers in the array
for (int i=0; i<n-1; i+=1) {
r = rang();
for (int l=0; l<r.length-1; l++) {
if(r[l] < r[l+1]) {
double tempValue = r[l+1];
r[l+1] = r[l];
r[l] = tempValue;
}
}
System.out.println(r[0]);
******************Between these stars*******************************
}
}
// Method to create two Gaussian random numbers from two
// uniform random numbers in [0,1].
public static double[] rang() {
double x[] = new double[1];
double r1, r2;
r1 = - Math.log(1-ranf());
r2 = 2*Math.PI*ranf();
r1 = Math.sqrt(2*r1);
x[0] = r1*Math.cos(r2);
return x;
}
// Method to generate a uniform random number in [0,1]
// following x(i+1)=a*x(i) mod c with a=pow(7,5) and
// c=pow(2,31)-1. Here the seed is a global variable.
public static double ranf() {
final int a = 16807, c = 2147483647, q = 127773,
r = 2836;
final double cd = c;
int h = seed/q;
int l = seed%q;
int t = a*l-r*h;
if (t > 0) seed = t;
else seed = c+t;
return seed/cd;
}
}
For some reason it is giving me this output:
-0.7286443240313888
0.9205595151394262
-0.1201523471771766
-0.2955395834645375
0.5562293071303744
0.5947383124976592
-0.5190410499731951
1.1878905341959594
-0.6530738641804281
1.92941716216534
-1.55458771926982
1.011542837179014
-1.2973072313970084
-0.5115664645635027
-0.4537839981939878
-0.43386113937789456
2.1877083571592637
-0.1869725174568339
1.0427194985616417
0.7491392218512473
-0.2837863829399006
0.09204148771478798
0.08980225475596745
-1.0595943397788652
0.2493101533697332
-1.3926086961785766
0.9722238128294852
0.4490619874581054
1.4379635505387074
1.4550206564181973
-0.9754513444753741
-1.6454765651087158
0.1683214049373476
0.9981636099004854
-0.7289169766110786
1.6612385375332162
0.19025688479326378
0.0830947016802825
0.4674778575126086
-0.9077431792737849
-0.5638299547034225
0.13229202082089384
1.2429372493642745
-0.006685432080368285
2.336192098747748
-0.5450098522726261
-1.6420372037670146
0.3400579125911062
0.48689741262698993
-0.5075527810259783
1.9679760629290328
-1.9114919760463223
0.5633783650935041
0.12871665512520616
-1.8826404473732248
0.16725744941405607
1.049647212107755
0.767071049830706
0.3366261688045942
-1.726395330988362
-0.15241706234915703
-0.17645549457761323
1.098469368528642
-0.3173352964219553
-2.6584067823396675
0.4136264577634812
-1.2506808927401905
2.0462718170224186
-2.380899123430688
-1.0340941198026203
-3.223035072470854
-0.1423807157151033
-0.048464495873010084
1.4690537691472332
0.9110766995396362
-0.040683539673625924
-0.3895836309957472
-0.4793889976948361
0.007621022168540105
0.4151797552606307
1.2734508381903344
0.6398148976757589
-2.0458807284022114
0.23937728902415573
0.09380205942857836
1.331532378407905
-0.09813530948364875
0.9515533393393638
-1.5924626733327882
-1.2504131049626441
0.3674623983411812
0.8204457493547238
0.2214473639135442
0.5573901544532469
1.6349106235864332
-1.4373482822115147
0.38216369985059967
-0.6869980429363977
0.30632157455967757
Instead of sorting the numbers in ascending order.
The reason the the array is not sorting is because of r = rang();.
Initially, double r[] = new double[100]; sets r to an array of length 100. However, r is being reassigned to the result of rang(), which is an array the length of 1. This causes the inner for loop to never run.
I recommend the following changes:
// I'm assuming that you want 100 Gaussian random numbers, not 99
for (int i = 0; i < r.length; i += 1) {
// you could also change rang() to return a
// double instead of an array of double
// because the array only contains 1 double
double[] randomGaussian = rang();
r[i] = randomGaussian[0];
}
// sort the array
Arrays.sort(r);
// print out the array
for(int i = 0; i < r.length; i++) {
System.out.print(r[i] + " ");
}
I figured it out guys!
// Put the Gaussian random numbers in the array
double copy[] = new double[n];
for (int i=0; i<n-1; i+=1) {
r = rang();
double temp = r[0];
copy[i] = temp;
}
// Sort the array
Arrays.sort(copy);
for (int i=0; i<n-1; i++) {
System.out.println(copy[i]);
}
Gives the right output!

How do I ensure that my fitness keep in range after mutation steps?

I use sphere benchmark function to test evolutionary strategy code with uncorrelate one step size mutation as follow:
public class cromosome {
private double[] variable = new double[2];
private double[] stepSize = new double[2];
private double fitness=0;
}
//=========================method set fitness=========================================
public void setFitness() {
for (int i=0; i<variable.length; i++) {
fitness += variable[i]*variable[i];
}
System.out.println("fitness= " + fitness);
}
my values are in range[-10;+10] after applying mutation steps its seems that my fitness is out of range.
this my mutation method
public static cromosome Mutation(cromosome cro) {
//Mutations with no correlation with one step size
Random r = new Random();
double a = r.nextGaussian();
double lr = 1 / (Math.sqrt(cro.getVariableLenght()));
double[] newMutationStep = new double[1];
newMutationStep[0] = cro.getMutationStep(0) * (Math.exp(lr * a));
double[] newVariable = new double[2];
for (int i = 0; i < cro.getVariableLenght(); i++) {
double b = r.nextGaussian();
newVariable[i] = cro.getVariable(i) + newMutationStep[0] * b;
}
cromosome newKromosom = new cromosome(newVariable[0], newVariable[1], newMutationStep[0]);
return newKromosom;
}
after many iteration the fitness values are out of range, how can I control my fitness ?
You are using r.nextGaussian(). The spread on this variable is larger than 1. Meaning you will sometimes get values below -1 or above 1. This is probably the source of the issue.
To fix it add a validation such as:
double a = r.nextGaussian();
if(a < -1){a = -1;}else if(a > 1){a = 1;}
After this handle it in the same way you are doing now.

How to make a loop for determining class KNN Method

i'm trying to create a program about KNN method and now I'm stuck in loop for determining the class. Here's my coding :
public static void main(String[] args) {
int titikx, titiky, k;
int[] titikxl = new int[]{1, 1, 3, 2, 4, 6}; //first feature
int[] titiky1 = new int[]{1, 3, 1, 5, 3, 2}; //second feature
ArrayList<Double> nx = new ArrayList<Double>(), ny = new ArrayList<Double>(),
fn = new ArrayList<Double>(), arclass1 = new ArrayList<Double>(),
arclass2 = new ArrayList<Double>();
//input hew data's features and k
Scanner input = new Scanner(System.in);
System.out.println("Input first feature : ");
titikx = input.nextInt();
System.out.println("Input second feature : ");
titiky = input.nextInt();
System.out.println("Input k : ");
k = input.nextInt();
//count distance between new data and training data
int i = 0, j = 0;
while(i < titikxl.length || j <titiky1.length){
nx.add(Math.pow(titikx - titikxl[i], 2));
ny.add(Math.pow(titiky - titiky1[j], 2));
i++;
j++;
}
System.out.println(nx);
System.out.println(ny);
//convert arraylist to array
Double[] nxarray = nx.toArray(new Double[nx.size()]);
Double[] nyarray = ny.toArray(new Double[ny.size()]);
//sum the array of distance first feature and second feature to get result
int ii = 0, jj = 0;
while (ii < nxarray.length || jj < nyarray.length){
fn.add(Math.sqrt(nxarray[ii] + nyarray[jj]));
ii++;
jj++;
}
System.out.println(fn);
Double[] fnarray = fn.toArray(new Double[fn.size()]);
Double[] oldfnarray = fnarray; //array result before sort ascending
//ascending array
for(int id1 = 0; id1 < fnarray.length; id1++){
for(int id2 = id1 + 1; id2 < fnarray.length; id2++){
if(fnarray[id1]>fnarray[id2]){
double temp = fnarray[id2];
fnarray[id2] = fnarray[id1];
fnarray[id1] = temp;
}
}
}
for(int id = 0; id < fnarray.length; id++){
System.out.print(fnarray[id] + " ");
}
System.out.println();
double[] classa = new double[]{oldfnarray[0], oldfnarray[1], oldfnarray[2]};
double[] classb = new double[]{oldfnarray[3], oldfnarray[4], oldfnarray[5]};
//determining what class the new data belongs
for(int idb = 0; idb < classa.length; idb++){
for(int idc = 0; idc < classb.length; idc++){
for(int ida = 0; ida < fnarray.length; ida++){
while(ida < k){
if (classa[idb] == fnarray[ida]){
arclass1.add(fnarray[ida]);
}
if (classb[idc] == fnarray[ida]){
arclass2.add(fnarray[ida]);
}
}
}
}
}
if(arclass1.size() < arclass2.size()){
System.out.println("The Class is B");
} else{
System.out.println("The Class is A");
}
}
And the result is :
Input first feature : 2
Input second feature : 3
Input k : 3
[1.0, 1.0, 1.0, 0.0, 4.0, 16.0] //distance feature x
[4.0, 0.0, 4.0, 4.0, 0.0, 1.0] //distance feature y
[2.23606797749979, 1.0, 2.23606797749979, 2.0, 2.0, 4.123105625617661] //result
1.0 2.0 2.0 2.23606797749979 2.23606797749979 4.123105625617661 //ascended result
//looping forever
BUILD STOPPED (total time: 35 seconds)
As you can see, in the section determining class, when enter the loop the program seems doing the last loop forever. I try to modified it as capable as I could, yet still there's no result but error and running forever. Please help. Thank you most kindly.
The problem is the endless while loop - ida's value never changes. I suggest modifying the entire code block because it is more complicated than it needs to be.
Before coming up with a solution, let's determine what we already know:
the nearest k-neighbors (the sorted distances array, with indexes smaller than k)
which neighbors belong to which class
It becomes obvious that in order to determine the class, we need to:
check for every neighbor (outer loop) whether it is in class A (we need a first inner loop) or class B (we need second inner loop)
if neighbor is found to be in class A, we increase counter for class A, otherwise we do that for class B
compare counters: if counter for class A is greater, then the feature belongs in class A, otherwise in class B
To better understand what is going on, the k-NN classification algorithm is described comprehensively in this tutorial.
Code (same structure as yours, though I renamed variables and simplified some parts for readability):
import java.util.Arrays;
import java.util.Scanner;
public class KNN {
public static void main(String[] args) {
int[] feature1 = new int[] { 1, 1, 3, 2, 4, 6 };
int[] feature2 = new int[] { 1, 3, 1, 5, 3, 2 };
//input hew data's features and k
Scanner input = new Scanner(System.in);
System.out.println("Input first feature : ");
int newFeature1 = input.nextInt();
System.out.println("Input second feature : ");
int newFeature2 = input.nextInt();
System.out.println("Input k : ");
int k = input.nextInt();
input.close();
//count distance between new data and training data
double[] distances1 = new double[feature1.length];
double[] distances2 = new double[feature2.length];
for (int i = 0; i < distances1.length; i++) {
distances1[i] = Math.pow(newFeature1 - feature1[i], 2);
}
for (int i = 0; i < distances2.length; i++) {
distances2[i] = Math.pow(newFeature2 - feature2[i], 2);
}
System.out.println("Distance between first feature and first feature training data: " + Arrays.toString(distances1));
System.out.println("Distance between second feature and second feature training data: " + Arrays.toString(distances2));
//sum the array of distance first feature and second feature to get result
double[] distanceSums = new double[distances1.length];
for (int i = 0; i < distances1.length; i++) {
distanceSums[i] = Math.sqrt(distances1[i] + distances2[i]);
}
System.out.println("Distance sums: " + Arrays.toString(distanceSums));
// sort array ascending
double[] distanceSumsSorted = new double[distanceSums.length];
System.arraycopy(distanceSums, 0, distanceSumsSorted, 0, distanceSums.length);
Arrays.sort(distanceSumsSorted);
System.out.println("Sorted distance sums: " + Arrays.toString(distanceSumsSorted));
double[] classAMembers = new double[] { distanceSums[0], distanceSums[1], distanceSums[2] };
double[] classBMembers = new double[] { distanceSums[3], distanceSums[4], distanceSums[5] };
//determining what class the new data belongs
int classACounts = 0;
int classBCounts = 0;
for (int i = 0; i < k; i++) {
// check if nearest neighbor belongs to class A
for (int j = 0; j < classAMembers.length; j++) {
if (distanceSumsSorted[i] == classAMembers[j]) {
classACounts++;
break;
}
}
// check if nearest neighbor belongs to class B
for (int j = 0; j < classBMembers.length; j++) {
if (distanceSumsSorted[i] == classBMembers[j]) {
classBCounts++;
break;
}
}
}
System.out.println("Class A members: " + Arrays.toString(classAMembers));
System.out.println("Class B members: " + Arrays.toString(classBMembers));
System.out.println("Counts for class A: " + classACounts);
System.out.println("Counts for class B: " + classBCounts);
if (classACounts < classBCounts){
System.out.println("The Class is B.");
}
else {
System.out.println("The Class is A.");
}
}
}
For your example data the program outputs:
Input first feature : 2
Input second feature : 3
Input k : 3
Distance between first feature and first feature training data: [1.0, 1.0, 1.0, 0.0, 4.0, 16.0]
Distance between second feature and second feature training data: [4.0, 0.0, 4.0, 4.0, 0.0, 1.0]
Distance sums: [2.23606797749979, 1.0, 2.23606797749979, 2.0, 2.0, 4.123105625617661]
Sorted distance sums: [1.0, 2.0, 2.0, 2.23606797749979, 2.23606797749979, 4.123105625617661]
Class A members: [2.23606797749979, 1.0, 2.23606797749979]
Class B members: [2.0, 2.0, 4.123105625617661]
Counts for class A: 1
Counts for class B: 2
The Class is B.

how to find average of a List java

I have a question on how to find the average of a List. I don't know what is wrong with my code, because I did the same for all the three averages but only the first one works, the others just show 0, as shown below in my output:
Average: 58 0 0
Below is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Hurricanes2{
public static void main(String args[]) throws FileNotFoundException{
Scanner scan = new Scanner(new FileReader(new File("/Users/timothylee/hurcdata2.txt")));
List<Integer> year = new ArrayList<Integer>();
List<Integer> windspeed = new ArrayList<Integer>();
List<Integer> pressure = new ArrayList<Integer>();
List<String> name = new ArrayList<String>();
List<Integer> category = new ArrayList<Integer>();
while(scan.hasNext()){
String input = scan.nextLine();
String[] hurricane = input.split("\\s+");
year.add(Integer.parseInt(hurricane[0]));
windspeed.add(Integer.parseInt(hurricane[2]));
pressure.add(Integer.parseInt(hurricane[3]));
name.add(hurricane[4].trim());
category.add(Integer.parseInt(hurricane[5]));
}
int sum = 0;
for(Integer integer : pressure){
sum += integer.intValue();
}
double average = sum / pressure.size();
// create menu
System.out.printf("%50s%n%n", "Hurricanes 1980 - 2006");
System.out.printf("%1s%20s%20s%20s%20s%n", "Year", "Hurricane",
"Category", "Pressure(mb)", "Wind Speed (mph)");
System.out.println("__________________________________________________"
+ "__________________________________");
for(int i = 0; i < year.size(); i++){
System.out.printf("%4d%20s%20d%20d%20d%n", year.get(i), name.get(i)
, category.get(i), pressure.get(i), windspeed.get(i));
}
System.out.println("__________________________________________________"
+ "__________________________________");
int averageCategory = 0;
int averagePressure = 0;
int averageWindSpeed = 0;
for(int i = 0; i < category.size(); i++){
averageCategory = i / category.get(i);
averagePressure = i / pressure.get(i);
averageWindSpeed = i / windspeed.get(i);
}
System.out.printf("%1s%35d%35d%35d%n", "Average: ", averageCategory,
averagePressure, averageWindSpeed);
}
}
How can I fix this? Any help will be greatly appreciated.
I can't see your input, but....
I don't think your for loop is doing what you want it to. Each iteration, it is completely overwriting what is in averageCategory, averagePressure, averageWindspeed with whatever is on the right side of the equals sign.
Is this is what you meant to do? Usually in calculating averages we get a sum and then divide once by the total number of items.
You are doing wrong here:
double average = sum / pressure.size();
In this way you are doing integer division, which is not good when computing average, expecially if the values are near to 1.
You need to cast it:
double average = (double)sum / (double)pressure.size();
also you need to cast here:
for(int i = 0; i < category.size(); i++){
averageCategory = (int) ((double)i / (double)category.get(i));
averagePressure =(int) ((double) i / (double)pressure.get(i));
averageWindSpeed = (int) ((double)i / (double)windspeed.get(i));
}
Also, this last piece of code doesn't seem to calculate any average. You should calculate the sum and divide it for the size of data. But remember to cast integer division to double as I shown.

Categories