Ecere SDK/eC Forums
https://ec-lang.org/community/
Print view

Plurality without containers
https://ec-lang.org/community/viewtopic.php?f=15&t=20
Page 1 of 1
Author:  sacrebleu [ Thu Jan 21, 2010 1:13 am ]
Post subject:  Plurality without containers

Code: Select all

 
import "ecere"

class Plural {
 Plural next;
 int index;
 virtual bool Compare ( Plural a, Plural b ) { return ( a.index<b.index ); }
 virtual void Copy( Plural from ) {}
 bool Contains( Plural L ) { Plural sL; for ( sL=this; sL!=null; sL=sL.next ) if ( sL==L ) return true; return false; }
 int Length() { Plural n; int count=0; for( n=this; n!=null; n=n.next ) n.index=count++; return count; }
 Plural Push( Plural L ) { L.next=this; return L; }
 Plural Append( Plural L ) { Plural x; if ( !this ) return L; x=this; while ( x.next ) x=x.next; x.next=L; return this; }
 Plural RemoveAndDelete( Plural L ) { Plural s, new_list, s_next; if ( !L ) return this; new_list=null; for ( s=this; s!=null; s=s_next ) { s_next=s.next; if ( s!=L ) { s.next = new_list; new_list=s; } } delete L; return new_list; }
 Plural Remove( Plural L ) { Plural s, new_list, s_next; if ( !L ) return this; new_list=null; for ( s=this; s!=null; s=s_next ) { s_next=s.next; if ( s!=L ) { s.next = new_list; new_list=s; } } return new_list; }
 Plural Reverse() { Plural m, mn, n=null; for ( m=this; m; m=mn ) { mn=m.next; m.next=n; n=m; } return n; }
 Plural Get( int i ) { Plural L; for ( L=this; L; L=L.next ) { i--; if ( i < 0 ) return L; } return null; } 
 Plural Sort() {  Plural head =this;  if (head != null) {   Plural M = head;   Plural c = M.next; while (c) { if(Compare(c,M) ) { Plural t=M; M = c; t.next = c.next; c.next=t; } M = M.next; } return M; } return null; }
 ~Plural() { delete next; }
}
Sample customization of Plural to sort points used as part of Graham Scan implementation:

Code: Select all

class gs_point2d : Struct { double x; double y; double angle; };

class gs_point2d_vector : Plural { gs_point2d p;
 gs_point2d anchor;

 inline bool is_equal_points( gs_point2d p1, gs_point2d p2) { return is_equal_Double(p1.x,p2.x) && is_equal_Double(p1.y,p2.y); }
 inline bool is_equal_Double(double v1, double v2) { double diff = v1 - v2; return  (-epsilon <= diff) && (diff <= epsilon); }
 inline double lay_distance(double x1, double y1, const double x2, const double y2) { double dx = (x1 - x2), dy = (y1 - y2); return (dx * dx + dy * dy); }     

 bool Compare(Plural a, Plural b) {
  gs_point2d_vector p1 = (gs_point2d_vector) a, p2 = (gs_point2d_vector) b;
  if (p1.p.angle < p2.p.angle)      return true;
  else if (p1.p.angle > p2.p.angle) return false;
  else if (is_equal_points(p1.p,p2.p))     return false;
  else if (lay_distance(anchor.x, anchor.y, p1.p.x, p1.p.y) < lay_distance(anchor.x, anchor.y, p2.p.x, p2.p.y)) return true;
  else return false;
 }
};
All times are UTC-05:00 Page 1 of 1