miércoles, 12 de diciembre de 2018

C++ Program: Armtrong nickname generation

C++ Program: Armtrong nickname generation

This is a sample C++ program that computes configurable length random "nicknames" and selects those nicknames that verifies "Armtrong property".

Armtrong property:
Given the number x1x2x3... it verifies Armtrong if : x1x2x3... = x1^3 + x2^3 + x3^3...
An example is the number 153 = 1^3 + 5^3 + 3^3

However!! this program works with a different criteria: which is x1x2x3...= x1*3+x2*3+x3*3....

For the iterations and nickname lengths specified in the code bellow, we get this result:

Note: Works fine with Codeblocks and gcc.

armtrongnames.cpp

/*
 * armtrongnames.cpp
 *
 *  Created on: 12 Dec 2018
 *      Author: david
 */

/*
 * This is an example of Armtrong numbers applied to person names generation:
 * Thus, we will map letters to numbers as a=1, b=2,...z=25
 * Then we will get vocals: a,e,i,o,u
 * Next we will generate names: cvcvcv(c) and vcvcvc(v), in the same time we will check if the number mapping is an Armtrong number
 * Finally we will keep the Armtrong names: What this will give us?
    Armstrong number (modified): x1x2...xn = x1*3+x2*3+...+xn*3
 */


#include
#include
#include
#include
#include
#include
#include

using namespace std;




int isVocal(int pos,vector vocalsW) {
	int r = -1;

	for(int i=0;i vocalsW,string letters){
	int r = -1;
	if(pos>0 && pos<=letters.length()){
		r =isVocal(pos,vocalsW);

		if(r==0)
			r=-1;
		else
			r = 0;
	}

	return r;

}
char getLetter(int pos,string letters){
	char c = '*';
	if(pos>0 && pos<=letters.length())
		c = letters.at(pos-1);
return c;
}

int getRandVocalPos(vector vocalsW){
	int pos = 0;
    pos = rand() % 5;
    return vocalsW[pos];

}

int getRandConsPos(vector vocalsW,string letters){
	int pos =-1;
	bool end = false;
	while(!end){
		pos = (rand()% letters.length()) +1;
		if(isConsonant(pos,vocalsW,letters)==0){
			end = true;
		}
	}

	return pos;
}

int compDec(vector v) {
	int n = 0;

	int i =  v.size() - 1;

	int pw = 0;
	while(i>=0){
		if(v[i] != 0 ){
			n = n + (v[i] * (int)(pow(10,pw)));
			pw++;
		}
	  i--;
	}
	return n;
}
int compArmtrong(int s){
	int a=0;
	int i = 1;
	int b = s;
	int c=0;
	while(b>1){
		c = b % i;
		b = (b-c)/i;
		i = i * 10;
		a = a + (c*3); /*a = a + (int) pow(c,3); */
	}
return a;
}
int sumVect(vector v) {
	int a=0;
		for(int i=0;i v){
	int r = -1;
	int ams = -1;
    int sum = sumVect(v);

	ams = compArmtrong(sum);

	if(ams==sum)
		r = 0;
	return r;
}

string buildName(vector v,string letters){
	string name("");
	char c;

	for(int i=0;i::iterator iter;

std::string letters("abcdefghijklmnopqrstuwxyz");
vector vocalsW;

int MAXITER = 900;
int MAXNAMELEN = 20;
int MINNAMELEN = 4;
int T = MAXITER * ((MAXNAMELEN-MINNAMELEN) + 1);
std:vector *amsnames = new vector();

vocalsW.push_back(1);vocalsW.push_back(5);
vocalsW.push_back(9);vocalsW.push_back(15);
vocalsW.push_back(21);


int i = 0;
while(i0){
    vector nameW;

        if(altern%2==0){ //first a consonant

            for(int k=1;k<=j;k++){
                if(k%2!=0)
                    nameW.push_back( getRandConsPos(vocalsW,letters) );
                else
                    nameW.push_back(getRandVocalPos(vocalsW));

            }

        }
        else {  //first a vocal
            for(int k=1;k<=j;k++){
                if(k%2!=0)
                    nameW.push_back( getRandVocalPos(vocalsW) );
                else
                    nameW.push_back(getRandConsPos(vocalsW,letters));

            }
        }

		int r = isArmtrong(nameW);
        string name = buildName(nameW,letters);
        cout << name << endl;
        if(r==0)
			amsnames->push_back(name);

        altern--;

        }
		j++;
	}
	i++;
}

cout << "+++++++++++++++++++++++++" << endl;
cout<< "Generated Armtrong Names:" << amsnames->size() << endl;
int cnt = 1;
for(iter=amsnames->begin();iter!=amsnames->end();iter++){
	cout<< cnt << " :" << *iter << endl;
    cnt++;
}
getch();
return 0;
}


jueves, 8 de marzo de 2018

Agent Oriented Programming (principles)

Principles of Agent-Oriented Programming

Introduction

In the early of 1970s the Artificial Intelligence (AI) was defined as a system based on the Von Neumann model (with a single control center) and the concepts of traditional Psychology. In the late of 1970s the idea of individual behavior was tested from several works that required a distributed control. For example, works related to blackboards (Fennel & Lesser, 1977) and actors (Hewitt, 1977) allowed the modeling of classical problems considering concepts such as cooperation, communication and distribution. Therefore, the researchers started to investigate the interaction between systems, trying to solve distributed problems in a more social perspective.

In order to find solutions for distributed systems, the Distributed Artificial Intelligence (DAI) started in the early of 1980s to be investigated. It combines the theoretical and practical concepts of AI and Distributed Systems (DS). The solution is also based on social behaviors where the cooperative behavior is utilized to solve a problem. The DAI is different of DS because (i) it is not based on the client-server model, and (ii) the DAI area does not address issues related to distributed processing, aiming to increase the efficiency of computation itself (transmission rate, bandwidth, etc). However it aims to develop technical cooperation between entities involved in a system. Also, the DAI differs from AI because it brings a new and broader perspectives on knowledge representation, planning, problem solving, coordination, communication, negotiation, etc.

The Multi-Agent Systems (MAS) is one of the research areas of DAI, and uses autonomous agents with their own actions and behaviors. The agents in a MAS are designed to act as experts in a particular area. The main characteristic is to control their own behaviors and, if necessary, to act without any intervention of humans or other systems. The focus of the designer is to develop agents working in an autonomous or social way, as well as systems of communication and cooperation/collaboration, so that the solution arises from the interactions. This bottom-up approach usually leads to an open architecture, where agents can be inserted, deleted, and reused. According to Sawyer (2003), the Internet is an example of MAS because it is constituted by thousands of independent computers, each on running autonomous software programs that are capable of communication with a program running on any other node in the network.

The term agent is used frequently in AI, but also outside its field, for example in connection with databases and manufacturing automation. When people in AI use the term, they are referring to an entity that functions continuously and autonomously in an environment where other processes take place and other agents exist. The sense of autonomy is not precise, but the term is taken to mean that the agent activities do not requires constant human guidance or intervention (Shoham, 1993). There are a number of good reasons for supposing that agent technology will enhance the ability of software engineers to construct complex and distributed applications. It is a powerful and natural metaphor to conceptualize, design and implement many systems.

This chapter makes an overview of theoretical and technical concepts of Agent-Oriented Programming (AOP). Historically, the AOP appears after the Object-Oriented Programming (OOP). However the differences between them are not clear in the research and development community. Section 2 discusses the differences between objects and agents and also the evolution of the programming language paradigms. Section 3 presents the micro and the macro levels of a society of agents. The pitfalls of AOP are explained in Section 4. Two multi-agent systems platforms are presented in Section 5. In Section 6 two multi-agent applications are presented: a cognitive modeling of stock exchange and a military application of real-time tactical information management.

2. Programming with objects or agents: What are the main differences?

Procedural programs are typically intended to be executed discretely in a batch mode with a specific start and end (Huhns, 2004). However, the modular programming approach employs smaller units of code that could be reused under a variety of situations. The structured loops and subroutines are designed to have a high degree of local integrity (Odell, 1999). The concept of objects and agents are the key to understand the OOP and AOP, respectively.

2.1 Agents versus objects

In (Silva et al., 2003) an agent is defined as an extension of an object with additional features, because it extends the definition of state and behavior associated with objects. The mental states consist of its states and behaviors. The beliefs and goals, plans, actions are equivalent to the object’s state and agent’s behaviors, respectively. Moreover, the behavior of an agent extends the behavior of objects because the agents have freedom to control and change their behaviors. They also not require external stimuli to carry out their jobs. These make the agents active elements and objects passive ones.

Agents use some degree of unpredictable behavior. For example, the ants appear to be taking a random walk when they are trying to find food. Their behavior starts to become predictable when the pheromones or food are detected. Therefore, an agent can range from being totally predictable to completely unpredictable. On the other hand, the objects do not have to be completely predictable (Odell, 2002).

The agent has the ability to communicate with the environment and other entities. In MAS the agents are autonomous and has the characteristics to interact with the environments and other agents. However, the object messages have the most basic form of interaction. Also, it request via message only one operation formatted in a very exacting way. The oriented-object message broker has the job of matching each message to exactly one method invocation for exactly one object.

In the communication between agents in the MAS is allowed to use the method invocation of OOP. However, the demand of messages are greater than those used by objects technology. An agent message could consist of a character string whose form can vary, yet obeys a formal syntax, while the conventional object-oriented method must contain parameters whose number and sequence are fixed. Agents may engage in multiple transactions concurrently, through the use of multiple threads or similar mechanisms. Conventional OOP have difficulty to support such requirements (Odell, 2002). But it is possible for the agents to employ objects for situations that require a little autonomous or interactive ability. In the MAS environment, an Agent Communication Language (ACL) is necessary to send a message to any agent. KQML (Group et al., 1992) and FIPA ACL (Buckle & Hadingham, 2000) are examples of the ACLs.

2.2 Object-Oriented Programming

Rentsch (Rentsch, 1982) predicted in 1982 that the OOP would be in 1980s what the structured programming was in the 1970s. The earliest precursor of MAS was OOP. The subsequent OOP evolution provide methods and techniques to identify the objects and their attributes needed to implement the software, to describe the associations between the identified objects, to define the behavior of the objects by describing the function implementations of each object, to refine objects and organize classes by using inheritance to share common structure are the challenges of object-oriented analysis and design (Wahono, 2001). In OOP, an object is a single computational process maintaining its own data structures and procedures (Sawyer, 2003). Also, it maintains the segments of code (methods) and gain local control over the variables manipulated by its methods. In traditional OOP, the objects are passive because their methods are invoked only when some external entity sends them a message. The basic element used in the OOP is the class. A class definition specifies the class variables of an object and the methods that the object accepts. One class inherits from another class such that the new class is an extension of the existing class, instances of two classes collaborates with each other by exchanging messages (Lind, 2000).

In Wahono (2001), the object is defined as the principal building blocks of OOP. Each object is a programming unit consisting of attributes (instance variables) and behaviors (instance methods). An object is a software bundle of variables and related methods. It is easy to see many examples of real-world objects. Also, it is possible to represent the real-world objects using software objects. For example, bicycles have attributes (gear, pedal cadence, two wheels) and behaviors (braking, accelerating, slowing down). A software object that modeled our real-world bicycle would have variables that indicate the bicycle’s current attribute: its speed is 10 mph, its pedal cadence is 90 rpm, and its current gear is the 5th gear. These variables and methods are formally known as instance variables and instance methods to distinguish them from class variables and class methods.

2.3 Agent-Oriented Programming

The MAS is considered as an object-oriented system that is associated to an intelligent meta-system. By this way, an agent is viewed as an object that has a layer of intelligence, comprising a number of capabilities such as uniform communication protocol, perception, reaction and deliberation, all of them not inherent to objects. However, the AOP has code, states and agent invocations. The agents also have individual rules and goals to make them appear like active objects with initiative. In AOP the class is replaced by role, state variable with belief/knowledge and method with message. The role definitions describe the agent capability and the information needed to desired results. In order to the agents act with intelligence in their environment, the idea is to develop the complex entities and provide the agents with the knowledge and beliefs to be able to achieve their desires.

Table 1. Relation between OOP and AOP.

2.4 Differences between Object-Oriented Programming and Agent-Oriented Programming

Table 1 summarizes the major features of the relation between OOP and AOP. In short, AOP is seen as an extension of OOP. On the other hand, OOP can be viewed as a successor of structured programming. Wagner (2003) defines two main characteristics about the AOP. First, while the state of an object in OOP has no generic structure, the state of an agent in AOP consists of mental components such as beliefs and commitments. Second, while messages in OOP are code in an application-specific ad-hoc manner, a message in AOP is coded as a speech act according to the standard Agent Communication Language that is application-independent.

The autonomy and interaction are the key areas to differentiate the AOP from OOP. The following list describes some underlying concepts that agent-based systems employ (Odell, 2002):

• Decentralization: the objects are centrally organized, because the objects methods are invoked under the control of other components in the system. On the other hand, the agent has a centralized and decentralized processing;

• Multiple and dynamic classification: in OOP, objects are created by a class and, once created, may never change their class or become instances of multiple classes (except by inheritance). However, the agents provide a more flexible approach;

• Small in impact: the objects and agents can be described as small grained or large grained. Also, in comparison with the whole system the agent or object can be small. In an agent-based supply chain, if a supplier or a buyer is lost, the collective dynamics can still dominate. If an object is lost in a system, an exception is raised;

• Emergence: the ant colonies have emergent qualities where groups of agents behave as a single entity. Each consists of individual agents acting according to their own rules and even cooperating to some extent. In MAS, simple rules produce emergence. Since traditional objects do not interact without a higher-level thread of control, emergence does not usually occur. As more agents become decentralized, their interaction is subject to emergence.

More: Multi-agent systems

Understanding java.util.concurrent.Future (Basics)

In this article you'll find a basic example of this Java interface and it will introduce you to the use of the @Async Spring, EJB, annotation

You can find it at: Future interface basics

lunes, 5 de marzo de 2018

miércoles, 21 de febrero de 2018

Branch & Bound + visitor pattern, path finder example (C++)

This example tries to solve the following problem: We have a NxN checker. Every (i,j) case contains k points (in this example k=4). One entry point that is a point located into the case's boundary. Two points are inside the case and the last point is an exit point, also at the boundary (different from entry). The algorithm uses Branch & Bound technique to: given an initial case and an end case, compute the minimal cost path from init to end. It also uses visitor pattern to get results. Implementation needs to be finished in some points.

Main library: "pathfinder.h"

#ifndef PATHFINDER_H_INCLUDED
#define PATHFINDER_H_INCLUDED

#include "visitor.h"

#include 
#include 
#include 
#include 
#include 

typedef struct {
B = 0, // boundary point
M = 1  // middle point
} PointType;

class Point2D {
public:
Point2D(double x, double y, PointType t){ this->_x = x; this->_y= y; this->_type = t;}
Point2D(double x, double y){ this->_x = x; this->_y= y; this->_type = PointType::I;}
~Point2D();
static double segment(Point2D * from, Point2D * to);
virtual Point2D* closest(Point2D * pa, Point2D* pb);
double getX() { return this->_x; }
double getY() { return this->_y; }
PointType getType() { return this->_type;}
bool equals (Point2D* other){
this->_type = other->_type;
this->_x = other->_x;
this->_y = other->_y;
}
private:
    double _x;
    double _y;
    PointType _type;
};

static double Point2D::segment(Point2D * a, Point2D * b) {
    return  (double)(abs(b->getX()-a->getX()) + abs(b->getY()-a->getY()));
}
/* returns the closest distance value pair  from an input points vector */
map * Point2D::closest(vector * points){
map * clst = NULL;
double da = 0, db = 0, m = 0;
Point2D* mp = NULL;
int i,j;

for(i=0;isize()-1;i++){
 da = Point2D::segment(this, points[i]);
 for(j=i+1;jsize();j++){
        db = Point2D::segment(this,points[j]);
        if(da<=db){
            m = da;
            mp = points[i];
        }else{
            m = db;
            mp = points[j];
        }
 }
}
 if(mp!=NULL){
    clst = new map();
    clst->insert(make_pair(m,mp));
 }
 return ( clst );
}

class Node {
public:
    Node(string name, double cost, int x, int y, long position, vector & values);
    ~Node();
    virtual double segment(Node* n, int atPointIdx);
    void setPosition(long pos) { this->_position = pos;}
    void setCost(double c) { this->_cost = c; }
    long getPosition() { return this->_position;}
    double getCost() { return this->_cost;}
    string getName() { return this->_name; }
    int getX() { return this->_x;}
    int getY() { return this->_y; }
    int getNextPointIdx();
    int getCurrentPointIdx() { return this->_currentPointIdx; }
    void setCurrentPointIdx(int v) { this->_currentPointIdx = v;}
    Point2D* getBPoint2D();
    Point2D * getPoint2D(int idx);
    void setUpMoveIdx(int v) { this->_currentUpMoveIdx = v; }
    void setBackMoveIdx(int v) { this->_currentBackMoveIdx = v; }
    void setFwdMoveIdx(int v){ this->_currentFwdMoveIdx = v; }
    int getUpMoveIdx(){ return this->_currentUpMoveIdx; }
    int getBackMoveIdx() { return this->_currentBackMoveIdx; }
    int getFwdMoveIdx(){ return this->_currentFwdMoveIdx; }
    vector & getValues() { return this->_values;}
    void setValues(vector & values) { this->_values = values;}
    static Node* copyNode(Node* fromNode);
    Point2D* getIntersection(Node* target);
    void computeMinPath(Node* toNode); /* this  and toNode have to have at least one boundary Point2D in common else returns NULL*/
    vector & getMinPath() { return this->_lastMinPath; }
    vector getMinCost() { return this->_lastMinCost; }
private:
    string _name;
    double _cost;
    vector _lastMinPath;
    vector _lastMinCost;
    int _x;
    int _y;
    long _position;
    int _currentPointIdx = 0;
    int _currentUpMoveIdx = 0;
    int _currentBackMoveIdx = 0;
    int _currentFwdMoveIdx = 0;
    vector _values;
};

Node::Node(string name, double cost, int x, int y, long position, vector & values) {
    this->_name = name; this->_cost = cost; this->_x= x; this->_y = y;
    this->_position = position;
    this->_values =  values;
}

static Node* Node::copyNode(Node* fromNode) {

Node * cpy = new Node(fromNode->getName(), fromNode->getCost(), fromNode->getX(), fromNode->getY(), fromNode->getPosition(), fromNode->getValues());

    cpy->setCurrentPointIdx(fromNode->getCurrentPointIdx());
    cpy->setCurrentUpMoveIdx(fromNode->getCurrentUpMoveIdx());
    cpy->setCurrentBackMoveIdx(fromNode->getCurrentBackMoveIdx());
    cpy->setCurrentFwdMoveIdx(fromNode->getCurrentFwdMoveIdx());

  return cpy;
}

int Node::getNextPointIdx() {

int next = this->_currentPointIdx +1;

if(next>=this->_values.size())
    next = -1;

 this->_currentPointIdx = next;

return this->_currentPointIdx;

}
Point2D * Node::getPoint2D(int idx){
Point2D * n =  NULL;
if(idx>=0 && idx_values.size())
    n = (Point2D *)this->values.at(idx);

    return n;
}
/* returns current indexed point if it is boundary or next boundary point */
Point2D* Node::getBPoint2D() {

    Point2D* bdry = NULL;
    int i = this->getCurrentPointIdx();
    int j = 0;
    while(i_values.size()){
        j = i % this->_values.size();
        Point2D* c = (Point2D*)(this->_values[j])->getType();
        if( c == PointType.B){
            bdry = c;
            break;
        }
        i++;
    }
   // this->setCurrentPointIdx(j);

    return bdry;
}
double Node::segment(int fromAtPointIdx, Node* to, int toAtPointIdx){
Point2D * from = this->getPoint2D(fromAtPointIdx);
Point2D * to = n->getPoint2D(toAtPointIdx);

    return Point2D::segment(from, to);

}

Point2D* Node::getIntersection(Node* from){

Point2D* intersec = NULL;
Point2D* cv = NULL;
Point2D* cf = NULL;
vector fv = from->getValues();

for(int i=0;i_values.size();i++){
    cv = this->_values[i];
    for(int j=0;jgetType() == PointType.B && cv->equals(cf)){
            intersec = cv;
            break;
        }
    }
}

 return intersec;

}
/* verifies if nodes are adjacent if true computes minimum path in current node to reach that boundary point */
void  Node::computeMinPath(Node* toNode){

vector * middles = new vector();
vector * segments = new vector();
map currentMinv = NULL;
mapgetBPoint2D();
Point2D* itsec = this->getIntersection(toNode);
if(startp!=NULL && itsec!=NULL &&
    !startp->equals(itsec)){

    middles = this->getMiddles();


}


}

class Maze {
public:
    Maze();
    Maze(int height, int legth, double scale);
    ~Maze();
    map*> * getData();
    vector* getRow(int rowNum);
    double getScale() { return this->_scale;}
    void setScale(double s) { this->_scale = s;}
    virtual int addNode(int x, int y, Node * node);
    virtual Node* getNode(int x, int y);
    virtual int getCurrentX();
    virtual int getCurrentY();
    virtual int getLevel();
    virtual int deleteNode(int x, int y);
    virtual void setNodeNumber(int x, int y, long nn);
    virtual long incNodeNumber(int delta);
    virtual long decNodeNumber(int delta);
    virtual Node* moveUp(Node* fromNode);
    virtual Node* moveFwd(Node* fromNode);
    virtual Node* moveBack(Node* fromNode);
    virtual Node* traverse(Node* innode, Node* tonode); /* returns a solution node from innode that contains optimized path to tonode*/
    virtual double computeMaxCost(Node* from, Node* to);
    virtual double computeMinCost(Node* from, Node* to);

private:
    map *> * _data;
    double _scale;
    int _level;
    int _currentX;
    int _currentY;
    long _nodeNumber;
    int _height;
    int _legth;
    const static vector * _fwdMoves = {new Point2D(0,1), new Point2D(1,0)};
    const static vector * _upMoves = {new Point2D(-1,0)};
    const static vector * _backMoves = { new Point2D(0,-1)};
};

Maze::Maze() {
    this->Maze(4,4,1);
}

Maze::Maze(int h, int l, double scale){
this->_scale = scale;
this->_level = 0;
this->_currentX = 0;
this->_currentY = 0;
this->_nodeNumber = 0;

 this->_height = h; this->length= l;

 map*>* d = new map*>(this->_height);
 vector * v;

 for(int i = 0;i_height;i++){
        v = new vector(NULL,this->_legth)
        d[i] = v;
 }

 this->_data = d;

}

Maze::~Maze(){
    delete this->_data;
}

map*> * Maze::getData() {
    return this->_data;
}

vector* Maze::getRow(int rownum) {
    return this->_data[rownum];
}
Node* Maze::getNode(int x, int y) {
    return this->_data[x][y];
}
int Maze::addNode(int x, int y , Node* n){
    this->_data[x][y] = n;
    return 0;
}

int Maze::deleteNode(int x, int y) {
    this->_data[x][y] = NULL;
    return 0;
}

int Maze::setNodeNumber(int x, int y, log nn) {
 Node * n  = this->getNode(x,y);
 if(n!=NULL){
    n->setPosition(nn);
    return 0;
 }
 return -1;
}

double Maze::computeMaxCost(Node* f, Node* t) {
Point2D * maxIntersecPoint = NULL;
Point2D * from = new Point2D(f->getX(),f->getY());
Point2D * to = new Point2D(t->getX(), t->getY());
/* intersection right to left and bottom to up */
maxIntersecPoint = new Point2D(to->getX(), from->getY());


return ( Point2D::segment(from, maxIntersecPoint) + Point2D::segment(maxIntersecPoint, to) +2 ) / this->_scale;


}

double Maze::computeMinCost(Node* f, Node* t){

Point2D * from = new Point2D(f->getX(),f->getY());
Point2D * to = new Point2D(t->getX(), t->getY());


return ( Point2D::segment(from, to)  + sqrt(2) / this->_scale;


}
class Solution:public Maze {
public:
    Solution();
    ~Solution();
    virtual vector* getOptSol();
    double getOptimalCost();
    vector* getCosts();
    void setCosts(vector * costs);
    void setOptSolIndex(int idx);
    double getOptCost();
private:
    vector * _costs
    int _optSolIndex;


};


class Backtracking {
public:
    Backtracking(Maze * maze);
    ~Backtracking();
    virtual int compute();
    virtual void accept(Visitor * v);
    virtual Solution * getSolution();
    virtual bool isSolution(int level);
    virtual bool criteria(int level, Node* n);
    virtual Node* computeNext(int level);
    virtual bool hasSibbling(int level);
    virtual int computeBack(int fromLevel);
    virtual bool isFinished(int level);
    virtual void setCurrentPoint(int x, int y);
    virtual setTargetPoint(int x, int y);
    virtual computeMaxTCost();
    virtual computeMinTCost();
private:
    long _totalNodes;
    long _numberOfNodes = 10000;
    double _minTotalCost = 100000;
    double _maxTotalCost = 0;
    int _currentLevel;
    Point2D _currentPoint = new Point2D(0,0);
    Point2D _targetPoint = NULL;
    bool isEnd = false;
    int _globalIterations = 0;
    Maze * _maze;
    Solution * _solution;
    Node* _tempNode;
    cons static _MAXITERATIONS = 10 * _numberOfNodes;
    Visitor * _visitor;
};



class PathFinder: public Backtracking {
public:
    PathFinder(Maze * maze):Backtracking(maze) {}
    void accept(Visitor * v);

private:

};

PathFinder::~PathFinder() { delete this->_maze; delete this->_solution;}

int PathFinder::compute(){
Node* solNode = NULL;
int status =  0;
this->_currentLevel = 0;

this->_tempNode = this->_maze->getNode(0,0);
if(this->_tempNode!=NULL){

 this->_solution->addNode(_tempNode->getCurrentX(),_tempNode->getCurrentY(),_tempNode);
    solNode = this->computeNext(this->_currentLevel);

    this->_totalNodes = 1;

    while(!isEnd && !isFinished(this->_currentLevel)){

        if(isSolution(this->_currentLevel)){
            isEnd = true;
        }else if(criteria(this->_currentLevel, solNode)){
            this->_solution->addNode(solNode->getCurrentX(),solNode->getCurrentY(),solNode);
            this->_tempNode = solNode;
            this->_currentLevel++;
            solNode = this->computeNext(this->_currentLevel);

        }else if(hasSibbling(this->_currentLevel)){

            solNode = this->computeNext(this->_currentLevel);
        }else {

            while(!hasSibbling(this->_currentLevel && !isFinished(this->_currentLevel))){
                this->_currentLevel = this->computeBack(_this->currentLevel);
            }
            if(!isFinished(this->_currentLevel)){
                solNode = this->computeNext(this->_currentLevel);
            }else   status = -100; /* no solution found */
        }


    }


}


return status;

}
void PathFinder::accept(Visitor * v){
        this->_visitor = v;
        this->_visitor->visit(this);
}

Solution * PathFinder::getSolution() {}
bool PathFinder::criteria(int level){}
Node* PathFinder::computeNext(int level){}
bool PathFinder::hasSibbling(int level){}
int PathFinder::computeBack(int fromLevel){}
bool PathFinder::isFinished(int level){}



#endif // PATHFINDER_H_INCLUDED

Getting results (visitor pattern): "visitor.h"

#ifndef VISITOR_H_INCLUDED
#define VISITOR_H_INCLUDED
#include "pathfinder.h"
#include 


class SolutionDisplay {
public:
    SolutionDisplay(Solution * sol);
    ~SolutionDisplay();
    virtual void print();
private:
    Solution * _solution;
};



class Visitor {
public:
    Visitor();
    ~Visitor();
    virtual void visit(Backtracking * b)
    virtual void printSolution();
    virtual vector* getSolution();
    virtual double getCost();
private:
    Solution * _solution;
    SolutionDisplay * _solutionDis;
};

void Visitor::printSolution(){
    this->_solutionDis = new SolutionDisplay(this->_solution);
    this->_solutionDis->print();
}


class PathFinderVisitor: public Visitor {
public:
        PathFinderVisitor();
        ~PathFinderVisitor();

private:

};

void PathFinderVisitor::visit(Backtracking * backtracking) {

    if(!backtracking->compute())
        this->_solution = backtracking->getSolution();

}

#endif // VISITOR_H_INCLUDED

jueves, 18 de enero de 2018

Southwind : Gof Patterns example of Template method and Strategy patterns

Southwind C++ (codeblocks ide) project for GoF patterns practicing. It takes as example a possible template method from the trader company "Southwind" and the use of 2 different Strategies (Kanban and JustInTime).

Files in project:

main.cpp

:
#include 
#include "templatemethod.h"
#include 

using namespace std;

int main()
{
 const static vector * catalog = {"Tablets offer", "SmartPhones offer", "Javas offer", "Androids offer", "Creatives offer"};
 const static vector  * locations = {"KanbanCity","JustInTimeCity"};

  int status = -1;
  map> * tradingdata;
  Strategy * strategy = NULL;
  Context* context = NULL;
  TraderCompany* southwind = NULL;


  vector * preorder = createPreOrder(catalog);
  string* location = getLocation(locations);

  if(location->compare(locations->at(0))== 0))
   /* we work with Kanban city */
    strategy = new KanbanStrategy();
   else
    strategy = new JustinStrategy();

   context = new Context(strategy);


   southwind = new Southwind(context);
   /* call to the template method */
   status = southwind->trade(preorder);


   tradingdata = southwind->getTraderdata();


   return status;






}



vector* createPreOrder(vector* catalog) {

 vector * selecteds(-1,5);
 vector * preOrder ;

 vector::iterator it = catalog->begin();
 int i = 1;
 int j = 0;
 bool exit = false;

 cout << "Welcome to Southwind company please choose our offers : ";
 cout << endl << endl;
 cout << "Catalog :" << endl;
 while(it!= catalog->end()) {
    cout << "Number: " << i << " " << "Product: " << *it << "  " << endl;
    it++;
    i++;
 }

i = 100;
cout << "Choose your offers : (input correct offer's number (1-" << catalog->size() << ") or 0 number for exit) " << endl;

while(i!= 0 && !exit){
cout << "Offer's number: " << endl;
 cin >> i;

 if(i>0 && i< catalog->size())
    selecteds->push_back( i--);
 else{
    j++;
    cout << " Input number is incorrect (1-6)" << endl;
    i = 100;
   if(j==10){
    cout << "Too many incorrect input, exiting..." << endl;
    exit = true;
   }

 }

 it = selecteds->begin();
 while(it!= selecteds->end()){
    preOrder->push_back( catalog[ *(it++)]);

 }

    return preOrder;
}

string * getLocation( vector* locations) {


 string * loc;

 vector::iterator it = locations->begin();
 int i = 1;
 int j = 0;
 int k = 0;

 cout << "Welcome to Southwind, this are the possible locations:";
 cout << endl << endl;
 cout << "Location :" << endl;
 while(it!= locations->end()) {
    cout << "Number: " << i << " " << "Location : " << *it << "  " << endl;
    it++;
    i++;
 }

i = 100;

cout << "Choose your location : (input correct location's number (1-" << locations->size() << ") or 0 number for exit) " << endl;


while(i!= 0 && k>1){
cout<< "Location's number: " << endl;
 cin >> i;

 if(i>0 && i< locations->size()){
    selecteds->push_back( i--);
    k++;
 }
 else{
    j++;
    cout << " Input number is incorrect (1-" << localtions->size() << ")" << endl;
    i = 100;
   if(j==10){
    cout << "Too many incorrect input, exiting..." << endl;
    exit = true;
   }

 }

}

 it = selecteds->begin();
 while(it!= selecteds->end())
    *loc  =   locations[ *(it++)]);


    return loc;

}








templatemethod.h

: It contains template method implementation and strategy pattern dependency.
#ifndef TEMPLATEMETHOD_H_INCLUDED
#define TEMPLATEMETHOD_H_INCLUDED

#include 
#include 
#include "strategy.h"
#include 
#include 


/**
Southwind trading company

*/

typedef map> TradeData;

class TraderCompany {
public:
    TraderCompany(Context* c);
    ~TraderCompany();
    int trade(vector* preorder);
    virtual int takeOrder();
    virtual int prepareOrder();
    virtual int computePrice();
    virtual int doShipping();
    virtual int doConfirm();
    map>* getTraderdata();
    int doReport();
private:
    Context* _context;
    map>  * _tradedata;
    vector _preorder;
};

TraderCompany::TraderCompany(Context* c){
    this->_context = c;
}
int TraderCompany::trade(vector * preorder) {
    this->_preorder = preorder;
    this->takeOrder();
    this->prepareOrder();
    this->computePrice();
    this->doShipping();

    return this->doConfirm();

}
int TraderCompany::doConfirm() {
    cout << " Operation confirm!!";
    return this->doReport();
}
map>* TraderCompany::getTraderdata() {
    return this->_tradedata;
}

class Southwind: public TraderCompany {
public:
    Southwind(Context * c);
    ~Southwind();
    int trade(vector * preorder);
    virtual int takeOrder();
    virtual int prepareOrder();
    virtual int computePrice();
    virtual int doShipping();
    virtual int doConfirm();
    int doReport();
private:
    Context* _context;
    map>  * _tradedata;
    vector * _preorder;
};


#endif // TEMPLATEMETHOD_H_INCLUDED

strategy.h

: specific strategies to be implemented
#ifndef STRATEGY_H_INCLUDED
#define STRATEGY_H_INCLUDED
#include 
#include 
#include 
#include 

using namespace std;

typedef map> * TradeData;

class Strategy {
public:
 Strategy();
 ~Strategy();
 virtual int create(vector * input);
 virtual int prepare();
 virtual int ship();
 virtual int confirm();
 map> * getData();
private:
    map> * _data;
};


class JustinStrategy: public Strategy {

};

class KanbanStrategy: public Strategy {


};


class Context {
public:
    Context(Strategy * s);
    ~Context();
    virtual int createOrder(vector * input);
    virtual int prepareOrder();
    virtual int ship();
    virtual int confirm();
    map> * getOrder();
private:
    Strategy * _strategy;
    map>* _order;

};



#endif // STRATEGY_H_INCLUDED

Download project from Github

jueves, 4 de enero de 2018

GoF patterns launcher and Chain of Resposibility pattern example (C++)

A C++ (codeblocks ide) project for GoF patterns practicing.It can be extended with the rest of patterns (command, state, factory, mediator, etc...).

Files in project:

main.cpp

:
#include 
#include 
#include "chainofresp.h"
#include "patternexec.h"

using namespace std;

const int CHAIN = 2;

int main()
{
    int sdirective = 2;
    PatternExec* _patterne = 0;
    string name ="CHAIN";
    string conf = "1000";

    switch(sdirective){
    case CHAIN:
        _patterne =  new PatternExec(new ChainOfResp(name,conf));
    break;
    default:
        return -100;

    }

   int r =   _patterne->execute();

   if(!r)
    cout << "Program ended correctly" << endl;

    return r;
}

patternexec.h

: It contains pattern's launcher (command) and specific pattern (in this case ChainOfResp) runner.
#ifndef PATTERNEXEC_H_INCLUDED
#define PATTERNEXEC_H_INCLUDED

#include 
#include 
#include 

using namespace std;

class Pattern {
public:
Pattern();
Pattern(string name, string conf);
virtual int run();
private:
    string _name;
    string _conf;
};
Pattern::Pattern() {}
Pattern::Pattern(string name, string conf) {
     _name = name; _conf= conf;
}
int Pattern::run() {
cout<< "Running an empty pattern " << endl;
return 10;
}
class PatternExec {

public:
PatternExec();
PatternExec(Pattern* pattern);
virtual int execute();
private:
    Pattern* _pattern;
};
PatternExec::PatternExec(Pattern* p){ _pattern = p;}
int PatternExec::execute() {
    return this->_pattern->run();
}


class ChainOfResp: public Pattern {
public:
ChainOfResp();
ChainOfResp(string name, string conf);
virtual int run();
void setConf(string conf);
private:
    string _staticName = "CHAIN";
    int _deep;
};
ChainOfResp::ChainOfResp(){}
ChainOfResp::ChainOfResp(string name, string conf){
   if( _staticName != name) cout<<"Incorrect pattern Name" <setConf(conf);
}
void ChainOfResp::setConf(string conf) {
 if(conf == "1000")
    _deep = 1000;
}
/**
Here is where pattern is applied
The value _deep indicates the TOPIC value which determines which component will process the call
*/
int ChainOfResp::run(){

Widget* aButton;
Widget* aField;
Dialog* aConfirm;
Application* anApp;

anApp = new Application(0, (TOPIC) _deep);
aConfirm = new Dialog(anApp, (TOPIC) _deep);
aField = new Widget(aConfirm, (TOPIC) _deep);
aButton = new Widget(aConfirm, (TOPIC) _deep);
cout << "Launch ChainOfResp from Button" << endl;
aButton->handle();
cout << "Launch CofResp from Field" << endl;
aField->handle();

cout << _staticName << " Pattern ended correctly " << endl;
return 0;
}

#endif // PATTERNEXEC_H_INCLUDED

chainofresp.h

: specific pattern implementation
#ifndef CHAINOFRESP_H_INCLUDED
#define CHAINOFRESP_H_INCLUDED

#include 
#include 

using namespace std;

typedef  int TOPIC;
const TOPIC NO_VALUE = -1;

class Handler {
public:
Handler();
Handler(Handler* sucessor,TOPIC topic);
 virtual int handle();

 virtual int doProcess();

private:
    Handler* _sucessor;
    TOPIC _topic;
    const static TOPIC _myTopic = 0;
};
Handler::Handler(){}
Handler::Handler(Handler* sucessor, TOPIC topic){
_sucessor=sucessor;
_topic = topic;
}

int Handler::handle() {
    cout<< "Handling from Handler class" << endl;

   if(_topic == _myTopic){
        _sucessor->handle();
   }else doProcess();

}
int Handler::doProcess() {
    cout<< "Processing!!! from Handler class " << endl;
}

class Widget: public Handler {
public:
Widget();
Widget(Handler* widget, TOPIC topic);
virtual int handle();
virtual int doProcess();
private:
    Handler* _parent;
    TOPIC _topic;
   const static TOPIC _myTopic = 1;
};
Widget::Widget(){}
Widget::Widget(Handler* w, TOPIC topic) {
    _parent = w;
    _topic = topic;
}
int Widget::handle(){
cout << "Hadling from Widget class " << endl;
 if(_topic == _myTopic){
    _parent->handle();
 }else doProcess();

}

int Widget::doProcess() {
cout << "Processing from Widget class " << endl;
Handler::doProcess();
}

class Dialog:public Handler{
public:
    Dialog();
    Dialog(Handler* h, TOPIC t);
    virtual int handle();
    virtual int doProcess();
private:
    Handler* _handler;
    TOPIC _topic;
    const static TOPIC _myTopic = 2;
};
Dialog::Dialog(){}
Dialog::Dialog(Handler* h, TOPIC t):Handler(h,t) {

}

class Application:public Handler {
public:
    Application();
    Application(Handler* h, TOPIC t);
    int handle();
    int doProcess();
private:
    const Application* _app = this;
    const static TOPIC _myTopic = 1000;

};
Application::Application(){}
Application::Application(Handler* h, TOPIC t):Handler(h,t){}


#endif // CHAINOFRESP_H_INCLUDED

Download project from Github