1

I have a list of rooms, times and students.

const students = ["a", "b", "c"];
const times = ["T1", "T2", "T3"];
const rooms = ["room1", "room2", "room3"];

Using the above data, I want to create a table like following. This will be arranged in such a way that every student will appear exam in every room in different time slots.

ROOM    T1  T2  T3
room1   a   b   c
room2   c   a   b
room3   b   c   a

I have the following function but it does not give me correct result.

const students = ["a", "b", "c"];
const times = ["T1", "T2", "T3"];
const rooms = ["room1", "room2", "room3"];

const newArr: any[] = [];
rooms.forEach((room, roomIndex) => {
  newArr.push({
    room: room
  });
  times.forEach((time, timeIndex) => {
    students.forEach(student => {
      const isExist = newArr.find(a => {
        const cond1 = a.room === room && a[time] === student;
        const keys = Object.keys(newArr[roomIndex]);
        const cond2 = keys.find(b => newArr[roomIndex][b] === student);
        const cond3 = newArr.find(a => a[time] === student);
        return cond1 || cond2 || cond3;
      });
      if (!isExist) {
        newArr[roomIndex][time] = student;
      }
    });
  });
});

Table rendered:

ROOM    T1  T2  T3
room1   c   b   a
room2   b   c   
room3   a       c

Stackblitz url - https://stackblitz.com/edit/angular-dynamic-table-example?file=src/app/table-basic-example.ts

Please help me on this.

1 Answer 1

1

You can try something like this:

const slots = [9, 10, 11, 12];
const students = ['a', 'b', 'c', 'd'];
const rooms = [1, 2, 3, 4]
// rooms 9  10  11  12
//.  1   a.  b  c.  d
//   2.  b   a. d.  c
//.  3.  c.  d. a.  b
//.  4.  d.  c. b   a

const allocations = [];

function allocate() {
  rooms.forEach(room => {
    slots.forEach(slot => {
      students.forEach(student => {
        const isExist = allocations.find(allocation => {
          return (allocation.room === room && allocation.student === student) 
          || (allocation.slot === slot && allocation.student === student) 
          || (allocation.slot === slot && allocation.room === room)
        });
        if (!isExist) {
          allocations.push({
            room,
            slot,
            student
          });
        }
      })
    })
  })
  return allocations;
}
console.table(allocate())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.