How to visualize an algorithm without changing the code of this algorithm?

I want to visualize two different algorithms that decide if they overlap in a collection of circles in a plane in Java:

  • O (nΒ²) algorithm that checks each combination of circles
  • O (nlogn) algorithm using a scan line

Is there a way to let an object of the vizualization class β€œlisten” to an object of the algorithm class so that it can, for example, see when the algorithm checks for overlap between two circles and knows when to update the visualization?

another example: I can save the list of active circles (those that intersect the scan line) as a variable of the scan line algorithm, and let another class (visualization class) receive this variable. But how does this class know when the list will be updated, and it should update the visualization?

This is just the strategy I was thinking about. Maybe there are better ways ...

+6
source share
3 answers

Perhaps reading the Observer pattern might help you: https://en.wikipedia.org/wiki/Observer_pattern

You can either implement java.util.Observer , or give the algorithm a function / callback object.

You can pass arbitrary observer data to let him decide when the algorithm performs an overlap check.

+1
source

I’m not sure if this will help you or not, but if you cannot change the algorithm code to support observers, then one (interesting) option will concern aspect-oriented programming.

For example, in AspectJ (for example, see http://en.wikipedia.org/wiki/AspectJ ) you can specify (using things called pointcut points) (so-called 'join points') where the extra code bit should be executed ( so-called "advice"). You can use this to detect overlap checks performed by the algorithm and to respond to them as you see fit.

Of course, in this case, the use of AspectJ will be involved, so it would be impossible with normal Java - but this is interesting, which you might think about.

+1
source
  • Have a class (s) that represent the circle (and any other object present in this task / algorithm) and contain methods for each operation.
  • Implement the algorithm as an operation on objects from (1) - as method calls.
  • Create a visualization class that examines objects from 1 and visualizes their state for each method - say - Update() .
  • Subclass all classes in (1) that, in addition to their initial behavior, call Visualization.Update() for each operation.

Create "your world" from (4) classes instead of (1) to have a visualization.

0
source

Source: https://habr.com/ru/post/912543/


All Articles