Custom calendar with event divs - javascript

I am working on an event system which is basically a container with 720px height with each pixel representing one minute from 9AM to 9PM and has width of 620px (10px padding from left and right)
The natural requirement for the calendar system is that:
The objects should be laid out so that they do not visually overlap.
If there is one event in a time slot, its width will be 600px
Every colliding event must be the same width as every other event that it collides width.
An event should use the maximum width possible while still adhering to the first constraint.
The input will be an array something like:
[
{id : 1, start : 30, end : 150}, // an event from 9:30am to 11:30am
{id : 2, start : 540, end : 600}, // an event from 6pm to 7pm
{id : 3, start : 560, end : 620}, // an event from 6:20pm to 7:20pm
{id : 4, start : 610, end : 670} // an event from 7:10pm to 8:10pm
]
I have created the needed layout but I am stuck with JavaScript part :( This is what I have so far:
var Calendar = function() {
var layOutDay = function(events) {
var eventsLength = events.length;
if (! eventsLength) return false;
// sort events
events.sort(function(a, b){return a.start - b.start;});
for (var i = 0; i < eventsLength; i++) {
// not sure what is next
}
};
return {
layOutDay : layOutDay,
}
}();
Need to create divs and position them as per above requirements.
Please see JSBin demo.
Any help will be greatly appreciated.

Here is a working solution: http://jsbin.com/igujil/13/edit#preview
As you can see, it's not an easy problem to solve. Let me walk you through how I did it.
The first step, labelled Step 0, is to make sure the events are sorted by id. This will make our lives easier when we start playing with the data.
Step 1 is to initialize a 2-dimensional array of timeslots. For each minute in the calendar, we're going to make an array which will contain the events that take place during that minute. We do that in...
Step 2! You'll note I added a check to make sure the event starts before it ends. A little defensive, but my algorithm would hit an infinite loop on bad data, so I want to make sure the events make sense.
At the end of this loop, our timeslot array will look like this:
0: []
1: []
...
30: [1]
31: [1]
...
(skipping ahead to some interesting numbers)
540: [2]
560: [2,3]
610: [3,4]
I encourage you to add console.log(timeslots) just before Step 3 if you're confused/curious. This is a very important piece of the solution, and the next step is a lot more difficult to explain.
Step 3 is where we resolve scheduling conflicts. Each event needs to know two things:
The maximum number of times it conflicts.
Its horizontal ordering (so that conflicts don't overlap).
(1) is easy because of how our data is stored; the width of each timeslot's array is the number of events. Timeslot 30, for example, has only 1 event, because Event #1 is the only one at that time. At Timeslot 560, however, we have two events, so each event (#2 and #3) gets a count of two. (And if there was a row with three events, they would all get a count of three, etc.)
(2) is a little more subtle. Event #1 is obvious enough, because it can span the entire width of the calendar. Event #2 will have to shrink its width, but it can still start along the left edge. Event #3 can't.
We solve this with a per-timeslot variable I called next_hindex. It starts at 0, because by default we want to position along the left edge, but it will increase each time we find a conflict. That way, the next event (the next piece of our conflict) will start at the next horizontal position.
Step 4 is quite a bit more straightforward. The width calculation uses our max-conflict count from Step 3. If we know we have 2 events at 5:50, for example, we know each event has to be 1/2 the width of the calendar. (If we had 3 events, each would be 1/3, etc.) The x-position is calculated similarly; we're multiplying by the hindex because we want to offset by the width of (number of conflict) events.
Finally, we just create a little DOM, position our event divs, and set a random colour so they're easy to tell apart. The result is (I think) what you were looking for.
If you have any questions, I'd be happy to answer. I know this is probably more code (and more complexity) than you were expecting, but it was a surprisingly complicated problem to solve :)

Here is my solution: # one-day
A one day calendar
Requirements
Part I: Write a function to lay out a series of events on the calendar for a single day.
Events will be placed in a container. The top of the container represents 9am and the bottom represents 9pm.
The width of the container will be 620px (10px padding on the left and right) and the height will be 720px (1 pixel for every minute between 9am and 9pm). The objects should be laid out so that they do not visually overlap. If there is only one event at a given time slot, its width should be 600px.
There are 2 major constraints:
1. Every colliding event must be the same width as every other event that it collides width.
2. An event should use the maximum width possible while still adhering to the first constraint.
See below image for an example.
The input to the function will be an array of event objects with the start and end times of the event. Example (JS):
[
{id : 1, start : 60, end : 120}, // an event from 10am to 11am
{id : 2, start : 100, end : 240}, // an event from 10:40am to 1pm
{id : 3, start : 700, end : 720} // an event from 8:40pm to 9pm
]
The function should return an array of event objects that have the left and top positions set (relative to the top left of the container), in addition to the id, start, and end time.
Part II: Use your function from Part I to create a web page that is styled just like the example image below.
with the following calendar events:
An event that starts at 9:30 am and ends at 11:30 am
An event that starts at 6:00 pm and ends at 7:00pm
An event that starts at 6:20pm and ends at 7:20pm
An event that starts at 7:10pm pm and ends at 8:10 pm
Code
Installation & Running
Clone this repo
Open the index.html file in your favourite browser.
Note: at startup there is a default set of events (required in the second part).
For testing, right below the default array (line 14), you can find generateEvents function which generates random array of events. The array size will be determined by the arrayLength attribute.
Dependencies
none!
Solution
Below you can find the algorithm to solve the problem according to requirements.
Introduction
I will try to address this task in manner of graphs, so few terms should be given.
Terms
Node: represents an event - $n$, $n \in N, N$ - group of all nodes.
Edge: represents colliding events - $e$, $e \in E, E$ - group of all edges. For example, if node $u$ and $v$ collide then there will be an edge $e_{u,v}$ connecting them.
Graph: the collection of nodes and edges $G, G\in(N,E)$ .
Cluster: represents a group of connected nodes ( sub group of the Graph) - $c$, $c \subseteq G$ . For example, if we have the following nodes: $u, v, w$ and edge $e_{u,v}$. Then there will be 2 clusters, the first will contain $u,v$ and the second will contain only $w$.
Clique: represents sub group of nodes in a cluster, each pair of nodes in this group has a connecting edge - $cq$, $cq \subseteq c$. Note, a clique represents a group of colliding events.
Board: The day container which holds all the events.
Terms example
For the following input:
[
{id : 1, start : 0, end : 120},
{id : 2, start : 60, end : 120},
{id : 3, start : 60, end : 180},
{id : 4, start : 150, end : 240},
{id : 5, start : 200, end : 240},
{id : 6, start : 300, end : 420},
{id : 7, start : 360, end : 420},
{id : 8, start : 300, end : 720}
]
The graph will be:
Black cycle - node - event
Green ellipse - clique - group of colliding events
Red ellipse - cluster - group of connected nodes
Blue line - edge - connector between colliding events
Note: the top left green ellipse is the biggest clique in the left cluster.
The board will be:
Red rectangle - cluster
Colored dots - clique (each color is a different clique).
Constraint paraphrase
Each node in the same cluster must have the same width on the board, in order to meet the first constraint.
Nodes must not overlap each other on the board while starching to maximum width and still adhering to the first constraint.
The width of nodes in a cluster will be set by the biggest clique in the cluster. This is true because, nodes in the same clique will share at least one minute on the board, meaning that they will have to have the same width (because they are colliding). So other nodes in the cluster will have the same width as the smallest node.
Each node in a clique will gain its X axis position relative to its neighbours.
Algorithm
For given array of events arrayOfEvents (from the requirements example):
[
{id : 1, start : 60, end : 120}, // an event from 10am to 11am
{id : 2, start : 100, end : 240}, // an event from 10:40am to 1pm
{id : 3, start : 700, end : 720} // an event from 8:40pm to 9pm
]
Step One: creating events histogram.
An Array of arrays will be created, lets call this array as histogram. The histogram length will be 720, each index of the histogram will represent a minute on the board (day).
Lets call each index of the histogram a minute. Each minute, is an array itself. Each index of the minute array represents an event which takes place at this minute.
pseudo code:
histogram = new Array(720);
forEach minute in histogram:
minute = new Array();
forEach event in arrayOfEvents:
forEach minute inBetween event.start and endMinute:
histogram[minute].push(event.id);
histogram array will look like this after this step (for given example):
[
1: [],
2: [],
.
.
.
59: [],
60: [1],
61: [1],
.
.
.
99: [1],
100: [1,2],
101: [1,2],
.
.
.
120: [1,2],
121: [2],
122: [2],
.
.
.
240: [2],
241: [],
242: [],
.
.
.
699: [],
700: [3],
701: [3],
.
.
.
720: [3]
]
Step Two: creating the graph
In this step the graph will be created, including nodes, node neighbours and clusters also the biggest clique of the cluster will be determined.
Note that there won't be an edge entity, each node will hold a map of nodes (key: node id, value: node) which it collides with (its neighbours). This map will be called neighbours. Also, a maxCliqueSize attribute will be added to each node. The maxCliqueSize is the biggest clique the node is part of.
pseudo code:
nodesMap := Map<nodeId, node>;
graph := Object<clusters, nodesMap>;
Node := Object<nodeId, start, end, neighbours, cluster, position, biggestCliqueSize>;
Cluster := Object<mapOfNodesInCluster, width>
//creating the nodes
forEach event in arrayOfEvents {
node = new Node(event.id, event.start, event.end, new Map<nodeId, node>, null)
nodeMap[node.nodeId] = node;
}
//creating the clusters
cluster = null;
forEach minute in histogram {
if(minute.length > 0) {
cluster = cluster || new Cluster(new Array(), 0);
forEach eventId in minute {
if(eventId not in cluster.nodes) {
cluster.nodes[eventId] = nodeMap[eventId];
nodeMap[eventId].cluster = cluster;
}
}
} else {
if(cluster != null) {
graph.clusters.push(cluster);
}
cluster = null;
}
}
//adding edges to nodes and finding biggest clique for each node
forEach minute in histogram {
forEach sourceEventId in minute {
sourceNode = eventsMap[sourceEventId];
sourceNode.biggestCliqueSize = Math.max(sourceNode.biggestCliqueSize, minute.length);
forEach targetEventId in minute {
if(sourceEventId != targetEventId) {
sourceNode.neighbours[targetEventId] = eventsMap[targetEventId];
}
}
}
}
Step Three: calculating the width of each cluster.
As mentioned above, the width of all nodes in the cluster will be determined by the size of the biggest clique in the cluster.
The width of each node $n$ in cluster $c$ will follow this equation:
$$n_{width} = \frac{Board_{width}}{Max\left ( n_{1}.biggestCliqueSize, n_{2}.biggestCliqueSize, ..., n_{n}.biggestCliqueSize\right )}$$
Each node width will be set in the cluster its related to. So the width property will be set on the cluster entity.
pseudo code:
forEach cluster in graph.clusters {
maxCliqueSize = 1;
forEach node in cluster.nodes {
maxCliqueSize = Max(node.biggestCliqueSize, sizeOf(node.clique);
}
cluster.width = BOARD_WIDTH / maxCliqueSize;
cluster.biggestCliqueSize = biggestCliqueSize;
}
Step Four: calculating the node position within its clique.
As already mentioned, nodes will have to share the X axis (the "real-estate") with its neighbours. In this step X axis position will be given for each node according to its neighbours. The biggest clique in the cluster will determine the amount of available places.
pseudo code:
forEach node in nodesMap {
positionArray = new Array(node.cluster.biggestCliqueSize);
forEach cliqueNode in node.clique {
if(cliqueNode.position != null) {
//marking occupied indexes
positionArray[cliqueNode.position] = true;
}
}
forEach index in positionArray {
if(!positionArray[index]) {
node.position = index;
break;
}
}
}
Step Five: Putting nodes on the board.
In this step we already have all the information we need to place an event (node) on its position on the board. The position and size of each node will be determined by:
height: node.end - node.start
width: node.cluster.width
top-offset: node.start
left-offset: node.cluster.width * node.position + left-padding
Algorithm Complexity
The time complexity of the algorithm is $O\left(n^{2} \right )$.
The space complexity of the algorithm is $O\left (n \right )$.
Github repo: https://github.com/vlio20/one-day

if you want to roll your own then use following code:
DEMO: http://jsfiddle.net/CBnJY/11/
var Calendar = function() {
var layOutDay = function(events) {
var eventsLength = events.length;
if (!eventsLength) return false;
// sort events
events.sort(function(a, b) {
return a.start - b.start;
});
$(".timeSlot").each(function(index, val) {
var CurSlot = $(this);
var SlotID = CurSlot.prop("SlotID");
var EventHeight = CurSlot.height() - 1;
//alert(SlotID);
//get events and add to calendar
var CurrEvent = [];
for (var i = 0; i < eventsLength; i++) {
// not sure what is next
if ((events[i].start <= SlotID) && (SlotID < events[i].end)) {
CurrEvent.push(events[i]);
}
}
var EventTable = $('<table style="border:1px dashed purple;width:100%"><tr></tr></table');
for (var x = 0; x < CurrEvent.length; x++) {
var newEvt = $('<td></td>');
newEvt.html(CurrEvent[x].start+"-"+CurrEvent[x].end);
newEvt.addClass("timeEvent");
newEvt.css("width", (100/CurrEvent.length)+"%");
newEvt.css("height", EventHeight);
newEvt.prop("id", CurrEvent[x].id);
newEvt.appendTo(EventTable.find("tr"));
}
EventTable.appendTo(CurSlot);
});
};
return {
layOutDay: layOutDay
}
}();
var events = [
{
id: 1,
start: 30,
end: 150},
{
id: 2,
start: 180,
end: 240},
{
id: 3,
start: 180,
end: 240}];
$(document).ready(function() {
var SlotId = 0;
$(".slot").each(function(index, val) {
var newDiv = $('<div></div>');
newDiv.prop("SlotID", SlotId)
//newDiv.html(SlotId);
newDiv.height($(this).height()+2);
newDiv.addClass("timeSlot");
newDiv.appendTo($("#calander"));
SlotId = SlotId + 30;
});
// call now
Calendar.layOutDay(events);
});
I strongly recommend to use http://arshaw.com/fullcalendar/
demo: http://jsfiddle.net/jGG34/2/
whatever you are trying to achieve is already implemented in this, just enable the day mode and do some css hacks.. thats it!!

If I understand you correctly, the input is a list of events with start and end times, and the output is, for each event, the column number of that event and the total number of columns during that event. You basically need to color an interval graph; here's some pseudocode.
For each event e, make two "instants" (start, e) and (end, e) pointing back to e.
Sort these instants by time, with end instants appearing before simultaneous start instants.
Initialize an empty list component, an empty list column_stack, a number num_columns = 0, and a number num_active = 0. component contains all of the events that will be assigned the same number of columns. column_stack remembers which columns are free.
Scan the instants in order. If it's a start instant for an event e, then we need to assign e a column. Get this column by popping column_stack if it's nonempty; otherwise, assign a new column (number num_columns) and increment num_columns (other order for 1-based indexing instead of 0-based). Append e to component. Increment num_active. If it's an end instant, then push e's assigned column onto column_stack. Decrement num_active. If num_active is now 0, then we begin a new connected component by popping all events from component and setting their total number of columns to num_columns, followed by clearing column_stack and resetting num_columns to 0.

I would approach the problem as follows.
A divider is any moment within a day that no event crosses. So if you have one event from 9 am to 11 am and another from 11 am to 1 pm, and no other events, there is a divider at 11 am, and at any time at 1 pm or later, and at any time at 9 am or earlier.
I would divide every day into a set of "eventful time spans" that are maximum time spans containing no dividers. For every eventful time span, I would calculate the maximum number of concurrently overlapping events, and use that as the "column number" for that event span. I would then layout every eventful time span greedily on the calculated number of columns so that every event would be laid out as left as possible, in the order of the starting times of the events.
So, for example the following schedule:
A 9 am - 11 am
B 10 am - 12 pm
C 10 am - 1 pm
D 1 pm - 2 pm
E 2 pm - 5 pm
F 3 pm - 4 pm
would be processed as follows. The eventful time spans are 9 am - 1 pm, 1 pm - 2 pm, and 2 pm - 5 pm as there are dividers at 1 pm and 2 pm (no event crosses those times).
On the first span, there are maximum three overlapping events, on the second only one, and on the third, two.
The columns are allocated like this:
9 am - 10 am | | | |
10 am - 11 am | | | |
11 am - 12 pm | | | |
12 pm - 1 pm | | | |___ end of first e.t.s.
1 pm - 2 pm | |___ end of second e.t.s.
2 pm - 3 pm | | |
3 pm - 4 pm | | |
4 pm - 5 pm | | |
After which the events are filled in, in their chronological order greedily:
9 am - 10 am | A |###|###|
10 am - 11 am |_A_| B | C |
11 am - 12 pm |###|_B_| C |
12 pm - 1 pm |###|###|_C_|
1 pm - 2 pm |_____D_____|
2 pm - 3 pm | E |#####|
3 pm - 4 pm | E |__F__|
4 pm - 5 pm |__E__|#####|
which looks very reasonable. # denotes free space

The keypoint is to count all the Collision from your appointments. There is a pretty simple algorithm to do so:
sort the appointment array appointments according to start-date and breaking ties with end-date.
maintain an array active with all active appointments, which is empty in the beginning
maintain a value collision for each appointment (since you already have objects, you could store it as another property) [{id : 1, start : 30, end : 150, collisions : 0},...]
iterate through appointments with the following steps:
shift the first item (i) from appointments
compare start-date from i with enddates from all items j in active - remove all items where j.enddate < i.startdate
update collisions from all remaining j (+1 for each)
update collision of i ( i.collision = active.length)
pop i into array active
repeat these steps for all items of appointments.
Example:
(beware, pseudo-code) :
var unsorted = [7,9],[2,8],[1,3],[2,5],[10,12]
// var appointments = sort(unsorted);
var appointments = [1,3],[2,5],[2,8],[7,9],[10,12]
// now for all items of appoitments:
for (var x = 0; x<appointments.length;x++){
var i = appointments[x]; // step 1
for (var j=0; j<active.length;j++){
// remove j if j.enddate < j.startdate // step 2
// else j.collision += 1; // step 3
}
i.collision = active.length; // step 4
active.pop(i); // step 5
}
If you collect the items removed from active, you get an array, sorted by end-dates before startdates, which you can use for displaying the divs.
Now, try out if you can get the code to make it work and write a comment if you need further help.

Related

Finding n-gram frequencies in a large set of sentences

I have a set of text messages. Lets call them m1, m2, ..... The maximum number of message is below 1,000,000. Each message is below 1024 characters in length, and all are in lowercase. Lets also pick an n-gram s1.
I need to find frequency of all possible substring from all of these messages. For example, lets say we have only two messages:
m1 = a cat in a cage
m2 = a bird in a cage
The frequency of some n-gram in these two messages:
'a' = 4
'in a cage' = 2
'a bird' = 1
'a cat' = 1
...
Note that, as in = 2, in a = 2, and a cage = 2 are subsets of in a cage = 2 and have same frequency, they should not be listed. Only take the longest one that have the highest frequency; follow this condition: the longest sn-gram should consist of at most 8 words, with a total character count below 30. If a n-gram exceeds this limit, it can be broken into two or more n-grams and listed separately.
I need to find such n-grams for all of these text messages and sort them by their number of occurrences in descending order.
How to I approach this problem? I need a solution in javascript.
PS: I need help, but do not know to where to ask this. If the question
is not for this site, then where should I post it? please guide this
newbie here.
May be you can approach as follows. I will edit to add explanation as soon as i have some time.
var subSentences = (w,...ws) => ws.length ? ws.reduce((r,s) => (r.push(r[r.length-1] + ` ${s}`), r),[w])
.concat(subSentences(...ws))
: [w],
frequencyMap = sss => sss.reduce((map,ss) => subSentences(...ss.split(/\s+/)).reduce((m,s) => m.set(s, m.get(s) + 1 || 1), map), new Map());
frequencies = frequencyMap(["this is a test string",
"this is another one",
"yet another one is here"]);
console.log(...frequencies.entries()); // logging map object seems not possible hence entries
.as-console-wrapper { max-height : 100% !important
}

Javascript number interval search optimization

As topic says i ran into optimization problem when it comes to a large amount of intervals
Variables: FirstPrice, LastPrice, Increment and the number that user writes
Task: Need to round number to one side or another in specific interval.
Example:
FirstPrice = 0.99, LastPrice = 9.99, Increment = 1 User number = 5.35
Workflow:
I need to find interval in which one number exists, and what i could think of is to push numbers into array. So for this example array would be:
["0.99","1.99","2.99","3.99","4.99","5.99","6.99","7.99","8.99","9.99"].
Then i use for loop to find in which interval (in this case number = 5.35) number exists. In this case interval would be from 4.99 to 5.99. And then user number is updating to 4.99 or 5.99.
Problem:
It works fine doing that with low amount of numbers. But it comes really hard to execute high ranges. E.g. if FirstPrice = 1 LastPrice = 1000000 and Increment = 1. Then my array gets thousands of values and it takes way too long to push every value into array and find the number. Array gets ~999999 values and then loop goes through all of them to find specific interval.
So i think my problem is clear. The optimization. I need a better way of doing this. I tried cutting price range to half and a half but then intervals are wrong. Tried working with the inserted number but the same problem occurred.
Correct me if I'm wrong, but isn't this simply:
lower = floor((q - s) / i) * i + s
upper = lower + i
where:
q = User number
s = FirstPrice
i = Increment
function foo(q, s, i) {
const lower = Math.floor((q - s) / i) * i + s;
const upper = lower + i;
return [lower, upper];
}
console.log(
foo(5.35, 0.99, 1),
foo(5.35, 0.99, 2),
foo(5.35, 0.99, 3)
);

Math: Pallet Packing (not quite the bin-packing situation)

I'm currently working on some private project on my spare time, and I've been stuck on a particular math problem.
I know that bin packing is a NP-HARD problem, but that's not exactly the problem I'm facing here.
What I must do is to calculate the number of pallets I would need to fit the given number of boxes, however the layout (of first/base level) is defined in advance. For me, the problem is that I have to take the box weight, pallet max weight, box height and pallet max height into consideration. In one moment it sounds like an elementary school math, but then I suddenly get lost with too many if and else statements.
The following is what I have:
Pallet (width, depth, max. height, max. weight)
Box ( total number of boxes, width, depth, height, weight)
Now, as I mentioned, the easy part is that I already know in advance how many boxes can I fit on a first layer. But then, I get lost because I'm trying to check too many things.
In example, the pallet can reach it's max weight before the max height is filled (and vice versa). Another (improbable but possible) scenario, the total number of boxes (if small enough) can be fitted on a single pallet without reaching the pallet's max height/weight.
In the end, I need to know the number of fully loaded pallets and if any boxes left for the last (partially filled) pallet.
I'm currently working in javascript. I'd be grateful if anyone can help me with with this, at least with some pseudo code that I can convert.
If you're willing to give it a shot, here are some numbers you can run your algorithm against:
Box Values:
+-----------+-----------+------------+------------+--------------------+-------------------+
| Width(cm) | Depth(cm) | Height(cm) | Weight(kg) | Fits(single layer) | Total (number of) |
+-----------+-----------+------------+------------+--------------------+-------------------+
| 32.5 | 24 | 22 | 14.7 | 9 | 111 |
+-----------+-----------+------------+------------+--------------------+-------------------+
Pallet Values:
+-----------+-----------+----------------+----------------+
| Width(cm) | Depth(cm) | Max.Height(cm) | Max.Weight(cm) |
+-----------+-----------+----------------+----------------+
| 120 | 80 | 145 | 725 |
+-----------+-----------+----------------+----------------+
EDIT:
I apologize for being unclear. I was lost in my own calculations. I updated the given values.
Also, I forgot to mention that the pallets are loaded to fill max in both weight and height. So, there can also be a partially filled layer on top (in case that max height isn't filled with previous layers and one more filled layer would go over allowed max weight).
OK, here is the code that I think embodies what meowgoesthedog meant:
function fillPallets(totalBoxNumber, boxHeight, boxWeight, boxesPerLayer, palletMaxHeight, palletMaxWeight) {
let maxBoxesByHeight = Math.floor(palletMaxHeight / boxHeight) * boxesPerLayer;
let maxBoxesByWeight = Math.floor(palletMaxWeight / boxWeight);
let maxBoxesPerPallet = Math.min(maxBoxesByHeight, maxBoxesByWeight);
let fullPalletsCount = Math.floor(totalBoxNumber / maxBoxesPerPallet);
let palletsCount = Math.ceil(totalBoxNumber / maxBoxesPerPallet);
let lastPalletBoxes = totalBoxNumber - fullPalletsCount * maxBoxesPerPallet;
let buildPallet = function (number) {
let palletLayers = [];
for (let rest = number; rest > 0; rest -= boxesPerLayer) {
palletLayers.push(Math.min(rest, boxesPerLayer))
}
return palletLayers;
}
let pallets = [];
let fullPallet = buildPallet(maxBoxesPerPallet);
for (let i = 0; i < fullPalletsCount; i++) {
pallets.push(fullPallet);
}
if (lastPalletBoxes > 0)
pallets.push(buildPallet(lastPalletBoxes));
return {
count: palletsCount,
palletsLayouts: pallets
}
}
Usage example
fillPallets(111,22,14.7,9,145,725)
produces following output
{
"count": 3,
"palletsLayouts": [[9, 9, 9, 9, 9, 4], [9, 9, 9, 9, 9, 4], [9, 4]]
}
The idea behind this code is that you want to calculate maxBoxesPerPallet and there are only two independent restrictions on that: either height or weight. So you calculate maxBoxesByHeight and maxBoxesByWeight first, then you get maxBoxesPerPallet, then you get the number of pallets (most of them will be "full" i.e. contain exactly maxBoxesPerPallet and there might be one last for the rest).

ThreeJS Molecules - Double Bonds

Working with threejs, I am trying to use the following example:
http://threejs.org/examples/#css3d_molecules
The problem is that in that example, the bonds from the grey to the red balls are supposed to be double bonds. I have found a few links that suggest how this is done, but it doesn't seem supported by threejs. Here is what I was talking about:
https://www.umass.edu/microbio/rasmol/faq_em.htm#doublebonds
There you can see the fumerate molecule (it is a text file) and how they structured it. Any tips on how to add a double bond either visually, or by changing the class of the line so I can change the size or color?
In the function loadMolecule, there is a loader.load function, some lines from it are pasted below, this is where you would add a second bond next to the first. You'd offset the start and end positions by some vector amount and draw another one.
for ( var i = 0; i < geometryBonds.vertices.length; i += 2 ) {
var start = geometryBonds.vertices[ i ];
var end = geometryBonds.vertices[ i + 1 ];
start.multiplyScalar( 75 );
end.multiplyScalar( 75 );
tmpVec1.subVectors( end, start );
var bondLength = tmpVec1.length() - 50;
}

Javascript record keystroke timings

I want to record the time between each keystroke (just one key to start with, the 'A' key) in millseconds.
After the user finishes his thing he can submit and check out the timings between each key stroke. Like:
1: 500
2: 300
3: 400
4: 500
5: 100
6: 50
7: 50
8: 25
I believe this is possible with Javascript, is it?
Sure:
var times = [];
// add an object with keycode and timestamp
$(document).keyup(function(evt) {
times.push({"timestamp":evt.timeStamp,
"keycode":evt.which})
});
// call this to get the string
function reportTimes() {
var reportString = "";
for(var i = 0; i < times.length - 1; ++i) {
reportString += (i+1) + ": " + (times[i+1].timestamp - times[i].timestamp) + " ";
}
return reportString; // add this somewhere or alert it
}
I added the keycode just in case you wanted it later; it's not necessary for your exact problem statement.
Clarification from comments discussion:
The for loop only goes to up to times.length - 2 (since i is always strictly less than times.length - 1), so there is no issue about times[i+1] being outside the bounds of the array. For example, if you do five key presses and therefore have a times array with five elements (indexed from 0 to 4):
1st pass: times[1].timestamp - times[0].timestamp
2nd pass: times[2].timestamp - times[1].timestamp
3rd pass: times[3].timestamp - times[2].timestamp
4th pass: times[4].timestamp - times[3].timestamp
Then the loop terminates, because setting i to 4 triggers the termination condition:
= i < times.length - 1
= 4 < 5 - 1
= 4 < 4
= false [i cannot be set to 4 by this loop]
Thus, times[i+1] is always a validly indexed element, because i is at most one less than the maximum index.

Categories

Resources