Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:add trade
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:01a7d7f0209193b2dd77e3ddc08d4892bcf9e6d3
User & Date: ravenspoint 2016-05-28 20:27:36
Context
2016-05-28
20:54
remove unneccessary double storage of trader instances check-in: c95dc85730 user: ravenspoint tags: trunk
20:27
add trade check-in: 01a7d7f020 user: ravenspoint tags: trunk
2016-05-27
21:26
remove functions from global namespace check-in: 6a5330309e user: ravenspoint tags: trunk
Changes

Changes to longestpath.cbp.

32
33
34
35
36
37
38

39
40
41
42
43
44
45
46
			<Add option="-march=i686" />
			<Add option="-std=c++11" />
			<Add option="-Wall" />
			<Add option="-fexceptions" />
			<Add directory="$(#boost)" />
		</Compiler>
		<Unit filename="main.cpp" />

		<Extensions>
			<code_completion />
			<envvars />
			<debugger />
			<lib_finder disable_auto="1" />
		</Extensions>
	</Project>
</CodeBlocks_project_file>







>








32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
			<Add option="-march=i686" />
			<Add option="-std=c++11" />
			<Add option="-Wall" />
			<Add option="-fexceptions" />
			<Add directory="$(#boost)" />
		</Compiler>
		<Unit filename="main.cpp" />
		<Unit filename="trade.h" />
		<Extensions>
			<code_completion />
			<envvars />
			<debugger />
			<lib_finder disable_auto="1" />
		</Extensions>
	</Project>
</CodeBlocks_project_file>

Changes to main.cpp.

7
8
9
10
11
12
13




14
15
16
17
18
19
20
...
356
357
358
359
360
361
362





363
364
365
366

367
368
369

370
371
372
373

374
375
376
377
378
379
380
#include <boost/graph/bellman_ford_shortest_paths.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/depth_first_search.hpp>

using namespace std;
using namespace boost;





/** Bundled properties for graph vertices - currently none
*/
class cVertex
{

};
................................................................................
    for( int v : myPath )
        cout << v << " ";
    cout << " length " << myDistance << endl;
}

int main()
{





    // Construct cyclic test graph
    cGraph g;
    g.ConstructWithCycle();


    // convert to DAG
    cDAG dag( g );


    // find longest path from first to last vertex
    cPath path;
    dag.Longest( 0, 9, path );


    g.DisplayEdges();
    cout << "Longest path: ";
    path.Display();


    return 0;
}







>
>
>
>







 







>
>
>
>
>
|
|
|
<
>
|
|
<
>
|
|
|
<
>
|
|
|




7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
...
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374

375
376
377

378
379
380
381

382
383
384
385
386
387
388
389
#include <boost/graph/bellman_ford_shortest_paths.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/depth_first_search.hpp>

using namespace std;
using namespace boost;

#include "trade.h"



/** Bundled properties for graph vertices - currently none
*/
class cVertex
{

};
................................................................................
    for( int v : myPath )
        cout << v << " ";
    cout << " length " << myDistance << endl;
}

int main()
{
    cVillage village;
    village.ConstructProblem1();
    village.Display();
    village.Travel();

//    // Construct cyclic test graph
//    cGraph g;
//    g.ConstructWithCycle();

//
//    // convert to DAG
//    cDAG dag( g );

//
//    // find longest path from first to last vertex
//    cPath path;
//    dag.Longest( 0, 9, path );

//
//    g.DisplayEdges();
//    cout << "Longest path: ";
//    path.Display();


    return 0;
}

Added trade.h.









































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/** The commodities that we can trade for each other */
enum class eCommodity
{
    wood,
    sand,
    gras,
};

vector< string > Names
{
    "wood",
    "sand",
    "gras",
};

/** A trader selling a commodity for another at a price */
class cTrader
{
public:
    eCommodity mySell;
    eCommodity myBuy;
    float myPrice;
    cTrader() {}
    cTrader( eCommodity sell,
             eCommodity buy,
             float price )
        : mySell( sell )
        , myBuy( buy )
        , myPrice( price )
    {

    }
    void Display()
    {
        if( myPrice >= 1 )
            cout << "Gives 1 " << Sell() << " For " << myPrice <<" "<< Buy() << endl;
        else
        {
            cout << "Gives " << 1 / myPrice <<" " << Sell() << " For 1 " << Buy() << endl;
        }
    }
    const string& Sell() const
    {
        return Names[(int)mySell];
    }
    const string& Buy() const
    {
        return Names[(int)myBuy];
    }
};

class cTrip
{
public:
    void Weight( int w )
    {
        myWeight = w;
    }
    int Weight()
    {
        return myWeight;
    }
    void negWeight()
    {
        myWeight = - myWeight;
    }

    int myWeight;
};

typedef adjacency_list<
vecS, vecS,  directedS,
      cTrader, cTrip  > trade_graph_t;

class cTraveler : public default_dfs_visitor
{
public:
    eCommodity * myHold;
    eCommodity myInitiallHold;
    float * myQuantity;
    float myInitialQuantity;
    unsigned int * src;
    unsigned int * dst;
    bool myfTrading;
    vector< int > * myPath;
    cTraveler() {}
    cTraveler( eCommodity hold,
               int quantity )
        : myInitiallHold( hold )
        , myInitialQuantity( quantity )
        , myfTrading( false )
    {
        *myHold = hold;
        *myQuantity = quantity;
    }

    template < typename Edge, typename Graph >

    /** Called by DFS when back edge found
        @param[in] e the back edge found
        @param[in] g the graph being searched

        A back edge is one that returns the search to a previously found vertex,
        indicating a cycle.

        This will throw an exception when it occurrs
    */
    void back_edge( Edge e, Graph& g)
    {
        *src = source( e, g );
        *dst = target( e, g );
        throw runtime_error("cyclic");
    }

    template < typename Vertex, typename Graph >
    void discover_vertex( Vertex u, Graph& g)
    {
        if( ! myfTrading )
            return;
        if( u == 0)
            return;

        cout << "Trader " << u << " ";
        cout << g[ u ].Buy() << " -> " << g[ u ].Sell() << " now holding ";

        // Do the trade
        *myHold = g[ u ].mySell;
        *myQuantity = *myQuantity / g[u].myPrice;
        myPath->push_back( u );

        Display();

        if( g[ u ].mySell == myInitiallHold )
        {
            *dst = u;
            throw runtime_error( "init hold ");
        }

        *src = u;
    }

    void Display()
    {
//        for( auto v : *myPath )
//            cout << v << " ";
//        cout << "\n";
        cout << "holding " << *myQuantity
             << " of " << Names[ (int)*myHold ] << endl;
    }
    void Restart()
    {
        *myHold = myInitiallHold;
        *myQuantity = myInitialQuantity;
        myPath->clear();
        cout << endl;
        //Display();
    }
    bool IsSuccess()
    {
        return *myHold == myInitiallHold;
    }
};

class cVillage
{
public:
    cTraveler myTraveler;
    vector< cTrader > myTrader;
    trade_graph_t myGraph;
    void ConstructProblem1()
    {
        static eCommodity hold = eCommodity::wood;
        static float quantity = 1;
        myTraveler.myHold = &hold;
        myTraveler.myQuantity = &quantity;
        myTraveler.myInitiallHold = hold;
        myTraveler.myInitialQuantity = quantity;

        static vector<int> path;
        myTraveler.myPath = &path;


        // initial starting point
        myTrader.push_back( cTrader(  eCommodity::wood,  eCommodity::wood, 1));

        myTrader.push_back( cTrader( eCommodity::wood, eCommodity::sand, 2));
        myTrader.push_back( cTrader( eCommodity::sand, eCommodity::gras, 0.5));
        myTrader.push_back( cTrader( eCommodity::gras, eCommodity::sand, 1));
        myTrader.push_back( cTrader( eCommodity::sand, eCommodity::wood, 0.25));
        myTrader.push_back( cTrader( eCommodity::gras, eCommodity::wood, 0.5));

        for( auto& t : myTrader )
        {
            myGraph[ add_vertex( myGraph ) ] = t;
        }

    }
    void Display()
    {
        int index = 0;
        for( auto& t : myTrader )
        {
            if( index != 0 )
            {

                cout << "Trader " << index << " ";
                t.Display();
            }
            index++;
        }
    }
    void ConstructSensibleTrips()
    {
        // A sensible trip betwee two traders:
        // the source is selling what the target is buying

        // loop over all pairs of traders
        for( int s = 0; s < (int)myTrader.size(); s++)
        {
            for( int t = 1; t < (int)myTrader.size(); t++)
            {
                if( myTrader[ s ].mySell == myTrader[ t].myBuy )
                {
                    //cout << s << " -> " << t << endl;
                    add_edge( s, t, myGraph );
                }
            }
        }
    }
    void Travel()
    {
        ConstructSensibleTrips();
        //ConvertToDAG();
        myTraveler.myfTrading = true;
        float bestQuantity = -1;
        vector< int > bestpath;
        unsigned int src, dst;
        myTraveler.src = &src;
        myTraveler.dst = &dst;
        int count = 0;
        while( count < 30 )
        {
            try
            {
                myTraveler.Restart();
                depth_first_search(
                    myGraph,
                    visitor( myTraveler )
                    .root_vertex( 0 ));
                break;
            }
            catch( runtime_error& e )
            {
                myTraveler.Display();
                if( myTraveler.IsSuccess() )
                {
                    if( *(myTraveler.myQuantity) > bestQuantity )
                    {
                        bestQuantity = *(myTraveler.myQuantity);
                        bestpath = *(myTraveler.myPath);

                    }
                }
                //cout << src << " - " << dst << endl;
                remove_edge( src, dst, myGraph );
                count++;
            }
        }

        cout << "\n=========================\n";
        cout << "Best: Holding " << bestQuantity << " from trades with ";
        for( auto v : bestpath )
            cout << v << " ";
        cout << endl;
    }
    void ConvertToDAG()
    {

        unsigned int src, dst;
        myTraveler.src = &src;
        myTraveler.dst = &dst;

        // loop while graph is still cyclic
        while( 1 )
        {
            try
            {
                // depth first search using back edge detecting visitor
                depth_first_search(
                    myGraph,
                    visitor(myTraveler)
                    .root_vertex( 0 ));

                // the seach found no cycles
                // so we can break out of the loop
                break;
            }
            catch( runtime_error& e )
            {
                // the search through an excepting indicating a cycle

                // remove back edge found
                cout << "removing " << src << " -> " << dst << endl;
                remove_edge( src, dst, myGraph );
            }
        }
    }
};