skip to Main Content

I’m really stuck on this task; i’m still learning JavaScript objects so not my ideal question:

We need to figure out how many tables we need! The number of guests
may not divide evenly by the number of seats, so we will have to add
some extra chairs to a few of the tables for them.

The function calculateTables takes two arguments, the number of guests
and the number of seats around a table.

It should return an object with two properties: a key of tables with
the value of the number tables, and a key of remainingGuests with a
value of the number of guests without a seat who will need to be added
to one of the other tables.

Example log we shoudl try:

calculateTables(4, 2);
// should return { tables: 2 , remainingGuests: 0 }

calculateTables(14, 6);
// should return { tables: 2 , remainingGuests: 2 }

calculateTables(26, 5);
// should return { tables: 5 , remainingGuests: 1 }

My code so far and i’m so stuck…..not sure where to go in solving this question. Any advice will be good:

function calculateTables(guests, seats) {
    // Your code goes here...
    
    let tables = 0;
    let remainingGuests = 0;

 for(let i=0; i<guests.length; i++){
if(guests % seats == 0){
tables = guests[i]

}

 }
    
    let obj ={'tables': tables, 'remainingGuests': remainingGuests}

    return obj
    }

2

Answers


  1. You can use this code, i think it’s accurate to your expected result.

    function calculateTables (guests, seats) {
        // Define Variable
        let tables = 0;
        let remainingGuests = 0;
        
        // First Validation is guests and seats must greater than 0
        if(guests > 0 && seats > 0) {
            // Check if total guests are greater than or equal from seats
            if(guests >= seats) {
               // Divide guests by seats
               let devideGuests = guests/seats;
        
               // Floor your devided calculation for total tables
               tables = Math.floor(devideGuests);
        
               // Multiply your calculated tables by seat before subtracting it to total guest
               const seatedGuests = tables * seats;
               remainingGuests = guests - seatedGuests;
            } else {
               //If seats are greater
               tables = guests;
            }
        }
        
        // Return your expected object
        return {
            tables,
            remainingGuests
        }
    }
    
    Login or Signup to reply.
  2. Am I overlooking something? This is just straight up division and modulo. The only catch I can see is that JS doesn’t have integer division, so you need to floor:

    function calculateTables(guests, seats) {
        return { 
            tables: Math.floor(guests / seats),
            remaingingGuests: guests % seats
        };
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search