How to recall a method n amount of times? - java

trying to recall a method here (so that it generates different results 100 times using a for loop)
Here is what I have in the main method:
for (int i = 0; i<99; i++) {
double scaleFitness = ScalesSolution.ScalesFitness(randomNumberFile);
System.out.print(scaleFitness + ", ");
}
and this is the method I'm trying to call 100 times (in the ScalesSolution class):
public static double ScalesFitness(ArrayList<Double> weights)
{
int n = scasol.length();
double lhs = 0.0, rhs = 0.0;
if (n > weights.size()) return(-1);
for(int i = 0; i < n; i++){
if(scasol.charAt(i) == '0'){
lhs += weights.get(i);
}
else if (scasol.charAt(i) == '1') {
rhs += weights.get(i);
}
}
return(Math.abs(lhs-rhs));
}
This however prints the same value 100 time over.

Your method "ScaleFitness" and the output of this method is dependent on two variables:
weights
scasol
It seems these variables stay the same for the whole run of the program. So it is not surprising that your output is the same.
If you want a different output for each run of your loop. You need to reset at least one of these variables to a new value.
Btw. methods in Java always start with a lowercase. Classes start with an uppercase.

public static double scalesFitness(ArrayList<Double> weights)
{
double randomElement = weights[((int) (Math.random() * weights.size()))];
This will enable you to retrieve a random element in the array, for manipulation later.

Related

Implementing Euclid's Algorithm in Java

I've been trying to implement Euclid's algorithm in Java for 2 numbers or more.The problem with my code is that
a) It works fine for 2 numbers,but returns the correct value multiple times when more than 2 numbers are entered.My guess is that this is probably because of the return statements in my code.
b) I don't quite understand how it works.Though I coded it myself,I don't quite understand how the return statements are working.
import java.util.*;
public class GCDCalc {
static int big, small, remainder, gcd;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Remove duplicates from the arraylist containing the user input.
ArrayList<Integer> listofnum = new ArrayList();
System.out.println("GCD Calculator");
System.out.println("Enter the number of values you want to calculate the GCD of: ");
int counter = sc.nextInt();
for (int i = 0; i < counter; i++) {
System.out.println("Enter #" + (i + 1) + ": ");
int val = sc.nextInt();
listofnum.add(val);
}
// Sorting algorithm.
// This removed the need of conditional statements(we don't have to
// check if the 1st number is greater than the 2nd element
// before applying Euclid's algorithm.
// The outer loop ensures that the maximum number of swaps are occurred.
// It ensures the implementation of the swapping process as many times
// as there are numbers in the array.
for (int i = 0; i < listofnum.size(); i++) {
// The inner loop performs the swapping.
for (int j = 1; j < listofnum.size(); j++) {
if (listofnum.get(j - 1) > listofnum.get(j)) {
int dummyvar = listofnum.get(j);
int dummyvar2 = listofnum.get(j - 1);
listofnum.set(j - 1, dummyvar);
listofnum.set(j, dummyvar2);
}
}
}
// nodup contains the array containing the userinput,without any
// duplicates.
ArrayList<Integer> nodup = new ArrayList();
// Remove duplicates.
for (int i = 0; i < listofnum.size(); i++) {
if (!nodup.contains(listofnum.get(i))) {
nodup.add(listofnum.get(i));
}
}
// Since the array is sorted in ascending order,we can easily determine
// which of the indexes has the bigger and smaller values.
small = nodup.get(0);
big = nodup.get(1);
remainder = big % small;
if (nodup.size() == 2) {
recursion(big, small, remainder);
} else if (nodup.size() > 2) {
largerlist(nodup, big, small, 2);
} else // In the case,the array only consists of one value.
{
System.out.println("GCD: " + nodup.get(0));
}
}
// recursive method.
public static int recursion(int big, int small, int remainder) {
remainder = big % small;
if (remainder == 0) {
System.out.println(small);
} else {
int dummyvar = remainder;
big = small;
small = dummyvar;
recursion(big, small, remainder);
}
return small;
}
// Method to deal with more than 2 numbers.
public static void largerlist(ArrayList<Integer> list, int big, int small, int counter) {
remainder = big % small;
gcd = recursion(big, small, remainder);
if (counter == list.size()) {
} else if (counter != list.size()) {
big = gcd;
small = list.get(counter);
counter++;
largerlist(list, gcd, small, counter);
}
}
}
I apologize in advance for any formatting errors etc.
Any suggestions would be appreciated.Thanks!
I think these two assignments are the wrong way around
big = gcd;
small = list.get(counter);
and then big not used
largerlist(list, gcd, small, counter);
Also you've used static variables, which is usually a problem.
I suggest removing static/global variables and generally don't reuse variables.
Edit: Oh yes, return. You've ignored the return value of the recursion method when called from the recursion method. That shouldn't matter as you are printing out instead of returning the value, but such solutions break when, say, you want to use the function more than once.

Comparing Two Arrays & Get the Percent that Match - Java

Background: Very new at Java, have little understanding. Would prefer a "point in the right direction" with explanation, if possible, than a copy/paste answer without explanation. If I want to stop being a novice, I need to learn! :)
Anyway, my goal is, as simply as possible, to be given 2 arrays numberList and winningNumbers, compare them, and return the percentage that numberList matches winningNumbers. Both array lengths will always be 10.
I have no idea where to start. I have been googling and going at this for 2 hours. My idea is to write a for loop that compares each individually integer in a string to one in the other, but I am not sure how to do that, or if there is a simpler method. I have little knowledge of arrays, and the more I google the more confused I become.
So far the only thing I have is
public double getPercentThatMatch(int[] winningNumbers) {}
numberList is preset.
one way you could approach it is to:
1) convert both lists to sets.
2) subtract one from the other. ie if 4 are the same, the resulting set will have the 6 values not the same
3) 10 - (size of resulting set) * 100 = %
Here's a runnable example of how you would compare the two arrays of ints to get a percent match.
public class LotteryTicket {
int[] numberList;
LotteryTicket(int... numbers) {
numberList = numbers;
}
public int getPercentThatMatch(int[] winningNumbers) {
Arrays.sort(numberList);
Arrays.sort(winningNumbers);
int i = 0, n = 0, match = 0;
while (i < numberList.length && n < winningNumbers.length) {
if (numberList[i] < winningNumbers[n]) {
i++;
} else if (numberList[i] > winningNumbers[n]) {
n++;
} else {
match++;
i++;
n++;
}
}
return match * 100 / winningNumbers.length;
}
public static void main(String[] args)
{
int[] winningNumbers = { 12, 10, 4, 3, 2, 5, 6, 7, 9, 1 };
LotteryTicket ticket = new LotteryTicket(5, 2, 6, 7, 8, 4, 3, 1, 9, 0);
int percentMatching = ticket.getPercentThatMatch(winningNumbers);
System.out.println(percentMatching + "%");
}
}
Output:
80%
Since you wanted to be pointed in the right direction, rather than havving proper code, and assuming you want to use arrays to solve the problem, try to put something like this in your method:
(loop through arrayA){
(loop through arrayB){
if (current arrayA number is equal to current arrayB number){
then increase match counter by one, since this exists.
also break out of current arrayB loop. (Check next arrayA now.)
}
}
}
When done: return 100*matchCount/totalCount, as a double
So for every index in one array, you check against every other index of the other array. Increase a counter each time there's a match, and you'll be able to get a ratio of matches. If you use an integer as a counter, remember that division with integers acts funky, so you'd need to throw to a double:
double aDoubleNumber = (double) intNumber / anotherIntNumber
The problem would be easier if we consider them set. Let you have two set -
Set<Integer> s1 = //a HashSet of Integer;
Set<Integer> s2 = //a HashSet of Integer;
Now make a copy of s1 for example s11 and do the following thing -
s1.retainAll(s2);
Now s1 contains only element of both sets - that is the intersection.
After that you can easily calculate the percentage
Edit: You can convert the array to a set easily by using the following code snippet (I am assuming you have array of int) -
Set<Integer> s1 = new HashSet<Integer>(Arrays.asList(somePrimiteiveIntArray));
I think this trick will works for other primitive type also.
Hope this will help.
Thanks a lot.
I am going to attempt to beat a dead horse and explain the easiest (conceptual) way to approach this problem I will include some code but leave a lot up to interpretation.
You have two arrays so I would change the overall method to something like this:
public double getPercentage(int[] arrayA, int[] arrayB) {
double percentage=0;
for(/*go through the first array*/) {
for(/*go through second array*/) {
if(arrayA[i]==arrayB[j]) { /*note the different indices*/
percentage++; /*count how many times you have matching values*/
/* NOTE: This only works if you don't have repeating values in arrayA*/
}
}
}
return (percentage/arrayA.length)*100; /*return the amount of times over the length times 100*/
}
You are going to move through the first array with the first loop and the second array with the second loop. So you go through every value in arrayB for each value in arrayA to check.
In my approach I tried storing the winning numbers in a Hashset (one pass iteration, O(n) )
And when iterating on the numberList, I would check for presence of number in Hashset and if so, I will increment the counter. (one pass iteration, so O(n) )
The percentage is thus calculated by dividing the counter with size of array.
See if the sample code makes sense:
import java.util.HashSet;
public class Arraycomparison {
public static void main(String ... args){
int[] arr0 = {1,4,2,7,6,3,5,0,3,9,3,5,7};
int[] arr1 = {5,2,4,1,3,7,8,3,2,6,4,4,1};
HashSet set = new HashSet();
for(int j = 0; j < arr1.length; j++){
set.add(arr1[j]);
}
double counter = 0;
for(int i = 0; i < arr0.length; i++){
if(set.contains(arr0[i])){
counter++;
}
}
System.out.println("Match percentage between arrays : " + counter/arr0.length*100);
}
}
You should use List over array, because that's a convenient way, but with array:
public class Winner {
public static void main(String... args) {
double result = getPercentThatMatch(new int[]{1,2,3,4,5}, new int[]{2,3,4,5,6});
System.out.println("Result="+result+"%");
}
public static double getPercentThatMatch(int[] winningNumbers,
int[] numberList) { // it is confusing to call an array as List
int match = 0;
for (int win : winningNumbers) {
for (int my : numberList ){
if (win == my){
System.out.println(win + " == " + my);
match++;
}
}
}
int max = winningNumbers.length; // assume that same length
System.out.println("max:"+max);
System.out.println("match:"+match);
double devide = match / max; // it won't be good, because the result will be intm so Java will trunc it!
System.out.println("int value:"+devide);
devide = (double) match / max; // you need to cast to float or double
System.out.println("float value:"+devide);
double percent = devide * 100;
return percent;
}
}
Hope this helps. ;)
//For unique elements
getpercentage(arr1, arr2){
res = arr1.filter(element=>arr2.includes(element))
return res.lenght/arr2.lenght * 100;
}
//For duplicate elements
getpercentage(arr1, arr2){
const setA = Set(arr1);
const setB = Set(arr2);
Let res = [ ];
for(let i of setB){
if(setA.has(i)){
res.push(i);
}
}
return res.lenght/setA.size* 100;

For loop containing if statements does not loop again

Below is a method that takes in studentarray and the topStudentIndexof a value calculated by another method previous.
I have multiple objects in my array. However, the for loop only managed to loop through once, and it returned the first value straight away.
I have no clue why the for loop stopped even though my st.lengthis more than
public static int computeNextHighestOverallStudentIndex(Student[] st, int topStudentIndex) {
double nextHighestOverall= 0;
int nextHighestStudentIndex = 0;
for (int i = 0; i < st.length; i++) {
if ((st[i] != null) && (!(i == topStudentIndex))){
double studentOverall = st[nextHighestStudentIndex ].getOverall();
if (studentOverall > nextHighestOverall) {
nextHighestOverall= studentOverall;
nextHighestStudentIndex = i;
}
}
}
return nextHighestStudentIndex ;
}
It looks like
double studentOverall = st[nextHighestStudentIndex ].getOverall();
should be
double studentOverall = st[i].getOverall();
since you want to check all the Students in the array and not just the first one (st[nextHighestStudentIndex ] will always return the first Student, since you initialize nextHighestStudentIndex to 0).
You want to traverse the entire array using st[i] (not st[nextHighestStudentIndex])

Function Values using Differential Evolution

How can I use differential evolution to find the maximum values of the function function f(x) = -x(x+1) from -500 to 500? I need this for a chess program I am making, I have begun researching on Differential Evolution and am still finding it quite difficult to understand, let alone use for a program. Can anyone please help me by introducing me to the algorithm in a simple way and possibly giving some example pseudo-code for such a program?
First, of all, sorry for the late reply.
I bet that you won't know the derivatives of the function that you'll be trying to max, that's why you want to use the Differential Evolution algorithm and not something like the Newton-Raphson method.
I found a great link that explains Differential Evolution in a straightforward manner: http://web.as.uky.edu/statistics/users/viele/sta705s06/diffev.pdf.
On the first page, there is a section with an explanation of the algorithm:
Let each generation of points consist of n points, with j terms in each.
Initialize an array with size j. Add a number j of distinct random x values from -500 to 500, the interval you are considering right now. Ideally, you would know around where the maximum value would be, and you would make it more probable for your x values to be there.
For each j, randomly select two points yj,1 and yj,2 uniformly from the set of points x
(m)
.
Construct a candidate point cj = x
(m)
j + α(yj,1 − yj,2). Basically the two y values involve
picking a random direction and distance, and the candidate is found by adding that random
direction and distance (scaled by α) to the current value.
Hmmm... This is a bit more complicated. Iterate through the array you made in the last step. For each x value, pick two random indexes (yj1 and yj2). Construct a candidate x value with cx = α(yj1 − yj2), where you choose your α. You can try experimenting with different values of alpha.
Check to see which one is larger, the candidate value or the x value at j. If the candidate value is larger, replace it for the x value at j.
Do this all until all of the values in the array are more or less similar.
Tahdah, any of the values of the array will be the maximum value. Just to reduce randomness (or maybe this is not important....), average them all together.
The more stringent you make the about method, the better approximations you will get, but the more time it will take.
For example, instead of Math.abs(a - b) <= alpha /10, I would do Math.abs(a - b) <= alpha /10000 to get a better approximation.
You will get a good approximation of the value that you want.
Happy coding!
Code I wrote for this response:
public class DifferentialEvolution {
public static final double alpha = 0.001;
public static double evaluate(double x) {
return -x*(x+1);
}
public static double max(int N) { // N is initial array size.
double[] xs = new double[N];
for(int j = 0; j < N; j++) {
xs[j] = Math.random()*1000.0 - 500.0; // Number from -500 to 500.
}
boolean done = false;
while(!done) {
for(int j = 0; j < N; j++) {
double yj1 = xs[(int)(Math.random()*N)]; // This might include xs[j], but that shouldn't be a problem.
double yj2 = xs[(int)(Math.random()*N)]; // It will only slow things down a bit.
double cj = xs[j] + alpha*(yj1-yj2);
if(evaluate(cj) > evaluate(xs[j])) {
xs[j] = cj;
}
}
double average = average(xs); // Edited
done = true;
for(int j = 0; j < N; j++) { // Edited
if(!about(xs[j], average)) { // Edited
done = false;
break;
}
}
}
return average(xs);
}
public static double average(double[] values) {
double sum = 0;
for(int i = 0; i < values.length; i++) {
sum += values[i];
}
return sum/values.length;
}
public static boolean about(double a, double b) {
if(Math.abs(a - b) <= alpha /10000) { // This should work.
return true;
}
return false;
}
public static void main(String[] args) {
long t = System.currentTimeMillis();
System.out.println(max(3));
System.out.println("Time (Milliseconds): " + (System.currentTimeMillis() - t));
}
}
If you have any questions after reading this, feel free to ask them in the comments. I'll do my best to help.

Java Fitness Function Not Working

I have a fitness function as part of a lab and wish to apply it to a set of 'weights' (ArrayList weights). I have created the array and stored some values in it. I have created random binary strings (which have an 'x' at the end in order to generate random values) which I wish to also apply the fitness function to; however, the problem I am having is that the fitness function always returns a value of 0. Am I missing something here?
The fitness function is as follows:
public static double scalesFitness(ArrayList<Double> weights){
if (scasol.length() > weights.size()) return(-1);
double lhs = 0.0,rhs = 0.0;
double L = 0.0;
double R = 0.0;
for(int i = 0; i < scasol.length(); i++){
if(scasol.charAt(i) == '0'){
L = L += 0;
}
else if(scasol.charAt(i) == '1'){
R = R += 1;
}
}//end for
int n = scasol.length();
return(L-R);
}
Random binary string method:
private static String RandomBinaryString(int n){
String s = new String();
for(int i = 0; i <= n; i++){
int y = CS2004.UI(0,1);
if(y == 0){
System.out.print(s + '0');
}
else if(y == 1){
System.out.print(s + '1');
}
}
return(s);
}
Main method (in separate class):
public static void main(String args[]){
for(int i = 0; i < 10; i++){
ScalesSolution s = new ScalesSolution("10101x");
s.println();
}
ArrayList<Double> weights = new ArrayList<Double>();
weights.add(1.0);
weights.add(2.0);
weights.add(3.0);
weights.add(4.0);
weights.add(10.0);
System.out.println();
System.out.print("Fitness: ");
System.out.print(ScalesSolution.scalesFitness(weights));
}
Once run, the random binary strings work perfectly well, yet the fitness function fails to change from 0. Here is a sample output:
1101100
1100111
0001111
1001010
1110000
0011111
1100111
1011001
0000110
1000000
Fitness: 0.0
If you wish to code for the whole class(es), then please let me know.
Thank you all so much for your time.
Mick.
Looks to me like you're always returning a blank String from RandomBinaryString() - you print out some digits but never actually append them. Use s = s+'0', or s += '0', or s.concat("0") ,or use a StringBuilder , etc...
I'm assuming scasol is your binary string, so that's empty, then nothing in your for loop gets called once, so L and R both stay at 0.0, and you wind up returning 0.0.
Your random string RandomBinaryString only ever prints 's' it never alters it so the sum of the function is equivalent to returning 'new String()'.
Another issue, 'L = L += 0' is redundant. It is the same as L = 0. Always.
'R = R+=1' is also redundant, it is the same as R += 1.
#DHall Code for scasol constructor:
public ScalesSolution(String s)
{
boolean ok = true;
int n = s.length();
for(int i=0;i<n;++i)
{
char si = s.charAt(i);
if (si != '0' && si != '1') ok = false;
}
if (ok)
{
scasol = s;
}
else
{
scasol = RandomBinaryString(n);
}
}
If this is not of help I can post the code for the class up.
Thanks.
Mick.

Categories