List of Common Algorithms – Part 4

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code and information is given ‘as is’. I do not take responsibilities of how they are used.

< List of Common Algorithms – Part 3

  1. Octrees Method: This method is used for the viewing of visible surface identification plus viewing volume by searching octree nodes in a front-to-back order.
  2. Ray-Casting Method: This is a visibility-detection tool based on geometric-optics method.
  3. Curved-Surface Representation: Representation of a surface using an implicit equation or a parametric representation.
  4. Surface Contour Plots: Explicit functional representation used to plot visible surface contour lines and elimination of contour sections that are hidden by the visible parts of the surface.
  5. Wire-Frame Surface-Visibility Algorithm: Similar method used for line-clipping algorithm, identify visible line sections comparing edge positions with the positions of the surface in a scene.
  6. Wire-Frame Depth-Cueing Algorithm: By variation of the brightness of objects in a scene as a function of distance from the viewing position, information for the displaying of objects can be obtained.

< List of Common Algorithms – Part 3

Share
Leave a comment

List of Common Algorithms – Part 3

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code and information is given ‘as is’. I do not take responsibilities of how they are used.

< List of Common Algorithms – Part 2 | List of Common Algorithms – Part 4 >

  1. Cohen-Sutherland Line Clipping Algorithm: Algorithm for fast line clipping. There are chances of clipping a single line segment multiple times.
  2. Cyrus–Beck Line Clipping Algorithm: Fast parametric line-clipping algorithm.
  3. Liang-Barsky Line Clipping Algorithm: simplified and optimized version of Cyrus-Beck line clipping algorithm for rectangular clip window.
  4. Nicholl–Lee–Nicholl Line Clipping Algorithm: Fast line clipping algorithm which reduces the chances of clipping a single line segment multiple times.
  5. Fast Clipping Algorithm: Using a nine area grid, start and end positions are classified. There exist some similarities between this algorithm and  Cohen-Sutherland algorithm; however, this algorithm may have to iterate several times.
  6. O(log N) Algorithm: Vertices are classified against a given line using an implicit form.
  7. Skala Algorithm: This algorithm is use for line or line segment clipping against rectangular window and/or convex polygon.
  8. Sutherland-Hodgman Polygon Clipping Algorithm: Method for clipping a convex-polygon fill area.
  9. Weiler-Atherton Polygon Clipping Algorithm: Polygon-clipping used for clip a fill area that can be a concave polygon or convex polygon.
  10. All-or-None String-Clipping Strategy: Display only those strings that are inside the clipping window.
  11. All-or-None Character-Clipping Strategy: Display only those characters that are completed inside the clipping window.
  12. Character-Clipping Strategy: Clip the components of individual characters.
  13. Natural Cubic Splines: Used for spline curves in which two adjacent curve sections have the same first and second parametric derivatives at their common boundary.
  14. Hermite Interpolation: Interpolating piecewise cubic polynomial in which each control point is an specified tangent.
  15. Cardinal Splines: They are similar to Hermite splines; however, the user do not input the values for the endpoint tangents.
  16. Catmull-Rom Splines: Also known as Overhauser splines. They are cardinal splines in which the value of the tension is zero.
  17. Kochanek-Bartels Splines: These splines are an extension of the cardinal splines. They have two additional parameters which provide a further flexibility when adjusting the shapes of the curve sections.
  18. Bézier Spline Curves: This kind of spline can be fitted with any number of control points. The number of control points and their relative position determine the degree of the Bézier polynomial.
  19. Bézier Surfaces: Object surface designed using two sets of Bézier curves.
  20. B-Spline Curves: Similar to Bézier splines since they are generated by approximating a set of control points. However, the degree of polynomial are set independently of the number of control points plus these control points can be located over the shape of the spline.
  21. Uniform Periodic B-Spline Curves: This kind of curve is the result of a constant spacing between the knot values.
  22. Open Uniform B-Spline Curves: Special type of uniform B-Spline. With exception of the ends, the knot spacing is uniform plus the knot values are repeated a certain number of times.
  23. Non-uniform B-Spline Curves: Multiple internal knots values and unequal spacing between these knots values can be chosen.
  24. B-Spline Surfaces: By using a Cartesian product of B-Spline blending functions, we can obtain a vector point over the surface.
  25. Beta-Splines: They are formulated by imposing geometric continuity conditions over the first and second parametric derivatives.
  26. Rational Splines: The ratio of two spline functions.
  27. Horner’s Rule: Method for polynomial evaluation by performing successive factoring.
  28. Forward-Difference Calculations: By generating successive values recursively, this method can evaluate polynomial functions fast.
  29. Recursive Spline-Subdivision: Method for repeatedly division of a given curve section in half by increasing the number of control points at each division.
  30. Sweep Representation: Construction techniques use for the construction of three-dimensional objects.
  31. Constructive Solid-Geometry Methods: Also known as constructive solid geometry (CSG). Solid objects are constructed by applying the union, intersection, or difference operation of two other solid objects.
  32. Octrees: These are hierarchical tree structures which are used for the representation of solid objects.
  33. Binary Space-Partitioning (BSP) Trees: A scene is subdivided into two sections at each step with a plane positioned in any position and orientation.
  34. Fractal-Geometry Methods: Procedures rather than equations are used in order to obtain a model object.
  35. Self-similar Fractals: All parts are scaled down versions of the entire object.
  36. Self-affine Fractals: All parts are versions of the entire object with different scaling parameters and coordinate directions.
  37. Invariant Fractal Sets: These are self-squaring fractals, self-inverse fractals, and Mandelbrot sets constructed using inversion procedures.
  38. Topological Conversion Methods: Used for the approximation of object subparts using simple shapes.
  39. Hausdorff-Besicovitch Dimension: Also known as fractional dimension. Covering method which use circles and spheres used as the fractal dimension of objects.
  40. Random Midpoint-Displacement Methods: They are used for geometric constructions and were developed for the approximation fractional Brownian-motion representation.
  41. Particle system: By using a collection of disjoint pieces, one or more objects can be described.
  42. Physical Based Modelling: Use to describe behaviours of an object in terms of interaction of internal and external forces.
  43. Contour Plots: They are used for the display of lines of constant values known as isolines which indicate a scalar data set distributed over the object’s surface.
  44. Back-Face Detection: A fast method used for locating the back faces of polyhedron.
  45. Depth-Buffer Method: By comparing surface depth values of each pixel position  throughout a scene, we can detect the visible surfaces.
  46. A-Buffer Method: This method is an extension of the depth-buffer method. By using anti-aliasing, area-averaging, and visibility-detection methods a buffer region is produced  (also known as accumulation buffer).
  47. Scan-Line Method: This method is used for the identification of visible surfaces by comparing depth values along the various scan lines for a scene.
  48. Depth-Sorting Method: Surfaces are sorted in order of decreasing depth and scan-converted in order ascending order from the greatest depth.
  49. BSP-Tree Method: By painting surfaces from the back of the frame buffer to the front of it, The object visibility is determined.
  50. Area-Subdivision Method: This method locates projection areas which are a representation of a single surface.

< List of Common Algorithms – Part 2 | List of Common Algorithms – Part 4 >

Share
Leave a comment

List of Common Algorithms – Part 2

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code and information is given ‘as is’. I do not take responsibilities of how they are used.

< List of Common Algoritms – Part 1 | List of Common Algorithms – Part 3 >

  1. Adjacency-matrix representation: Numbered vertices of a graph are represented in a matrix.
  2. Breadth-first search: Algorithm for searching a graph. All the edges of a graph are discovered in a systematic search. Computing the distance from the start point  to each reachable vertex.
  3. Topological sort: Linear ordering of all vertices of a graph in with the one vertex must appear before another in an order.
  4. Minimum Spanning Trees: Algorithm design to solve undirected graphs.
  5. Kruskal’s algorithm: Algorithm based on the generic minimum-spanning-tree algorithm. It finds all the edges that connect any two trees in the forest.
  6. Prim’s algorithm: Algorithm based on the generic minimum-spanning-tree algorithm but behaves similar to Dijkstra algorithm. Used for finding the shortest path in a graph.
  7. Shortest-paths problem (SPP): Given a weighted, directed graph plus a weight function map the edges to real-valued weights. Find the shortest path.
  8. Bellman-Ford algorithm: Single-source shortest-paths problem in which edge weights may be negative.
  9. Single source shortest paths in directed acyclic graphs: Topologically sorting the directed acyclic path to provide a linear ordering on the vertices.
  10. Dijkstra’s algorithm: Repeatedly a vertex is selected with the minimum shortest-path estimate by adding the weight and relaxing all edges leaving the first edge.
  11. All-Pairs Shortest Paths: Finding the shortest paths between all pairs of vertices in a graph.
  12. Floyd-Warshall algorithm: Dynamic-programming formulation to solve all-pairs shortest-paths problem on a directed graph.
  13. Johnson’s algorithm for sparse graphs: Finding the shortest  paths between all pairs. Better than either repeated squaring of matrices or Floyd-Warshall algorithm.
  14. Maximum Flow: Problem concerting flow networks.
  15. Ford-Fulkerson method: Methods for maximum flow problem which focus on residual networks, augmenting paths, and cuts. Essential concept for maximum flow min-cut theorem.
  16. Edmonds-Karp algorithm: Algorithm that implement the computation of the augmenting path with a breadth-first search.
  17. Maximum Bipartite Matching: Matching of maximum cardinality.
  18. Push-relabel Algorithm: Way to solve asymptotically fastest maximum-flow algorithms.
  19. Relabel-to-front algorithm: A push-relabel algorithm better fit for dense networks.
  20. Zero-one principle: Sorting a network with this principle allows to focus on their operation for input sequences consisting solely of 0’s and 1’s.
  21. Bitonic sorting network: A bitonic sequence that monotonically increases and then decreases. This is a comparison network that sorts bitonic sequences of 0’s and 1’s.
  22. Half-cleaner: Bitonic sorter which is composed  of several stages. Each of these stages is called half-cleaner which are a comparison network of depth 1.
  23. Bitonic sorter: A network that sorts bitonic sequences.
  24. Merging network: Networks that can be merge two sorted input sequences into one sorted output sequence.
  25. Permutation network: inputs and output are connected according to any allowed permutation.
  26. Strassen’s algorithm: Recursively algorithm used for matrix multiplication.
  27. LUP decomposition: Find three matrices such that the multiplication of a permutation matrix with a custom defined matrix is the same as the multiplication of a a unit lower-triangular matrix with an upper-triangular matrix.
  28. Forward and back substitution: Way to solve lower-triangular system.
  29. Least-squares approximation: Way to provide curves to given sets of data points in symmetric positive-defined matrices.
  30. Rabin-Karp algorithm: string-matching algorithm.
  31. Knuth-Morris-Patt algorithm: linear-time sting-matching algorithm.
  32. Jarvis’s march: Way to compute the convex hull of a set of points by using package wrapping technique.
  33. Hamiltonian Cycles: A simple cycle that contains each vertex of an undirected graph.
  34. Vertex-cover problem: Undirected graph in which each vertex covers its incident edge.
  35. Digital Differential Analyzer (DDA): Scan-conversion line-drawing algorithm.
  36. Bresenham’s Line Algorithm: Efficient raster line-generating algorithm in which only incremental integer calculations are used.
  37. Midpoint Circle Algorithm: Raster algorithm in which each unit interval, we determine the closest pixel position that match the circle path at each step.
  38. Midpoint Ellipse Algorithm: Similar algorithm used for drawing circles. After determining the curve positions for the ellipse, all the points are shift using a fixed offset so that the ellipse is centered.
  39. Spilling Concave Polygons: Split identified concave polygon into a set of convex polygons. Another variation is to split the concave polygon into a set of triangles.
  40. Inside-Outside Test: System to identify interior areas of a plane figure by using odd-even rule (also known as odd-parity rule). Another method use is called non-zero winding-number rule.
  41. Odd-Parity Rule: Method to identify interior regions by counting the number of segments crossed by a line.
  42. Non-zero Winding-Number Rule: Method to define interior regions by counting the number of times the boundary of an object “winding” around a defined point in the counter-clockwise direction.
  43. Polygon Tables: Normally consistent of three listing of geometric data which provides reference to the individual components (such as edges, vertices, and surface facets) for each object.
  44. Linear Soft-Fill Algorithm: Algorithm which help to repaint an area which was originally painted by merging a single background color with foreground color.
  45. Scan-Line Fill Algorithm: Algorithm which help to identify the same interior regions as the Odd-Parity rule.
  46. Boundary-Fill Algorithm: This algorithm will fill the interior of a region pixel by pixel until a boundary specified by a color is encountered.
  47. Flood-Fill Algorithm: This algorithm paints an area defined by different color regions by replacing a specified interior color instead of searching for a boundary color.
  48. Pitteway-Watkinson Algorithm: This algorithm is a modification to Bresenham’s algorithm. Depending of the area of overlap of the line plus the pixel, each pixel is given an intensity; therefore,  the effect of anti-aliasing is reduced due to the
  49. blurring effect which goes along the line edges.
  50. Rigid-body Transformation: Its a translation which moves objects without deforming them.

< List of Common Algoritms – Part 1 | List of Common Algorithms – Part 3 >

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code and information is given ‘as is’. I do not take responsibilities of how they are used.

  1. Digital Differential Analyzer (DDA): Scan-conversion line-drawing algorithm.
  2. Bresenham’s Line Algorithm: Efficient raster line-generating algorithm in which only incremental integer calculations are used.
  3. Midpoint Circle Algorithm: Raster algorithm in which each unit interval, we determine the closest pixel position that match the circle path at each step.
  4. Midpoint Ellipse Algorithm: Similar algorithm used for drawing circles. After determining the curve positions for the ellipse, all the points are shift using a fixed offset so that the ellipse is centered.
  5. Spilling Concave Polygons: Split identified concave polygon into a set of convex polygons. Another variation is to split the concave polygon into a set of triangles.
  6. Inside-Outside Test: System to identify interior areas of a plane figure by using odd-even rule (also known as odd-parity rule). Another method use is called non-zero winding-number rule.
  7. Odd-Parity Rule: Method to identify interior regions by counting the number of segments crossed by a line.
  8. Non-zero Winding-Number Rule: Method to define interior regions by counting the number of times the boundary of an object “winding” around a defined point in the counter-clockwise direction.
  9. Polygon Tables: Normally consistent of three listing of geometric data which provides reference to the individual components (such as edges, vertices, and surface facets) for each object.
  10. Linear Soft-Fill Algorithm: Algorithm which help to repaint an area which was originally painted by merging a single background color with foreground color.
  11. Scan-Line Fill Algorithm: Algorithm which help to identify the same interior regions as the Odd-Parity rule.
  12. Boundary-Fill Algorithm: This algorithm will fill the interior of a region pixel by pixel until a boundary specified by a color is encountered.
  13. Flood-Fill Algorithm: This algorithm paints an area defined by different color regions by replacing a specified interior color instead of searching for a boundary color.
  14. Pitteway-Watkinson Algorithm: This algorithm is a modification to Bresenham’s algorithm. Depending of the area of overlap of the line plus the pixel, each pixel is given an intensity; therefore,  the effect of antialiasing is reduced due to the blurring effect which goes along the line edges.
  15. Rigid-body Transformation: Its a translation which moves objects without deforming them.
  16. Cohen-Sutherland Line Clipping Algorithm: Algorithm for fast line clipping. There are chances of clipping a single line segment multiple times.
  17. Cyrus–Beck Line Clipping Algorithm: Fast parametric line-clipping algorithm.
  18. Liang-Barsky Line Clipping Algorithm: simplified and optimized version of Cyrus-Beck line clipping algorithm for rectangular clip window.
  19. Nicholl–Lee–Nicholl Line Clipping Algorithm: Fast line clipping algorithm which reduces the chances of clipping a single line segment multiple times.
  20. Fast Clipping Algorithm: Using a nine area grid, start and end positions are classified. There exist some similarities between this algorithm and  Cohen-Sutherland algorithm; however, this algorithm may have to iterate several times.
  21. O(log N) Algorithm: Vertices are classified against a given line using an implicit form.
  22. Skala Algorithm: This algorithm is use for line or line segment clipping against rectangular window and/or convex polygon.
  23. Sutherland-Hodgman Polygon Clipping Algorithm: Method for clipping a convex-polygon fill area.
  24. Weiler-Atherton Polygon Clipping Algorithm: Polygon-clipping used for clip a fill area that can be a concave polygon or convex polygon.
  25. All-or-None String-Clipping Strategy: Display only those strings that are inside the clipping window.
  26. All-or-None Character-Clipping Strategy: Display only those characters that are completed inside the clipping window.
  27. Character-Clipping Strategy: Clip the components of individual characters.
  28. Natural Cubic Splines: Used for spline curves in which two adjacent curve sections have the same first and second parametric derivatives at their common boundary.
  29. Hermite Interpolation: Interpolating piecewise cubic polynomial in which each control point is an specified tangent.
  30. Cardinal Splines: They are similar to Hermite splines; however, the user do not input the values for the endpoint tangents.
  31. Catmull-Rom Splines: Also known as Overhauser splines. They are cardinal splines in which the value of the tension is zero.
  32. Kochanek-Bartels Splines: These splines are an extension of the cardinal splines. They have two additional parameters which provide a further flexibility when adjusting the shapes of the curve sections.
  33. Bézier Spline Curves: This kind of spline can be fitted with any number of control points. The number of control points and their relative position determine the degree of the Bézier polynomial.
  34. Bézier Surfaces: Object surface designed using two sets of Bézier curves.
  35. B-Spline Curves: Similar to Bézier splines since they are generated by approximating a set of control points. However, the degree of polynomial are set independently of the number of control points plus these control points can be located over the shape of the spline.
  36. Uniform Periodic B-Spline Curves: This kind of curve is the result of a constant spacing between the knot values.
  37. Open Uniform B-Spline Curves: Special type of uniform B-Spline. With exception of the ends, the knot spacing is uniform plus the knot values are repeated a certain number of times.
  38. Non-uniform B-Spline Curves: Multiple internal knots values and unequal spacing between these knots values can be chosen.
  39. B-Spline Surfaces: By using a Cartesian product of B-Spline blending functions, we can obtain a vector point over the surface.
  40. Beta-Splines: They are formulated by imposing geometric continuity conditions over the first and second parametric derivatives.
  41. Rational Splines: The ratio of two spline functions.
  42. Horner’s Rule: Method for polynomial evaluation by performing successive factoring.
  43. Forward-Difference Calculations: By generating successive values recursively, this method can evaluate polynomial functions fast.
  44. Recursive Spline-Subdivision: Method for repeatedly division of a given curve section in half by increasing the number of control points at each division.
  45. Sweep Representation: Construction techniques use for the construction of three-dimensional objects.
  46. Constructive Solid-Geometry Methods: Also known as constructive solid geometry (CSG). Solid objects are constructed by applying the union, intersection, or difference operation of two other solid objects.
Share
Leave a comment

List of Common Algorithms – Part 1

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code and information is given ‘as is’. I do not take responsibilities of how they are used.

List of Common Algorithms – Part 2 >

  1. Insertion sort: Efficient for sorting small number of elements. Remove one element at a time and insert it back into the correct position.
  2. Merge sort: Divide-and-conquer sorting algorithm. Divide the problem into small sub-problems. Solve the sub-problems recursively. Combine the solution of the sub-problems into the solution for the original problem.
  3. Bubble sort: Repeatedly swap adjacent elements in the right order.
  4. Horner’s polynomial rule: A rule which the number of necessary multiplications and results in less numerical instability due to potential subtraction of one large number from another are reduced.
  5. Permute-By-Sorting: Randomized algorithm in which the input is randomized by permuting the input array. This algorithm belong to the uniform random permutation algorithms.
  6. Randomize-In-Place: This algorithm belong to the uniform random permutation algorithm.
  7. Heapsort: Array in which elements can be viewed as a complete binary tree. Each node satisfy a heap property.
  8. Max-Heapify: subroutine for manipulating max-heaps. Normally used for Heapsort.
  9. Priority Queues: A set of data sequence in which each set of elements is associated with a value called key.
  10. Quicksort: Divide-and-conquer sorting algorithm. Uses a partition algorithm in order to divided the array.
  11. Random Sampling Quicksort: This version of the Quicksort algorithm performs a randomized-partition.
  12. Hoare partition: This version of the Quicksort algorithm performs a partition with the use of two indices in which each begins at the extreme ends of the input array.
  13. Stooge sort: Recursively sorting algorithm. Slower than Bubble sort.
  14. Stack Depth: Also known as tail recursion. After the partition, first sub-array to be recursively shorted will be the left sub-array, then the right sub-array.
  15. Median-of-3 partition: An improved version of the Randomized-Quicksort.
  16. Fuzzy sorting of intervals: Produce a permutation of the intervals such that the existent must satisfy a rule.
  17. Counting sort: For each input element, determine the number of elements less than the input. Assumes that the input consists of integers in a small range.
  18. Radix sort: Used for card-sorting. All cards are organized into 80 columns.  In each column a card is punched into one of twelve places. Then a sort is perform on a list of seven 3-digit numbers.
  19. Bucket sort: Similar to counting sort however it assumes that the input is generated by a random process in which the numbers are distributed uniformly and independently over an interval [0,1).
  20. Randomized-Select: This algorithm only works on one side of the partition instead of both as in Quicksort. This algorithm uses a Randomized-Partition.
  21. Stacks: In a stack, the stack can implement a last-in, first-out (LIFO) policy or first-in, first-out (FIFO) policy.
  22. Queue: An stack with FIFO property which have a head and a tail.
  23. Enqueue: Insert operation on a queue.
  24. Dequeue: Delete operation on a queue.
  25. Linked-list: data structure in which each node is arranged in a linear order.
  26. Binary Tree: A parent node which have a left and right child node.
  27. Hash Tables: Generalization of a simpler notion of an ordinary array. It performs a direct addressing, applicable when allocating an array that has one position for every possible key is affordable.
  28. Direct-Address Tables: A dynamic set is represented by an array or direct-address table in which each slot (or position) correspond to a key.
  29. Open Addressing: Each table entry contain either an element of the dynamic set or none; therefore, we can say that all elements are being store in the hast table itself.
  30. Double Hashing: A method of open addressing in which permutations produced have randomly even permutations.
  31. Red-Black Trees: Binary tree in which each node have an extra bit of storage which is use to indicate the colour of the node: red or black.
  32. Matrix-chain multiplication: Compute the product of a given sequence (chain) of n number of matrices.
  33. Length of Less Common Denominator (LCS): Compute two sequences as input.
  34. Bitonic Euclidean Travelling-Salesman Problem: Also known as TSP. Algorithm that help to simplify the problem of determining the shortest closed tour that connects a set of given points.
  35. Viterbi Algorithm: Algorithm used for speech recognition. It help to solve a labelled graph made of  a person speaking a restricted language.
  36. Greedy Algorithm: It is an algorithm in which the best looking choice is made at the moment.
  37. Fractional Knapsack Problem: Greedy algorithm for a problem related with items size, their price and storage.
  38. Huffman Algorithm: Algorithm use for compressing data in an effective way.
  39. B-Trees: Balanced search trees.
  40. Binomial trees: ordered tree defined recursively.
  41. Binomial heaps: Set of binomial trees which have binomial heap properties.
  42. Fibonacci heaps: Collection of min-heap-ordered trees.
  43. Unordered binomial tree: Binomial tree with a single node, and an unordered binomial tree consisted of two unordered binomial trees.
  44. Disjoint-set operations: Maintenance of  a collection of disjoint dynamic sets.
  45. Disjoint-set forests: Set of rooted trees which in each of their nodes contain one member and each of these trees represent one set.
  46. Union by rank: Linked-list representation of the weighted-union heuristic.
  47. Path compression: simple and effective heuristic without changing any ranks.
  48. Union by rank with path compression: Combination of union-by-rank and path-compression heuristic.
  49. Off-line minimum problem: Maintenance of a dynamic set of elements from an specific domain.
  50. Adjacency-list representation: representation of a graph using adjacent list for each vertex.

List of Common Algorithms – Part 2 >

 

Share
Leave a comment

Example of Coding on haXe (SnapSack Algorithm) – Part 7

In this example you will see: Snapsack algorithm using multi-dimensional arrays

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

example_7.hx:

/**
 * @author: Alejandro G. Carlstein R. M.
 */

class Item{
	public var name : String;
	public var weight : Int;
  public var value : Int;
 	public function new(?name : String, ?weight : Int, ?value : Int){
		this.name = (name == null) ? '' : name;
		this.weight = (weight == null) ? 0 : weight;
		this.value = (value == null) ? 0 : value;
	}

	public function setName(name : String) : Void{
		this.name = (name == null) ? '' : name;
	}

	public function getName() : String{
		return this.name;
	}

	public function setWeight(weight : Int) : Void{
		this.weight = weight;
	}

	public function getWeight() : Int{
		return this.weight;
	}

	public function setValue(value : Int) : Void{
		this.value = value;
	}

	public function getValue() : Int{
		return this.value;
	}

}

/* Our dynamic programming table element.
 * We have the value that we can store, and
 * also a way to remember what we selected.
 */
class Prog{
  public var value : Int;
  public var prev_row : Int;
  public var prev_column : Int;
	public function new(?prev_row : Int, ?prev_column : Int, ?value : Int){
		this.value = (value == null) ? 0 : value;
		this.prev_row = (prev_row == null) ? -1 : prev_row;
		this.prev_column = (prev_column == null) ? -1 : prev_column;
	}

	public function setValue(value : Int) : Void{
		this.value = value;
	}

	public function getValue() : Int{
		return this.value;
	}

	public function setPrevRow(prev_row : Int) : Void{
		this.prev_row = prev_row;
	}

	public function getPrevRow() : Int{
		return this.prev_row;
	}

	public function setPrevColumn(prev_column : Int) : Void{
		this.value = prev_column;
	}

	public function getPrevColumn() : Int{
		return this.prev_column;
	}
}

class Snapsack{
	private var items : Array<Item>;
	private var selected_items : Array<Item>;
	private var table : Array<Array<Prog>>;

	private var max_weight : Int;
	private var num_items : Int;
	private var total_weight : Int;
	private var total_value : Int;

	private function initTable() : Void{
		trace('initTable()');
		var i : Int = 0;
		var j : Int = 0;
		for (i in 0...num_items) {
			table[i] = new Array<Prog>();
			for (j in 0...max_weight) {
				table[i][j] = new Prog(0, 0, 0);
			}
		}
	}

	private function initItems(){
		trace('initItems()');
		var i : Int = 0;
		for (i in 0...num_items){
			items[i] = new Item('', 0, 0);
		}
	}

	private function printTable() : Void{
		trace('printTable()');
		var str : String = '';
		var i : Int = 0;
		var j : Int = 0;
		for (i in 0...table.length) {
			for (j in 0...max_weight) {
				str += '[(' +
							table[i][j].prev_row +
							', ' +
							table[i][j].prev_column +
							') ' +
						  table[i][j].value +
						  ']';
			}
			trace(str);
			str = '';
		}
	}

	private function printItems(){
		trace('printItems()');
		var i : Int = 0;
		for (i in 0...num_items){
			trace('name: ' +
						items[i].name +
						', weight: ' +
						items[i].weight +
						', value: ' +
						items[i].value);
		}
	}

	public function new(num_items : Int, max_weight : Int){
		this.num_items = num_items;
		this.max_weight = ++max_weight;
		total_weight = 0;
		total_value = 0;
		items = new Array<Item>();
		table = new Array<Array<Prog>>();

		table.push(new Array<Prog>());
		for (i in 0...max_weight) {
			table[table.length - 1][i] = new Prog(-1, -1, 0);
		}
	}

	public function pushItem(name : String, weight : Int, value : Int){
		items.push(new Item(name, weight, value));
		table.push(new Array<Prog>());
		var i : Int = 0;
		for (i in 0...max_weight) {
			table[table.length - 1][i] = new Prog(-1, -1, 0);
		}
	}

	public function pickItems() : Void {
		printTable();
		printItems();
		var i : Int = 1;
		var w : Int = 0;

	  // Perform knapsack and find maximun value
	  for (i in 1...num_items + 1){
	    for (w in 0...max_weight){
	  		table[i][w].prev_row = i - 1;
			  table[i][w].prev_column = w;		

				// Check if item fit inside the knapsack
				if(items[i - 1].weight <= w) {
	        var diff_weight : Int = w - items[i - 1].weight;

	        // Check which value is higher
					table[i][w].value = Math.round(Math.max((items[i - 1].value + table[i - 1][diff_weight].value),
                              				             table[i - 1][w].value));

	        // Keep track of the previous column
					if(table[i][w].value > table[i - 1][w].value)
						table[i][w].prev_column = diff_weight;

				}else{
					table[i][w].value = table[i - 1][w].value;
				}
	    }
	  }

	  total_value = table[num_items - 1][max_weight - 1].value;

		total_weight = 0;
	  var w : Int = max_weight - 1;
  	var t : Int = 0;
  	selected_items = new Array<Item>();

  	var i : Int = num_items - 1;
  	while (i > 0){

			if(table[i][w].value != table[i - 1][w].value){

				total_weight += items[i - 1].weight;				

				selected_items.push(new Item(items[i - 1].name,
																		 items[i - 1].weight,
																		 items[i - 1].value));

		  }
			t = w;
		  w = table[i][w].prev_column;
		  i = table[i][t].prev_row;
		}

		printTable();
	}

	public function getTotalValue() : Int{
		return total_value;
	}

	public function getTotalWeight() : Int{
		return total_weight;
	}

	public function printResult() : Void{

		for (i in 0...selected_items.length)
			trace('name: ' +
						selected_items[i].name +
						', weight: ' +
						selected_items[i].weight +
						', value: ' +
						selected_items[i].value);
	}
}

class Example_7 {

	static function main(){

		trace('Creating Snapsack');
		var snapsack : Snapsack = new Snapsack(4, 5);

		trace('adding items to snapsack');
		snapsack.pushItem('item_A', 2, 3);
		snapsack.pushItem('item_B', 3, 4);
		snapsack.pushItem('item_C', 4, 5);
		snapsack.pushItem('item_D', 5, 6);
		snapsack.pickItems();
		trace('Total value: ' + snapsack.getTotalValue());
		trace('Total Weight: ' + snapsack.getTotalWeight());
		snapsack.printResult();

	}

}

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.

Share
Leave a comment