<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
};

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
        UNKNOWN,
        GRAVEYARD,
        GRAVEYARD_GATES,
        KHATHARRS_MOMS_HOUSE,
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
	}
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<
/*
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
*/

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        auto& cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
        if(direction=="north"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction=="south"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction=="east"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false
        ;if(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction=="north")map.y++;if(direction=="south")map.y--;if(direction=="east")map.x++;if(direction=="west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
};

struct Room {
	string description;
	vector<Entity> entities; vector<RoomObject> objects; unordered_map<string, RoomID> exits; };

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<commit_msg>Not as fast as your mom's plot in this text adventure<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
};

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
        UNKNOWN,
        GRAVEYARD,
        GRAVEYARD_GATES,
        KHATHARRS_MOMS_HOUSE,
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
	}
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
*/

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        auto& cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
        if(direction=="north"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction=="south"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction=="east"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false
        ;if(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction=="north")map.y++;if(direction=="south")map.y--;if(direction=="east")map.x++;if(direction=="west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
};

struct Room {
	string description;
	vector<Entity> entities; vector<RoomObject> objects; unordered_map<string, RoomID> exits; };

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

bool sortHighLow(int i, int j) {
	return j < i;
};

int main(int argc, char** argv) {
	std::vector<int> tradingValues;
	std::vector<int> currentItems;
	int startingValue;
	int currentValue = startingValue;
	int numTrades = 0;
	bool turnTime = true;
	//temporary values
	startingValue = 120;
	tradingValues.push_back(15);
	tradingValues.push_back(8);
	tradingValues.push_back(5);
	tradingValues.push_back(62);
	tradingValues.push_back(1);

	std::sort(tradingValues.begin(), tradingValues.end(), sortHighLow);
	while(currentItems.empty()) {
		std::cout << "test1" << std::endl;
		currentValue = *currentItems.begin();
		std::cout << "test2" << std::endl;
		currentItems.erase(currentItems.begin());
		std::vector<int>::iterator itr = tradingValues.begin();
		while(itr != tradingValues.end()) {
			if(*itr < currentValue){
				std::cout << "test";
				++numTrades;
				currentValue -= *itr;
				if(*itr != 1)
					currentItems.push_back(*itr);
			}
			else
				++itr;
		}
	}
	std::cout << numTrades;
}<commit_msg>More updates<commit_after>#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <string>

bool sortHighLow(int i, int j) {
	return j < i;
};

int main(int argc, char** argv) {
	std::vector<int> tradingValues;
	std::vector<int> currentItems;
	int startingValue;
	int currentValue;
	int numTrades = 0;
	bool turnTime = true;
	//temporary values
	startingValue = 10;
	tradingValues.push_back(15);
	tradingValues.push_back(10);
	tradingValues.push_back(3);
	tradingValues.push_back(1);

	currentItems.push_back(startingValue);
	while(!currentItems.empty()) {
		currentValue = currentItems[0];
		currentItems.erase(currentItems.begin());
		for(std::vector<int>::iterator itr = tradingValues.begin(); itr != tradingValues.end();) {
			while(currentValue > *itr){
				currentValue -= *itr;
				if(*itr != 1)
					currentItems.push_back(*itr);
				++numTrades;
				std::cout << "currentValue = " << currentValue << " *itr = " << *itr << " numTrades = " << numTrades << std::endl;
				std::string dummy;
				std::getline(std::cin, dummy);
			}
			++itr;
			std::cout << "The currentItems list is: ";
			for(std::vector<int>::iterator mtr = currentItems.begin(); mtr != currentItems.end(); ++mtr) {
				std::cout << *mtr << " ";
			}
			std::cout << std::endl;
			std::string dummy;
			std::getline(std::cin, dummy);
		}
	}

//	currentItems.push_back(startingValue);
//	std::sort(tradingValues.begin(), tradingValues.end(), sortHighLow);
//	while(!currentItems.empty()) {
//		currentValue = currentItems[0];
//		currentItems.erase(currentItems.begin());
//		for(std::vector<int>::iterator itr = tradingValues.begin(); itr != tradingValues.end();) {
//			std::cout << "The current value of the iterator is " << *itr << std::endl;
//			std::cout << "The current value of currentValue is " << currentValue << std::endl;
//			if(*itr < currentValue){
//				++numTrades;
//				currentValue -= *itr;
//				if(*itr != 1)
//					currentItems.push_back(*itr);
//			}
//			else
//				++itr;
//		}
//	}
	std::cout << numTrades;
}<|endoftext|>


<commit_before>#include "matrix.h"
#include "parser.h"
#include "finite.h"
#include <iostream>
#include <map>
#include <sstream>
#include <cstdlib>

using namespace std;

void die(const string &s)
{
    cout << s << endl;
    exit(1);
}

string safeGetline()
{
    string s;
    while (s.empty())
    {
        getline(cin, s);
        while (s.size() && isspace(s.back()))
            s.pop_back();
    }
    return s;
}

template<class NumMatrix>
NumMatrix getMatrix(string prompt)
{
    string s, sum;
    cout << prompt << endl;
    s = safeGetline();
    unsigned width = 0, height = 0;
    while (s.length())
    {
        istringstream is;
        is.str(s);
        unsigned cwidth = 0;
        Rational dummy;
        while (is >> dummy)
            ++cwidth;
        if (!cwidth)
            break;
        if (width && width != cwidth)
            die("Incorrect matrix");
        width = cwidth;
        ++height;
        sum += s + ' ';
        getline(cin, s);
    }
    NumMatrix m(height, width);
    istringstream is;
    is.str(sum);
    is >> m;
    return m;
}

template<class NumMatrix>
NumMatrix f_solve(const vector<NumMatrix*> &a)
{
    unsigned sz = a[0]->height();
    if (!sz || a[0]->width() != sz + 1)
        die("Invalid use of solve: N*N+1 matrix required");
    NumMatrix sys = a[0]->submatrix(0, 0, sz - 1, sz - 1);
    NumMatrix right = a[0]->submatrix(0, sz, sz - 1, sz);
    sys.inverseExt(right);
    return right.transposed();

}

template<class NumMatrix>
void processOp(string op, vector<NumMatrix> &st, map<string, pair<int, NumMatrix (*)(const vector<NumMatrix*>&)> > &operations)
{
    if (operations[op].first == 1)
    {
        st.back() = operations[op].second({&st.back()});
    }
    else if (operations[op].first == 2)
    {
        NumMatrix a = st.back();
        st.pop_back();
        st.back() = operations[op].second({&st.back(), &a});
    }
    else
    {
        NumMatrix a = st.back();
        st.pop_back();
        NumMatrix b = st.back();
        st.pop_back();
        st.back() = operations[op].second({&st.back(), &b, &a});
    }
}

template<class Field>
void f_expr()
{

    typedef Matrix<Field> NumMatrix;
    map<string, pair<int, NumMatrix (*)(const vector<NumMatrix*>&)> > operations =
            {
                    {"+",      {2, [](const vector<NumMatrix*>& a) { return *a[0] + *a[1]; }}},
                    {"^",      {2, [](const vector<NumMatrix*>& a) {
                        if (a[1]->width() != 1 || a[1]->height() != 1 || (*a[1])[0][0] != int((*a[1])[0][0]))
                            die("Invalid use of ^: integer required");
                        return a[0]->power(int((*a[1])[0][0]));
                    }}},
                    {"*",      {2, [](const vector<NumMatrix*>& a) {
                        if (a[0]->height() == 1 && a[0]->width() == 1)
                            return *a[1] * (*a[0])[0][0];
                        else if (a[1]->height() == 1 && a[1]->width() == 1)
                            return *a[0] * (*a[1])[0][0];
                        else
                            return *a[0] * *a[1];
                    }}},
                    {"/",      {2, [](const vector<NumMatrix*>& a) {
                        if (a[0]->height() == 1 && a[0]->width() == 1)
                            return a[1]->inverted() * (*a[0])[0][0];
                        else if (a[1]->height() == 1 && a[1]->width() == 1)
                            return *a[0] * a[1]->inverted()[0][0];
                        else
                            return *a[0] * a[1]->inverted();
                    }}},
                    {"-",      {2, [](const vector<NumMatrix*>& a) { return *a[0] - *a[1]; }}},
                    {"_",      {1, [](const vector<NumMatrix*>& a) { return -*a[0]; }}},
                    {"det",    {1, [](const vector<NumMatrix*>& a) { return NumMatrix::fromNumber(a[0]->det()); }}},
                    {"rank",   {1, [](const vector<NumMatrix*>& a) { return NumMatrix::fromNumber(a[0]->rank()); }}},
                    {"trace",  {1, [](const vector<NumMatrix*>& a) { return NumMatrix::fromNumber(a[0]->trace()); }}},
                    {"t",      {1, [](const vector<NumMatrix*>& a) { return a[0]->transposed(); }}},
                    {"inv",    {1, [](const vector<NumMatrix*>& a) { return a[0]->inverted(); }}},
                    {"id",     {1, [](const vector<NumMatrix*>& a) {
                        if (a[0]->width() != 1 || a[0]->height() != 1)
                            die("Invalid use of id");
                        return NumMatrix::identity(abs(int((*a[0])[0][0])));
                    }}},
                    {"=",      {2, [](const vector<NumMatrix*> &a) { return NumMatrix::fromNumber(*a[0] == *a[1]); }}},
                    {"width",  {1, [](const vector<NumMatrix*> &a) { return NumMatrix::fromNumber(a[0]->width()); }}},
                    {"height", {1, [](const vector<NumMatrix*> &a) { return NumMatrix::fromNumber(a[0]->height()); }}},
                    {"solve",  {1, f_solve}},
                    {"at",     {3, [](const vector<NumMatrix*> &a) {
                        if (a[1]->width() != 1 || a[1]->height() != 1 || a[2]->width() != 1 || a[2]->height() != 1)
                            die("Invalid use of at");
                        if (int((*a[1])[0][0]) != (*a[1])[0][0] || int((*a[2])[0][0]) != (*a[2])[0][0])
                            die("at: indices must be integers");
                        if (int((*a[1])[0][0]) < 0 || int((*a[1])[0][0]) >= int(a[0]->height()) ||
                            int((*a[2])[0][0]) < 0 || int((*a[2])[0][0]) >= int(a[0]->width()))
                            die("at: out of range");
                        return NumMatrix::fromNumber((*a[0])[int((*a[1])[0][0])][int((*a[2])[0][0])]);
                    }}}
            };
    cout << "Expression: ";
    string s = safeGetline();
    auto v = splitExpression(s);
    map<char, NumMatrix> mmap;
    vector<pair<token_type, string> > opst;
    vector<NumMatrix> st;
    int st_size = 0;
    for (pair<token_type, string> &i : v)
    {
        switch (i.first)
        {
            case TOKEN_NUMBER:
            case TOKEN_MATRIX:
                ++st_size;
                break;
            case TOKEN_OP:
                while (opst.size() && opst.back().first == TOKEN_OP &&
                       priority[int(i.second[0])] + rightassoc[int(i.second[0])] <=
                       priority[int(opst.back().second[0])])
                {
                    st_size -= operations[opst.back().second].first - 1;
                    opst.pop_back();
                }
                if (st_size <= 0)
                    die("Invalid expression");
            case TOKEN_FUNC:
                if (!operations.count(i.second))
                    die("Invalid function: " + i.second);
            case TOKEN_LEFTPAR:
                opst.push_back(i);
                break;
            case TOKEN_RIGHTPAR:
                while (opst.size() && opst.back().first != TOKEN_LEFTPAR)
                {
                    st_size -= operations[opst.back().second].first - 1;
                    opst.pop_back();
                }
                if (opst.empty() || st_size <= 0)
                    die("Invalid expression");
                opst.pop_back();
                if (opst.size() && opst.back().first == TOKEN_FUNC)
                {
                    st_size -= operations[opst.back().second].first - 1;
                    opst.pop_back();
                }
                break;
            case TOKEN_COMMA:
                while (opst.size() && opst.back().first != TOKEN_LEFTPAR)
                {
                    st_size -= operations[opst.back().second].first - 1;
                    opst.pop_back();
                }
                if (opst.empty() || st_size <= 0)
                    die("Invalid expression");
                break;
        }
    }
    while (opst.size())
    {
        if (opst.back().first == TOKEN_LEFTPAR || opst.back().first == TOKEN_RIGHTPAR)
            die("Invalid expression");
        st_size -= operations[opst.back().second].first - 1;
        opst.pop_back();
    }
    if (st_size != 1)
        die("Invalid expression");
    for (pair<token_type, string> &i : v)
    {
        NumMatrix tt(1, 1);
        istringstream is;
        switch (i.first)
        {
            case TOKEN_NUMBER:
                is.str(i.second);
                is >> tt[0][0];
                st.push_back(tt);
                break;
            case TOKEN_MATRIX:
                if (!mmap.count(i.second[0]))
                    mmap[i.second[0]] = getMatrix<NumMatrix>(string("Matrix ") + i.second + ':');
                st.push_back(mmap[i.second[0]]);
                break;
            case TOKEN_OP:
                while (opst.size() && opst.back().first == TOKEN_OP &&
                       priority[int(i.second[0])] + rightassoc[int(i.second[0])] <=
                       priority[int(opst.back().second[0])])
                {
                    processOp(opst.back().second, st, operations);
                    opst.pop_back();
                }
            case TOKEN_FUNC:
            case TOKEN_LEFTPAR:
                opst.push_back(i);
                break;
            case TOKEN_RIGHTPAR:
                while (opst.size() && opst.back().first != TOKEN_LEFTPAR)
                {
                    processOp(opst.back().second, st, operations);
                    opst.pop_back();
                }
                opst.pop_back();
                if (opst.size() && opst.back().first == TOKEN_FUNC)
                {
                    processOp(opst.back().second, st, operations);
                    opst.pop_back();
                }
                break;
            case TOKEN_COMMA:
                while (opst.size() && opst.back().first != TOKEN_LEFTPAR)
                {
                    processOp(opst.back().second, st, operations);
                    opst.pop_back();
                }
                break;
        }
    }
    while (opst.size())
    {
        processOp(opst.back().second, st, operations);
        opst.pop_back();
    }
    cout << "Result:\n" << st[0];
}

int main(int argc, char **argv)
{
    try
    {
        if (argc == 1)
        {
            f_expr<Rational>();
        }
        else
        {
            _FINITE_ORDER = atoi(argv[1]);
            if(_FINITE_ORDER < 2)
                die("Order must be at least 2");
            f_expr<Finite>();
        }
    }
    catch (matrix_error e)
    {
        cout << "Matrix error: " << e.what() << endl;
        return 1;
    }
    return 0;
}
<commit_msg>Типизация<commit_after>#include "matrix.h"
#include "parser.h"
#include "finite.h"
#include <iostream>
#include <map>
#include <sstream>
#include <cstdlib>

using namespace std;

void die(const string &s)
{
    cout << s << endl;
    exit(1);
}

string safeGetline()
{
    string s;
    while (s.empty())
    {
        getline(cin, s);
        while (s.size() && isspace(s.back()))
            s.pop_back();
    }
    return s;
}

template<class FMatrix>
FMatrix getMatrix(string prompt)
{
    string s, sum;
    cout << prompt << endl;
    s = safeGetline();
    unsigned width = 0, height = 0;
    while (s.length())
    {
        istringstream is;
        is.str(s);
        unsigned cwidth = 0;
        Rational dummy;
        while (is >> dummy)
            ++cwidth;
        if (!cwidth)
            break;
        if (width && width != cwidth)
            die("Incorrect matrix");
        width = cwidth;
        ++height;
        sum += s + ' ';
        getline(cin, s);
    }
    FMatrix m(height, width);
    istringstream is;
    is.str(sum);
    is >> m;
    return m;
}

template<class NumMatrix>
void processOp(string op, vector<NumMatrix> &st,
               map<string, pair<int, NumMatrix (*)(const vector<NumMatrix *> &)> > &operations)
{
    if (operations[op].first == 1)
    {
        st.back() = operations[op].second({&st.back()});
    }
    else if (operations[op].first == 2)
    {
        NumMatrix a = st.back();
        st.pop_back();
        st.back() = operations[op].second({&st.back(), &a});
    }
    else
    {
        NumMatrix a = st.back();
        st.pop_back();
        NumMatrix b = st.back();
        st.pop_back();
        st.back() = operations[op].second({&st.back(), &b, &a});
    }
}

template<class Field>
struct _NumMatrix
{
    union
    {
        int im;
        Matrix<Field> fm;
    };
    bool is_int;

    _NumMatrix(): im(0), is_int(true) {}

    _NumMatrix(const _NumMatrix &a): is_int(a.is_int)
    {
        if (is_int)
            im = a.im;
        else
        {
            new(&fm) Matrix<Field>();
            fm = a.fm;
        }
    }

    _NumMatrix(int a): im(a), is_int(true) {}

    _NumMatrix(const Matrix<Field> &a): fm(a), is_int(false) {}

    _NumMatrix(const Field &a): fm(Matrix<Field>::fromNumber(a)), is_int(false) {}

    _NumMatrix &operator=(const _NumMatrix &a)
    {
        if(this == &a)
            return *this;
        if(!is_int && a.is_int)
            fm.~Matrix();
        is_int = a.is_int;
        if(is_int)
            im = a.im;
        else
            fm = a.fm;
        return *this;
    }

    Matrix<Field> toMatrix() const
    {
        if (is_int)
            return Matrix<Field>::fromNumber(Field(im));
        else
            return fm;
    }

    ~_NumMatrix()
    {
        if (!is_int)
            fm.~Matrix();
    }

    _NumMatrix operator*(const _NumMatrix &m) const
    {
        if (is_int && m.is_int)
            return im * m.im;
        if (is_int)
            return m.fm * Field(im);
        if (m.is_int)
            return fm * Field(m.im);
        if (fm.width() == 1 && fm.height() == 1)
            return m.fm * fm[0][0];
        if (m.fm.width() == 1 && m.fm.height() == 1)
            return fm * m.fm[0][0];
        return fm * m.fm;
    }

    _NumMatrix operator/(const _NumMatrix &m) const
    {
        return operator*(m.toMatrix().inverted());
    }

    _NumMatrix operator+(const _NumMatrix &m) const
    {
        if (is_int && m.is_int)
            return im + m.im;
        return toMatrix() + m.toMatrix();
    }

    _NumMatrix operator-() const
    {
        if (is_int)
            return -im;
        else
            return -fm;
    }

};

template<class Field>
void f_expr()
{
    typedef _NumMatrix<Field> NumMatrix;
    map<string, pair<int, NumMatrix (*)(const vector<NumMatrix *> &)> > operations =
            {
                    {"+",      {2, [](const vector<NumMatrix *> &a) { return *a[0] + *a[1]; }}},
                    {"^",      {2, [](const vector<NumMatrix *> &a) {
                        if (!a[1]->is_int)
                            die("Invalid use of ^: integer required");
                        return NumMatrix(a[0]->toMatrix().power(a[1]->im));
                    }}},
                    {"*",      {2, [](const vector<NumMatrix *> &a) {
                        return *a[0] * *a[1];
                    }}},
                    {"/",      {2, [](const vector<NumMatrix *> &a) {
                        return *a[0] / *a[1];
                    }}},
                    {"-",      {2, [](const vector<NumMatrix *> &a) { return *a[0] + -*a[1]; }}},
                    {"_",      {1, [](const vector<NumMatrix *> &a) { return -*a[0]; }}},
                    {"det",    {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().det()); }}},
                    {"rank",   {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().rank()); }}},
                    {"trace",  {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().trace()); }}},
                    {"t",      {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().transposed()); }}},
                    {"inv",    {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().inverted()); }}},
                    {"id",     {1, [](const vector<NumMatrix *> &a) {
                        if (!a[1]->is_int)
                            die("Invalid use of id");
                        return NumMatrix(Matrix<Field>::identity(abs(a[0]->im)));
                    }}},
                    {"=",      {2, [](const vector<NumMatrix *> &a) {
                        return NumMatrix(a[0]->toMatrix() == a[1]->toMatrix());
                    }}},
                    {"width",  {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().width()); }}},
                    {"height", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().height()); }}},
                    {"solve",  {1, [](const vector<NumMatrix *> &a) {
                        unsigned sz = a[0]->toMatrix().height();
                        if (!sz || a[0]->toMatrix().width() != sz + 1)
                            die("Invalid use of solve: N*N+1 matrix required");
                        Matrix<Field> sys = a[0]->toMatrix().submatrix(0, 0, sz - 1, sz - 1);
                        Matrix<Field> right = a[0]->toMatrix().submatrix(0, sz, sz - 1, sz);
                        sys.inverseExt(right);
                        return NumMatrix(right.transposed());
                    }}},
                    {"at",     {3, [](const vector<NumMatrix *> &a) {
                        if (!a[1]->is_int || !a[2]->is_int)
                            die("Invalid use of at");
                        if (a[1]->im < 0 || a[1]->im >= int(a[0]->toMatrix().height()) ||
                            a[2]->im < 0 || a[2]->im >= int(a[0]->toMatrix().width()))
                            die("at: out of range");
                        return NumMatrix(a[0]->toMatrix()[a[1]->im][a[2]->im]);
                    }}}
            };
    cout << "Expression: ";
    string s = safeGetline();
    auto v = splitExpression(s);
    map<char, NumMatrix> mmap;
    vector<pair<token_type, string> > opst;
    vector<NumMatrix> st;
    int st_size = 0;
    for (pair<token_type, string> &i : v)
    {
        switch (i.first)
        {
            case TOKEN_NUMBER:
            case TOKEN_MATRIX:
                ++st_size;
                break;
            case TOKEN_OP:
                while (opst.size() && opst.back().first == TOKEN_OP &&
                       priority[int(i.second[0])] + rightassoc[int(i.second[0])] <=
                       priority[int(opst.back().second[0])])
                {
                    st_size -= operations[opst.back().second].first - 1;
                    opst.pop_back();
                }
                if (st_size <= 0)
                    die("Invalid expression");
            case TOKEN_FUNC:
                if (!operations.count(i.second))
                    die("Invalid function: " + i.second);
            case TOKEN_LEFTPAR:
                opst.push_back(i);
                break;
            case TOKEN_RIGHTPAR:
                while (opst.size() && opst.back().first != TOKEN_LEFTPAR)
                {
                    st_size -= operations[opst.back().second].first - 1;
                    opst.pop_back();
                }
                if (opst.empty() || st_size <= 0)
                    die("Invalid expression");
                opst.pop_back();
                if (opst.size() && opst.back().first == TOKEN_FUNC)
                {
                    st_size -= operations[opst.back().second].first - 1;
                    opst.pop_back();
                }
                break;
            case TOKEN_COMMA:
                while (opst.size() && opst.back().first != TOKEN_LEFTPAR)
                {
                    st_size -= operations[opst.back().second].first - 1;
                    opst.pop_back();
                }
                if (opst.empty() || st_size <= 0)
                    die("Invalid expression");
                break;
        }
    }
    while (opst.size())
    {
        if (opst.back().first == TOKEN_LEFTPAR || opst.back().first == TOKEN_RIGHTPAR)
            die("Invalid expression");
        st_size -= operations[opst.back().second].first - 1;
        opst.pop_back();
    }
    if (st_size != 1)
        die("Invalid expression");
    for (pair<token_type, string> &i : v)
    {
        Rational tt;
        istringstream is, iis;
        switch (i.first)
        {
            case TOKEN_NUMBER:
                is.str(i.second);
                is >> tt;
                if(tt == int(tt))
                    st.push_back(NumMatrix(int(tt)));
                else
                {
                    Field tf;
                    iis.str(i.second);
                    iis >> tf;
                    st.push_back(NumMatrix(tf));
                }
                break;
            case TOKEN_MATRIX:
                if (!mmap.count(i.second[0]))
                    mmap[i.second[0]] = getMatrix<Matrix<Field>>(string("Matrix ") + i.second + ':');
                st.push_back(mmap[i.second[0]]);
                break;
            case TOKEN_OP:
                while (opst.size() && opst.back().first == TOKEN_OP &&
                       priority[int(i.second[0])] + rightassoc[int(i.second[0])] <=
                       priority[int(opst.back().second[0])])
                {
                    processOp(opst.back().second, st, operations);
                    opst.pop_back();
                }
            case TOKEN_FUNC:
            case TOKEN_LEFTPAR:
                opst.push_back(i);
                break;
            case TOKEN_RIGHTPAR:
                while (opst.size() && opst.back().first != TOKEN_LEFTPAR)
                {
                    processOp(opst.back().second, st, operations);
                    opst.pop_back();
                }
                opst.pop_back();
                if (opst.size() && opst.back().first == TOKEN_FUNC)
                {
                    processOp(opst.back().second, st, operations);
                    opst.pop_back();
                }
                break;
            case TOKEN_COMMA:
                while (opst.size() && opst.back().first != TOKEN_LEFTPAR)
                {
                    processOp(opst.back().second, st, operations);
                    opst.pop_back();
                }
                break;
        }
    }
    while (opst.size())
    {
        processOp(opst.back().second, st, operations);
        opst.pop_back();
    }
    cout << "Result:\n" << st[0].toMatrix();
}

int main(int argc, char **argv)
{
    try
    {
        if (argc == 1)
        {
            f_expr<Rational>();
        }
        else
        {
            _FINITE_ORDER = atoi(argv[1]);
            if (_FINITE_ORDER < 2)
                die("Order must be at least 2");
            f_expr<Finite>();
        }
    }
    catch (matrix_error e)
    {
        cout << "Matrix error: " << e.what() << endl;
        return 1;
    }
    return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** The MIT License (MIT)
**
** Copyright (c) 2016 The University of Sheffield (www.sheffield.ac.uk)
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE
**
****************************************************************************/
#include <misc/CODeMMisc.h>
#include <misc/examples/CODeMProblems.h>
#include <core/CODeMGlobal.h>

#include <random>
#include <ctime>
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;
using namespace CODeM;

inline void defineSeed(int seed) {std::srand(seed);}
inline void randomSeed() {std::srand((unsigned)std::time(0));}

void dispVector(vector<double> vec, string sep=", ", string endVec="; ")
{
    for(auto i = vec.begin(); i != (vec.end() -1); ++i) {
        cout << *i << sep;
    }
    cout << vec.back() << endVec;
}

void showUsage(progName) {

    printf("\n"
           "Usage: %s [OPTION(S)]\n\n", progName);

    printf(
"This program evaluates a set of candidate solutions for an uncertain           \n"
" multiobjective optimization problem using the CODeM toolkit. The output of the\n"
" program is a set of decision vectors and a set of objective vectors for each  \n"
" decision vector. The objective vectors for every solution represent different \n"
" samples from the random variate.                                              \n\n"

"Options:                                                                       \n"
" -h, --help                Print this summary and exit.                        \n"
" -v, --version             Print version number and exit.                      \n"
" -f, --file    = FILENAME  An input file with all the configuration options.   \n"
"                           If FILENAME is not specified, the options are       \n"
"                           configured from the command. FILENAME may include a \n"
"                           relative or absolute path.                          \n"
" -o, --output  = FILENAME  A file to write the outputs. If FILENAME is not     \n"
"                           specified, the output is printed to the console.    \n"
" -p, --problem = NUMBER    A chioce of benchmark problem from the CODeM suite. \n"
"                           Use NUMBER = 0 for the problem in the GECCO'16      \n"
"                           paper. Use NUMBER = 1,...,6 for CODeM1,...,CODeM6.  \n"
" -x, --solSet  = SET       A set of decision vectors to evaluate. SET needs to \n"
"                           be provided within double qoutes, where each vector \n"
"                           is separated with a semicolon, and the elements     \n"
"                           within a vector separated with a space. e.g., a set \n"
"                           of three vectors with two variables each:           \n"
"                           SET = \"1.1 1.2; 2.1 2.2; 3.0 4.0\"                 \n"
"                           If SET is not specified two defalut sets are        \n"
"                           generated: one with solutions that are optimal for  \n"
"                           the deterministic problem, and one with random      \n"
"                           vectors. Their sizes are specified with the -s and  \n"
"                           -n options.                                         \n"
" -m, --nObj    = NUMBER    The dimensionality of the objective space. If NUMBER\n"
"                           is not specified, the default is 2 objectives.      \n"
" -d, --nVars   = NUMBER    The dimensionality of the decision space. If NUMBER \n"
"                           is not specified, the default is nObj + 10.         \n"
" -s, --nSols   = NUMBER    The number of decision vectors to evaluate. Two     \n"
"                           sets of size NUMBER are generated: one with         \n"
"                           solutions that are optimal for the deterministic    \n"
"                           problem, and one with random vectors. If NUMBER is  \n"
"                           not specified, the default value is NUMBER = 10.    \n"
" -n, --nSamps  = NUMBER    The number of function evaluations for each decision\n"
"                           vector. if NUMER is not specified, the default value\n"
"                           is NUMBER = 5."
"\n");

}

//int main(int argc, char* argv[])
//{
//    if (argc < 3) {
//        showUsage(argv[0]);
//        return 1;
//    }
//    std::vector <std::string> sources;
//    std::string destination;
//    for (int i = 1; i < argc; ++i) {
//        std::string arg = argv[i];
//        if ((arg == "-h") || (arg == "--help")) {
//            show_usage(argv[0]);
//            return 0;
//        } else if ((arg == "-d") || (arg == "--destination")) {
//            if (i + 1 < argc) { // Make sure we aren't at the end of argv!
//                destination = argv[i++]; // Increment 'i' so we don't get the argument as the next argv[i].
//            } else { // Uh-oh, there was no argument to the destination option.
//                  std::cerr << "--destination option requires one argument." << std::endl;
//                return 1;
//            }
//        } else {
//            sources.push_back(argv[i]);
//        }
//    }
//    return move(sources, destination);
//}

int main(int argc, char** argv)
{
    for(int i = 0; i < argc; ++i) {
        cout << "Argument " << i << ": " << argv[i] << endl;
    }
    return 0;
}

//int main()
//{
//    defineSeed(0);

//    int nObj = 2;
//    int nVar = 6;
//    int nPareto = 5;
//    int nRand   = 10;
//    int nSamp = 50;

//    vector<vector<double> > paretoDeterministic;
//    vector<vector<double> > randDeterministic;
//    vector<vector<vector<double> > > paretoObj;
//    vector<vector<vector<double> > > randObj;

//    vector<vector<double> > paretoDirVars = simplexLattice(nPareto-1, 2);

//    // Pareto optimal vectors
//    for(int i=0; i<paretoDirVars.size(); i++) {
//        vector<double> iVec(nVar, 0.5);
//        iVec[0] = paretoDirVars[i][0];
//        vector<double> determObjVec = deterministicOVec(7, iVec, nObj);
//        paretoDeterministic.push_back(determObjVec);
//        vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp);
//        paretoObj.push_back(oVecSamps);
//    }

//    // Random vectors
//    for(int i=0; i<nRand; i++) {
//        vector<double> iVec;
//        for(int j=0; j<nVar; j++) {
//            iVec.push_back(randUni());
//        }
//        vector<double> determObjVec = deterministicOVec(7, iVec, nObj);
//        randDeterministic.push_back(determObjVec);
//        vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp);
//        randObj.push_back(oVecSamps);
//    }

//    // Display the results
//    cout << "\n% Optimal vectors:" << endl;
//    for(int v=0; v<paretoObj.size(); v++) {
//        cout << "paretoObj{" << v+1 << "} = [";
//        for(int i=0; i<paretoObj[v].size(); i++) {
//            dispVector(paretoObj[v][i]);
//        }
//        cout << "];" << endl;
//    }

//    cout << "\n% Random vectors:" << endl;
//    for(int v=0; v<randObj.size(); v++) {
//        cout << "randObj{" << v+1 << "} = [";
//        for(int i=0; i<randObj[v].size(); i++) {
//            dispVector(randObj[v][i]);
//        }
//        cout << "];" << endl;
//    }

//    cout << "\n% Optimal deterministic vectors:" << endl;
//    cout << "determOptimal = [";
//    for(int i=0; i<paretoDeterministic.size(); i++) {
//        dispVector(paretoDeterministic[i]);
//    }
//    cout << "];" << endl;

//    cout << "\n% Random deterministic vectors:" << endl;
//    cout << "determRand = [";
//    for(int i=0; i<randDeterministic.size(); i++) {
//        dispVector(randDeterministic[i]);
//    }
//    cout << "];\n" << endl;

//    return 0;
//}
<commit_msg>enabled command line argument input<commit_after>/****************************************************************************
**
** The MIT License (MIT)
**
** Copyright (c) 2016 The University of Sheffield (www.sheffield.ac.uk)
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE
**
****************************************************************************/
#include <misc/CODeMMisc.h>
#include <misc/examples/CODeMProblems.h>
#include <core/CODeMGlobal.h>

#include <random>
#include <ctime>
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;
using namespace CODeM;

inline void defineSeed(int seed) {std::srand(seed);}
inline void randomSeed() {std::srand((unsigned)std::time(0));}

void printVector(vector<double> vec, string sep=", ", string endVec="; ")
{
    for(auto i = vec.begin(); i != (vec.end() -1); ++i) {
        cout << *i << sep;
    }
    cout << vec.back() << endVec;
}

void showUsage(char* progName)
{
    cout << "\nUsage: " << progName << " [OPTION(S)]\n\n";

    cout <<
"This program evaluates a set of candidate solutions for an uncertain           \n"
" multiobjective optimization problem using the CODeM toolkit. The output of the\n"
" program is a set of decision vectors and a set of objective vectors for each  \n"
" decision vector. The objective vectors for every solution represent different \n"
" samples from the random variate.                                              \n\n"

"Options:                                                                       \n"
"--------                                                                       \n"
" -h, --help                Print this summary and exit.                        \n\n"
//" -i, --inFile  = FILENAME  An input file with all the configuration options.   \n"
//"                           If FILENAME is not specified, the options are       \n"
//"                           configured from the command. FILENAME may include a \n"
//"                           relative or absolute path.                          \n\n"
" -f, --file    = FILENAME  A file to write the outputs. If FILENAME is not     \n"
"                           specified, the output is printed to the console.    \n\n"
" -p, --problem = NUMBER    A chioce of benchmark problem from the CODeM suite. \n"
"                           Use NUMBER = 0 for the problem in the GECCO'16      \n"
"                           paper. Use NUMBER = 1,...,6 for CODeM1,...,CODeM6.  \n"
"                           Default is NUMBER = 0.                              \n\n"
//" -x, --solSet  = SET       A set of decision vectors to evaluate. SET needs to \n"
//"                           be provided within double qoutes, where each vector \n"
//"                           is separated with a semicolon, and the elements     \n"
//"                           within a vector separated with a space. e.g., a set \n"
//"                           of three vectors with two variables each:           \n"
//"                           SET = \"1.1 1.2; 2.1 2.2; 3.0 4.0\"                 \n"
//"                           If SET is not specified two defalut sets are        \n"
//"                           generated: one with solutions that are optimal for  \n"
//"                           the deterministic problem, and one with random      \n"
//"                           vectors. Their sizes are specified with the -s and  \n"
//"                           -n options.                                         \n\n"
" -m, --nObj    = NUMBER    The dimensionality of the objective space. If NUMBER\n"
"                           is not specified, the default is 2 objectives.      \n\n"
" -d, --nVars   = NUMBER    The dimensionality of the decision space. If NUMBER \n"
"                           is not specified, the default is 10, or nobj + 1    \n"
"                           when nObj >= 9.                                     \n\n"
" -s, --nSols   = NUMBER    The number of decision vectors to evaluate. Two     \n"
"                           sets of size NUMBER are generated: one with         \n"
"                           solutions that are optimal for the deterministic    \n"
"                           problem, and one with random vectors. If NUMBER is  \n"
"                           not specified, the default value is NUMBER = 10.    \n\n"
" -n, --nSamps  = NUMBER    The number of function evaluations for each decision\n"
"                           vector. if NUMER is not specified, the default value\n"
"                           is NUMBER = 5.                                      \n\n"
" -r, --rndSeed = NUMBER    The seed for the pseudo-random number generator. If \n"
"                           NUMBER is not specified, the default seed is 0. For \n"
"                           a random seed, based on the CPU time, provide a     \n"
"                           negative value for NUMBER.                          \n"
"\n";
}

int main(int argc, char** argv)
{
    if (argc < 2) {
        showUsage(argv[0]);
        return EXIT_FAILURE;
    }

    // set defaults
    int seed   = 0;
    int nObj   = 2;
    int nVars  = 10;
    int nSols  = 10;
    int nSamps = 5;
    int prob   = 0;

    int argInd = 1;
    while(argInd < argc) {
        string arg = argv[argInd++];

        if ((arg == "-h") || (arg == "--help")) {
            showUsage(argv[0]);
            return EXIT_SUCCESS;

        } else if ((arg == "-f") || (arg == "--file")) {
            if (argInd < argc) {
                freopen(argv[argInd++], "w", stdout);
            } else {
                cerr << "--file option requires one argument." << endl;
                return EXIT_FAILURE;
            }

        } else if ((arg == "-p") || (arg == "--problem")) {
            if (argInd < argc) {
                int argI = atoi(argv[argInd++]);
                if((argI >= 0) && (argI <= 6)) {
                    prob = argI;
                } else {
                    cerr << "Invalid argument for --problem option: Requires a "
                            "number between 0-6." << endl;
                    return EXIT_FAILURE;
                }
            } else {
                cerr << "--problem option requires one argument." << endl;
                return EXIT_FAILURE;
            }
            // TODO: accept a set to evaluate
            //        } else if ((arg == "-x") || (arg == "--solSet")) {
            //            if (argInd < argc) {

            //            } else {
            //                cerr << "--solSet option requires one argument." << endl;
            //                return EXIT_FAILURE;
            //            }

        } else if ((arg == "-m") || (arg == "--nObj")) {
            if (argInd < argc) {
                int argI = atoi(argv[argInd++]);
                if(argI >= 2) {
                    nObj = argI;
                } else {
                    cerr << "Invalid argument for --nObj option: Number of "
                            "objectives must be larger than 1." << endl;
                    return EXIT_FAILURE;
                }
            } else {
                cerr << "--nObj option requires one argument." << endl;
                return EXIT_FAILURE;
            }

        } else if ((arg == "-d") || (arg == "--nVars")) {
            if (argInd < argc) {
                int argI = atoi(argv[argInd++]);
                if(argI >= 3) {
                    nVars = argI;
                } else {
                    cerr << "Invalid argument for --nVars option: Number of "
                            "variables must be larger than 2." << endl;
                    return EXIT_FAILURE;
                }
            } else {
                cerr << "--nVars option requires one argument." << endl;
                return EXIT_FAILURE;
            }

        } else if ((arg == "-s") || (arg == "--nSols")) {
            if (argInd < argc) {
                int argI = atoi(argv[argInd++]);
                if(argI >= 0) {
                    nSols = argI;
                } else {
                    cerr << "Invalid argument for --nSols option: Number of "
                            "solutions must be larger than 0." << endl;
                    return EXIT_FAILURE;
                }
            } else {
                cerr << "--nSols option requires one argument." << endl;
                return EXIT_FAILURE;
            }

        } else if ((arg == "-n") || (arg == "--nSamps")) {
            if (argInd < argc) {
                int argI = atoi(argv[argInd++]);
                if(argI >= 0) {
                    nSamps = argI;
                } else {
                    cerr << "Invalid argument for --nSamps option: Number of "
                            "solutions must be larger than 0." << endl;
                    return EXIT_FAILURE;
                }
            } else {
                cerr << "--nSamps option requires one argument." << endl;
                return EXIT_FAILURE;
            }

        } else if ((arg == "-r") || (arg == "--rndSeed")) {
            if (argInd < argc) {
                seed = atoi(argv[argInd++]);
            } else {
                cerr << "--rndSeed option requires one argument." << endl;
                return EXIT_FAILURE;
            }
        } else {
            cerr << "Unknown argument " << arg << endl;
            return EXIT_FAILURE;
        }
    }

    if(seed < 0) {
        randomSeed();
    } else {
        defineSeed(seed);
    }

    cout << "seed   = " << seed   << endl;
    cout << "nObj   = " << nObj   << endl;
    cout << "nVars  = " << nVars  << endl;
    cout << "nSols  = " << nSols  << endl;
    cout << "nSamps = " << nSamps << endl;
    cout << "prob   = " << prob   << endl;
}

//int main()
//{
//    defineSeed(0);

//    int nObj = 2;
//    int nVar = 6;
//    int nPareto = 5;
//    int nRand   = 10;
//    int nSamp = 50;

//    vector<vector<double> > paretoDeterministic;
//    vector<vector<double> > randDeterministic;
//    vector<vector<vector<double> > > paretoObj;
//    vector<vector<vector<double> > > randObj;

//    vector<vector<double> > paretoDirVars = simplexLattice(nPareto-1, 2);

//    // Pareto optimal vectors
//    for(int i=0; i<paretoDirVars.size(); i++) {
//        vector<double> iVec(nVar, 0.5);
//        iVec[0] = paretoDirVars[i][0];
//        vector<double> determObjVec = deterministicOVec(7, iVec, nObj);
//        paretoDeterministic.push_back(determObjVec);
//        vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp);
//        paretoObj.push_back(oVecSamps);
//    }

//    // Random vectors
//    for(int i=0; i<nRand; i++) {
//        vector<double> iVec;
//        for(int j=0; j<nVar; j++) {
//            iVec.push_back(randUni());
//        }
//        vector<double> determObjVec = deterministicOVec(7, iVec, nObj);
//        randDeterministic.push_back(determObjVec);
//        vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp);
//        randObj.push_back(oVecSamps);
//    }

//    // Display the results
//    cout << "\n% Optimal vectors:" << endl;
//    for(int v=0; v<paretoObj.size(); v++) {
//        cout << "paretoObj{" << v+1 << "} = [";
//        for(int i=0; i<paretoObj[v].size(); i++) {
//            printVector(paretoObj[v][i]);
//        }
//        cout << "];" << endl;
//    }

//    cout << "\n% Random vectors:" << endl;
//    for(int v=0; v<randObj.size(); v++) {
//        cout << "randObj{" << v+1 << "} = [";
//        for(int i=0; i<randObj[v].size(); i++) {
//            printVector(randObj[v][i]);
//        }
//        cout << "];" << endl;
//    }

//    cout << "\n% Optimal deterministic vectors:" << endl;
//    cout << "determOptimal = [";
//    for(int i=0; i<paretoDeterministic.size(); i++) {
//        printVector(paretoDeterministic[i]);
//    }
//    cout << "];" << endl;

//    cout << "\n% Random deterministic vectors:" << endl;
//    cout << "determRand = [";
//    for(int i=0; i<randDeterministic.size(); i++) {
//        printVector(randDeterministic[i]);
//    }
//    cout << "];\n" << endl;

//    return 0;
//}

//int main(int argc, char** argv)
//{
//    for(int i = 0; i < argc; ++i) {
//        cout << "Argument " << i << ": " << argv[i] << endl;
//    }
//    return 0;
//}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <direct.h>
#include <fcntl.h>
#include <math.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <io.h>
using namespace std;
int info_RF(const char * dirName);
int info_D(const char * dirName);
int info_CS(const char * dirName);
int info_BS(const char * dirName);
int info_S(const char * dirName);
int info_SL(const char * dirName);
int info_R(const char * dirName);
int info_W(const char * dirName);
int info_X(const char * dirName);
int main()
{
	char *word[50];
    char buf[500] = "\0";
	while(word[0] != "exit"){
    int i, k=0;
	cin.getline(buf, 500);

    word[k] = strtok(buf, " ");

    while (word[k++] != NULL) {
        word[k] = strtok(NULL, " ");
    }
 	char checking_first = *word[0];
/*	pid_t pid;
	pid = fork();
	if(pid == 0)
	{
		if(k<=3  && word[0] != "exit"){
			string cmd("./src./single_command.sh ");
			cmd += word[0];
			cmd += " ";
			cmd += word[1];
			system(cmd.c_str());
			perror("invalid input");
		}								//run for single_command.sh
		else if(checking_first == '#'){
			string cmd("./src./comment_command.sh ");
			system(cmd.c_str());		//run for comment_command.sh
			perror("invalid input");
		}
		else if(word[0] == "exit"){
			string cmd("./src./exit.sh ");
			cmd += word[0];
			system(cmd.c_str());
			perror("invalid input");
		}								//run for exit.sh
		else	{
			int initial = 0;
			int hold_number = 0;
			int hold_other_number = 0;
			int ret[20];
			int v[20];

			while(initial <= k){
			string cmd("./src./multi_command.sh ");
				if(word[initial] == "|"|| word[initial] == "&" || word[initial][strlen(word[initial]-1)] == ';'){
					if(hold_number < initial){
						while(hold_number <initial){
						cmd += word[hold_number];
						hold_number++;
						}
						ret[hold_other_number] = system(cmd.c_str());
						v[hold_other_number] = WEXITSTATUS(ret[hold_other_number]);
					}
				}
				initial++;
			}
		}
		int status = 0;
		waitpid(pid, status, WNOHANG);
		if(status != 1){
			perror("fail to close child process");
		}

	}
	else if(pid == -1){
		cout<<"fork error!"<<endl;
	}
	else{
		cout<<"Should not be in parents"<<endl;
	}
*/
//top of part is for homework 01 which does not working so i made it as comment
		if(checking_first == '[' || word[0] =="test"){
			checking_first = *word[1];
			if(checking_first == '-'){
				//All functions need that file exist
					if(word[1] == "-a" || word[1] == "-e"){ //True if <file> exist
						cout<<"file exist"<<endl;
					}
					else if(word[1] == "-f"){//True if <file> exist and is regular file
						info_RF(*word[2]);
					}
					else if(word[1] == "-d"){//True if <file> exist and is a directory
						info_D(*word[2]);
					}
					else if(word[1] == "-c"){//True if <file> exist and is character special file
						info_CS(*word[2]);
					}
					else if(word[1] == "-b"){//True if <file> exist and is block special file
						info_BS(*word[2]);
					}
					else if(word[1] == "-p"){//True if <file> exist and is named pipe
						// need to
					}
					else if(word[1] == "-S"){//True if <file> exist and is socket file
						info_S(*word[2]);
					}
					else if(word[1] == "-L" || word[1] =="-h"){//True if <file> exist and is symbolic link
						info_SL(*word[2]);
					}
					else if(word[1] == "-g"){//True if <file> exist and is sgid bit set
						// need to
					}
					else if(word[1] == "-u"){//True if <file> exist and is suid bit set
						// need to
					}
					else if(word[1] == "-r"){//True if <file> exist and is readable
						info_R(*word[2]);
					}
					else if(word[1] == "-w"){//True if <file> exist and is writeable
						info_W(*word[2]);
					}
					else if(word[1] == "-x"){//True if <file> exist and is excutable
						info_X(*word[2]);
					}
					else if(word[1] == "-s"){//True if <file> exist and size of file is bigger than 0 (not empty)
						//need to
					}
					else if(word[1] == "-t"){//True if file descriptor <fd> is open and refers to a terminal
						//need to
					}
			}
			checking_first = *word[2];
			if(checking_first == '-'){ // there is two files to compare
				if(word[2] == "-nt"){// True if <file1> is newer than <file2>

				}
				else if(word[2] == "-ot"){// True if <file1> is older than <file2>

				}
				else if(word[2] == "-ef"){// True if <file1> and <file2> refer to the same device and inode numbers.

				}
			}
		}
	}
	return 0;
}
int info_RF(const char * dirName){//regular file
	struct stat sb;
	if((sb.st_mode & S_IFREG)){
		return 1;
	}
	return 0;
}
int info_D(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_ISDIR)){
		return 1;
	}
	return 0;
}
int info_CS(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IFCHR)){
		return 1;
	}
	return 0;
}
int info_BS(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IFBLK)){
		return 1;
	}
	return 0;
}
int info_S(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IFSOCK)){
		return 1;
	}
	return 0;
}
int info_SL(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IFKNK)){
		return 1;
	}
	return 0;
}
 int info_R(const char * dirName){//read
	 struct stat sb;
	 if((sb.st_mode & S_IRUSR)){
		return 1;
	 }
	 return 0;
 }
int info_W(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IWUSR)){
		return 1;
	}
	return 0;
}
int info_X(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IXUSR)){
		return 1;
	}
	return 0;
}<commit_msg>201611191753<commit_after>#include <iostream>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <direct.h>
#include <fcntl.h>
#include <math.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <io.h>
using namespace std;
int info_RF(char* dirName);
int info_D(char* dirName);
int info_CS(char* dirName);
int info_BS(char* dirName);
int info_S(char* dirName);
int info_SL(char* dirName);
int info_R(char* dirName);
int info_W(char* dirName);
int info_X(char* dirName);
int main()
{
	char *word[50];
    char buf[500] = "\0";
	while(word[0] != "exit"){
    int i, k=0;
	cin.getline(buf, 500);

    word[k] = strtok(buf, " ");

    while (word[k++] != NULL) {
        word[k] = strtok(NULL, " ");
    }
 	char checking_first = *word[0];
/*	pid_t pid;
	pid = fork();
	if(pid == 0)
	{
		if(k<=3  && word[0] != "exit"){
			string cmd("./src./single_command.sh ");
			cmd += word[0];
			cmd += " ";
			cmd += word[1];
			system(cmd.c_str());
			perror("invalid input");
		}								//run for single_command.sh
		else if(checking_first == '#'){
			string cmd("./src./comment_command.sh ");
			system(cmd.c_str());		//run for comment_command.sh
			perror("invalid input");
		}
		else if(word[0] == "exit"){
			string cmd("./src./exit.sh ");
			cmd += word[0];
			system(cmd.c_str());
			perror("invalid input");
		}								//run for exit.sh
		else	{
			int initial = 0;
			int hold_number = 0;
			int hold_other_number = 0;
			int ret[20];
			int v[20];

			while(initial <= k){
			string cmd("./src./multi_command.sh ");
				if(word[initial] == "|"|| word[initial] == "&" || word[initial][strlen(word[initial]-1)] == ';'){
					if(hold_number < initial){
						while(hold_number <initial){
						cmd += word[hold_number];
						hold_number++;
						}
						ret[hold_other_number] = system(cmd.c_str());
						v[hold_other_number] = WEXITSTATUS(ret[hold_other_number]);
					}
				}
				initial++;
			}
		}
		int status = 0;
		waitpid(pid, status, WNOHANG);
		if(status != 1){
			perror("fail to close child process");
		}

	}
	else if(pid == -1){
		cout<<"fork error!"<<endl;
	}
	else{
		cout<<"Should not be in parents"<<endl;
	}
*/
//top of part is for homework 01 which does not working so i made it as comment
		if(checking_first == '[' || word[0] =="test"){
			checking_first = *word[1];
			if(checking_first == '-'){
				//All functions need that file exist
					if(word[1] == "-a" || word[1] == "-e"){ //True if <file> exist
						cout<<"file exist"<<endl;
					}
					else if(word[1] == "-f"){//True if <file> exist and is regular file
						info_RF(*word[2]);
					}
					else if(word[1] == "-d"){//True if <file> exist and is a directory
						info_D(*word[2]);
					}
					else if(word[1] == "-c"){//True if <file> exist and is character special file
						info_CS(*word[2]);
					}
					else if(word[1] == "-b"){//True if <file> exist and is block special file
						info_BS(*word[2]);
					}
					else if(word[1] == "-p"){//True if <file> exist and is named pipe
						// need to
					}
					else if(word[1] == "-S"){//True if <file> exist and is socket file
						info_S(*word[2]);
					}
					else if(word[1] == "-L" || word[1] =="-h"){//True if <file> exist and is symbolic link
						info_SL(*word[2]);
					}
					else if(word[1] == "-g"){//True if <file> exist and is sgid bit set
						// need to
					}
					else if(word[1] == "-u"){//True if <file> exist and is suid bit set
						// need to
					}
					else if(word[1] == "-r"){//True if <file> exist and is readable
						info_R(*word[2]);
					}
					else if(word[1] == "-w"){//True if <file> exist and is writeable
						info_W(*word[2]);
					}
					else if(word[1] == "-x"){//True if <file> exist and is excutable
						info_X(*word[2]);
					}
					else if(word[1] == "-s"){//True if <file> exist and size of file is bigger than 0 (not empty)
						//need to
					}
					else if(word[1] == "-t"){//True if file descriptor <fd> is open and refers to a terminal
						//need to
					}
			}
			checking_first = *word[2];
			if(checking_first == '-'){ // there is two files to compare
				if(word[2] == "-nt"){// True if <file1> is newer than <file2>

				}
				else if(word[2] == "-ot"){// True if <file1> is older than <file2>

				}
				else if(word[2] == "-ef"){// True if <file1> and <file2> refer to the same device and inode numbers.

				}
			}
		}
	}
	return 0;
}
int info_RF(char* dirName){//regular file
	struct stat sb;
	if((sb.st_mode & S_IFREG)){
		return 1;
	}
	return 0;
}
int info_D(char* dirName){
	struct stat sb;
	if((sb.st_mode & S_ISDIR)){
		return 1;
	}
	return 0;
}
int info_CS(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IFCHR)){
		return 1;
	}
	return 0;
}
int info_BS(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IFBLK)){
		return 1;
	}
	return 0;
}
int info_S(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IFSOCK)){
		return 1;
	}
	return 0;
}
int info_SL(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IFKNK)){
		return 1;
	}
	return 0;
}
 int info_R(const char * dirName){//read
	 struct stat sb;
	 if((sb.st_mode & S_IRUSR)){
		return 1;
	 }
	 return 0;
 }
int info_W(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IWUSR)){
		return 1;
	}
	return 0;
}
int info_X(const char * dirName){
	struct stat sb;
	if((sb.st_mode & S_IXUSR)){
		return 1;
	}
	return 0;
}<|endoftext|>


<commit_before>9c2de3c2-2747-11e6-bc07-e0f84713e7b8<commit_msg>My Life for Auir<commit_after>9c3e3500-2747-11e6-ae0a-e0f84713e7b8<|endoftext|>


<commit_before>/*
 * Copyright 2017 Jussi Pakkanen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include<speedup.hpp>
#include<cstdio>
#include<vector>
#include<random>
#include<chrono>

constexpr const int BUFSIZE=100*1024*1024;

std::vector<uint8_t> create_random_array() {
  std::vector<uint8_t> buf;
  std::mt19937 gen(42); // For reproducibility.
  std::uniform_int_distribution<> dis(0, 255);

  buf.reserve(BUFSIZE);
  for(int i=0; i<BUFSIZE; i++) {
    buf.push_back(dis(gen));
  }
  return buf;
}

int main(int, char**) {
  int failed = 0;
  const uint64_t correct_answer = 10038597640;
  auto buf = create_random_array();
  auto mutbuf = buf;
  auto mutbuf2 = buf;
  auto t0 = std::chrono::high_resolution_clock::now();
  auto simple_answer = simple_loop(buf.data(), buf.size());
  auto t1 = std::chrono::high_resolution_clock::now();
  auto cheaty_answer = cheaty_mccheatface(buf.data(), buf.size());
  auto t2 = std::chrono::high_resolution_clock::now();
  auto lut_answer = lookup_table(buf.data(), buf.size());
  auto t3 = std::chrono::high_resolution_clock::now();
  auto bit_answer = bit_fiddling(buf.data(), buf.size());
  auto t4 = std::chrono::high_resolution_clock::now();
  auto partition_answer = partition(mutbuf.data(), mutbuf.size());
  auto t5 = std::chrono::high_resolution_clock::now();
  auto zeroing_answer = zeroing(mutbuf2.data(), mutbuf.size());
  auto t6 = std::chrono::high_resolution_clock::now();
  auto bucket_answer = bucket(buf.data(), buf.size());
  auto t7 = std::chrono::high_resolution_clock::now();

  if(simple_answer != correct_answer) {
    printf("Simple loop produced wrong answer: %ld\n", simple_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count();
    printf("Simple loop took %ld ms\n", count);
  }

  if(cheaty_answer != correct_answer) {
    printf("Cheaty produced wrong answer: %ld\n", cheaty_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count();
    printf("Cheaty McCheatface took %ld ms\n", count);
  }

  if(lut_answer != correct_answer) {
    printf("Lookup table produced wrong answer: %ld\n", lut_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t3-t2).count();
    printf("Lookup table took %ld ms\n", count);
  }

  if(bit_answer != correct_answer) {
    printf("Bit fiddling produced wrong answer: %ld\n", bit_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t4-t3).count();
    printf("Bit fiddling took %ld ms\n", count);
  }

  if(partition_answer != correct_answer) {
    printf("Partitioning produced wrong answer: %ld\n", partition_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t5-t4).count();
    printf("Partitioning took %ld ms\n", count);
  }

  if(zeroing_answer != correct_answer) {
    printf("Zeroing produced wrong answer: %ld\n", zeroing_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t6-t5).count();
    printf("Zeroing took %ld ms\n", count);
  }

  if(bucket_answer != correct_answer) {
    printf("Bucket produced wrong answer: %ld\n", bucket_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t7-t6).count();
    printf("Bucket took %ld ms\n", count);
  }

  return failed;
}
<commit_msg>Portability fix.<commit_after>/*
 * Copyright 2017 Jussi Pakkanen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include<speedup.hpp>
#include<cstdio>
#include<vector>
#include<random>
#include<chrono>

constexpr const int BUFSIZE=100*1024*1024;

std::vector<uint8_t> create_random_array() {
  std::vector<uint8_t> buf;
  std::mt19937 gen(42); // For reproducibility.
  std::uniform_int_distribution<> dis(0, 255);

  buf.reserve(BUFSIZE);
  for(int i=0; i<BUFSIZE; i++) {
    buf.push_back(dis(gen));
  }
  return buf;
}

int main(int, char**) {
  int failed = 0;
  const uint64_t correct_answer = 10038597640;
  auto buf = create_random_array();
  auto mutbuf = buf;
  auto mutbuf2 = buf;
  auto t0 = std::chrono::high_resolution_clock::now();
  auto simple_answer = simple_loop(buf.data(), buf.size());
  auto t1 = std::chrono::high_resolution_clock::now();
  auto cheaty_answer = cheaty_mccheatface(buf.data(), buf.size());
  auto t2 = std::chrono::high_resolution_clock::now();
  auto lut_answer = lookup_table(buf.data(), buf.size());
  auto t3 = std::chrono::high_resolution_clock::now();
  auto bit_answer = bit_fiddling(buf.data(), buf.size());
  auto t4 = std::chrono::high_resolution_clock::now();
  auto partition_answer = partition(mutbuf.data(), mutbuf.size());
  auto t5 = std::chrono::high_resolution_clock::now();
  auto zeroing_answer = zeroing(mutbuf2.data(), mutbuf.size());
  auto t6 = std::chrono::high_resolution_clock::now();
  auto bucket_answer = bucket(buf.data(), buf.size());
  auto t7 = std::chrono::high_resolution_clock::now();

  if(simple_answer != correct_answer) {
    printf("Simple loop produced wrong answer: %ld\n", (long)simple_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count();
    printf("Simple loop took %ld ms\n", (long)count);
  }

  if(cheaty_answer != correct_answer) {
    printf("Cheaty produced wrong answer: %ld\n", (long)cheaty_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count();
    printf("Cheaty McCheatface took %ld ms\n", (long)count);
  }

  if(lut_answer != correct_answer) {
    printf("Lookup table produced wrong answer: %ld\n", (long)lut_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t3-t2).count();
    printf("Lookup table took %ld ms\n", (long)count);
  }

  if(bit_answer != correct_answer) {
    printf("Bit fiddling produced wrong answer: %ld\n", (long)bit_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t4-t3).count();
    printf("Bit fiddling took %ld ms\n", (long)count);
  }

  if(partition_answer != correct_answer) {
    printf("Partitioning produced wrong answer: %ld\n", (long)partition_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t5-t4).count();
    printf("Partitioning took %ld ms\n", (long)count);
  }

  if(zeroing_answer != correct_answer) {
    printf("Zeroing produced wrong answer: %ld\n", (long)zeroing_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t6-t5).count();
    printf("Zeroing took %ld ms\n", (long)count);
  }

  if(bucket_answer != correct_answer) {
    printf("Bucket produced wrong answer: %ld\n", (long)bucket_answer);
    failed++;
  } else {
    int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t7-t6).count();
    printf("Bucket took %ld ms\n", (long)count);
  }

  return failed;
}
<|endoftext|>


<commit_before>2fe096ba-ad5b-11e7-9e61-ac87a332f658<commit_msg>roselyn added more bugs<commit_after>30470f3d-ad5b-11e7-b65e-ac87a332f658<|endoftext|>


<commit_before>#include <omp.h>

#include "evaluate_circuit.h"

// Input: ./qflex.x I J K fidelity circuit_filename ordering_filename \
//            grid_filename [initial_conf] [final_conf]
//
// Example:
// $ ./qflex.x 11 12 2 0.005 ./circuits/ben_11_16_0.txt \
//       ./ordering/bristlecone_48.txt ./grid/bristlecone_48.txt
int main(int argc, char** argv) {
  // Reading input.
  if (argc < 8) throw std::logic_error("ERROR: Not enough arguments.");
  int current_arg = 1;
  qflex::QflexInput input;
  input.I = atoi(argv[current_arg++]);
  input.J = atoi(argv[current_arg++]);
  input.K = atoi(argv[current_arg++]);
  input.fidelity = atof(argv[current_arg++]);

  // Creating streams for input files.
  std::string circuit_filename = std::string(argv[current_arg++]);
  auto circuit_data = std::ifstream(circuit_filename);
  if (!circuit_data.good()) {
    std::cout << "Cannot open circuit data file: " << circuit_filename
              << std::endl;
    assert(circuit_data.good());
  }
  input.circuit_data = &circuit_data;
  std::string ordering_filename = std::string(argv[current_arg++]);
  auto ordering_data = std::ifstream(ordering_filename);
  if (!ordering_data.good()) {
    std::cout << "Cannot open ordering data file: " << ordering_filename
              << std::endl;
    assert(ordering_data.good());
  }
  input.ordering_data = &ordering_data;
  std::string grid_filename = std::string(argv[current_arg++]);
  auto grid_data = std::ifstream(grid_filename);
  if (!grid_data.good()) {
    std::cout << "Cannot open grid data file: " << grid_filename << std::endl;
    assert(grid_data.good());
  }
  input.grid_data = &grid_data;

  // Setting initial and final circuit states.
  if (argc > current_arg) {
    input.initial_state = std::string(argv[current_arg++]);
  }
  if (argc > current_arg) {
    input.final_state_A = std::string(argv[current_arg++]);
  }

  // Evaluating circuit.
  std::vector<std::pair<std::string, std::complex<double>>> amplitudes =
      qflex::EvaluateCircuit(&input);

  // Printing output.
  for (int c = 0; c < amplitudes.size(); ++c) {
    const auto& state = amplitudes[c].first;
    const auto& amplitude = amplitudes[c].second;
    std::cout << input.initial_state << " --> " << state << ": "
              << std::real(amplitude) << " " << std::imag(amplitude)
              << std::endl;
  }
  return 0;
}
<commit_msg>Changed example in main.cpp<commit_after>#include <omp.h>

#include "evaluate_circuit.h"

// Input: ./qflex.x I J K fidelity circuit_filename ordering_filename \
//            grid_filename [initial_conf] [final_conf]
//
// Example:
// $ ./qflex.x 11 12 2 0.005 ./circuits/bristlecone_48_1-40-1_0.txt \
//       ./ordering/bristlecone_48.txt ./grid/bristlecone_48.txt
int main(int argc, char** argv) {
  // Reading input.
  if (argc < 8) throw std::logic_error("ERROR: Not enough arguments.");
  int current_arg = 1;
  qflex::QflexInput input;
  input.I = atoi(argv[current_arg++]);
  input.J = atoi(argv[current_arg++]);
  input.K = atoi(argv[current_arg++]);
  input.fidelity = atof(argv[current_arg++]);

  // Creating streams for input files.
  std::string circuit_filename = std::string(argv[current_arg++]);
  auto circuit_data = std::ifstream(circuit_filename);
  if (!circuit_data.good()) {
    std::cout << "Cannot open circuit data file: " << circuit_filename
              << std::endl;
    assert(circuit_data.good());
  }
  input.circuit_data = &circuit_data;
  std::string ordering_filename = std::string(argv[current_arg++]);
  auto ordering_data = std::ifstream(ordering_filename);
  if (!ordering_data.good()) {
    std::cout << "Cannot open ordering data file: " << ordering_filename
              << std::endl;
    assert(ordering_data.good());
  }
  input.ordering_data = &ordering_data;
  std::string grid_filename = std::string(argv[current_arg++]);
  auto grid_data = std::ifstream(grid_filename);
  if (!grid_data.good()) {
    std::cout << "Cannot open grid data file: " << grid_filename << std::endl;
    assert(grid_data.good());
  }
  input.grid_data = &grid_data;

  // Setting initial and final circuit states.
  if (argc > current_arg) {
    input.initial_state = std::string(argv[current_arg++]);
  }
  if (argc > current_arg) {
    input.final_state_A = std::string(argv[current_arg++]);
  }

  // Evaluating circuit.
  std::vector<std::pair<std::string, std::complex<double>>> amplitudes =
      qflex::EvaluateCircuit(&input);

  // Printing output.
  for (int c = 0; c < amplitudes.size(); ++c) {
    const auto& state = amplitudes[c].first;
    const auto& amplitude = amplitudes[c].second;
    std::cout << input.initial_state << " --> " << state << ": "
              << std::real(amplitude) << " " << std::imag(amplitude)
              << std::endl;
  }
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <list>

#include "opencv.hpp"

using namespace cv;
using namespace std;

static const double PI = 3.1415926536;

struct Options
{
	int threshold;
};

struct Star
{
	double x, y;
	double r;

	Star(double x, double y, double r)
	{
		this->x = x;
		this->y = y;
		this->r = r;
	}
};

struct Blob
{
	double x, y;
	double S;
};

Blob operator+(const Blob & l, const Blob & r)
{
	Blob q;
	q.S = l.S + r.S;
	q.x = (l.S*l.x + r.S*r.x) / q.S;
	q.y = (l.S*l.y + r.S*r.y) / q.S;
}

Blob & operator+=(Blob & blob, const Blob & x)
{
	double S = blob.S + x.S;
	blob.x = (blob.S*blob.x + x.S*x.x) / S;
	blob.y = (blob.S*blob.y + x.S*x.y) / S;
}

bool operator<(const Star & l, const Star & r)
{
	if (l.r < r.r)
		return true;
	if (l.r > r.r)
		return false;

	return (l.x < r.x);
}

typedef vector<Star> Stars;
typedef vector<Blob> Blobs;

void die(const string & msg)
{
	cerr << "Error: " << msg << endl;
	exit(1);
}

inline double sqr(double x)
{
	return x*x;
}

inline double min3(double x, double y, double z)
{
	return (x < y) ? ((x < z) ? x : z) : ((y < z) ? y : z);
}

void getTransform(Stars & xs, Stars & ys)
{
}

struct ScanItem
{
	Blob blob;
	int l, r;

	ScanItem(int _l, int _r, const Blob & _b)
		: l(_l), r(_r), blob(_b)
	{}
};

void findBlobs(const Mat & mat, Blobs & blobs)
{
	/*
	namedWindow("foo");
	imshow("foo", mat);
	waitKey(1000);
	*/

	cout << "depth: " << mat.depth() << ", type: " << mat.type() << ", chans: " << mat.channels() << endl;
	list<ScanItem> scan, newscan;
	for (int y = 0; y < mat.rows; ++y)
	{
		const uint8_t * row = mat.ptr<uint8_t>(y);
		list<ScanItem>::iterator it = scan.begin();
		int l = 0;
		for (int x = 0; x < mat.cols; ++x)
		{
			// skip blanks
			while (it != scan.end() && it->r < x)
			{
				blobs.push_back(it->blob);
				++it;
			}

			// find the end of the white segment
			while (x < mat.cols && row[x])
				++x;

			// if white segment found
			if (row[l])
			{
				cout << "rowscan at " << l << ".." << x << "," << y << endl;
				Blob cur = {(x+l-1)/2.0, y, x-l};
				while (it != scan.end() && it->l < x)
				{
					cur += it->blob;
					++it;
				}
				newscan.push_back(ScanItem(l,x-1,cur));
			}

			l = ++x;
		}
		scan = newscan;
	}

	for (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it)

	{
		blobs.push_back(it->blob);
	}
}

void getStars(const vector<string> & fn, vector<Stars *> & stars, const Options & opt)
{
	stars.clear();
	for (vector<string>::const_iterator it = fn.begin(); it != fn.end(); ++it)
	{
		cout << "  * " << *it << ": ";

		// load the image
		Mat image = imread(*it, CV_LOAD_IMAGE_GRAYSCALE);
		Mat srcimg;
		resize(image, srcimg, Size(0,0), 0.25, 0.25);
		threshold(srcimg, image, opt.threshold, 255, THRESH_BINARY);

		// find the blobs
		Blobs blobs;
		findBlobs(image, blobs);

		// traverse the blobs
		Stars * st = new vector<Star>();
		for (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it)
		{
			st->push_back(Star(it->x, it->y, sqrt(it->S / PI)));
		}

		cout << st->size() << " stars" << endl;

		stars.push_back(st);
	}
}

int main(int argc, char ** argv)
{
	char ** end =  argv + argc;
	++argv; // skip the name of the executable

	// some default options
	Options opt;
	opt.threshold = 128;

	// get the options
	while (argv < end)
	{
		// end of options
		if (**argv != '-')
			break;

		string opt = *argv++;

		// no options will follow
		if (opt == "--")
			break;

		die("unknown option " + opt);
	}

	// get the list of images
	vector<string> imgNames;
	while (argv < end)
		imgNames.push_back(*argv++);

	// perform some sanity checks
	if (imgNames.size() < 2)
		die("no point in aligning less than two images");

	// find stars on each image
	cout << "Finding stars..." << endl;
	vector<Stars *> stars;
	getStars(imgNames, stars, opt); // allocates stars

	// sort each vector by star size
	for (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)
	{
		sort((*it)->rbegin(), (*it)->rend());
	}

	// align the stars
	getTransform(*stars[0], *stars[1]);

	// free the memory
	for (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)
	{
		delete *it;
	}

	return 0;
}
<commit_msg>Blob += fixed.<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <list>

#include "opencv.hpp"

using namespace cv;
using namespace std;

static const double PI = 3.1415926536;

struct Options
{
	int threshold;
};

struct Star
{
	double x, y;
	double r;

	Star(double x, double y, double r)
	{
		this->x = x;
		this->y = y;
		this->r = r;
	}
};

struct Blob
{
	double x, y;
	double S;
};

Blob operator+(const Blob & l, const Blob & r)
{
	Blob q;
	q.S = l.S + r.S;
	q.x = (l.S*l.x + r.S*r.x) / q.S;
	q.y = (l.S*l.y + r.S*r.y) / q.S;
}

Blob & operator+=(Blob & blob, const Blob & x)
{
	double S = blob.S + x.S;
	blob.x = (blob.S*blob.x + x.S*x.x) / S;
	blob.y = (blob.S*blob.y + x.S*x.y) / S;
	blob.S = S;
}

bool operator<(const Star & l, const Star & r)
{
	if (l.r < r.r)
		return true;
	if (l.r > r.r)
		return false;

	return (l.x < r.x);
}

typedef vector<Star> Stars;
typedef vector<Blob> Blobs;

void die(const string & msg)
{
	cerr << "Error: " << msg << endl;
	exit(1);
}

inline double sqr(double x)
{
	return x*x;
}

inline double min3(double x, double y, double z)
{
	return (x < y) ? ((x < z) ? x : z) : ((y < z) ? y : z);
}

void getTransform(Stars & xs, Stars & ys)
{
}

struct ScanItem
{
	Blob blob;
	int l, r;

	ScanItem(int _l, int _r, const Blob & _b)
		: l(_l), r(_r), blob(_b)
	{}
};

void findBlobs(const Mat & mat, Blobs & blobs)
{
	/*
	namedWindow("foo");
	imshow("foo", mat);
	waitKey(1000);
	*/

	cout << "depth: " << mat.depth() << ", type: " << mat.type() << ", chans: " << mat.channels() << endl;
	list<ScanItem> scan, newscan;
	for (int y = 0; y < mat.rows; ++y)
	{
		const uint8_t * row = mat.ptr<uint8_t>(y);
		list<ScanItem>::iterator it = scan.begin();
		int l = 0;
		for (int x = 0; x < mat.cols; ++x)
		{
			// skip blanks
			while (it != scan.end() && it->r < x)
			{
				blobs.push_back(it->blob);
				++it;
			}

			// find the end of the white segment
			while (x < mat.cols && row[x])
				++x;

			// if white segment found
			if (row[l])
			{
				cout << "rowscan at " << l << ".." << x << "," << y << endl;
				Blob cur = {(x+l-1)/2.0, y, x-l};
				while (it != scan.end() && it->l < x)
				{
					cur += it->blob;
					++it;
				}
				newscan.push_back(ScanItem(l,x-1,cur));
			}

			l = ++x;
		}
		scan = newscan;
	}

	for (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it)

	{
		blobs.push_back(it->blob);
	}
}

void getStars(const vector<string> & fn, vector<Stars *> & stars, const Options & opt)
{
	stars.clear();
	for (vector<string>::const_iterator it = fn.begin(); it != fn.end(); ++it)
	{
		cout << "  * " << *it << ": ";

		// load the image
		Mat image = imread(*it, CV_LOAD_IMAGE_GRAYSCALE);
		Mat srcimg;
		resize(image, srcimg, Size(0,0), 0.25, 0.25);
		threshold(srcimg, image, opt.threshold, 255, THRESH_BINARY);

		// find the blobs
		Blobs blobs;
		findBlobs(image, blobs);

		// traverse the blobs
		Stars * st = new vector<Star>();
		for (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it)
		{
			st->push_back(Star(it->x, it->y, sqrt(it->S / PI)));
		}

		cout << st->size() << " stars" << endl;

		stars.push_back(st);
	}
}

int main(int argc, char ** argv)
{
	char ** end =  argv + argc;
	++argv; // skip the name of the executable

	// some default options
	Options opt;
	opt.threshold = 128;

	// get the options
	while (argv < end)
	{
		// end of options
		if (**argv != '-')
			break;

		string opt = *argv++;

		// no options will follow
		if (opt == "--")
			break;

		die("unknown option " + opt);
	}

	// get the list of images
	vector<string> imgNames;
	while (argv < end)
		imgNames.push_back(*argv++);

	// perform some sanity checks
	if (imgNames.size() < 2)
		die("no point in aligning less than two images");

	// find stars on each image
	cout << "Finding stars..." << endl;
	vector<Stars *> stars;
	getStars(imgNames, stars, opt); // allocates stars

	// sort each vector by star size
	for (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)
	{
		sort((*it)->rbegin(), (*it)->rend());
	}

	// align the stars
	getTransform(*stars[0], *stars[1]);

	// free the memory
	for (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)
	{
		delete *it;
	}

	return 0;
}
<|endoftext|>