Say I have a list of elements of type

{name, direction, time}

where direction can be in or out and represent the time the person name has entered or leaved a meeting. The list is sorted by the time of the event.

I would like to build a list of elements of type

{number-of-people, time-interval}

where number-of-people is 0 at the beginning and is incremented by 1 if someone enters or decremented if leaves. time-interval is the time between events.

I could build the list like this

list2 = {};
numberOfPeople = 0;
prevTime = list1[[1,3]];
  {name, direction, time} = list1[[i]];
  numberOfPeople += If[direction === in, 1, -1];
  AppendTo[list2, {numberOfPeople, time-prevTime}];
  prevTime = time,
  {i, 2, Length[list1]}

but I am pretty sure that there are far better and concise ways.

  • $\begingroup$ Lookup MovingMap. Something like MovingMap[func, list1, 1], where func returns {n, dt}. $\endgroup$
    – Michael E2
    Apr 3, 2021 at 21:59
  • $\begingroup$ @MichaelE2: I tried but I don't seem to understand how to use it $\endgroup$
    – enzotib
    Apr 4, 2021 at 8:51

1 Answer 1

dates = Sort[RandomSample[With[{first = Now}, 
     DateRange[first, DatePlus[first, Quantity[1000, "Minutes"]], "Minutes"]], 20] ];

events = RandomChoice[{3, 1} -> {"in", "out"}, 20];

names = RandomWord["Noun", 20];

data = Transpose[{names, events, dates}];

Grid @ data

enter image description here

Prepend dates with an initial date and use Differencesto get durations.

time0 = Now - Quantity[10, "Minutes"];
durations = Differences[Prepend[time0]@data[[All, 3]]];

Replace "in" with with 1 and "out" with -1 in the second column of data and use Accumulate to get numberofpeople:

numberofpeople = Accumulate[data[[All, 2]] /. {"in" -> 1, "out" -> -1}];

Add the new columns to data:

newdata = Join[data, List /@ numberofpeople, List /@ durations, 2];

Grid @ newdata

enter image description here

  • $\begingroup$ Thank you, I only need to know about Accumulate and Differences, there are so many functions that sometimes you don't find what you're looking for $\endgroup$
    – enzotib
    Apr 4, 2021 at 8:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.