从随机列表中选择并减少下一个选择的结果

时间:2013-04-03 11:57:34

标签: google-apps-script google-spreadsheet-api

我想要完成的是从A列中的人员列表中随机挑选,但是一旦他们被挑选,他们应该从列表中删除。这个想法是创建一个名单,每周随机选择一个人 - 但是一旦他们被挑选就移除该人(并在0时重新创建数组)

Example

Paul
David
John
Matt

通过运行随机(A1:A4),我可能会选择David作为我的选择,但是下次我运行该函数时,Array会再次从A1:A4构建 - 因此David不会被删除。

我尝试添加第二列来跟踪选择,然后从数组中删除它们,但是我只能从数组中删除1个值而不保留已完成的操作

Example

List of Users      Tracking        Result (print all values)
Paul                               John   David,Paul,Matt
David              John            David  Paul,Matt
John               David           Matt   Paul,John
Matt               Matt            David  Paul,John

虽然结果不是所有值,但我包含了所有值以显示我遇到的逻辑问题。在跟踪列中,我留下了第一个空白,以便跟踪字段中的值是我从结果中得到的值(结果通常只得到1个值)..所以B2 = C1

我能否就如何做到这一点获得一些指示。 (谷歌应用程式脚本)

对于那些要求代码的人来说,这是

function random(a,b) {
  var listPeople = new Array();
  for (var i = 0; i < a.length; i++) {
    var row = a[i];
    for (var j = 0; j < row.length; j++) {
      var value = row[j];
      if (value) {
        listPeople.push(value); 
      }
    }
  }
//deleting someone
  var trackPeople = listPeople.slice(0);
  for (var i = 0; i < trackPeople.length; i++) {
    if (trackPeople[i] == b) {
      trackPeople.splice(i,1);
    }
  } 
// Returning a persons name
  if (trackPeople.length > 0) {
    var pick = Math.floor(Math.random() * trackPeople.length);
    return trackPeople[pick];
  }
}

1 个答案:

答案 0 :(得分:2)

我已经使用你的一些代码拼凑了下面的内容。它期望一个带有空白列A的电子表格;在单元格B1中输入随机选择的名称,并将耗尽的列表重写回Col A.

function pickAPerson(){
  var ss = SpreadsheetApp.openById("your_spreadsheet_id_here").getSheets()[0];
  var completeList = [["Paul"],["David"],["John"],["Matt"]]; //this list can be as long as necessary // you could also get this list from another spreadsheet range, for example
  var currentList = [];
  var columnWithNames = "A"; // expects: start in row 1; no empty cells 
  try{var populatedRange = getPopulatedRange(ss,columnWithNames); currentList = populatedRange.getValues(); populatedRange.clear()}
  catch (e) {currentList = completeList; Logger.log(e)} //if the ss list is exhausted, currentList will be filled from the completList array
  var randomIndex = Math.floor(Math.random() * currentList.length);
  var theChosenOne = currentList.splice(randomIndex,1)
  if(currentList.length>0)
  ss.getRange(1,1,currentList.length,1).setValues(currentList);
  ss.getRange("B1").setValue(theChosenOne)
}

function getPopulatedRange(ss,column) { //Returns the range in a single column from row 1 to the last populated cell in that column
  var lastRow = ss.getMaxRows();
  var values = ss.getRange(column + "1:" + column + lastRow).getValues();
  for (; values[lastRow - 1] == "" && lastRow > 0; lastRow--) {}
  return ss.getRange(column  + "1:" + column + lastRow);
}