0
我試圖從列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.');
}
}
請問[此](http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript)有幫助嗎? –