I am trying to find best subset of set. Imagine that we need to find subset of objects. We have got some fitness function for this subset. So at the beginning we should make a population of subsets and then using GA we should try to find the best subset.
I would like to use Jenetics.io but I do not know how to use it in this case. Problem for me is that chromosomes are much different data structure than subset.
I would like to have a function( population, fitness function) which makes all needed job.
I tried to understand how Jenetics exactly works. Maybe I am wrong but I think there is no way to make it works the way I want.
Please give me advice , maybe there is option to use Jenetics in this case?
There is a sub-set example in the Jenetics library. Essentially, it has the following form:
class SubsetExample
implements Problem<ISeq<MyObject>, EnumGene<MyObject>, Double>
{
// Define your basic set here.
private final ISeq<MyObject> basicSet = ISeq.empty();
private final int subSetSize = 5;
#Override
public Function<ISeq<MyObject>, Double> fitness() {
return subSet -> {
assert(subset.size() == subSetSize);
double fitness = 0;
for (MyObject obj : subSet) {
// Do some fitness calculation
}
return fitness;
};
}
#Override
public Codec<ISeq<MyObject>, EnumGene<MyObject>> codec() {
return codecs.ofSubSet(basicSet, subSetSize);
}
public static void main(final String[] args) {
final SubsetExample problem = new SubsetExample()
final Engine<EnumGene<MyObject>, Double> engine = Engine.builder(problem)
.minimizing()
.maximalPhenotypeAge(5)
.alterers(
new PartiallyMatchedCrossover<>(0.4),
new Mutator<>(0.3))
.build();
final Phenotype<EnumGene<MyObject>, Double> result = engine.stream()
.limit(limit.bySteadyFitness(55))
.collect(EvolutionResult.toBestPhenotype());
System.out.print(result);
}
}
Related
I am trying to use JUNG's EdmondsKarpMaxFlow object to find the max flow between all node pairs in a directed graph. I created a simple directed graph and ran it on each combination of nodes with no error. Here's the working example for reference:
https://pastebin.com/TLsEduxZ
However, when I call the same 'edkAlg.evaluate()' code on a more complex graph, the loop stops on a certain edge/iteration each time.
public class SomeClass{
...
...
MyEdmondsKarpMaxFlow edk = new MyEdmondsKarpMaxFlow(dirGraph);
edk.runEdk();
}
public class MyEdmondsKarpMaxFlow {
int edgeFlowMapId = 0;
protected DirectedSparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> dirGraph;
protected Map<GraphElements.MyEdge, Double> edgeFlowMap = new HashMap<GraphElements.MyEdge, Double>();
protected Transformer<GraphElements.MyEdge, Double> capTransformer = new Transformer<GraphElements.MyEdge, Double>() {
public Double transform(GraphElements.MyEdge edge) {
return edge.getCapacity();
}
};
// This Factory produces new edges for use by the algorithm
protected Factory<GraphElements.MyEdge> edgeFactory = new Factory<GraphElements.MyEdge>() {
public GraphElements.MyEdge create() {
return new GraphElements.MyEdge(Integer.toString(edgeFlowMapId++));
}
};
public MyEdmondsKarpMaxFlow(DirectedSparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> dirGraph) {
this.dirGraph = dirGraph;
}
public void runEdk() {
Collection<GraphElements.MyVertex> vertexCollection = dirGraph.getVertices();
for (Iterator iterator1 = vertexCollection.iterator(); iterator1.hasNext(); ) {
GraphElements.MyVertex v1 = (GraphElements.MyVertex) iterator1.next();
Collection<GraphElements.MyVertex> vertexCollection2 = dirGraph.getVertices();
for (Iterator iterator2 = vertexCollection2.iterator(); iterator2.hasNext(); ) {
GraphElements.MyVertex v2 = (GraphElements.MyVertex) iterator2.next();
if (v1.equals(v2)) continue;
EdmondsKarpMaxFlow<GraphElements.MyVertex, GraphElements.MyEdge> edkAlg = new EdmondsKarpMaxFlow(dirGraph, v1, v2, capTransformer, edgeFlowMap, edgeFactory);
edkAlg.evaluate();
System.out.println("max edk flow between v1 and v2 is : " + edkAlg.getMaxFlow());
}
}
System.out.println("FIN");
}
}
I use custom definitions of Vertices and Edges which behave as expected but simply have more attributes than the trivial example. The code finds max flow between v1 and v2 perfectly fine up to the first 201 iterations, but gets stuck in '.evaluate()' after each time (it uses the same order of pairs each time so it is always stuck on problemNode123 -> problemNode456). Not too sure where I'm going wrong, and there isn't much help online so any pointers are appreciated!
You're not providing quite enough information to be sure, but the problem is almost certainly related to the fact that you haven't defined hashCode() and equals() for your custom node and edge objects.
I used TreeSet for this and it works in a per snapshot style. In other words, sort once displays once.
Now, I want to implement a realtime sorted table.
Whenever there is a value change in any elements, the sorted table will be updated accordingly.
To make the sorting work on a per update style, I tried to remove the element and add it to the TreeSet again.
quotes.remove(quote);
quotes.add(quote);
It doesn't work because I have to implement the sorting logic in compareTo() but it breaks the contract for identifying the object which makes the remove() work. TreeSet never call equals() and hashcode() as described in the Java Doc.
Any idea? Please advise.
code:
import java.util.TreeSet;
public class TreeSetTest {
public static void main(String args[]) {
TreeSetTest test = new TreeSetTest();
test.onQuoteUpdate("appl", 1000d);
test.onQuoteUpdate("msft", 2000d);
test.onQuoteUpdate("face", 3000d);
test.printTopStocks();
test.onQuoteUpdate("msft", 5000d);
test.printTopStocks();
}
private Set<Quote> quotes = new TreeSet<Quote>();
public void onQuoteUpdate(String symbol, double turnover) {
final Quote quote = new Quote(symbol, turnover);
quotes.remove(quote);
quotes.add(quote);
}
public void printTopStocks() {
System.out.println("--Top Stocks By Turnover--");
for (final Quote quote : quotes) {
System.out.println(quote);
}
}
public static class Quote implements Comparable<Quote> {
private String symbol;
private double turnover;
public Quote(String symbol, double turnover) {
this.symbol = symbol;
this.turnover = turnover;
}
#Override
public int compareTo(Quote o) {
return Double.compare(o.turnover, turnover);
// return symbol.compareTo(o.symbol);
}
}
}
Update 1:
As proposed I tried this:
public static void main(String args[]) {
TreeMapTest test = new TreeMapTest();
test.onQuoteUpdate("appl", 1000d);
test.onQuoteUpdate("msft", 2000d);
test.onQuoteUpdate("face", 3000d);
test.printTopStocks();
test.onQuoteUpdate("face", 50d);
test.printTopStocks();
}
public int compareTo(Quote o) {
if(o.symbol.equals(symbol)) return 0;
return Double.compare(o.turnover, turnover);
}
The remove() return false which eventually there are four elements (expected 3) in the Set.
--Top Stocks By Turnover--
Quote [symbol=face, turnover=3000.0]
Quote [symbol=msft, turnover=2000.0]
Quote [symbol=appl, turnover=1000.0]
remove symbol face : false
add symbol face : true
--Top Stocks By Turnover--
Quote [symbol=face, turnover=3000.0]
Quote [symbol=msft, turnover=2000.0]
Quote [symbol=appl, turnover=1000.0]
Quote [symbol=face, turnover=50.0]
Update 2:
I tried PriorityQueue and here is the code:
https://code.sololearn.com/cb38Eo036c8y/#java
It doesn't work because PriorityQueue doesn't store elements in order. The ordering only works when you poll element from the Queue.
Update 3:
Tried user54321's suggestion that by using a custom collection(see below answer). However, it doesn't look good if there are two more elements having the same value of 'turnover'.
My requirement is a very ordinary one. It seems that none of a collection from JDK fits my case.
Update 4:
The solution from user54321 fits for my interim need.
https://code.sololearn.com/c14Ybab7AOFm/#java
Deleted my previously added answer. Looks like a wrong data structure is being used for the scenario.
Here is why.
When an item is being added or removed, TreeSet does a binary search through the available elements using compareTo().
In your case,
After adding first 3 elements, set looks like this.
[{appl, 1000d}, {msft, 2000d}, {face, 3000d}]
Now when you try to remove the element {face, 50d},
It starts searching at {msft, 2000d},
From compareTo() result it determines {face, 50d} should come before {msft, 2000d}.
And continues to search towards start of the elements ( checking with {appl, 1000d} next).
Since the search doesn't find {face, 3000d}, that element remains without being removed.
Next when you add the element {face,50}, similar search happens and since the search does not find {face, 3000},
It adds {face, 50} to the beginning.
Now the set looks like this.
[{face, 50}, {appl, 1000d}, {msft, 2000d}, {face, 3000d}]
Now the problem here is that compareTo() isn't capable of considering both symbol and turnover for a sensible sorting.
TreeSet can be used for getting a sorted collection of unique elements.
If you need to get a sorted collection of different objects with a particular sorting criteria, in this case turnover value, you can use a PriorityQueue
Update: Using a List and a Set in custom data structure
The problem here is that we have to maintain two conditions.
1. Symbol has to be unique
2. Collection should be sorted by turnover value
compareTo() in Quote can check one at a time and not both.
So in this case we may have to go for a custom data structure.
First use only turnover in compareTo();
#Override
public int compareTo(Quote o) {
return Double.compare(o.turnover, turnover);
}
Then implement the custom data structure.
Note that we are using a HashSet to keep track of the symbol alone.
Using a list so that duplicate turnover values can be kept.
static class QuoteCollection {
Set<String> symbols = new HashSet<>();
List<Quote> quotes = new LinkedList<>();
public void onQuoteUpdate(Quote q) {
if (symbols.contains(q.getSymbol())) {
// this requires quotes.equals() to be implemented
quotes.remove(q);
} else {
symbols.add(q.getSymbol());
}
insertToCollection(q);
}
// inserting at correct position to remain sorted
private void insertToCollection(Quote q) {
int index = Collections.binarySearch(quotes, q);
if (index < 0)
index = ~index; // bitwise compliment to find insert position if it is not available in the list
quotes.add(index, q);
}
public List<Quote> getQuotes() {
return quotes;
}
}
Then use it in the main(). Note that printTopStocks() has been changed a little.
public static void main(String args[]) {
Main test = new Main();
QuoteCollection quoteCollection = new QuoteCollection();
quoteCollection.onQuoteUpdate(new Quote("appl", 1000d));
quoteCollection.onQuoteUpdate(new Quote("msft", 2000d));
quoteCollection.onQuoteUpdate(new Quote("face", 3000d));
test.printTopStocks(quoteCollection.getQuotes());
quoteCollection.onQuoteUpdate(new Quote("face", 50d));
test.printTopStocks(quoteCollection.getQuotes());
}
public void printTopStocks(List<Quote> quotes) {
System.out.println("--Top Stocks By Turnover--");
for (final Quote quote : quotes) {
System.out.println(quote);
}
}
This approach does involve data duplication. However a sorted collection can be maintained at linear time complexity(since it uses 'List.remove()')
Couple of points :
Trying to remove elements even when you are adding it first time.
While updating you are trying to remove new element which does not exist in TreeSet. final Quote quote = new Quote(symbol, turnover); here you are building new element which is Quote("face","50d") which does not exist when you are calling quotes.remove(quote);
Below is the one of the way to solve it, I am hard coding oldQuote to keep it short but you can update it:
public void onAdd(String symbol, double turnover) {
final Quote quote = new Quote(symbol, turnover);
quotes.remove(quote);
quotes.add(quote);
}
public void onQuoteUpdate(String symbol, double turnover) {
final Quote newQuote = new Quote(symbol, turnover);
final Quote oldQuote = new Quote("face", 3000d);
quotes.remove(oldQuote);
quotes.add(quote);
}
public static void main(String args[]) {
TreeSetTest test = new TreeSetTest();
test.onAdd("appl", 1000d);
test.onAdd("msft", 2000d);
test.onAdd("face", 3000d);
test.printTopStocks();
test.onQuoteUpdate("face", 50d);
test.printTopStocks();
}
I decided to create a Map to store metric names and the Ranges representing live periods for each metric. At first I used a TreeRangeMap to store the Ranges but since each Metric contains a single Range I switched to Ranges as shown below.
My goal is to keep the latest time range in the DEFAULT_METRICS_MAP when I receive a Range for the metric from external API.
When I had a TreeRangeMap representing Ranges, comparing them was easy. I added new metric to the TreeRangeMap and then got the max range like this:
private static Optional<Range<Long>> maxRange(TreeRangeSet<Long> rangeSet) {
Set<Range<Long>> ranges = rangeSet.asRanges();
return ranges.stream().max(Comparator.comparing(Range::upperEndpoint));
}
What would be the correct way to compare Ranges when they are not wrapped into a TreeRangeMap?
public static final Map<String, Range<Long>> DEFAULT_METRICS_MAP;
static {
Map<String, Range<Long>> theMap = new HashMap<>();
theMap.put("Metric1", Range.closed(Long.MIN_VALUE, Long.MAX_VALUE));
theMap.put("Metric2", Range.closed(10L, 20L));
theMap.put("Metric3", Range.closed(30L, 50L));
METRICS_MAP = Collections.unmodifiableMap(theMap);
}
First of all it was a correct decission to avoid using TreeRangeMap/TreeRangeSet in this particular case. As I understand (correct me if I'm wrong), you don't need to keep all the ranges for all the metrics. What you need is the latest range for each metric at every moment in time.
Ideally you would like to have a very fast method of retriving, like:
Range<Long> range = getRange(metric);
The most efficient way is to compare Range objects on receiving them:
public void setRange(String metric, Range<Long> newRange) {
Range<Long> oldRange = metricRanges.get(metric);
if (comparator.compare(newRange, oldRange) > 0) {
metricRanges.put(metric, newRange);
}
}
Here is the full example:
// Better keep this map encapsulated
private final Map<String, Range<Long>> metricRanges = new HashMap<>();
private final Comparator<Range<Long>> comparator =
Comparator.nullsFirst(Comparator.comparing(Range::upperEndpoint));
static {
// Fill in your map with default ranges
}
public void setRange(String metric, Range<Long> newRange) {
Range<Long> oldRange = metricRanges.get(metric);
if (comparator.compare(newRange, oldRange) > 0) {
metricRanges.put(metric, newRange);
}
}
public Range<Long> getRange(String metric) {
return metricRanges.get(metric);
}
If you still need Optional:
public Optional<Range<Long>> getRange(String metric) {
return Optional.of(metricRanges.get(metric));
}
I have a list as follows
List<Summary> summary;
Summary {
int key;
String value1;
String value2;
}
Is there a way in java (or any other utility library) to replace all occurrences of a String "String1" in the variable value1 without having to loop through the list?
Looping the list is inevitable so you or some third party library has to do the looping. Is it really that hard to do:
for (Summary s : summary)
if (s.value1.equals("String1"))
s.value1 = "...";
? :)
Maybe you could use a library that allow you use it without loops, the problem is that in the low level the compiler must use something like a loop for do it.
I think that direct or indirectly you will use a loop.
So, for this reason you havenĀ“t any problem if use a loop in your code.
Sorry for my English, I hope you can understand all.
You can add a method to find by the object part:
public class ListOfString {
public static void main(String[] args) {
List<Model> models = new ArrayList<>();
for(int i = 0 ; i < 5; i++) {
Model model = new Model();
model.setStr("String"+i);
models.add(model);
}
Model temp = new Model();
temp.setStr("String1");
System.out.println(containsObjectPart(temp, models));
}
// This method just a prototype, you can modify as you like...
private static boolean containsObjectPart(Model obj, List<Model> models) {
for(Model model : models) {
if(model.getStr().equals(obj.getStr()))
return true;
}
return false;
}
}
class Model {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
No you cannot, Loop is invetible.But you can optimize it many area like, selecting loop, how do you find the string and replacing it .etc....
You could avoid a bit of looping - at the expense of losing your list ordering - by using a TreeSet, with value1 values as keys and the Summary objects as values. Then you can do a binary chop search to find all matching entries. A collection which uses hashing would have similar trade-offs and gains.
Otherwise, as everyone else has said, looping is inevitable. The only optimisation you could make is counting the entries as they go into the list so you know when you've found them all so you can stop looping.
But remember, premature optimisation is the root of all evil. :)
I know there is no direct equivalent in Java itself, but perhaps a third party?
It is really convenient. Currently I'd like to implement an iterator that yields all nodes in a tree, which is about five lines of code with yield.
The two options I know of is Aviad Ben Dov's infomancers-collections library from 2007 and Jim Blackler's YieldAdapter library from 2008 (which is also mentioned in the other answer).
Both will allow you to write code with yield return-like construct in Java, so both will satisfy your request. The notable differences between the two are:
Mechanics
Aviad's library is using bytecode manipulation while Jim's uses multithreading. Depending on your needs, each may have its own advantages and disadvantages. It's likely Aviad's solution is faster, while Jim's is more portable (for example, I don't think Aviad's library will work on Android).
Interface
Aviad's library has a cleaner interface - here's an example:
Iterable<Integer> it = new Yielder<Integer>() {
#Override protected void yieldNextCore() {
for (int i = 0; i < 10; i++) {
yieldReturn(i);
if (i == 5) yieldBreak();
}
}
};
While Jim's is way more complicated, requiring you to adept a generic Collector which has a collect(ResultHandler) method... ugh. However, you could use something like this wrapper around Jim's code by Zoom Information which greatly simplifies that:
Iterable<Integer> it = new Generator<Integer>() {
#Override protected void run() {
for (int i = 0; i < 10; i++) {
yield(i);
if (i == 5) return;
}
}
};
License
Aviad's solution is BSD.
Jim's solution is public domain, and so is its wrapper mentioned above.
Both of these approaches can be made a bit cleaner now Java has Lambdas. You can do something like
public Yielderable<Integer> oneToFive() {
return yield -> {
for (int i = 1; i < 10; i++) {
if (i == 6) yield.breaking();
yield.returning(i);
}
};
}
I explained a bit more here.
I know it's a very old question here, and there are two ways described above:
bytecode manipulation that's not that easy while porting;
thread-based yield that obviously has resource costs.
However, there is another, the third and probably the most natural, way of implementing the yield generator in Java that is the closest implementation to what C# 2.0+ compilers do for yield return/break generation: lombok-pg. It's fully based on a state machine, and requires tight cooperation with javac to manipulate the source code AST. Unfortunately, the lombok-pg support seems to be discontinued (no repository activity for more than a year or two), and the original Project Lombok unfortunately lacks the yield feature (it has better IDE like Eclipse, IntelliJ IDEA support, though).
I just published another (MIT-licensed) solution here, which launches the producer in a separate thread, and sets up a bounded queue between the producer and the consumer, allowing for buffering, flow control, and parallel pipelining between producer and consumer (so that the consumer can be working on consuming the previous item while the producer is working on producing the next item).
You can use this anonymous inner class form:
Iterable<T> iterable = new Producer<T>(queueSize) {
#Override
public void producer() {
produce(someT);
}
};
for example:
for (Integer item : new Producer<Integer>(/* queueSize = */ 5) {
#Override
public void producer() {
for (int i = 0; i < 20; i++) {
System.out.println("Producing " + i);
produce(i);
}
System.out.println("Producer exiting");
}
}) {
System.out.println(" Consuming " + item);
Thread.sleep(200);
}
Or you can use lambda notation to cut down on boilerplate:
for (Integer item : new Producer<Integer>(/* queueSize = */ 5, producer -> {
for (int i = 0; i < 20; i++) {
System.out.println("Producing " + i);
producer.produce(i);
}
System.out.println("Producer exiting");
})) {
System.out.println(" Consuming " + item);
Thread.sleep(200);
}
Stream.iterate(seed, seedOperator).limit(n).foreach(action) is not the same as yield operator, but it may be usefull to write your own generators this way:
import java.util.stream.Stream;
public class Test01 {
private static void myFoo(int someVar){
//do some work
System.out.println(someVar);
}
private static void myFoo2(){
//do some work
System.out.println("some work");
}
public static void main(String[] args) {
Stream.iterate(1, x -> x + 1).limit(15).forEach(Test01::myFoo); //var1
Stream.iterate(1, x -> x + 1).limit(10).forEach(item -> myFoo2()); //var2
}
}
I'd also suggest if you're already using RXJava in your project to use an Observable as a "yielder". It can be used in a similar fashion if you make your own Observable.
public class Example extends Observable<String> {
public static void main(String[] args) {
new Example().blockingSubscribe(System.out::println); // "a", "b", "c", "d"
}
#Override
protected void subscribeActual(Observer<? super String> observer) {
observer.onNext("a"); // yield
observer.onNext("b"); // yield
observer.onNext("c"); // yield
observer.onNext("d"); // yield
observer.onComplete(); // finish
}
}
Observables can be transformed into iterators so you can even use them in more traditional for loops. Also RXJava gives you really powerful tools, but if you only need something simple then maybe this would be an overkill.
// Java code for Stream.generate()
// to generate an infinite sequential
// unordered stream
import java.util.*;
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args) {
// using Stream.generate() method
// to generate 5 random Integer values
Stream.generate(new Random()::nextInt)
.limit(5).forEach(System.out::println);
}
}
From here.
I wrote a new library that has implemented generator for Java. It's simple, thread-free and fast.
Here is an example of generating endless fibonacci numbers:
public static Seq<Integer> fibonacci() {
return c -> {
int a = 1;
int b = 1;
c.accept(a);
c.accept(b);
while (true) {
c.accept(b = a + (a = b));
}
};
}
The Seq interface is just like Java Stream and Kotlin Sequence, but faster than all of them.
Here, let's print the first 7 elements of the fibonacci series
Seq<Integer> fib = fibonacci();
fib.take(7).printAll(","); // => 1,1,2,3,5,8,13
For the original problem, yielding all nodes of a tree? One line is enough.
Seq<Node> seq = Seq.ofTree(root, n -> Seq.of(n.left, n.right));