How to subclass in Go - oop

In C I can do something like this
struct Point {
int x,y;
}
struct Circle {
struct Point p; // must be first!
int rad;
}
void move(struct Point *p,int dx,int dy) {
....
}
struct Circle c = .....;
move( (struct Point*)&c,1,2);
Using this approach, I can pass any struct(Circle,Rectangle,etc) that has struct Point as first member.
How can I do the same in google go?

Actually, there's a simpler way to do it, which is more similar to the OP's example:
type Point struct {
x, y int
}
func (p *Point) Move(dx, dy int) {
p.x += dx
p.y += dy
}
type Circle struct {
*Point // embedding Point in Circle
rad int
}
// Circle now implicitly has the "Move" method
c := &Circle{&Point{0, 0}, 5}
c.Move(7, 3)
Also notice that Circle would also fulfill the Mover interface that PeterSO posted.
http://golang.org/doc/effective_go.html#embedding

Although Go has types and methods and
allows an object-oriented style of
programming, there is no type
hierarchy. The concept of “interface”
in Go provides a different approach
that we believe is easy to use and in
some ways more general. There are also
ways to embed types in other types to
provide something analogous—but not
identical—to subclassing. Is Go an
object-oriented language?, FAQ.
For example,
package main
import "fmt"
type Mover interface {
Move(x, y int)
}
type Point struct {
x, y int
}
type Circle struct {
point Point
rad int
}
func (c *Circle) Move(x, y int) {
c.point.x = x
c.point.y = y
}
type Square struct {
diagonal int
point Point
}
func (s *Square) Move(x, y int) {
s.point.x = x
s.point.y = y
}
func main() {
var m Mover
m = &Circle{point: Point{1, 2}}
m.Move(3, 4)
fmt.Println(m)
m = &Square{3, Point{1, 2}}
m.Move(4, 5)
fmt.Println(m)
}

Related

Is there a way to generate 2D stretched mesh using CGAL?

I currently use CGAL to generate 2D Delaunay triangulation.One of the mesh control parameter is the maximum length of the triangle edge. The examples suggests that this parameter is a constant. I would like to know how this parameter be made function of some thing else, for example spatial location.
I think Delaunay meshing with variable density is not directly supported by CGAL although you could mesh your regions independently. Alternatively you may have a look at: http://www.geom.at/advanced-mesh-generation/ where I have implemented that as a callback function.
It doesn't look like CGAL provides an example of this but they machinery is all there. The details get a little complicated since the objects that control if triangles need to be refined also have to understand the priority under which triangles get refined.
To do this, I copied Delaunay_mesh_size_criteria_2 to create a new class (Delaunay_mesh_user_criteria_2) that has a spatially varying sizing field. Buried in the class is a function (user_sizing_field) that can be implemented with a varying size field based on location. The code below compares the size of the longest edge of the triangle to the minimum of the sizing field at the three vertices, but you could use a size at the barycenter or circumcenter or even send the entire triangle to the sizing function if you have a good way to compute the smallest allowable size on the triangle altogether.
This is a starting point, although a better solution would,
refactor some things to avoid so much duplication with with existing Delaunay_mesh_size_criteria,
allow the user to pass in the sizing function as an argument to the criteria object, and
be shipped with CGAL.
template <class CDT>
class Delaunay_mesh_user_criteria_2 :
public virtual Delaunay_mesh_criteria_2<CDT>
{
protected:
typedef typename CDT::Geom_traits Geom_traits;
double sizebound;
public:
typedef Delaunay_mesh_criteria_2<CDT> Base;
Delaunay_mesh_user_criteria_2(const double aspect_bound = 0.125,
const Geom_traits& traits = Geom_traits())
: Base(aspect_bound, traits){}
// first: squared_minimum_sine
// second: size
struct Quality : public std::pair<double, double>
{
typedef std::pair<double, double> Base;
Quality() : Base() {};
Quality(double _sine, double _size) : Base(_sine, _size) {}
const double& size() const { return second; }
const double& sine() const { return first; }
// q1<q2 means q1 is prioritised over q2
// ( q1 == *this, q2 == q )
bool operator<(const Quality& q) const
{
if( size() > 1 )
if( q.size() > 1 )
return ( size() > q.size() );
else
return true; // *this is big but not q
else
if( q.size() > 1 )
return false; // q is big but not *this
return( sine() < q.sine() );
}
std::ostream& operator<<(std::ostream& out) const
{
return out << "(size=" << size()
<< ", sine=" << sine() << ")";
}
};
class Is_bad: public Base::Is_bad
{
public:
typedef typename Base::Is_bad::Point_2 Point_2;
Is_bad(const double aspect_bound,
const Geom_traits& traits)
: Base::Is_bad(aspect_bound, traits) {}
Mesh_2::Face_badness operator()(const Quality q) const
{
if( q.size() > 1 )
return Mesh_2::IMPERATIVELY_BAD;
if( q.sine() < this->B )
return Mesh_2::BAD;
else
return Mesh_2::NOT_BAD;
}
double user_sizing_function(const Point_2 p) const
{
// IMPLEMENT YOUR CUSTOM SIZING FUNCTION HERE.
// BUT MAKE SURE THIS RETURNS SOMETHING LARGER
// THAN ZERO TO ALLOW THE ALGORITHM TO TERMINATE
return std::abs(p.x()) + .025;
}
Mesh_2::Face_badness operator()(const typename CDT::Face_handle& fh,
Quality& q) const
{
typedef typename CDT::Geom_traits Geom_traits;
typedef typename Geom_traits::Compute_area_2 Compute_area_2;
typedef typename Geom_traits::Compute_squared_distance_2 Compute_squared_distance_2;
Geom_traits traits; /** #warning traits with data!! */
Compute_squared_distance_2 squared_distance =
traits.compute_squared_distance_2_object();
const Point_2& pa = fh->vertex(0)->point();
const Point_2& pb = fh->vertex(1)->point();
const Point_2& pc = fh->vertex(2)->point();
double size_bound = std::min(std::min(user_sizing_function(pa),
user_sizing_function(pb)),
user_sizing_function(pc));
double
a = CGAL::to_double(squared_distance(pb, pc)),
b = CGAL::to_double(squared_distance(pc, pa)),
c = CGAL::to_double(squared_distance(pa, pb));
double max_sq_length; // squared max edge length
double second_max_sq_length;
if(a<b)
{
if(b<c) {
max_sq_length = c;
second_max_sq_length = b;
}
else { // c<=b
max_sq_length = b;
second_max_sq_length = ( a < c ? c : a );
}
}
else // b<=a
{
if(a<c) {
max_sq_length = c;
second_max_sq_length = a;
}
else { // c<=a
max_sq_length = a;
second_max_sq_length = ( b < c ? c : b );
}
}
q.second = 0;
q.second = max_sq_length / (size_bound*size_bound);
// normalized by size bound to deal
// with size field
if( q.size() > 1 )
{
q.first = 1; // (do not compute sine)
return Mesh_2::IMPERATIVELY_BAD;
}
Compute_area_2 area_2 = traits.compute_area_2_object();
double area = 2*CGAL::to_double(area_2(pa, pb, pc));
q.first = (area * area) / (max_sq_length * second_max_sq_length); // (sine)
if( q.sine() < this->B )
return Mesh_2::BAD;
else
return Mesh_2::NOT_BAD;
}
};
Is_bad is_bad_object() const
{ return Is_bad(this->bound(), this->traits /* from the bad class */); }
};
I am also interested for variable mesh criteria on the domaine with CGAL. I have found an alternative many years ago : https://www.cs.cmu.edu/~quake/triangle.html
But i am still interested to do the same things with CGAL ... I don't know if it is possible ...

How to convert between vector_float2 and CGPoint*?

What's the easiest/fastest way to convert between vector_float2 and CGPoint* in Objective-C?
Does Apple provide any built-in functionality for this kind of type conversion? I noticed in 2-3 places in sample apps they just call CGPointMake() etc. to make the conversion
Is it possible to simply cast a CGPoint* to vector_float2 and vice versa? Is it safe to do so?
Update: obviously the solution is:
vector_float2 v = (vector_float2){(float)point.x, (float)point.y};
CGPoint p = CGPointMake(v.x, v.y);
But this is cumbersome if you need to do so frequently, and more so if there's a C array of either vector_float2* or CGPoint*. So I'm looking for already-existing solutions or very simple alternatives that I may be overlooking.
I tried to simply extend CGPoint but couldnt seem to import vector_float2; not even with the bridging header file.
// Doesn't work!!
extension CGPoint {
init(vector: vector_float2)
{
self.x = CGFloat(vector.x)
self.y = CGFloat(vector.y)
}
}
You do have several options though. You can extend Float with a calculated var that returns a CGFloat and extend GKAgent2D to convert it's position to a CGPoint:
extension Float {
var f: CGFloat { return CGFloat(self) }
}
extension GKAgent2D {
var cgposition: CGPoint {
return CGPoint(x: self.position.x.f, y: self.position.y.f)
}
}
You can also extend CGPoint itself to accept two Float's:
extension CGPoint {
init(x: Float, y: Float) {
self.x = CGFloat(x)
self.y = CGFloat(y)
}
}
extension GKAgent2D {
var cgposition: CGPoint {
// Note that the ".f" is gone from the example above
return CGPoint(x: self.position.x, y: self.position.y)
}
}
In both cases, you can use it like this:
let agent = GKAgent2D()
let point = agent.cgposition
Example:
CGPoint p = CGPointMake(1.0f, 1.0f);
vector_float2 v = simd_make_float2(p.x, p.y);
CGPoint x = CGPointMake(v[0], v[1]);

How to pass variables as parameters

I have two bits of code
Tree tree;
void setup() {
int SZ = 512; // screen size
int d = 2;
int x = SZ/2;
int y = SZ;
size(SZ,SZ);
background(255);
noLoop();
tree = new Tree(d, x, y);
}
void draw() {
tree.draw();
}
and also
class Tree {
// member variables
int m_lineLength; // turtle line length
int m_x; // initial x position
int m_y; // initial y position
float m_branchAngle; // turtle rotation at branch
float m_initOrientation; // initial orientation
String m_state; // initial state
float m_scaleFactor; // branch scale factor
String m_F_rule; // F-rule substitution
String m_H_rule; // H-rule substitution
String m_f_rule; // f-rule substitution
int m_numIterations; // number of times to substitute
// constructor
// (d = line length, x & y = start position of drawing)
Tree(int d, int x, int y) {
m_lineLength = d;
m_x = x;
m_y = y;
m_branchAngle = (25.7/180.0)*PI;
m_initOrientation = -HALF_PI;
m_scaleFactor = 1;
m_state = "F";
m_F_rule = "F[+F]F[-F]F";
m_H_rule = "";
m_f_rule = "";
m_numIterations = 5;
// Perform L rounds of substitutions on the initial state
for (int k=0; k < m_numIterations; k++) {
m_state = substitute(m_state);
}
}
void draw() {
pushMatrix();
pushStyle();
stroke(0);
translate(m_x, m_y); // initial position
rotate(m_initOrientation); // initial rotation
// now walk along the state string, executing the
// corresponding turtle command for each character
for (int i=0; i < m_state.length(); i++) {
turtle(m_state.charAt(i));
}
popStyle();
popMatrix();
}
// Turtle command definitions for each character in our alphabet
void turtle(char c) {
switch(c) {
case 'F': // drop through to next case
case 'H':
line(0, 0, m_lineLength, 0);
translate(m_lineLength, 0);
break;
case 'f':
translate(m_lineLength, 0);
break;
case 's':
scale(m_scaleFactor);
break;
case '-':
rotate(m_branchAngle);
break;
case '+':
rotate(-m_branchAngle);
break;
case '[':
pushMatrix();
break;
case ']':
popMatrix();
break;
default:
println("Bad character: " + c);
exit();
}
}
// apply substitution rules to string s and return the resulting string
String substitute(String s) {
String newState = new String();
for (int j=0; j < s.length(); j++) {
switch (s.charAt(j)) {
case 'F':
newState += m_F_rule;
break;
case 'H':
newState += m_F_rule;
break;
case 'f':
newState += m_f_rule;
break;
default:
newState += s.charAt(j);
}
}
return newState;
}
}
This isn't assessed homework, it's an end of chapter exercise but I'm very stuck.
I want to "extend the Tree constructor so that values for all of the Tree member variables can be passed in as parameters."
Whilst I understand what variables and parameters are, I'm very stuck as to what to begin reading / where to begin editing the code.
One thing that has confused me and made me question my understanding is that, if I change the constructor values, (for example m_numiterations = 10;), the output when the code is run is the same.
Any pointers in the right direction would be greatly appreciated.
You already have everything in there to add more stuff to your Tree.
You see, in your setup(), you call:
tree = new Tree(d, x, y);
Now, that line, is actually calling the contructor implemented here:
Tree(int d, int x, int y) {
m_lineLength = d;
m_x = x;
etc....
So, if you want you can change that constructor to accept any variable that you want to pass from setup()
For instance, Tree(int d, int x, int y, String word, float number, double bigNumber)
Try experimenting with that. If you have any questions, PM me
EDIT
Let me add a little more flavor to it:
You see constructors are the way to initialize your class. It does not matter the access level (protected, public, private) or the number of constructors.
So, for example, Let's say you have this class with two public fields:
public class Book
{
public String Author;
public String Title;
public Book(String title, String author)
{
this.Title = title;
this.Author = author;
}
public Book()
{
this("Any title");//default title
}
}
Here, you can create books with both author and title OR only title! isn't that great? You can create things that are not inclusively attached to other things!
I hope you understand this. But, basically the idea is to encapsulate everything that matters to a certain topic to its own class.
NEW EDIT
Mike, you see, according to your comment you added this line:
int m_numIterations = 25;
The thing is that what you just did was only create a variable. A variable holds the information that you eventually want to use in the program. Let's say you are in high school physics trying to solve a basic free fall problem. You have to state the gravity, don't you?
So, in your notebook, you would go:
g = 9.8 m/s^2
right? it is a constant. But, a variable that you will use in your problem.
Well, the same thing applies in programming.
You added the line. That means that now, you can use it in your problem.
Now, go to this line,
tree = new Tree(d, x, y);
and change it to:
tree = new Tree(d, x, y, m_numIterations);
As you can see, now you are ready to "use" your variable in your tree. However! you are not done yet. You have to update as well your constructor because if not, the compiler will complain!
Go to this line now,
Tree(int d, int x, int y) {
m_lineLength = d;
m_x = x;
....
And change it to:
Tree(int d, int x, int y, int iterations) {
m_lineLength = d;
m_x = x;
....
You, see, now, you are telling your tree to accept a new variable call iterations that you are setting from somewhere else.
However! Be warned! There is a little problem with this :(
You don't have any code regarding the use of that variable. So, if you are expecting to actually see something different in the Tree, it won't happen! You need to find a use to the variable within the scope of the Tree (the one that I called iterations). So, first, find a use for it! or post any more code that you have to help you solve it. If you are calling a variable iterations, it is because you are planning to use a loop somewhere, amirite? Take care man. Little steps. Be patient. I added a little more to the Books example. I forgot to explain it yesterday :p

Slow Swift Arrays and Strings performance

Here is two pretty similar Levenshtein Distance algorithms.
Swift implementation:
https://gist.github.com/bgreenlee/52d93a1d8fa1b8c1f38b
And Objective-C implementation:
https://gist.github.com/boratlibre/1593632
The swift one is dramatically slower then ObjC implementation
I've send couple of hours to make it faster but... It seems like Swift arrays and Strings manipulation are not as fast as objC.
On 2000 random Strings calculations Swift implementation is about 100(!!!) times slower then ObjC.
Honestly speaking, I've got no idea what could be wrong, coz even this part of swift
func levenshtein(aStr: String, bStr: String) -> Int {
// create character arrays
let a = Array(aStr)
let b = Array(bStr)
...
is few times slower then whole algorithm in Objective C
Is anyone knows how to speedup swift calculations?
Thank you in advance!
Append
After all suggested improvements swift code looks like this.
And it is 4 times slower then ObjC in release configuration.
import Foundation
class Array2D {
var cols:Int, rows:Int
var matrix:UnsafeMutablePointer<Int>
init(cols:Int, rows:Int) {
self.cols = cols
self.rows = rows
matrix = UnsafeMutablePointer<Int>(malloc(UInt(cols * rows) * UInt(sizeof(Int))))
for i in 0...cols*rows {
matrix[i] = 0
}
}
subscript(col:Int, row:Int) -> Int {
get {
return matrix[cols * row + col] as Int
}
set {
matrix[cols*row+col] = newValue
}
}
func colCount() -> Int {
return self.cols
}
func rowCount() -> Int {
return self.rows
}
}
extension String {
func levenshteinDistanceFromStringSwift(comparingString: NSString) -> Int {
let aStr = self
let bStr = comparingString
// let a = Array(aStr.unicodeScalars)
// let b = Array(bStr.unicodeScalars)
let a:NSString = aStr
let b:NSString = bStr
var dist = Array2D(cols: a.length + 1, rows: b.length + 1)
for i in 1...a.length {
dist[i, 0] = i
}
for j in 1...b.length {
dist[0, j] = j
}
for i in 1...a.length {
for j in 1...b.length {
if a.characterAtIndex(i-1) == b.characterAtIndex(j-1) {
dist[i, j] = dist[i-1, j-1] // noop
} else {
dist[i, j] = min(
dist[i-1, j] + 1, // deletion
dist[i, j-1] + 1, // insertion
dist[i-1, j-1] + 1 // substitution
)
}
}
}
return dist[a.length, b.length]
}
func levenshteinDistanceFromStringObjC(comparingString: String) -> Int {
let aStr = self
let bStr = comparingString
//It is really strange, but I should link Objective-C coz dramatic slow swift performance
return aStr.compareWithWord(bStr, matchGain: 0, missingCost: 1)
}
}
malloc?? NSString?? and at the end 4 times speed decrease? Is anybody needs swift anymore?
There are multiple reasons why the Swift code is slower than the Objective-C code.
I made a very simple test case by comparing two fixed strings 100 times.
Objective-C code: 0.026 seconds
Swift code: 3.14 seconds
The first reason is that a Swift Character represents an "extended grapheme cluster",
which can contain several Unicode code points (e.g. "flags"). This makes the
decomposition of a string into characters slow. On the other hand, Objective-C
NSString stores the strings as a sequence of UTF-16 code points.
If you replace
let a = Array(aStr)
let b = Array(bStr)
by
let a = Array(aStr.utf16)
let b = Array(bStr.utf16)
so that the Swift code works on UTF-16 sequences as well then the time goes down
to 1.88 seconds.
The allocation of the 2-dimensional array is also slow. It is faster to allocate
a single one-dimensional array. I found a simple Array2D class here:
http://blog.trolieb.com/trouble-multidimensional-arrays-swift/
class Array2D {
var cols:Int, rows:Int
var matrix: [Int]
init(cols:Int, rows:Int) {
self.cols = cols
self.rows = rows
matrix = Array(count:cols*rows, repeatedValue:0)
}
subscript(col:Int, row:Int) -> Int {
get {
return matrix[cols * row + col]
}
set {
matrix[cols*row+col] = newValue
}
}
func colCount() -> Int {
return self.cols
}
func rowCount() -> Int {
return self.rows
}
}
Using that class in your code
func levenshtein(aStr: String, bStr: String) -> Int {
let a = Array(aStr.utf16)
let b = Array(bStr.utf16)
var dist = Array2D(cols: a.count + 1, rows: b.count + 1)
for i in 1...a.count {
dist[i, 0] = i
}
for j in 1...b.count {
dist[0, j] = j
}
for i in 1...a.count {
for j in 1...b.count {
if a[i-1] == b[j-1] {
dist[i, j] = dist[i-1, j-1] // noop
} else {
dist[i, j] = min(
dist[i-1, j] + 1, // deletion
dist[i, j-1] + 1, // insertion
dist[i-1, j-1] + 1 // substitution
)
}
}
}
return dist[a.count, b.count]
}
the time in the test case goes down to 0.84 seconds.
The last bottleneck that I found in the Swift code is the min() function.
The Swift library has a built-in min() function which is faster. So just removing
the custom function from the Swift code reduces the time for the test case to
0.04 seconds, which is almost as good as the Objective-C version.
Addendum: Using Unicode scalars seems to be even slightly faster:
let a = Array(aStr.unicodeScalars)
let b = Array(bStr.unicodeScalars)
and has the advantage that it works correctly with surrogate pairs such
as Emojis.

Trying to create a C Function List

I have been trying to create a list of general global C functions for various classes to use, and although i've done this in the past, this one is having problems. Here are the .h and .c parts of the list.
CGGeometry.h
//CDPoint
//////////////////////////////////////////////////////////////////////
typedef struct CDPoint {
CGFloat x, y, z;
} CDPoint;
// Creates a CDPoint from 3 float numbers
CDPoint CDPointMake(float x, float y, float z);
//CDLine
//////////////////////////////////////////////////////////////////////
typedef struct CDLine {
CDPoint a, b;
} CDLine;
// Creates a CDPoint from 2 CDPoints
CDLine CDLineMake(CDPoint a, CDPoint b);
//CDVector
//////////////////////////////////////////////////////////////////////
typedef struct CDVector {
CDPoint start, finish;
CDPoint gradient;
} CDVector;
// Creates a CDVector from 2 CDPoints
CDVector CDVectorMake(CDPoint startPoint, CDPoint endPoint);
// Returns a point travelled to on a given vector, using a start point and a distance scalar.
CDPoint CDVectorTrace(CDVector vecToTrace, CDPoint startPoint, float distance);
//CDExtra
//////////////////////////////////////////////////////////////////////
// This is stuff that shoudn't really be in this section, but are for convenience purposes until it has enough functions to be standalone.
GLfloat* CDMeshColorsCreateGrey(CGFloat bValue, CGFloat vertCount);
CGFloat* CDMeshVertexesCreateRectangle(CGFloat height, CGFloat width);
CDGeometry.c
#include "CDGeometry.h"
//CDGeometry.c
/* A collection of functions and typedefs that aid 2D and 3D environment positioning and provides methods for objects and processes. Also includes elements relevant to collision detection. */
//CDPoint
//////////////////////////////////////////////////////////////////////
CDPoint CDPointMake(float x, float y, float z)
{
return (CDPoint) {x, y, z};
}
//CDLine
//////////////////////////////////////////////////////////////////////
CDLine CDLineMake(CDPoint a, CDPoint b)
{
return (CDLine) {a, b};
}
//CDVector
//////////////////////////////////////////////////////////////////////
CDVector CDVectorMake(CDPoint startPoint, CDPoint endPoint)
{
CDPoint grad = CDPointMake(startPoint.x / endPoint.x,
startPoint.y / endPoint.y,
startPoint.z / endPoint.z);
return (CDVector) {startPoint, endPoint, grad};
}
//CDExtra
/////////////////////////////////////////////////////////////////////
GLfloat* CDMeshColorsCreateGrey(CGFloat bValue, CGFloat vertCount)
{
GLfloat *greyColor = (GLfloat *) malloc(vertCount * 4 * sizeof(GLfloat));
int index = 0;
for (index = 0; index < (vertCount); index++)
{
int position = index * 4;
greyColor[position] = bValue;
greyColor[position + 1] = bValue;
greyColor[position + 2] = bValue;
greyColor[position + 3] = 1.0;
}
return greyColor;
}
CGFloat* CDMeshVertexesCreateRectangle(CGFloat height, CGFloat width) {
CGFloat *squareVertexes = (CGFloat *) malloc(8 * sizeof(CGFloat));
squareVertexes[0] = -(width / 2);
squareVertexes[1] = -(height / 2);
squareVertexes[2] = (width / 2);
squareVertexes[3] = -(height / 2);
squareVertexes[4] = (width / 2);
squareVertexes[5] = (height / 2);
squareVertexes[6] = -(width / 2);
squareVertexes[7] = (height / 2);
return squareVertexes;
}
When I don't import or any other framework, I receive 'Parse Error: unknown type name' for CGFloat and GLfloat. When I do inside the .h file, I get Parse and Semantic errors, where NSString is an unknown type name inside the framework, as well as other, 'Expected Identifier or (" errors.
I've never had to include this header for my original C function lists, i've gone through other example code from Apple and i've checked headers on other classes that use these functions and typedefs, and I cant find the problem.
CGFloat is part of the CoreGraphics Framework. If you want to use pure C you will not have access to the CGFloat and need to define it as just a float. If your class is only going to be used with Objective-C you can make it a .m file and you should not have any trouble.