Skip to content

Instantly share code, notes, and snippets.

@pen
Created February 7, 2015 18:43
Show Gist options
  • Save pen/a49f71e31429bef662e6 to your computer and use it in GitHub Desktop.
Save pen/a49f71e31429bef662e6 to your computer and use it in GitHub Desktop.
Google Spreadsheetで、名前付き範囲"members"の中の、空白でないセルの文字列をランダムに入れ替える。ランチ会の組み合わせを決めるとき等に。
function onclick() {
var lock = LockService.getDocumentLock();
if (lock.tryLock(10)) {
shuffle_members();
lock.releaseLock();
}
}
function shuffle_members() {
var range = SpreadsheetApp.getActiveSheet().getRange("members");
var values = range.getValues();
var colors = range.getFontColors();
var pos = [];
var cell = [];
for (var y = 0; y < values.length; ++y) {
for (x = 0; x < values[y].length; ++x) {
var v = values[y][x];
if (v) {
pos.push({ x:x, y:y });
cell.push({ v:v, c:colors[y][x] });
}
}
}
var n = pos.length;
while (n > 0) {
var i = Math.floor(Math.random() * n--);
var t = pos[i];
pos[i] = pos[n];
pos[n] = t;
}
for (var i = 0; i < pos.length; ++i) {
var x = pos[i].x;
var y = pos[i].y;
values[y][x] = cell[i].v;
colors[y][x] = cell[i].c;
}
range.setValues(values);
range.setFontColors(colors);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment