【问题标题】:Navigating the columns and rows in pasting array values在粘贴数组值中导航列和行
【发布时间】:2016-10-07 07:48:34
【问题描述】:

我正在尝试从 A 列获取名称列表,将列表随机化,然后按用户指定的组数均匀分布(尽可能多地,包括除法的余数)。

我需要的一个例子是这样的:

名称列表:A、B、C、D、E、F、G、H、I、J、K

3组结果:

  • 第 1 组:D、A、F
  • 第 2 组:B、H、G、K
  • 第 3 组:E、C、I、J

已编辑:我已经清理了代码:我已将名称列表分配给一个空数组并成功随机化该数组。现在我必须弄清楚如何将这些值粘贴到每个组的自己的列中。如何将值粘贴到每列的右侧和下方,同时考虑余数(第一个值是每列的标题):

  • C 列:第 1、D、A、F 组
  • D 列:第 2 组、B、H、G、K
  • E 列:第 3 组、E、C、I、J

这是我目前所拥有的:

function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
  .createMenu('Custom Menu')
  .addItem('Show prompt', 'showPrompt')
  .addToUi();
}

function SortNames() {
var ui = SpreadsheetApp.getUi();

var result = ui.prompt(
  'How many groups?',
  ui.ButtonSet.OK_CANCEL);

// Process the user's response.
var button = result.getSelectedButton();
var groupquantity = result.getResponseText();
if (button == ui.Button.OK) {
// User clicked "OK"  - Need to clear the cells from the previous sorting in this step

// Get the last row number of the names list
var Avals = SpreadsheetApp.getActiveSheet().getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;

// Set an empty Array
var ar = [];

/****** In its original order, append the names to the array *****/
for (var i = 2; i < Alast+1; i++) {

  var source = 'A' + i;
  var Avals = SpreadsheetApp.getActiveSheet().getRange(source).getValues();
  ar.push(Avals);
}
/***************************/

/****** Shuffle the array    *****/
function shuffle(a) {
  var j, x, i;
  for (i = a.length; i; i--) {
    j = Math.floor(Math.random() * i);
    x = a[i - 1];
    a[i - 1] = a[j];
    a[j] = x;
  }
}

shuffle(ar);
/***************************/


/****** Calculates the rounded down # of members per group    *****/
var memberspergroup = ar.length / groupquantity;
var memberspergroup = Math.floor(memberspergroup);
/*********************************/



/****** Copy and Paste the rounded down number of members to each groups until 
the remainder is 0, then distribute evenly with remaining number of groups    *****/

// First Cell location to paste
var pasteloc = "C1";
for (var i = 1; i <= groupquantity; i++) {

  SpreadsheetApp.getActiveSheet().getRange(pasteloc).setValue('Group ' + i);
  var source = 'A' + i;
  var Avals = SpreadsheetApp.getActiveSheet().getRange(source).getValues();
}
/*********************************/



} 

else if (button == ui.Button.CANCEL) {
// User clicked "Cancel".
ui.alert('The request has been cancelled');
} 
else if (button == ui.Button.CLOSE) {
// User clicked X in the title bar.
ui.alert('You closed the dialog.');
}

}

【问题讨论】:

  • this 有帮助吗?

标签: javascript for-loop google-apps-script google-sheets rows


【解决方案1】:

我找到了我的问题的解决方案。它不是最佳状态 - 它可以使用改进来解决名称列表中的空单元格。但是,它可以正常运行,并且可以满足我的所有需求:

  • 它分配数组中的名称列表
  • 随机化数组
  • 考虑余数的情况下完全均匀分布(就像我上面提供的示例)

    function onOpen() {
      SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Custom Menu')
      .addItem('Show prompt', 'showPrompt')
      .addToUi();
    /******closing function onOpen()*********************/
    }
    
    function SortNames() {
      var ui = SpreadsheetApp.getUi();
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
    
      var result = ui.prompt(
        'How many groups?',
      ui.ButtonSet.OK_CANCEL);
    
      // Process the user's response.
      var button = result.getSelectedButton();
      var groupquantity = result.getResponseText();
      if (button == ui.Button.OK) {
      // User clicked "OK"
    
      // Get the last row number of the names list
      var Avalues = sheet.getRange("A1:A").getValues();
      var Alast = Avalues.filter(String).length;
    
        if(groupquantity > 0 && groupquantity <= Alast)
        {
        // User inputted a valid group quantity  - Need to clear the cells from the previous sorting in this step
       var lastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
       sheet.getRange('C1:Z'+lastRow).clearContent();
    
       // Set an empty Array
       var ar = [];
    
       /****** In its original order, append the names to the array *****/
       for (var i = 2; i < Alast+1; i++) {
    
       var source = 'A' + i;
       var Avals = sheet.getRange(source).getValues();
    
       ar.push(Avals);
    
       }
       /***************************/
    
       /****** Shuffles array    *****/
       function shuffle(a) {
         var j, x, i;
         for (i = a.length; i; i--) {
           j = Math.floor(Math.random() * i);
           x = a[i - 1];
           a[i - 1] = a[j];
           a[j] = x;
         }
       /**********closing function shuffle(a)*****************/
       }
    
       shuffle(ar);
    
       /****** Calculates the rounded down # of members per group    *****/
       var memberspergroup = Math.floor(ar.length / groupquantity);
       /*********************************/  
    
    
       /****** Main Goal: Copy and Paste the rounded down number of members to each groups until 
       the remainder is 0, then distribute evenly with remaining number of groups    *****/
       // 1. Define the first Cell location to paste
       var pasteloc = "C1";
    
       // 2. Begin a for-loop: Navigate Horizontally across from the first cell location
       for (var i = 1; i <= groupquantity; i++)
         {
    
           // 3. Set the Column Headings in the current column, i
           sheet.getRange(1,i+2).setValue('Group ' + i);
    
           /************** 4. Fill in the Rows of names for each groups **********/
           // List out the values in array "ar" by the expected group qty, until the remainder is zero
    
           if ((ar.length)%(groupquantity-(i-1)) > 0)
           {
             for (var rows = 2; rows <= memberspergroup+1; rows++)
             {
               var j = 0;
               sheet.getRange(rows,i+2).setValue(ar[j]);
               var index = ar.indexOf(ar[j]);
                ar.splice(index, 1);
             }
    
            }
            else
            {
              var memberspergroup = ar.length/(groupquantity-(i-1))
              for (var rows = 2; rows <= memberspergroup+1; rows++)
              {
               var j = 0;
               sheet.getRange(rows,i+2).setValue(ar[j]);
               var index = ar.indexOf(ar[j]);
               ar.splice(index, 1);
              }
            }
    
         }
       /*********************************/
    
    }
       /*****************closing if(groupquantity > 0 && groupquantity <= Alast)****************/
    
    else{
     ui.alert("Error: " + '"' + groupquantity + '"' +" is not a proper group quantity")
    }
    
    
    
    
       }
    
      else if (button == ui.Button.CANCEL) {
      // User clicked "Cancel".
       }
    else if (button == ui.Button.CLOSE) {
    // User clicked X in the title bar.
     }
    
    
    }
    

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-26
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多