Tengo una cantidad de ingredientes y debo saber la cantidad máxima de sándwiches (sándwiches grandes y pequeños) que puedo hacer con él. Si quedan ingredientes, el resultado debe ser falso.
Mi código funciona si todos los ingredientes se pueden usar solo con sándwiches pequeños o con un máximo de un sándwich grande. También devuelve falso si quedan ingredientes. Sin embargo, devuelve falso si necesitamos más de un sándwich grande para usar todos los ingredientes.
var result = [] var ispossible = function(tomatoes, cheese) { /* we need in any case an even number of tomatoes slices */ if (tomatoes % 2 === 0) { /* the easiest way is making as many small sandwiches as possible. The minimum number of big sandwiches is the number of cheese slices remaining when we devise the total number by 2 */ var bigSandwich = cheese % 2 var smallSandwichTomatoes = (tomatoes - 4 * bigSandwich) / 2 var smallSandwich = cheese - bigSandwich console.log("we need" + smallSandwich + "small sandwiches and " + bigSandwich + "big sandwiches") } else { console.log("false, all the ingredients cannot be used") } } ispossible(10, 3)Suponiendo que esta solución ayude a otros lectores a mejorar su algoritmo rudimentario, habilidades de programación:
const bigSmallSandwiches = (t = 10, c = 5) => ( t % 2 !== 0 || t / c !== 2 ? 'false, all the ingredients cannot be used' : 'we need ' + Math.floor((t - Math.floor(t / 4) * 4) / 2).toString() + ' small sandwiches and ' + Math.floor(t / 4).toString() + ' big sandwiches' );Explicación
Fragmento de código:
const bigSmallSandwiches = (t = 10, c = 5) => ( t % 2 !== 0 || t / c !== 2 ? 'false, all the ingredients cannot be used' : 'we need ' + Math.floor((t - Math.floor(t / 4) * 4) / 2).toString() + ' small sandwiches and ' + Math.floor(t / 4).toString() + ' big sandwiches' ); [ [20, 10], [8, 4], [4, 3], [14, 7] ].forEach(x => console.log('tomatoes: ' + x[0] + '\tcheese slices ' + x[1] + '\n' + bigSmallSandwiches(x[0], x[1])));