Instantly share code, notes, and snippets.

@almet /code.gs Secret
Created Feb 25, 2018

Embed
What would you like to do?
Répartition des montants - commande groupement d'achats
/**
* Code par Rémy Hubscher et Fredéric Sureau.
**/
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Groupement d\'achats').addItem('Répartir les montants', 'dispatch').addToUi();
}
function has_values() {
for (var i in arguments) {
for (var j in arguments[i]) {
if (arguments[i][j] > 0.01) {
return true;
}
}
}
return false;
}
function max_index(array) {
var maximum = 0;
for (var i in array) {
if (array[i] > array[maximum]) {
maximum = i;
}
}
return parseInt(maximum);
}
function dispatch() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Répartition chèques");
var clients = sheet.getRange("E4:4").getValues()[0];
var providers_values = sheet.getRange("D5:D").getValues();
var providers = [];
for (var i in providers_values) {
providers[i] = providers_values[i][0];
}
var amounts = sheet.getRange(5, 5, providers.length, clients.length);
while (has_values(clients, providers)) {
var client = max_index(clients);
var provider = max_index(providers);
var amount_client = clients[client];
var amount_provider = providers[provider];
if (amount_client < amount_provider) {
clients[client] = 0;
providers[provider] -= amount_client;
amounts.getCell(provider+1, client+1).setValue(amount_client);
}
else {
providers[provider] = 0;
clients[client] -= amount_provider;
amounts.getCell(provider+1, client+1).setValue(amount_provider);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment