Rewrite few familiar Cocoa Touch code examples from Obj-C to Swift by learning to use Closures, Enums, Switch-Case with Pattern matching, Singleton, GCD, CoreGraphics.
Presented at Tel Aviv iOS Developers Meetup.
Rewrite few familiar Cocoa Touch code examples from Obj-C to Swift by learning to use Closures, Enums, Switch-Case with Pattern matching, Singleton, GCD, CoreGraphics.
Presented at Tel Aviv iOS Developers Meetup.
Example of Dynamic Programming to achieve O(n).
Interview question: N houses, each with weighting on value of goods. How can a burglar maximise profit if they are not allowed to visit neighbouring houses?
Solution: optimum(i) = max( optimum(i-1)-w(i-1)+w(i) , optimum(i-2)+w(i) )
WebGL brings hardware accelerated 3D to your browser. The code may be complex, but the possibilities are amazing. Given as a lecture in the fh ooe in Hagenberg, Austria in December 2011.
Please implement in Java. comments would be appreciated 5.pdffms12345
Please i need help with these question, thanks.
4.) What is Total Revenue and How is it calculated (formula)? MacBook Air
Solution
Total revenue is the sum of the revenue generated by selling each unit of good. It is the revenues
which are generated by selling given level of input.
Total revenue can be computed by adding up Marginal revenue generated from selling each
additional unit of good.
Therefore, the Total revenue = MR1+MR2+MR3+MR4+.... MRn.
Proper distribution of functionalities throughout many machines is very hard, especially when we leave those decisions for later. Akka toolkit gives us many tools for scaling out and we can start using them very early in a development process, enhancing our chances of success. In this introductory talk, I want to go through a very simple example and show snippets of single-noded and sharded implementations.
I have compilation errors that I'm struggling with in my code- please.pdfColinjHJParsonsa
I have compilation errors that I'm struggling with in my code, please can you help me fix the
errors. I'm trying to make a road map, where each place is a vertex and each road between two
places is an edge. Each edge stores a number indicating the length of the road. Assume that there
is at most one road directly connecting two given places, so that there is at most one edge
between two vertices. The map is loaded in via a text file that starts with a line that contains the
number of vertices and the number of edges. After the line mentioned, there are two sections of
content. The initial section holds details regarding the vertices, where each line represents a
single vertex. The information stored for each vertex includes its name and the availability of
charging stations, represented as an integer with 1 indicating availability and 0 indicating
unavailability. The second section stores information about the edges, with each line
corresponding to one edge. Each line contains three numbers: the first two are 0-based indices of
its two incident vertices within the places array; the last number is the edge length. An example
of the map input would look like this as a txt file:
import java.util.*;
import java.io.*;
class Vertex {
// Constructor: set name, chargingStation and index according to given values,
// initilaize incidentRoads as empty array
public Vertex(String placeName, boolean chargingStationAvailable, int idx) {
name = placeName;
incidentRoads = new ArrayList<Edge>();
index = idx;
chargingStation = chargingStationAvailable;
}
public String getName() {
return name;
}
public boolean hasChargingStation() {
return chargingStation;
}
public ArrayList<Edge> getIncidentRoads() {
return incidentRoads;
}
// Add a road to the array incidentRoads
public void addIncidentRoad(Edge road) {
incidentRoads.add(road);
}
public int getIndex() {
return index;
}
private String name; // Name of the place
private ArrayList<Edge> incidentRoads; // Incident edges
private boolean chargingStation; // Availability of charging station
private int index; // Index of this vertex in the vertex array of the map
}
class Edge {
public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) {
length = roadLength;
incidentPlaces = new Vertex[] { firstPlace, secondPlace };
}
public Vertex getFirstVertex() {
return incidentPlaces[0];
}
public Vertex getSecondVertex() {
return incidentPlaces[1];
}
public int getLength() {
return length;
}
private int length;
private Vertex[] incidentPlaces;
}
// A class that represents a sparse matrix
public class RoadMap {
// Default constructor
public RoadMap() {
places = new ArrayList<Vertex>();
roads = new ArrayList<Edge>();
}
// Auxiliary function that prints out the command syntax
public static void printCommandError() {
System.err.println("ERROR: use one of the following commands");
System.err.println(" - Load a map and print information:");
System.err.println(" java RoadMap -i <MapFile>");
System.err.println(" - Load a map an.
Example of Dynamic Programming to achieve O(n).
Interview question: N houses, each with weighting on value of goods. How can a burglar maximise profit if they are not allowed to visit neighbouring houses?
Solution: optimum(i) = max( optimum(i-1)-w(i-1)+w(i) , optimum(i-2)+w(i) )
WebGL brings hardware accelerated 3D to your browser. The code may be complex, but the possibilities are amazing. Given as a lecture in the fh ooe in Hagenberg, Austria in December 2011.
Please implement in Java. comments would be appreciated 5.pdffms12345
Please i need help with these question, thanks.
4.) What is Total Revenue and How is it calculated (formula)? MacBook Air
Solution
Total revenue is the sum of the revenue generated by selling each unit of good. It is the revenues
which are generated by selling given level of input.
Total revenue can be computed by adding up Marginal revenue generated from selling each
additional unit of good.
Therefore, the Total revenue = MR1+MR2+MR3+MR4+.... MRn.
Proper distribution of functionalities throughout many machines is very hard, especially when we leave those decisions for later. Akka toolkit gives us many tools for scaling out and we can start using them very early in a development process, enhancing our chances of success. In this introductory talk, I want to go through a very simple example and show snippets of single-noded and sharded implementations.
I have compilation errors that I'm struggling with in my code- please.pdfColinjHJParsonsa
I have compilation errors that I'm struggling with in my code, please can you help me fix the
errors. I'm trying to make a road map, where each place is a vertex and each road between two
places is an edge. Each edge stores a number indicating the length of the road. Assume that there
is at most one road directly connecting two given places, so that there is at most one edge
between two vertices. The map is loaded in via a text file that starts with a line that contains the
number of vertices and the number of edges. After the line mentioned, there are two sections of
content. The initial section holds details regarding the vertices, where each line represents a
single vertex. The information stored for each vertex includes its name and the availability of
charging stations, represented as an integer with 1 indicating availability and 0 indicating
unavailability. The second section stores information about the edges, with each line
corresponding to one edge. Each line contains three numbers: the first two are 0-based indices of
its two incident vertices within the places array; the last number is the edge length. An example
of the map input would look like this as a txt file:
import java.util.*;
import java.io.*;
class Vertex {
// Constructor: set name, chargingStation and index according to given values,
// initilaize incidentRoads as empty array
public Vertex(String placeName, boolean chargingStationAvailable, int idx) {
name = placeName;
incidentRoads = new ArrayList<Edge>();
index = idx;
chargingStation = chargingStationAvailable;
}
public String getName() {
return name;
}
public boolean hasChargingStation() {
return chargingStation;
}
public ArrayList<Edge> getIncidentRoads() {
return incidentRoads;
}
// Add a road to the array incidentRoads
public void addIncidentRoad(Edge road) {
incidentRoads.add(road);
}
public int getIndex() {
return index;
}
private String name; // Name of the place
private ArrayList<Edge> incidentRoads; // Incident edges
private boolean chargingStation; // Availability of charging station
private int index; // Index of this vertex in the vertex array of the map
}
class Edge {
public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) {
length = roadLength;
incidentPlaces = new Vertex[] { firstPlace, secondPlace };
}
public Vertex getFirstVertex() {
return incidentPlaces[0];
}
public Vertex getSecondVertex() {
return incidentPlaces[1];
}
public int getLength() {
return length;
}
private int length;
private Vertex[] incidentPlaces;
}
// A class that represents a sparse matrix
public class RoadMap {
// Default constructor
public RoadMap() {
places = new ArrayList<Vertex>();
roads = new ArrayList<Edge>();
}
// Auxiliary function that prints out the command syntax
public static void printCommandError() {
System.err.println("ERROR: use one of the following commands");
System.err.println(" - Load a map and print information:");
System.err.println(" java RoadMap -i <MapFile>");
System.err.println(" - Load a map an.
Super TypeScript II Turbo - FP Remix (NG Conf 2017)Sean May
This talk focuses on typical functional programming paradigms in JavaScript, as implemented in TypeScript.
The goal of this talk was to provide common ground in FP paradigms, between C# .NET developers, Java Spring developers and JS programmers. The slides have been annotated and extended from the talk, to cover intended concepts not explicit in the code examples, themselves.
https://www.youtube.com/watch?v=9oVKjZrgXmU
Why using composition in React ? What are the alternative (mixins, inheritance)? How to use composition to build your React application? What are the pros and cons?
Object-Oriented JavaScript presentation given at the 2010 ESRI Developer Summit. Code and slides are also available at http://github.com/kvangork/OOJS-Presentation
Find me on twitter @kvangork
or my blog http://prng.vangorkom.org
Object-Oriented JavaScript presentation given at ESRI's 2010 Developer Summit. Slides and code available at http://github.com/kvangork/OOJS-Presentation
Find me on twitter @kvangork
or at my blog: http://prng.vangorkom.org
Refactoring can either completely disrupt your project or make you go faster. This presentation will help you to avoid some pitfalls.
It also demonstrates refactorings that you could apply straight away to make your code better.
This pdf shows some part of the code of my private stand-alone C++ library, in particular the implementation of a Libor Market Model, with a term structure of skew and stochastic volatility. It runs on a simple laptop! The underlying Monte Carlo engine is a piece of art that I managed to replicate from SCB's C++ library without any remote access or usb key, only:
1. from memory and a couple of double-sided 'cheat cheets'
2. a week-end day at the office in April 2016 to make some comparison tests to make the calculation results perfectly in line with those from the Bank's library (with 1.0e-8 accuracy).
Credits for the Libor Market Model go to me, credits for the Monte Carlo engine go to the quants who made it at Standard Chartered. This pdf shows some partial code of the Libor Market Model ONLY (obviously I keep the code of the MC engine secret since I am not the author of it).
QuantActive 2016. VIEW ONLY (DOWNLOAD MODE DEACTIVATED ).
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018Codemotion
ECMAScript 2018 o simplemente ES2018, es la última revisión de nuestro lenguaje favorito y ha llegado con interesantes novedades que, sin lugar a dudas, cambiarán la forma en la que trabajaremos con el lenguaje en los próximos años. A lo largo de la charla repasaremos, no solo las novedades incluidas en la especificación ES2018 si no que echaremos un vistazo a las propuestas de la próxima especificación ES2019. Una mirada al futuro de JavaScript.
Find out more presentations at https://madrid2018.codemotionworld.com/speakers/
Please the following is the currency class of perious one- class Curre.pdfadmin463580
Please the following is the currency class of perious one.
class Currency {
protected:
int whole;
int fraction;
virtual std::string get_name() = 0;
public:
Currency() {
whole = 0;
fraction = 0;
}
Currency(double value) {
if (value < 0)
throw "Invalid value";
whole = int(value);
fraction = std::round(100 * (value - whole));
}
Currency(const Currency& curr) {
whole = curr.whole;
fraction = curr.fraction;
}
/* This algorithm gets the whole part or fractional part of the currency
Pre: whole, fraction - integer numbers
Post:
Return: whole or fraction
*/
int get_whole() { return whole; }
int get_fraction() { return fraction; }
/* This algorithm adds an object to the same currency
Pre: object (same currency)
Post:
Return:
*/
void set_whole(int w) {
if (w >= 0)
whole = w;
}
void set_fraction(int f) {
if (f >= 0 && f < 100)
fraction = f;
}
/* This algorithm adds an object to the same currency
Pre: object (same currency)
Post:
Return:
*/
void add(const Currency* curr) {
whole += curr->whole;
fraction += curr->fraction;
if (fraction > 100) {
whole++;
fraction %= 100;
}
}
/* This algorithm subtracts an object to the same currency
Pre: object (same currency)
Post:
Return:
*/
void subtract(const Currency* curr) {
if (!isGreater(*curr))
throw "Invalid Subtraction";
whole -= curr->whole;
if (fraction < curr->fraction) {
fraction = fraction + 100 - curr->fraction;
whole--;
}
else {
fraction -= curr->fraction;
}
}
/* This algorithm compares the an object of the same currency for equality or inequality
Pre: object (same currency)
Post:
Return: whole/fraction
*/
bool isEqual(const Currency& curr) {
return curr.whole == whole && curr.fraction == fraction;
}
/* This algorithm compares the an object of the same currency to determine which is greater or
smaller
Pre: object (same currency)
Post:
Return: true/false
*/
bool isGreater(const Currency& curr) {
if (whole < curr.whole)
return false;
if (whole == curr.whole && fraction < curr.fraction)
return false;
return true;
}
/* This algorithm prints the name and value of the currency object
Pre: value of whole, fraction, and the name
Post: whole, fraction, get_name()
Return:
*/
void print() {
std::cout << whole << "." << fraction << " " << get_name() << std::endl;
}
};
class Krone : public Currency {
protected:
/*
This algorithm gets the name for the Currency.
Pre: name - declared as string and initialized as Krone
Post:
Return: name
*/
std::string name = "Krone";
std::string get_name() {
return name;
}
public:
Krone() : Currency() { }
Krone(double value) : Currency(value) { }
Krone(Krone& curr) : Currency(curr) { }
};
class Soum : public Currency {
protected:
/* This algorithm gets the name for the Currency.
Pre: name - declared as string and initialized as Soum
Post:
Return: name
*/
std::string name = "Soum";
std::string get_name() {
return name;
}
public:
Soum() : Currency() { }
Soum(double value) : Currency(value) { }
Soum(Krone& curr) : Currency(curr) { }
};
A LinkNode structure or class which will have two attrib.
2. 집단 행동(group behavior)
기본적인 집단 행동
결합(cohesion)
분리(separation)
정렬(alignment)
집단 행동의 예 :
무리짓기 행동(flocking behavior) (새떼,물고기떼 등)-
결합(cohesion),분리(separation),정렬(alignment)의 조합
집단에 속하는 각 운반기(vehicle)의 조종힘(steering force)은 이
웃 반경(neighborhood radius) 내의 모든 운반기를 고려하여 결정
됨.
3. 이웃 반경 tagging
template <class T, class conT>
void TagNeighbors(const T* entity, conT& ContainerOfEntities, double radius)
{
//iterate through all entities checking for range
for (typename conT::iterator curEntity = ContainerOfEntities.begin();
curEntity != ContainerOfEntities.end();++curEntity)
{
//first clear any current tag
(*curEntity)->UnTag();
Vector2D to = (*curEntity)->Pos() - entity->Pos();
//the bounding radius of the other is taken into account by adding it
//to the range
double range = radius + (*curEntity)->BRadius();
//if entity within range, tag for further consideration. (working in
//distance-squared space to avoid sqrts)
if ( ((*curEntity) != entity) && (to.LengthSq() < range*range))
{
(*curEntity)->Tag();
}
}//next entity
}
tip - tagging시 가시범위(field-of-view)를 제한 하는 것을 통한 사실감 향상
4. 분리(separation)
Vector2D SteeringBehaviors::Separation(const std::vector<Vehicle*>& neighbors)
{
Vector2D SteeringForce;
for (int a=0; a<neighbors.size(); ++a)
{
//make sure this agent isn't included in the calculations and that
//the agent being examined is close enough.
if((neighbors[a] != m_pVehicle) && neighbors[a]->IsTagged())
{
Vector2D ToAgent = m_pVehicle->Pos() - neighbors[a]->Pos();
//scale the force inversely proportional to the agent's distance
//from its neighbor.
SteeringForce += Vec2DNormalize(ToAgent)/ToAgent.Length();
}
}
return SteeringForce;
}
5. 정렬(alignment)
Vector2D SteeringBehaviors::Alignment(const std::vector<Vehicle*>& neighbors)
{
//used to record the average heading of the neighbors
Vector2D AverageHeading;
//used to count the number of vehicles in the neighborhood
int NeighborCount = 0
//iterate through all the tagged vehicles and sum their heading vectors
for (int a=0; a<neighbors.size(); ++a)
{
//make sure *this* agent isn't included in the calculations and that
//the agent being examined is close enough
if((neighbors[a] != m_pVehicle) && neighbors[a]->IsTagged)
{
AverageHeading += neighbors[a]->Heading();
++NeighborCount;
}
}
//if the neighborhood contained one or more vehicles, average their
//heading vectors.
if (NeighborCount > 0)
{
AverageHeading /= (double)NeighborCount;
AverageHeading -= m_pVehicle->Heading();
}
return AverageHeading;
}
6. 결합(cohesion)
Vector2D SteeringBehaviors::Cohesion(const std::vector<Vehicle*>& neighbors)
{
//first find the center of mass of all the agents
Vector2D CenterOfMass, SteeringForce;
int NeighborCount = 0;
//iterate through the neighbors and sum up all the position vectors
for (int a=0; a<neighbors.size(); ++a)
{
//make sure *this* agent isn't included in the calculations and that
//the agent being examined is a neighbor
if((neighbors[a] != m_pVehicle) && neighbors[a]->IsTagged())
{
CenterOfMass += neighbors[a]->Pos();
++NeighborCount;
}
}
if (NeighborCount > 0)
{
//the center of mass is the average of the sum of positions
CenterOfMass /= (double)NeighborCount;
//now seek toward that position
SteeringForce = Seek(CenterOfMass);
}
return SteeringForce;
}
7. 무리짓기? 떼지어 다니기?(flocking)
발현성 행동(emergent behavior) - 복잡하고 의도 된 mass
game인 듯 보이지만, 실재로는 인접한 이웃의 정보만을 가지고
간단한 법칙으로 자연 발생적으로 나타나는 행동.
무리짓기 - 분리,정렬,결합의 조합.
+ 제한 된 시야(tagging range?)때문에 고립되는 걸 막기 위해 배
회하기 행동을 추가하는 것이 선호됨.
8. 조종 행동들의 조합
(combining steering behaviors)
가중 절단된 합(Weighted Truncated Sum)
우선순위와 함께 가중 절단된 연속합
(Weighted Truncated Running Sum with Prioritization)
우선순위가 주어진 디더링(Prioritized Dithering)
10. 우선순위와 함께 가중 절단된 연속합
(Weighted Truncated Running Sum with Prioritization)
SVector2D SteeringBehaviors::Calculate()
{
//reset the force.
m_vSteeringForce.Zero();
SVector2D force;
if (On(wall_avoidance)) {
force = WallAvoidance(m_pVehicle->World()->Walls()) *m_dMultWallAvoidance;
if (!AccumulateForce(m_vSteeringForce, force)) return m_vSteeringForce;
}
if (On(obstacle_avoidance)){
force = ObstacleAvoidance(m_pVehicle->World()->Obstacles()) *m_dMultObstacleAvoidance;
if (!AccumulateForce(m_vSteeringForce, force)) return m_vSteeringForce;
}
if (On(separation)){
force = Separation(m_pVehicle->World()->Agents()) *m_dMultSeparation;
if (!AccumulateForce(m_vSteeringForce, force)) return m_vSteeringForce;
}
/* EXTRANEOUS STEERING FORCES OMITTED */
return m_vSteeringForce;
}
X 순서대로 힘에 붙일때까지만 행위들을 수행함.
11. bool SteeringBehaviors::AccumulateForce(Vector2D &RunningTot,
Vector2D ForceToAdd)
{
//calculate how much steering force the vehicle has used so far
double MagnitudeSoFar = RunningTot.Length();
//calculate how much steering force remains to be used by this vehicle
double MagnitudeRemaining = m_pVehicle->MaxForce() - MagnitudeSoFar;
//return false if there is no more force left to use
if (MagnitudeRemaining <= 0.0) return false;
//calculate the magnitude of the force we want to add
double MagnitudeToAdd = ForceToAdd.Length();
//if the magnitude of the sum of ForceToAdd and the running total
//does not exceed the maximum force available to this vehicle, just
//add together. Otherwise add as much of the ForceToAdd vector as
//possible without going over the max.
if (MagnitudeToAdd < MagnitudeRemaining){
RunningTot += ForceToAdd;
}else{
//add it to the steering force
RunningTot += (Vec2DNormalize(ForceToAdd) * MagnitudeRemaining);
}
return true;
}
13. 겹치기 피하기 (ensuring zero overlap)
template <class T, class conT> void EnforceNonPenetrationConstraint(const T& entity,const conT&
ContainerOfEntities){
//iterate through all entities checking for any overlap of bounding radii
for (typename conT::const_iterator curEntity =ContainerOfEntities.begin();curEntity !=
ContainerOfEntities.end();++curEntity){
//make sure we don't check against the individual
if (*curEntity == entity) continue;
//calculate the distance between the positions of the entities
Vector2D ToEntity = entity->Pos() - (*curEntity)->Pos();
double DistFromEachOther = ToEntity.Length();
//if this distance is smaller than the sum of their radii then this
//entity must be moved away in the direction parallel to the
//ToEntity vector
double AmountOfOverLap = (*curEntity)->BRadius() + entity->BRadius() -DistFromEachOther;
if (AmountOfOverLap >= 0) {
//move the entity a distance away equivalent to the amount of overlap.
entity->SetPos(entity->Pos() + (ToEntity/DistFromEachOther) *AmountOfOverLap);
}
}//next entity
}
14. Coping with Lots of Vehicles: Spatial Partitioning
template <class entity>
class CellSpacePartition
{
private:
//the required number of cells in the space
std::vector<Cell<entity> > m_Cells;
//this is used to store any valid neighbors when an agent searches
//its neighboring space
std::vector<entity> m_Neighbors;
//this iterator will be used by the methods next and begin to traverse
//through the above vector of neighbors
std::vector<entity>::iterator m_curNeighbor;
//the width and height of the world space the entities inhabit
double m_dSpaceWidth;
double m_dSpaceHeight;
//the number of cells the space is going to be divided into
int m_iNumCellsX;
int m_iNumCellsY;
double m_dCellSizeX;
double m_dCellSizeY;
//given a position in the game space, this method determines the
//relevant cell's index
inline int PositionToIndex(const Vector2D& pos)const;
15. public:
CellSpacePartition(double width, double height, int cellsX, int cellsY, int MaxEntitys);
//width of the environment,height,number of cells horizontally,number of cells vertically,maximum number
of entities to add
//adds entities to the class by allocating them to the appropriate cell
inline void AddEntity(const entity& ent);
//update an entity's cell by calling this from your entity's Update method
inline void UpdateEntity(const entity& ent, Vector2D OldPos);
//this method calculates all a target's neighbors and stores them in
//the neighbor vector. After you have called this method use the begin,
//next, and end methods to iterate through the vector.
inline void CalculateNeighbors(Vector2D TargetPos, double QueryRadius);
//returns a reference to the entity at the front of the neighbor vector
inline entity& begin();
//this returns the next entity in the neighbor vector
inline entity& next();
//returns true if the end of the vector is found (a zero value marks the end)
inline bool end();
//empties the cells of entities
void EmptyCells();
};
16. Coping with Lots of Vehicles: Spatial
Partitioning
template <class entity>
struct Cell
{
//all the entities inhabiting this cell
std::list<entity> Members;
//the cell's bounding box (it's inverted because the Windows' default
//coordinate system has a y-axis that increases as it descends)
InvertedAABBox2D BBox;
Cell(Vector2D topleft,Vector2D botright):BBox(InvertedAABBox2D(topleft, botright))
{}
};
17. template<class entity>
void CellSpacePartition<entity>::CalculateNeighbors(Vector2D TargetPos,double QueryRadius)
{
//create an iterator and set it to the beginning of the neighbor list
std::list<entity>::iterator curNbor = m_Neighbors.begin();
//create the query box that is the bounding box of the target's query
//area
InvertedAABBox2D QueryBox(TargetPos - Vector2D(QueryRadius, QueryRadius),TargetPos +
Vector2D(QueryRadius, QueryRadius));
//iterate through each cell and test to see if its bounding box overlaps
//with the query box. If it does and it also contains entities then
//make further proximity tests.
std::vector<Cell<entity> >::iterator curCell;
for (curCell=m_Cells.begin(); curCell!=m_Cells.end(); ++curCell)
{
//test to see if this cell contains members and if it overlaps the
//query box
if (curCell->pBBox->isOverlappedWith(QueryBox) &&!curCell->Members.empty()){
//add any entities found within query radius to the neighbor list
std::list<entity>::iterator it = curCell->Members.begin();
for (it; it!=curCell->Members.end(); ++it){
if (Vec2DDistanceSq((*it)->Pos(), TargetPos) <QueryRadius*QueryRadius){
*curNbor++ = *it;
}
}
}
}//next cell
/ /mark the end of the list with a zero.
*curNbor = 0;
}
19. if (SmoothingIsOn())
{
m_vSmoothedHeading = m_pHeadingSmoother->Update(Heading());
}
--------------------------------------------------------------------------------------------------------------------
template <class T> class Smoother {
private:
//this holds the history
std::vector<T> m_History;
int m_iNextUpdateSlot;
//an example of the 'zero' value of the type to be smoothed. This
//would be something like Vector2D(0,0)
T m_ZeroValue;
public: //to instantiate a Smoother pass it the number of samples you want to
// use in the smoothing, and an exampe of a 'zero' type
Smoother(int SampleSize, T ZeroValue):m_History(SampleSize, ZeroValue),
m_ZeroValue(ZeroValue),m_iNextUpdateSlot(0) {}
//each time you want to get a new average, feed it the most recent value
//and this method will return an average over the last SampleSize updates
T Update(const T& MostRecentValue) {
//overwrite the oldest value with the newest
m_History[m_iNextUpdateSlot++] = MostRecentValue;
//make sure m_iNextUpdateSlot wraps around.
if (m_iNextUpdateSlot == m_History.size()) m_iNextUpdateSlot = 0;
//now to calculate the average of the history list
T sum = m_ZeroValue;
std::vector<T>::iterator it = m_History.begin();
for (it; it != m_History.end(); ++it){ sum += *it; }
return sum / (double)m_History.size();
}
};