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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
/* asprgen.cpp
name: approximate single-peaked ranking generator
function: find ordering of candidates for which most voters are single-peaked
info: branch and bound algorithm constructing partial axes in nodes, filtering
participants according to single-peakdness consistency with partial axis,
bounding when upper bound of participants less than lower bound found in leaf
implementation: Alex Francois Nienaber
 
Copyright (c) 2012 University of Toronto. All rights reserved. */
 
#include <cstring>
#include <iostream>
#include <sstream>
#include <fstream>
#include <algorithm>
 
using namespace std;
 
/*general functionality global variables*/
 
//name of input profile
// candidates must be numbered from 1 to total number of candidates.
// participants' rankings have to be sequences of (nonzero) integers
// seperated by spaces, corresponding to their ordering of the
// candidates. each individual profile has to be a total order.
string input = "./sushi.data";
//number of candidates
int candidates = 10;
//number of participants
int participants = 5000;
//verbosity
int verbose = 0;
//cpu time computation
int timecheck = 0;
//preferences
int** preferences;
//best axis so far
int* bestAxis = new int[candidates];
//consistent prefs so far
int* bestPref = new int[participants];
//max lower bound
int lowerBound = 0;
//approximation method
// 0 exact single-peakdness
// 1 k-local candidate deletion approximate single-peakdness
int approx = 0;
//k approximation parameter
// k-local candidate deletion imposes: k < candidates
int k = 1;
 
/*satellite functionality global variables*/
 
// instead of tracking the best leaf, it is
// possible to modify code at #leaf to track
// leaves over a certain threshold
 
//total number of leaves reached
int leaves = 0;
//total number of distinct voters in leaves
//since there may be overlapping in leaves
int totalc = 0;
//array to store distinct prefs of leaves
static int* distinctParticipants = new int[participants];
 
//tree data structure, nodes are distinguished by partial axes
class node
{
public:
    //parent
    node* parent;
    //children
    int totalChildren; //number of children
    int currentChild; //position in children
    node** children; //array of children ordered by upperBound
    //preferences
    int upperBound; //number of preference rankings
    int* consistentPref; //index of preferences consistent with partial axis
    //partial axis
    int* partialAxis;
    //constructor
    node(node* p, int ub, int* prefs, int* paxis)
    {
        parent = p;
        totalChildren = 0;
        currentChild = 0;
        children = NULL;
        upperBound = ub;
        consistentPref = prefs;
        partialAxis = paxis;
    }
    //deconstructor
    ~node()
    {
        delete[] consistentPref;
        delete[] partialAxis;
        delete[] children;
    }
};
 
//reversed sort comparator to sort pointer to nodes according to their induced ub
bool ubcomp(const node* less, const node* greater)
{
      return less->upperBound > greater->upperBound;
}
/*note to self: the reason you needed to overload sort with ubcomp instead of
of using regular 2 args sort and overriding bool operator < (const struct, const struct)
is because the latter method will not work with pointers to structs but with structs.*/
 
//factorial function
int factorial(int n)
{
    if (n > 1) { return n*factorial(n-1); }
    else { return 1; }
}
 
//helper prototypes
void printUsage();
void printPref(int** preferences);
void printAxis(int* Axis);
void printNode(node* node, int vp);
node* lonelyChild(node* parent, int lastc);
int fillConsistent(int* childAxis, int* parentArray, int parentSize, int* childArray, int approxMethod);
int exactCons(int* childAxis, int* parentArray, int parentSize, int* childArray);
int localCandidateCons(int* childAxis, int* parentArray, int parentSize, int* childArray);
 
//find best ordering of candidates for given profile
int main(int argc, const char * argv[])
{
    //parse parameters
    if(argc>1)
    {
            for(int p=1;p<argc;p++)
            {
                string param=argv[p];
                if(param == "-i") {input=argv[p+1];}
                else if(param == "-a") {approx=atoi(argv[p+1]);}
                else if(param == "-c") {candidates=atoi(argv[p+1]);}
                else if(param == "-k") {k=atoi(argv[p+1]);}
                else if(param == "-p") {participants=atoi(argv[p+1]);}
                else if(param == "-v") {verbose=1;}
                else if(param == "-t") {timecheck=1;}
                else if(param == "-h") {printUsage(); exit(0);}
            }
    }
 
    //CPU time initialization
    clock_t start, end;
    double cputime;
    if(timecheck == 1)
    {
        start = clock();
    }
 
    //check zero conditions
    if(candidates == 0 || participants == 0)
    {
        cout<<"error: candidates or participants cannot be zero"<<endl;
        return -1;
    }
 
    //create an array of individual preference profiles
    preferences = new int*[participants];
    for(int i=0; i<participants; i++)
    {
        preferences[i]=new int[candidates];
    }
 
    //fill the array from input
    ifstream in;
    in.open(input.c_str());
    if(!in.is_open()) { cout<<"cannot open file"<<endl; return -1;}
    int temp;
    for(int i=0; i<participants; i++)
    {
        for(int j=0; j<candidates; j++)
        {
            in>>temp;
            preferences[i][j]=temp;
        }
    }
    in.close();
 
    //temporary array to store consistent ids
    int* tempConsistent = new int[participants];
 
    //create parent node (with all participants)
    int* parentArray = new int[participants];
    for(int i=0; i<participants; i++)
    {
        parentArray[i] = i;
    }
    int* parentAxis = new int[candidates];
    for(int j=0; j<candidates; j++)
    {
        parentAxis[j] = 0;
    }
    node* parent = new node(NULL, participants, parentArray, parentAxis);
 
    //create parents array of children pointers
    int firstgensize = factorial(candidates)/(2*factorial(candidates-2));
    node** parentChildren = new node*[firstgensize];
 
    //create first generation of tree
    node* child;
    int ubchild;
    int childpos = 0;
    for(int left=1; left<candidates; left++)
    {
        for(int right=left+1; right<=candidates; right++)
        {
            //create child axis
            int* axis = new int[candidates];
            axis[0] = left;
            for(int j=1; j<candidates-1; j++)
            {
                axis[j] = 0;
            }
            axis[candidates-1] = right;
 
            //fill temporary array with consistent ids from parent array
            ubchild = fillConsistent(axis, parentArray, participants, tempConsistent, approx);
 
            //copy those ids to child's array
            int* array = new int[ubchild];
            memcpy(array, tempConsistent, ubchild*sizeof(int));
 
            //create the child
            child = new node(parent, ubchild, array, axis);
 
            //add child pointer to parent's array of children
            parentChildren[childpos] = child;
            childpos++;
        }
    }
 
    //sort array of children by upperbound and give it to parent
    sort(parentChildren, parentChildren+firstgensize, ubcomp);
    parent->children = parentChildren;
    parent->totalChildren = firstgensize;
 
//    //print first generation #print
//    for(int k=0; k<firstgensize; k++)
//    {
//        printNode(parentChildren[k], 0);
//        cout<<endl;
//    }
//    cout<<endl<<endl<<endl<<endl;
 
    //branch and bound algorithm
    //setup
    int traversed = 0;
    int gen, partial, remainingsize, newchildrensize;
    int remaining[candidates];
    node** newchildren;
 
    //traverse the tree
    node* driver = parent;
    while(!traversed)
    {
        //climb down the tree (to the next child)
        if(driver->currentChild < driver->totalChildren)
        {
            driver = driver->children[driver->currentChild];
        }
        //climb up the tree (if no child left)
        else if(driver->parent != NULL)
        {\
            driver = driver->parent;
            delete driver->children[driver->currentChild];
            driver->currentChild++;
            continue;
        }
        //done traversing the tree
        else
        {
            traversed = 1; //just making a point.
            break;
        }
 
        //get to a leaf, i.e. build a complete axis
        partial = 1;
        while(partial)
        {
            if(verbose == 1) { printAxis(driver->partialAxis); } //#print
 
            //check bounding condition
            if(driver->upperBound > lowerBound) //#bounding
            {
                //store remaining candidates
                remainingsize = 0;
                for(int j=1; j<=candidates; j++)
                {
                    for(int jj=0; jj<candidates; jj++)
                    {
                        //already placed
                        if(driver->partialAxis[jj] == j)
                        {
                            break;
                        }
                        //not yet placed
                        else if(jj == candidates-1)
                        {
                            remaining[remainingsize] = j;
                            remainingsize++;
                        }
                    }
                }
 
                //check for completion
                if(remainingsize == 0)
                {
                    break;
                }
                else if(remainingsize == 1)
                {
                    partial = 0;
                    child = lonelyChild(driver, remaining[0]);
                    newchildren = new node*[1];
                    newchildren[0] = child;
                    driver->children = newchildren;
                    driver->totalChildren = 1;
                    driver = child;
                    break;
                }
                else if(remainingsize == 2)
                {
                    partial = 0;
                }
 
                //create children array
                newchildrensize = remainingsize*(remainingsize-1);//p=2 => n!/(n-p)! = n(n-1)
                newchildren = new node*[newchildrensize];
                childpos = 0;
 
                //spawn children
                for(int left=0; left<remainingsize; left++) //#branching
                {
                    for(int right=0; right<remainingsize; right++)
                    {
                        if(right != left)
                        {
                            //find generation
                            for(int j=1; j<candidates; j++)
                            {
                                if(driver->partialAxis[j] == 0)
                                {
                                    gen = j;
                                    break;
                                }
                            }
 
                            //create child axis
                            int* childaxis = new int[candidates];
                            memcpy(childaxis, driver->partialAxis, candidates*sizeof(int));
                            childaxis[gen] = remaining[left];
                            childaxis[candidates-1-gen] = remaining[right];
 
                            //fill temporary array with consistent ids from parent array
                            ubchild = fillConsistent(childaxis, driver->consistentPref, driver->upperBound, tempConsistent, approx);
 
                            //copy those ids to child's array
                            int* childpref = new int[ubchild];
                            memcpy(childpref, tempConsistent, ubchild*sizeof(int));
 
                            //create the child
                            child = new node(driver, ubchild, childpref, childaxis);
 
                            //add child pointer to parent's array of children
                            newchildren[childpos] = child;
                            childpos++;
                        }
                    }
                }
 
                //sort array of children by upperbound and give it to parent
                sort(newchildren, newchildren+newchildrensize, ubcomp);
                driver->children = newchildren;
                driver->totalChildren = newchildrensize;
 
//                //print current driver's offspring #print
//                for(int k=0; k<newchildrensize; k++)
//                {
//                    printNode(driver->children[k], 1);
//                    cout<<endl;
//                } cout<<endl<<endl<<endl<<endl;
 
                //climb down the tree (to the best child)
                driver = driver->children[driver->currentChild];
            }
            else
            {
                break;
            }
        }
 
        //get a new lowerbound #leaf
        //checking the bounding is useful only in cases with lonely children (odd number of participants)
        if(partial == 0 && driver->upperBound > lowerBound)
        {
            lowerBound = driver->upperBound;
            memcpy(bestAxis, driver->partialAxis, candidates*sizeof(int));
            memcpy(bestPref, driver->consistentPref, driver->upperBound*sizeof(int));
            /*the following code can be used to get a rough idea of how many participants can be covered after several iterations*/
            //printNode(driver, 1); cout<<endl; //#print
            //for(int i=0; i<driver->upperBound; i++) { distinctParticipants[bestPref[i]] = 1; }
            //leaves++;
        }
 
        //climb up the tree (if leaf or bounded node)
        driver = driver->parent;
        delete driver->children[driver->currentChild];
        driver->currentChild++;
    }
 
    //print results
    cout<<endl<<"Best ordering of candidates found: ";
    printAxis(bestAxis); cout<<"   "<<lowerBound<<endl;
    cout<<"Consistent participants "<<lowerBound<<endl;
    cout<<"prefs "; for(int x=0; x<lowerBound; x++) { cout<<bestPref[x]<<" "; } cout<<endl;
    /*the following code can be used to get a rough idea of how many participants can be covered after several iterations*/
    //cout<<"leaves traversed "<<leaves<<endl;
    //for(int i=0; i<participants; i++) { if (distinctParticipants[i] == 1) { totalc++; } }
    //cout<<"total distinct participants "<<totalc<<endl;
    /*the following code can be used to export all preference rankings excluding the ones consistent with the best axis found to stderr*/
//    int filterpos = 0;
//    int filter = bestPref[filterpos];
//    for(int i=0; i<participants; i++)
//    {
//        if(i != filter)
//        {
//            for(int j=0; j<candidates; j++)
//            {
//                cerr<<preferences[i][j]<<" ";
//            }
//            cerr<<endl;
//        }
//        else
//        {
//            if(filterpos < lowerBound-1)
//            {
//                filterpos++;
//                filter = bestPref[filterpos];
//            }
//        }
//    }
 
    //CPU time retrieval
    if(timecheck == 1)
    {
        end = clock();
        cputime = ((double)(end - start))/CLOCKS_PER_SEC;
        cout<<endl<<"Processing time: "<<cputime<<endl;
    }
 
    return 0;
}
 
//print usage
void printUsage()
{
    cout<<"Usage:"<<endl;
    cout<<"asprgen -a [arg] -i [arg] -c [arg] -k [arg] -v [arg] -t -h"<<endl;
    cout<<"-a: approximation"<<endl;
    cout<<"  [0] exact single-peaked consistency (no approximation)"<<endl;
    cout<<"  [1] k-local candidate deletion approximate sp consistency"<<endl;
    cout<<"-i: input profile"<<endl;
    cout<<"-c: number of candidates"<<endl;
    cout<<"-k: k parameter"<<endl;
    cout<<"-p: number of participants"<<endl;
    cout<<"-v: verbosity (nodes traversed)"<<endl;
    cout<<"-t: running time"<<endl;
    cout<<"-h: help"<<endl;
}
 
//print preferences
void printPref(int** preferences)
{
    for(int i=0; i<participants; i++)
    {
        for(int j=0; j<candidates; j++)
        {
            cout<<preferences[i][j]<<" ";
        }
        cout<<endl;
    }
}
 
//print axis
void printAxis(int* Axis)
{
    for(int j=0; j<candidates; j++)
    {
        cout<<Axis[j]<<" ";
    }
}
 
//print node info
void printNode(node* node, int vp)
{
    cout<<"upper bound "<<node->upperBound<<endl<<"partial axis ";
    printAxis(node->partialAxis);
    if(vp == 1)
    {
        cout<<"consistent prefs ";
        for(int i=0; i<node->upperBound; i++)
        {
            cout<<node->consistentPref[i]<<" ";
        }
        cout<<endl;
    }
}
 
//creates a node for a single child and returns pointer to it
node* lonelyChild(node* parent, int lastc)
{
    //setup
    int tempConsistent[parent->upperBound];
 
    //create child axis
    int* childaxis = new int[candidates];
    memcpy(childaxis, parent->partialAxis, candidates*sizeof(int));
    for(int j=0; j<candidates; j++)
    {
        if(parent->partialAxis[j] == 0)
        {
            childaxis[j] = lastc;
            break;
        }
    }
 
    //fill temporary array with consistent ids from parent array
    //no proof has been given, but commented code below provides the same result
    //int ublonely = 0;
    //for(int i=0; i<parent->upperBound; i++) { tempConsistent[ublonely] = parent->consistentPref[i]; ublonely++; }
    int ublonely = fillConsistent(childaxis, parent->consistentPref, parent->upperBound, tempConsistent, approx);
 
    //copy those ids to child's array
    int* childpref = new int[ublonely];
    memcpy(childpref, tempConsistent, ublonely*sizeof(int));
 
    //create the child
    node* child = new node(parent, ublonely, childpref, childaxis);
 
    return child;
}
 
//fill childArray with parentArray's ids that are consistent with axis, return num of ids transferred
int fillConsistent(int* childAxis, int* parentArray, int parentSize, int* childArray, int approxMethod)
{
    int ubConsistent = 0;
 
    //exact single-peaked consistency
    if(approxMethod == 0)
    {
        ubConsistent = exactCons(childAxis, parentArray, parentSize, childArray);
    }
    //k-local candidate deletion approximate single-peaked consistency
    else if(approxMethod == 1)
    {
        ubConsistent = localCandidateCons(childAxis, parentArray, parentSize, childArray);
    }
 
    return ubConsistent;
}
 
//fill Array with ids exactly single-peaked consistent
int exactCons(int* childAxis, int* parentArray, int parentSize, int* childArray)
{
    //setup
    int left, right, posleft, posright;
    int pospart, pospref, skip, checkval;
    int poschild = 0;
 
    //loop through parentArray's ids
    for(int i=0; i<parentSize; i++)
    {
        //initialization
        posleft = 0;
        posright = candidates-1;
        left = childAxis[posleft];
        right = childAxis[posright];
        pospart = parentArray[i];
        pospref = candidates-1;
        skip = 0;
 
        //check if lastpref is either left or right or undefined
        //(posleft <= posright) <=> (posleft < posright) because the last check is bound to be true
         while(pospref >= 0 &&  ((left != 0 || right != 0) || posleft <= posright))
        {
            checkval = preferences[pospart][pospref];
 
            //checkval is left
            if(checkval == left)
            {
                posleft++;
                left = childAxis[posleft];
                pospref--;
            }
            //checkval is right
            else if(checkval == right)
            {
                posright--;
                right = childAxis[posright];
                pospref--;
            }
            //checkval is undefined (left)
            else if(left == 0)
            {
                posleft++;
                left = childAxis[posleft];
                pospref--;
            }
            //checkval is undefined (right)
            else if(right == 0)
            {
                posright--;
                right = childAxis[posright];
                pospref--;
            }
            //the ranking is not consistent
            else
            {
                skip = 1;
                break;
            }
        }
 
        if(skip != 1)
        {
            //transfer id to child's array
            childArray[poschild] = pospart;
            poschild++;
 
        }
    }
 
    return poschild;
}
 
//fill Array with ids k-local candidate deletion approximate single-peaked consistent
int localCandidateCons(int* childAxis, int* parentArray, int parentSize, int* childArray)
{
    //setup
    int left, right, posleft, posright;
    int pospart, pospref, skip, checkval;
    int poschild = 0;
 
    int tempaxis[candidates];
    memcpy(tempaxis, childAxis, candidates*sizeof(int));
    int count = 0;
 
    //loop through parentArray's ids
    for(int i=0; i<parentSize; i++)
    {
        //axis reset
        if(count != 0)
        {
            memcpy(tempaxis, childAxis, candidates*sizeof(int));
            count = 0;
        }
 
        //initialization
        posleft = 0;
        posright = candidates-1;
        left = tempaxis[posleft];
        right = tempaxis[posright];
        pospart = parentArray[i];
        pospref = candidates-1;
        skip = 0;
 
        //check if lastpref is either left or right or undefined knowing that the axis can adapt k times
         while(pospref >= 0 &&  ((left != 0 || right != 0) || posleft < posright))
        {
            checkval = preferences[pospart][pospref];
 
            //checkval is left
            if(checkval == left)
            {
                posleft++;
                left = tempaxis[posleft];
                pospref--;
 
                //skip correction
                if(left == -1)
                {
                    posleft++;
                    left = tempaxis[posleft];
                }
            }
            //checkval is right
            else if(checkval == right)
            {
                posright--;
                right = tempaxis[posright];
                pospref--;
 
                //skip correction
                if(right == -1)
                {
                    posright--;
                    right = tempaxis[posright];
                }
            }
            //checkval is unplaced (left)
            else if(left == 0)
            {
                posleft++;
                left = tempaxis[posleft];
                pospref--;
 
                //skip correction
                if(left == -1)
                {
                    posleft++;
                    left = tempaxis[posleft];
                }
            }
            //checkval is unplaced (right)
            else if(right == 0)
            {
                posright--;
                right = tempaxis[posright];
                pospref--;
 
                //skip correction
                if(right == -1)
                {
                    posright--;
                    right = tempaxis[posright];
                }
            }
            else if(count < k)
            {
                //assign a skip value of -1 to the value of checkval if placed on the axis
                int placed = 0;
                for(int j=posleft+1; j<posright; j++)
                {
                    if(tempaxis[j] == checkval)
                    {
                        tempaxis[j] = -1;
                        placed = 1;
                    }
                }
                //assign a skip value of -1 to a placeholder of checkval if not placed on the axis
                if(placed == 0)
                {
                    for(int j=posleft+1; j<posright; j++)
                    {
                        if(tempaxis[j] == 0)
                        {
                            tempaxis[j] = -1;
                            break;
                        }
                    }
                }
 
                //update count and pospref
                count++;
                pospref--;
 
            }
            //the ranking is not consistent
            else
            {
                skip = 1;
                break;
            }
        }
 
        if(skip != 1)
        {
            //transfer id to child's array
            childArray[poschild] = pospart;
            poschild++;
        }
    }
 
    return poschild;
}