How to append values to an ArrayList? - collections

How to put the results of this if condition in a array list?
import java.util.ArrayList;
import java.util.Scanner;
public class GreatestCommonDivisor {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a value whose GCD to be computed");
int number = scan.nextInt();
for(int i=1;i<=10;i++) {
if(number%i==0) {
ArrayList<Integer> arr = new ArrayList<Integer>(number) {
}
}
}
}
}

GCD stands for Greatest Common Divisor...which finds the greatest number that divides all the numbers that you specify, but in your code I just see one number.
So from your code I get the idea that you wish to find all the numbers less than 10 (inclusive) that divide number and store those numbers in an arraylist. Assuming my assumption to be correct you can do the following.
Declare your arraylist before the loop:
ArrayList<Integer>arr = new ArrayList<Integer>()
Now run the loop:
for(int i=1;i<=10;i++){
if(number%i==0){
v.add(i);
}
}

Related

Have values of keys of dictionary mapped to their own key

I have this python dictionary
dct = {'A': ['B', 'C'], 'B': ['D'], 'D': ['E'], 'C': ['F'], 'E': ['G']}
and i need a function to return it as
(A(B(D(E(G)))))(C(F))
I am unable to map the elements of each values to their own values. Any help would be appreciated.
Thank you
I'm not good at Python. I developed the function you want in Java. Hope you can convert it easily to Python.
import java.util.HashMap;
import java.util.Map;
public class MapTheMap {
// Count of open parentheses
static int parentheses = 0;
public static void main(String[] args) {
// Creating the map (i.e. dictionary in python)
Map<Character, Character[]> map = new HashMap<>();
map.put('A', new Character[]{'B', 'C'});
map.put('B', new Character[]{'D'});
map.put('D', new Character[]{'E'});
map.put('C', new Character[]{'F'});
map.put('E', new Character[]{'G'});
// The start key is A, you can develop a logic to get the first key if you want to
Character key = 'A';
System.out.print("(" + key);
recursion(map, key);
}
public static void recursion(Map<Character, Character[]> map, Character key) {
// If the map contains the key, add 1 parenthesis, print the value of that key, and call the function again with value as a key (Call 1: Key A -> Value B -- Call 2: Key B --> ...)
if (map.containsKey(key)) {
for (Character valueKey : map.get(key)) {
parentheses++;
System.out.print("(" + valueKey);
recursion(map, valueKey);
}
}
// If the map doesn't contain the key, print close parentheses
else {
while (parentheses >= 0) {
System.out.print(")");
parentheses--;
}
}
}
}
If there is something you don't understand, tell me and I'll try to edit the answer.

How I get real time statistics in MOEA Framework?

I know there is the Instrumenter class, however this method outputs the data after the run finish. I would like to get (near) real-time data, like in the Symbolic Regression in the Demos.
Looking at its code, it seems I need to use the step method and try to imitate the runSingleSeed in Executor. Is there a better way? Some other class like Instrumenter but asynchronous. I cannot really find something similar online.
Just build a wrapper around the cycle (similar to the next one) and make it also a subject in an observer pattern.
import java.util.Properties;
import java.util.Arrays;
import java.text.DecimalFormat;
import org.moeaframework.core.Algorithm;
import org.moeaframework.core.Solution;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Population;
import org.moeaframework.core.NondominatedPopulation;
import org.moeaframework.core.variable.EncodingUtils;
import org.moeaframework.core.spi.AlgorithmFactory;
import org.moeaframework.problem.misc.Kursawe;
public class Main{
public static void main(String[] args){
String algorithmName = "NSGAII";
Properties properties = new Properties();
properties.setProperty("populationSize", "100"); // to change properties
Problem problem = new Kursawe();
Algorithm algorithm = AlgorithmFactory.getInstance()
.getAlgorithm(algorithmName, properties, problem);
int maxGenerations = 100;
int generation = 0;
while( generation < maxGenerations ){
if( generation % 10 == 1 ){
System.out.println("Generation " + generation);
NondominatedPopulation paretoFront = algorithm.getResult();
// metrics
System.out.print("One of the pareto front: ");
System.out.println(toString(paretoFront.get(0)));
}
algorithm.step();
generation++;
}
algorithm.terminate();
System.out.println("Parento Front:");
for(Solution solution: algorithm.getResult()){
System.out.println(toString(solution));
}
export(algorithm.getResult());
}
private static String toString(Solution solution){
StringBuilder out = new StringBuilder();
double[] variables = EncodingUtils.getReal(solution);
double[] objectives = solution.getObjectives();
out.append("f");
out.append(doubleArrayToString(variables));
out.append(" = ");
out.append(doubleArrayToString(objectives));
return out.toString();
}
private static String doubleArrayToString(double[] array){
DecimalFormat format = new DecimalFormat("+#,##0.00;-#");
StringBuilder out = new StringBuilder();
out.append("[");
for(int i = 0; i < array.length-1; i++){
out.append(format.format(array[i]));
out.append(", ");
}
out.append(format.format(array[array.length-1]));
out.append("]");
return out.toString();
}
private static void export(Population population){
System.out.println();
for(Solution solution: population){
double[] objectives = solution.getObjectives();
System.out.println(String.format("%.3f,%.3f", objectives[0], objectives[1]));
}
}
}
Another option for the one indicated by Black Arrow, if you are using multithread, is to extentend AlgorithmFactory. For example:
public class MyAlgorithmFactory extends AlgorithmFactory {
private static Algorithm algorithm;
public Algorithm getGeneratedAlgorithm() {
return this.algorithm;
}
#Override
public Algorithm getAlgorithm(String name, Properties properties, Problem problem){
this.algorithm = super.getAlgorithm(name, properties, problem);
return algorithm;
}
}
Then you use this Factory on your Executor, for example:
MyAlgorithmFactory af = new MyAlgorithmFactory();
Executor executor = new Executor()
.usingAlgorithmFactory(af)
.withAlgorithm("NSGAII") //
.withProblem(yourProblemHere) //
.withMaxEvaluations(10000);
After this you can start the Executor on a separated thread, and call af.getGeneratedAlgorithm() to get the instance of Algorithm initialized by the Executor. From this Algorithm you can get, while the Executor is still running, the actual NondominatedPopulation to calc statistics.

I can't get the output for the vector

Supposedly,this program allows us to store data into the vector.We can keep on entering integers and then the program terminates when there is a non-integer.The program is supposed to print the largest value entered.
****however when I run this code below,I can only keep on entering the integers.And when I enter a non-integer,it gives a list of errors.
My code is(I'm not sure if Im running it correctly):
package javaapplication58;
import java.util.Scanner;
import java.util.Vector;
public class JavaApplication58 {
public static void main(String[] args) {
Vector <Integer> v=new Vector();
v=readInVectorOfIntegers();
System.out.println(largest(v));
}
public static Vector <Integer> readInVectorOfIntegers()
{Scanner in=new Scanner(System.in);
Vector<Integer>w=new Vector ();
while (in.hasNextLine())w.addElement(in.nextInt());
return w;
}
public static int largest(Vector <Integer> v)
{int largestsofar;
if(v.size()>0){largestsofar=v.elementAt(0);
for (int i=0;i<v.size();i++)
if(largestsofar<v.elementAt(i))
largestsofar=v.elementAt(i);
return largestsofar;
}
return 0;
}
}

Coin Change Dynamic Programming

QUESTION:
I'm having trouble finding the minimum amount of coins needed to reach a specific sum. I'm pretty sure this is done easiest recursively and using the dynamic programming methodology, I should basically get Math.min("takeACoin","leaveACoin");
Unfortunately, My code doesn't terminate though I do have if statements that terminate under the condition that the sum is met, the array of coins is depleted, or if the sum is over. Please look at my code below and let me know what I'm doing wrong and especially why my code continues executing until it receives a stackoverflow error though I have the appropriate terminating conditions.
CODE:
private static final int S = 3;
public static int arr[] = {1,2};
public static void main(String[] args) {
Interview i = new Interview();
i.sumCoins(arr, 0);
}
public int sumCoins(int[] ar, int sum) {
//if the sum is met, dont add any coins, just return 0
if(sum == S){
return 0;
}
//if the sum is greater, then return max value as it is impossible to get less sum
if(sum > S){
return Integer.MAX_VALUE;
}
//if the array is out of coins return max value
if(ar.length == 0){
return Integer.MAX_VALUE;
}
//if the sum is less than S and there is still more coins to use, keep checking
//add the first coin
int tmpSum = sum + ar[0];
//delete the first coin from the list
int[] tmp = Arrays.copyOfRange(ar, 1, ar.length);
//add one coin to the solution
int one = 1+sumCoins(tmp, tmpSum);
//don't add one coin to the solution
int two = sumCoins(ar,sum);
//see which is more minimized
return Math.min(one,two);
}
Requested Stack Trace:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.Math.min(Math.java:879)
at java.util.Arrays.copyOfRange(Arrays.java:2623)
at Interview.sumCoins(Interview.java:28)
at Interview.sumCoins(Interview.java:32)
at Interview.sumCoins(Interview.java:32)
The answer to this question is in regards to how I was implementing my dynamic programming. I was using the original array in the case where you left the coin. this is incorrect. In more detail:
If you take the coin: get rid of the first (coin) index of the array, add the sum, add +1 for the number of coins.
If you don't take the coin: get rid of the first (coin) index of the array since you're leaving that coin to not be considered.
In my solution, I received a stackoverflow because I was going through the "leaving the coin" scenario infinite times as the array never decreased and I wasn't actually "leaving the coin".
Correct Code here:
private static final int S = 5;
public static int arr[] = {1,1,1,1,1};
public static void main(String[] args) {
Interview i = new Interview();
System.out.println(i.sumCoins(arr, 0));
}
public int sumCoins(int[] ar, int sum) {
//if the sum is met, dont add any coins, just return 0
if(sum == S){
return 0;
}
//if the sum is greater, then return global array (not local)
//length +1 as it's impossible to get more coins than indices
if(sum > S){
return arr.length+1;
}
//if the array is out of coins return max value
if(ar.length == 0){
return arr.length+1;
}
//if the sum is less than S and there is still more coins to use, keep checking
//add the first coin
int tmpSum = sum + ar[0];
//delete the first coin from the list
int[] tmp = Arrays.copyOfRange(ar, 1, ar.length);
//add one coin to the solution
int one = 1+sumCoins(tmp, tmpSum);
//don't add one coin to the solution
int two = sumCoins(tmp,sum);
//see which is more minimized
return Math.min(one,two);
}

Fibonacci linear time recursion

Why does this work only up to n=90 or so?
Trying to calculate the 94th fibonacci number gives the incorrect result.
Same thing happens if I use the Integer class instead of Long.
import java.util.HashMap;
public class FDP {
private static HashMap<Long, Long> fib = new HashMap<Long, Long>();
private static Long calculateFib(Long n) {
if(fib.get(n)==null){
Long temp = calculateFib(n-1) + calculateFib(n-2);
fib.put(n, temp);
return temp;
}
else{
return fib.get(n);
}
}
}
public static void main(String[] args) {
fib.put(0L, 0L);
fib.put(1L, 1L);
System.out.println(calculateFib(90L)); //success
System.out.println(calculateFib(94L)); //garbage??
}
}
here is a list of the Fibonacci numbers:
http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html
Its an overflow.
The 94th Fibonacci number is: 19740274219868223167
Long.MAX_VALUE is:
9223372036854775807
19740274219868223167 - 9223372036854775807 > 0
You can use BigInteger to handle numbers with arbitrary length.
You reach the limitations of the type Long (64bit), use BigInteger instead

Resources