Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html><body>
 <textarea id='input' >
134: a[5] b[4] c[2] d[1] e[0] f[0]
64: a[5] b[4] c[3] d[1] e[0] f[0]
94: a[3] b[5] c[4] d[1] e[0] f[0]
70: a[2] b[2] c[5] d[2] e[0] f[0]
63: a[0] b[0] c[0] d[3] e[4] f[5]
55: a[0] b[0] c[1] d[3] e[5] f[4]
55: a[0] b[1] c[2] d[3] e[5] f[3]
48: a[0] b[0] c[1] d[3] e[5] f[5]
30: a[1] b[0] c[0] d[3] e[3] f[5]
30: a[0] b[1] c[2] d[5] e[5] f[4]
28: a[2] b[1] c[0] d[3] e[3] f[5]
27: a[0] b[0] c[0] d[3] e[5] f[5]
26: a[0] b[1] c[3] d[3] e[5] f[3]
22: a[1] b[0] c[0] d[3] e[4] f[5]
20: a[1] b[1] c[0] d[3] e[3] f[5]
4: a[1] b[3] c[5] d[2] e[2] f[0]
13: a[0] b[2] c[5] d[3] e[5] f[2]
13: a[0] b[0] c[0] d[3] e[3] f[5]
12: a[0] b[2] c[5] d[4] e[5] f[2]
6: a[0] b[0] c[1] d[3] e[5] f[5]
5: a[5] b[4] c[4] d[2] e[1] f[0]
4: a[1] b[0] c[0] d[3] e[5] f[5]
3: a[0] b[1] c[2] d[3] e[5] f[4]
3: a[1] b[0] c[0] d[3] e[4] f[5]
3: a[0] b[0] c[0] d[3] e[5] f[5]
3: a[5] b[5] c[5] d[2] e[0] f[0]
3: a[4] b[4] c[5] d[2] e[0] f[0]
3: a[5] b[5] c[3] d[1] e[0] f[0]
3: a[5] b[5] c[3] d[1] e[0] f[1]
2: a[5] b[4] c[4] d[2] e[0] f[0]
2: a[0] b[0] c[1] d[3] e[5] f[4]
2: a[4] b[5] c[4] d[1] e[1] f[0]
2: a[0] b[0] c[0] d[3] e[4] f[5]
2: a[2] b[3] c[5] d[2] e[0] f[1]
2: a[3] b[1] c[0] d[3] e[4] f[5]
2: a[1] b[1] c[0] d[3] e[3] f[5]
2: a[0] b[3] c[5] d[3] e[5] f[3]
2: a[4] b[5] c[5] d[2] e[1] f[0]
2: a[3] b[5] c[3] d[1] e[0] f[1]
2: a[0] b[1] c[1] d[3] e[4] f[5]
2: a[3] b[3] c[5] d[2] e[2] f[0]
2: a[0] b[1] c[1] d[3] e[5] f[5]
2: a[5] b[4] c[3] d[2] e[0] f[1]
2: a[0] b[2] c[3] d[3] e[5] f[3]
2: a[5] b[4] c[2] d[1] e[0] f[0]
2: a[3] b[4] c[5] d[2] e[0] f[0]
2: a[1] b[0] c[0] d[3] e[5] f[4]
2: a[0] b[0] c[1] d[4] e[5] f[5]
2: a[5] b[3] c[4] d[3] e[0] f[2]
a[1] b[0] c[3] d[4] e[4] f[5]
a[0] b[1] c[3] d[4] e[5] f[3]
a[0] b[1] c[2] d[4] e[5] f[2]
a[5] b[5] c[0] d[2] e[3] f[3]
a[5] b[3] c[0] d[5] e[5] f[5]
a[3] b[1] c[0] d[4] e[5] f[5]
a[4] b[3] c[5] d[3] e[1] f[0]
a[5] b[3] c[0] d[3] e[4] f[4]
a[4] b[5] c[4] d[1] e[0] f[0]
  </textarea>
 <textarea id='results'></textarea>
 <textarea id='blurred'></textarea>
  <div class='dialog'>
  <input type='text' id='numBlurred' value='25'></input>
 <button onclick='makeBlurred()'>make blurred</button><br><br>
 <button onclick='tabulate()'>tabulate</button>
  </div>
    <script>
    // easy ways to get and set the values of 
    // the textareas
    function getVal(id){
      return document.getElementById(id).value;
    };
    
     function setVal(id, value){
      document.getElementById(id).value = value;
    };
    
    
    function makeBlurred() { 
     var ballots = parseScoreBallots(getVal('input'));
      var candidates = getCandidateList(ballots);
      ballots = buildExpandedScoreBallotList(ballots, candidates);
      var blurredBallots = [ ];
      var numBlurredBallots = parseInt(getVal('numBlurred'));
      for(var i=0; i<numBlurredBallots; i++) {
        blurredBallots.push(makeBlurredBallot(ballots, (Math.random()*4)+2, 5));
      }

      setVal('blurred',
        condenseScoreBallots(blurredBallots).map(function(ballot) {
            return ballotToString(ballot, candidates);
          }).join('\n')
      );
    }  
      
   function tabulate() {
     var ballots = parseScoreBallots(getVal('input'));
     var blurred = parseScoreBallots(getVal('blurred'), true);
     var candidates = getCandidateList(ballots);
     ballots = buildExpandedScoreBallotList(ballots, candidates);
     blurred = buildExpandedScoreBallotList(blurred, candidates);

     for(var i=0; i<blurred.length; i++) {
       ballots.push(blurred[i]);
     }
     var roundCountCB = 1;
     
     var cbScores = tabulateCardinalBaldwin(ballots, candidates);
     // setVal('blurred',JSON.stringify(cbScores,0,1))
     
     setVal('results',  
       "****** processed " + ballots.length + " ballots ******\n" +
       " (" + (ballots.length-blurred.length) + " explicit and "  + 
        blurred.length + " blurred)\n" +

       "\n****** Pairwise wins ******\n" + 
       tabulateCondorcet(ballots, candidates).map(function(score){
          return score.name + ': ' + score.score;  
        }).join('\n') + 
            
       "\n****** Score ******\n" + 
       tabulateScore(ballots, candidates).map(function(score){
          return score.name + ': ' + score.score + ' (' +
            (score.score / ballots.length).toFixed(4) + ')';  
        }).join('\n') + 
            
    "\n****** Interpolated Median ******\n" + 
       tabulateIMedian(ballots, candidates).map(function(score){
          return score.name + ': ' + score.score.toFixed(4);  
        }).join('\n') + 
            
       "\n****** STAR ******\n" + 
       tabulateStar(ballots, candidates).round2.map(function(score){
          return score.name + ': ' + score.score;  
        }).join('\n') +        
       
       "\n****** Cardinal Baldwin ******\n" + 
        cbScores.map(function(scores){
         return '\n ***** round ' + roundCountCB++ + ' *****\n' +
           scores.map(function(score){
             return '    ' + score.name + ': ' + 
                (score.score / ballots.length).toFixed(4); 
          }).join('\n') }) +
       
       "\n****** STLR ******\n" + 
       tabulateStlr(ballots, candidates, 5).round2.map(function(score){
          return score.name + ': ' + score.score.toFixed(4);
        }).join('\n')       
       
       
       
     );
   }
  </script>
</body></html>
              
            
!

CSS

              
                input {
  background-color: white;
  color: black;
  width: 60px;
  display: inline-block;
}
button {
  width: 120px;
  display: inline-block;
}
.dialog {
  position: absolute;
  bottom: 20px;
  right: 30px;
  vertical-align: top;
  text-align: right;
  width: 100px;
}
textarea {
  width: 25%;
  background-color: black;
  color: #0f0;
  font-size: 15px;
  padding: 3px;
  box-shadow: 2px 2px 4px #000;
}

              
            
!

JS

              
                function ballotToString(ballot) {
  var s = '';
  if(ballot.count != undefined &&
     ballot.count != 1) {
    s += ballot.count + ': ';
  }

  if(ballot.ranks) {
    s += ballot.ranks.map(function(item) {
      return item.join('=');
    }).join('>');
    return s;
  }
  if(ballot.scores) {
    s += scoreBallotToString(ballot.scores);
    return s;
  }
   if(ballot.approvals) {
    s += ballot.approvals.join(',');
    return s;
  }
}

function scoreBallotToString(scores) {
  var a = [];
  for (var x in scores) {
    a.push ({n: x, v: scores[x]});
  }
  a.sort(function(x, y) {
      return x.n.localeCompare(y.n);
    });
  return a.map(function(item) {
      return item.n + '[' + item.v + ']';
    }).join(' ');
}

function preparseBallot(str) {
  var count = 0;
  var index = str.indexOf(':')
  if(index != -1) {
    var s = str.substring(0, index);
    var a = s.split(' ');
    for(var i=0; i<a.length; i++) {
      var f = parseFloat(a[i]);
      if(f != 0 && !isNaN(f)) {
        count = f;
      }
    }
    str = str.substring(index+1);
  }
  if(str.length == 0) {
    return {};
  }
  return (count > 1) ? {
    count: count,
    str: str
  } : {
    str: str
  };
}

function parseScoreBallot(ballot) {
  var str = ballot.str;
  var open = getIndices(str, '[');
  var close = getIndices(str, ']');
  if(open.length && open.length == close.length) {
    var scores = {};
    var pos = 0;
    for(var i=0; i<open.length; i++) {
      var f = parseFloat(cleanString(str.substring(open[i]+1, close[i])));
      var n = str.substring(pos, open[i]);
      pos = close[i] + 1;
      scores[cleanString(n)] = f;
    }
    ballot.scores = scores;
    delete ballot.str;
    return ballot;
  }
  return null;
}

function parseApprovalBallot(ballot) {
  var str = ballot.str;
  var approvals = [];
  var a = ballot.str.split(',');
  for(var i=0; i<a.length; i++) {
    var s = cleanString(a[i]);
    if(s.length) {
      approvals.push(s);
    }
  }
  if(approvals.length > 0) {
    ballot.approvals = approvals;
    delete ballot.str;
    return ballot;
  }
  return null;
}

//-------------------------------------
function parseRankedBallot(ballot) {
  var str = ballot.str;
  var greater = getIndices(str, '>');
  var equal = getIndices(str, '=');
  if(greater.length || equal.length) {
    var arr = [];
    var ranks = [];
    for(var i=0; i<greater.length; i++ ){
      arr.push(['>', greater[i]]);
    }
    for(var i=0; i<equal.length; i++ ){
      arr.push(['=', equal[i]]);
    }
    arr.sort(function(a,b){
        return a[1] - b[1];
      });

    var last = null;
    var index = 0, mode = '>';
    for(var i=0; i<arr.length+1; i++ ){
      var item = arr[i];
      var nextIndex = (item)?item[1]:undefined;
      var s = cleanString(str.substring(index, nextIndex));
      if(s.length) {
        if (mode == '=') {
          if(last) {
            last.push(s);
          }
        } else {
          last = [s];
          ranks.push(last);
        }
      }index = (nextIndex)?(nextIndex+1) : -1;
      mode = (item)?item[0]:1;
    }
    delete ballot.str;
    ballot.ranks = ranks;
  }
}

//-------------------------------------
function getIndices (str, c){
  var pos = 0, index, a = [];

  while((index = str.indexOf(c, pos)) != -1) {
    a.push(index);
    pos = index + 1;
  }
  return a;
}

function cleanString(str) {
  return str.split(' ').join('').split(',').join('').split('\n').join('');
}


// make new array where the ballots with a
// "count" are represented by that many ballots
// note: also create zero scores for any candidates
// mentioned in any ballot
function buildExpandedScoreBallotList (ballotList, candidates) {
  var list = [];

  for(var i=0; i<ballotList.length; i++) {
    var origVote = ballotList[i];
    if(origVote.scores) {
      var newVote = {};
      var count = origVote.count || 1;
      for(var j = 0; j<candidates.length; j++) {
        newVote[candidates[j]] = origVote.scores[candidates[j]] || 0;
      }
      for(var n=0; n<count; n++) {
        list.push(newVote);
      }
    }
  }
  return list;
}

function getCandidateList (ballotList) {
  var candidateArray = [], candidateHash = {};
  for(var i=0; i<ballotList.length; i++) {
    var ballot = ballotList[i];
    if(ballot.scores) {
      for(var j in ballot.scores) {
        if(!candidateHash[j]) {
          candidateArray.push(j);
          candidateHash[j] = true;
        }
      }
    }
  }
  candidateArray.sort();
  return candidateArray;
}

function condenseScoreBallots(ballots) {
  var hash = {};

  for(var i=0; i<ballots.length; i++) {
    var s = scoreBallotToString(ballots[i]);
    if(hash[s]) {
      hash[s]++;
    } else {
      hash[s] = 1;
    }
  }
  var array = [];
  for(var i in hash) {
    var b = {str: i};
    parseScoreBallot(b);
    b.count = hash[i];
    array.push(b);
  }
  array.sort(function(a,b) {
      return b.count - a.count;
    });

  return array;
}

function getSingleCBScore(cbOutput) {



  return 1;
}


function tabulateCardinalBaldwin(ballots, candidates, preNormalize) {
  var output = [];
  if(preNormalize) {
    ballots = ballots.map(function(b){
        return eliminateCandidateAndNormalize (b, null, 5);
      });
  }
  for(;;) {
    var scores = tabulateScore(ballots, candidates);
    output.push(scores); // save each round's results
    if(scores.length > 2) {
      // eliminate the lowest scoring candidate
      var eliminateName = scores[scores.length-1].name;
      candidates = candidates.filter(item => item !== eliminateName);
      ballots = ballots.map(function(b){
          return eliminateCandidateAndNormalize (b, eliminateName, 5);
        });
    } else {
      return output;
    }
  }
}

function tabulateScore(ballots, candidates) {
  var scores = [];
  for(var j=0; j<candidates.length; j++) {
    scores[j] = {
      name: candidates[j],
      score: 0
    };
  }
  for(var i=0; i<ballots.length; i++) {
    var ballot = ballots[i];
    for(var j=0; j<candidates.length; j++) {
      scores[j].score += ballot[candidates[j]] || 0;
    }
  }
  scores.sort(function(a, b){
    return b.score - a.score;
  });
  return scores;
}

function eliminateCandidateAndNormalize (b, elim, maxValue) {
  var out = {};
  var min = Number.MAX_VALUE, max = 0;

  for(var i in b) {
    if(i != elim){
      out[i] = b[i];
      if(out[i] < min) {
        min = out[i];
      }
      if(out[i] > max) {
        max = out[i];
      }
    }
  }
  if(min != max) {
    for(var i in out) {
      out[i] = (out[i]-min) * (maxValue/(max-min));
    }
    return out;
  } else {
    for(var i in out) {
      out[i] = 0;
    }
    return out;
  }
}

function tabulateStar(ballots, candidates) {
  var scores = tabulateScore(ballots, candidates);
  var s1 = scores[0], s2 = scores[1];
  var v1 = 0, v2 = 0;
  for(var i=0; i<ballots.length; i++) {
     var r1 = ballots[i][s1.name] || 0;
     var r2 = ballots[i][s2.name] || 0;
     if(r1 > r2) {
       v1++;
     } else if(r2 > r1) {
       v2++;
     }
  }
  var round2 = [
      {
       name: s1.name,
       score: v1
      },
      {
       name: s2.name,
       score: v2
      }
    ];
  round2.sort(function(a, b){
    return b.s - a.s;
  });
  return {
    round1: scores,
    round2: round2
  };
}

function tabulateCondorcet(ballots, candidates) {
  var scores = [];
  for(var j=0; j<candidates.length; j++) {
    scores[j] = {
      name: candidates[j],
      score: 0
    };
  }
  for(var j=0; j<candidates.length; j++) {
    for(var i=0; i<candidates.length; i++) {
      var res = compareTwoCandidates(candidates[i], candidates[j], ballots);
      if (res[1] > res[0]) {
        scores[j].score += 1;
      }
    }
  }
  scores.sort(function(a, b){
    return b.score - a.score;
  });
  return scores;
}

function tabulateStlr(ballots, candidates, maxVal) {
  var scores = tabulateScore(ballots, candidates);
  var s1 = scores[0], s2 = scores[1];
  var total1 = 0, total2 = 0;
  for(var i=0; i<ballots.length; i++) {
    var rating1 = ballots[i][s1.name] || 0;
    var rating2 = ballots[i][s2.name] || 0;
    if(rating1 > 0 || rating2 > 0) {
      var scaler = maxVal / ((rating1>rating2)?rating1:rating2);
      total1 += rating1 * scaler;
      total2 += rating2 * scaler;
     }
  }
  var round2 = [
      {
       name: s1.name,
       score: total1
      },
      {
       name: s2.name,
       score: total2
      }
    ];
  round2.sort(function(a, b){
    return b.score - a.score;
  });
  return {
    round1: scores,
    round2: round2
  };
}

function scoreBallotToSimpleString(ballot, candidates) {
  return candidates.map(function(c){
    return ballot[c] || 0;
  }).join(',');
}

function compareTwoCandidates (c1, c2, ballots) {
  var count1 = 0, count2 = 0, ties = 0;
  for(var i=0; i<ballots.length; i++) {
    var diff = ballots[i][c2] -  ballots[i][c1];
    if(diff > 0) {
      count2++;
    } else if (diff < 0){
      count1++;
    } else {
      ties++;
    }
  }
  return [count1, count2, ties];
}


function tabulateIMedian(ballots, candidates) {
  var scores = [];
  for(var j=0; j<candidates.length; j++) {
    scores[j] = {
      name: candidates[j],
      sc: new ScoreCollection(5)
    };
  }
  for(var i=0; i<ballots.length; i++) {
    var ballot = ballots[i];
    for(var j=0; j<candidates.length; j++) {
      scores[j].sc.addScore (ballot[candidates[j]] || 0);
    }
  }
  for(var i=0; i<scores.length; i++) {
    scores[i].score = scores[i].sc.getMedian(true);
  }
  scores.sort(function(a, b){
    return b.score - a.score;
  });
  return scores;
}


// for median
class ScoreCollection {

  constructor (max) {
    this.max = max;
    this.counts = [];
    for(var i=0;i<max+1; i++) {
      this.counts.push(0);
    }
    this.numScores = 0;
  }

  addScore(which) {
    which = Math.round(which);
    if(which < 0) {
      which = 0;
    }
    if(which > this.max) {
      which = this.max;
    }
    this.counts[which]++;
    this.numScores++;
  }

  getMedian(interpolate){
    var counts = this.counts;

    var half = this.numScores / 2;
    var min = 0, max;
    for(var i=0; i<this.counts.length; i++) {
      max = min + this.counts[i];
      if(min < half && half <= max) {
        if(interpolate) {
          return i + ((half-min)/(max-min)) - .5;
        } else {
          return i + ((max==half)?.5:0);
        }
      }
      min = max;
    }
    return null;
  }
}


// parse many of them
function parseScoreBallots  (string) {
  var a = string.split('\n');
  var ballots = [ ];
  for(var i=0; i<a.length; i++) {
   var b = preparseBallot(a[i]);
   if(b.str) {
     parseScoreBallot(b);
   }
   if(!b.str) {
     ballots.push(b);
   }
  }
  return ballots;
}


function getRandomBallot (list){
  return list[Math.floor(Math.random()*list.length)];
}

function makeBlurredBallot (list, num, maxValue) {
  var v, out = {};

  while(true) {
    var min = 999999999, max = 0;
    num = num || 1;

    for(var j=0; j<num; j++) {
      v = getRandomBallot(list);
      for(var i in v) {
        out[i] = (out[i]||0) + v[i];
      }
    }
    for(var i in v) {
      if(out[i] < min) {
        min = out[i]
      }
      if(out[i] > max) {
        max = out[i]
      }
    }

    if(min != max) {
      for(var i in v) {
        out[i] = Math.round((out[i]-min) * (maxValue/(max-min)));
      }
    return out;
    }
  }
}

              
            
!
999px

Console