DMelt:Programming/8 Algorithms

From HandWiki
Jump to: navigation, search
Limitted access. First login to DataMelt if you are a full DataMelt member. Then login to HandWiki as a user.

Programming algorithms

DataMelt includes many 3rd party Java libraries that can be used to learn Java, or can be called by Java scripting languages. For example, it includes java classes from the textbook Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne (http://amzn.to/13VNJi7). The Javadoc of this library is given here edu.princeton.cs.algs4.package-summary edu.princeton.cs.algs4.package-summary. Here we give a simple example of how to use this library using Java.


In our next example we will use the edu.princeton.cs.algs4.StdDraw edu.princeton.cs.algs4.StdDraw for drawing geometric objects. According to the description, it provides a basic capability for creating drawings with your programs. It uses a simple graphics model that allows you to create drawings consisting of points, lines, squares, circles, and other geometric shapes in a window on your computer and to save the drawings to a file. Standard drawing also includes facilities for text, color, pictures, and animation, along with user interaction via the keyboard and mouse.

Here is Jython code that uses edu.princeton.cs.algs4.StdDraw edu.princeton.cs.algs4.StdDraw

# StdDraw class provides a basic capability for creating drawings with your programs. It uses a simple graphics model that allows you to create drawings consisting of points, lines, squares, circles, and other geometric shapes in a window on your computer and to save the drawings to a file.

# You can save the image using "File" and use "*.png" as a file extension.


from edu.princeton.cs.algs4 import StdDraw

StdDraw.square(0.2, 0.8, 0.1)
StdDraw.filledSquare(0.8, 0.8, 0.2)
StdDraw.circle(0.8, 0.2, 0.2)

StdDraw.setPenColor(StdDraw.BOOK_RED)
StdDraw.setPenRadius(0.02)
StdDraw.arc(0.8, 0.2, 0.1, 200, 45)

# draw a blue diamond
StdDraw.setPenRadius()
StdDraw.setPenColor(StdDraw.BOOK_BLUE)
x = [ 0.1, 0.2, 0.3, 0.2 ]
y = [ 0.2, 0.3, 0.2, 0.1 ]
StdDraw.filledPolygon(x, y)

# text
StdDraw.setPenColor(StdDraw.BLACK)
StdDraw.text(0.2, 0.5, "black text")
StdDraw.setPenColor(StdDraw.WHITE)
StdDraw.text(0.8, 0.8, "white text")

This generates an output:

DMelt example: Creating drawings consisting of geometric shapes

Similarly, one can use Java, BeanShell, Groovy and JRuby.