Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- РЕШЕНИЯ С WHILE:
- function cake(input) {
- let index = 2;
- let width = Number(input[0]);
- let length = Number(input[1]);
- let cakePieces = width * length;
- let command = input[index];
- while (command !== "STOP") {
- cakePieces -= Number(command);
- if (cakePieces <= 0) {
- break;
- }
- index++;
- command = input[index];
- }
- if (cakePieces >= 0) {
- console.log(`${cakePieces} pieces are left.`);
- } else {
- console.log(`No more cake left! You need ${Math.abs(cakePieces)} pieces more.`);
- }
- }
- Или леко тарикатската:)
- function cake(input) {
- let index = 2;
- let cakePieces = Number(input[0]) * Number(input[1]);
- while (input[index] !== "STOP" && cakePieces > 0) {
- cakePieces -= Number(input[index++]);
- }
- if (cakePieces >= 0) {
- console.log(`${cakePieces} pieces are left.`);
- } else {
- console.log(`No more cake left! You need ${Math.abs(cakePieces)} pieces more.`);
- }
- }
- Решение със shift() и тернарен оператор:
- function cake(input) {
- let cakePieces = Number(input.shift()) * Number(input.shift());
- while (input[0] !== "STOP" && cakePieces > 0) {
- cakePieces -= Number(input.shift());
- }
- console.log(cakePieces >= 0 ? `${cakePieces} pieces are left.` :
- `No more cake left! You need ${Math.abs(cakePieces)} pieces more.`);
- }
- РЕШЕНИЯ С FOR:
- function cake(input) {
- let width = Number(input[0]);
- let length = Number(input[1]);
- let cakePieces = width * length;
- for (let i = 2; i < input.length; i++) {
- let command = input[i];
- if (command === "STOP") {
- break;
- }
- cakePieces -= Number(command);
- if (cakePieces <= 0) {
- break;
- }
- }
- if (cakePieces >= 0) {
- console.log(`${cakePieces} pieces are left.`);
- } else {
- console.log(`No more cake left! You need ${Math.abs(cakePieces)} pieces more.`);
- }
- }
- Или леко тарикатската и с тернарен оператор:)
- function cake(input) {
- let cakePieces = Number(input[0]) * Number(input[1]);
- for (let i = 2; i < input.length; i++) {
- if (input[i] === "STOP" || cakePieces < 0) {
- break;
- }
- cakePieces -= Number(input[i]);
- }
- console.log(cakePieces >= 0 ? `${cakePieces} pieces are left.` :
- `No more cake left! You need ${Math.abs(cakePieces)} pieces more.`);
- }
- РЕШЕНИЕ С МЕТОДИ И ТЕРНАРЕН ОПЕРАТОР:
- function cake(input) {
- let cakePieces = Number(input.shift()) * Number(input.shift()) -
- input.slice(0, input.includes("STOP") ? -1 : input.length).map(Number).reduce((a, b) => a + b);
- console.log(cakePieces >= 0 ? `${cakePieces} pieces are left.` :
- `No more cake left! You need ${Math.abs(cakePieces)} pieces more.`);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement