JavaScript: calculating the complexity of the algorithm's time

I will begin by saying that, according to my understanding of the Code Review, this question is fine, since you are using a work code.

I am trying to calculate the time complexity of an algorithm using n in the code below.

I have a working solution for an encoding challenge to sort a stack using just another stack, and I have added a counter variable n which increases in any place where an element of the battery is pushed, busted or retained.


const sortStack = (stack) => {
  let n = 0;
  sorted = new Stack();
  while ( {
    tmp = stack.pop();
    n += 1;  
    if (tmp >= sorted.peek()) {
      n += 1;
    } else {
      while (tmp < sorted.peek()) {
        n += 1;
      n += 1;
  console.log("n: ", n);
  return sorted;

sortedStack = sortStack(s);

If my calculations and use of n are correct, then this algorithm has an input n of 6 (length of stack) with a final n of 30, which would give a time complexity of O (N * 5).

Is this correct?

mysql: problem when calculating the SQL count when the dates overlap

I am trying to consult a database with reservations. Each reservation has a Start date (Start), End date (End) and Type (type) and a month (month) is fed

I want to consult the DB to get the # of each type of reservation within a given month. However, for my life I can not make it only count reserves within a range of dates.

I already got him to give me recounts, by type, for all reservations. And also give me only reservations within the range of dates. But filtering for specific months and counting the type is proving difficult and Google has not taken me anywhere.

My current attempt:

// Check the database for reservations currently scheduled and account by type
DateTime today = DateTime.UtcNow;
DateTime firstDayOfMonth = new DateTime (today.Year, month, 1);
DateTime lastDayOfMonth = firstDayOfMonth.AddMonths (1) .AddDays (-1);
string query = $ "type SELECT," +
$ "SUM (CASE WHEN it starts> = & # 39; {firstDayOfMonth} & # 39; And begins <& # 39; {lastDayOfMonth} & # 39; THEN 1 ELSE 0 END) AS counts as" +
$ "FROM the reservation" +
$ "GROUP BY type";

Any guidance would be useful. How do I get it to only count what is in the range of dates?

javascript – calculating the value of two fields

I have to try to calculate the value of two sub-total fields with JavaScript. unfortunately, the application I am using to do this requires that the scripts be in line with the input fields. In the example code there are four input fields that I want the values ​​of ch3_training_days_benefit_total and ch3_bsme_total to be total in ch3_benefit_sub_total. I did not buy this software, but I'm the only one that stays with making it work.

0) document.getElementById ("ch3_training_days_benefit_total"). Focus (); if (this.form.ch3_training_days.value<=0) document.getElementById("ch3_training_days_benefit_total").focus();"/>

0) && (this.form.ch3_training_days.value<=4)) ch3_training_days_benefit_total.value = Number(this.form.ch3_training_days.value*10); else if(this.form.ch3_training_days.value>4) ch3_training_days_benefit_total.value = & # 39; 40 & # 39 ;; else if ((this.form.ch3_training_days.value<=0) || (this.form.ch3_training_days.value=='')) ch3_training_days_benefit_total.value = '0'; ch3_benefit_sub_total.value = ch3_training_days_benefit_total.value; document.getElementById('ch3_training_days_benefit_total').setAttribute('readonly', 'readonly');"/>

0) document.getElementById ("ch3_bsme_total"). Focus (); ">

0) ch3_bsme_total.value = & # 39; 10 & # 39 ;; ch3_benefit_sub_total.value = ch3_bsme_total.value; document.getElementById (& # 39; ch3_bsme_total & # 39;). setAttribute (& # 39; readonly & # 39 ;, & # 39; readonly & # 39;); "/>

calculating a shorter route in a table structure that changes in real time

I have a table like this

enter the description of the image here

In the NPC table, they are characters similar to AI that move from one point to another. Player – a character that is controlled by the user.

At any time the character of the player can move to any cell in the table. But NPC has a particular target cell that they must reach while they move. For example, the blue NPC needs to read the blue cell.

enter the description of the image here

Other NPCs are also moving. My goal is to write an algorithm that allows NPC to reach the cell using the shortest route. As I understand it, it's a typical problem with the shortest route.

My question is: is there an algorithm that is particularly optimized to handle such workflows, or will some algorithm suffice, just to recalculate the route after each movement?

Confused in calculating the shortest route using the Dijkstra algorithm

enter the description of the image here

I must find the shortest route using the Dijkstra algorithm. After making the calculations, do I get the following correct values ​​?:

A = 0
B = 13
C = 8
D = 20
E = 14
F = 25
G = 31
H = 38
I = 46
J = 52

Calculating x% faster than y?

I am working on an application as a small parallel project, I can handle the code without problems, but I can not understand some (quite basic) mathematics at this time.

So, I need a formula, please.

The easiest way I can illustrate my problem is to give an example:

A spell has a casting speed of 0.50 seconds, if I apply a throw time benefit of x%, what is its new velocity?

that is, its base launch time is 0.5s and currently its launch time is + 144%

Again, I need a general formula where I can connect the base times and the% increase in speed.

Thank you!

Directx: abnormal lighting when calculating in tangent space. Probably something wrong with the coordinate transformation matrix

I'm trying to calculate the lighting in the tangent space. But I'm still getting abnormal results. I was modifying the demo code of the book and I am amused if there is any problem with the transformation matrix that I created.

I'm having trouble solving a problem in Introduction to programming 3D games with DirectX 11. I tried to use the TBN matrix

Tx, Ty, Tz,
Bx, by, Bz,
Nx, Ny, Nz

according to the book provided, but I found that the light vector was erroneously transformed into tangent space and now I have no idea how to debug this shader.

Here is my Pixel Shader:

float4 PS1 (VertexOut pin,
uniform int gLightCount,
uniform bool gUseTexure,
bool uniform gAlphaClip,
uniform bool gFogEnabled,
uniform bool gReflectionEnabled): SV_Target {
// Normal interpolation can abnormalize it, so normalize it.
pin.NormalW = normalize (pin.NormalW);
pin.TangentW = normalize (pin.TangentW);

// The vector toEye is used in lighting.
float3 toEye = gEyePosW - pin.PosW;

// Caches the distance to the eye from this surface point.
float distToEye = length (toEye);

// Calculate normalMapSample
float3 normalMapSample =
normalize (SampledNormal2Normal (gNormalMap.Sample (samLinear, pin.Tex) .rgb));

// normalize to Eye
toEye = normalize (toEye);

// Default to the multiplicative identity.
float4 texColor = float4 (1, 1, 1, 1);
yes (gUseTexure)
// Show the texture.
texColor = gDiffuseMap.Sample (samLinear, pin.Tex);

yes (gAlphaClip)
// Discard pixel if texture is alpha < 0.1.  Note that we do this
        // test as soon as possible so that we can potentially exit the shader 
        // early, thereby skipping the rest of the shader code.
        clip(texColor.a - 0.1f);

// Lighting.

float4 litColor = texColor;
if (gLightCount > 0)
// Start with a sum of zero.
float4 ambient = float4 (0.0f, 0.0f, 0.0f, 0.0f);
diffused float4 = float4 (0.0f, 0.0f, 0.0f, 0.0f);
float4 spec = float4 (0.0f, 0.0f, 0.0f, 0.0f);

// Add the contribution of light from each light source.  
    for (int i = 0; i <gLightCount; ++ i)
float4 A, D, S;
ComputeDirectionalLightInTangent (gMaterial, gDirLights[i],
normalMapSample, World2TangentSpace (pin.NormalW, pin.TangentW, gTexTransform), toEye,
A, D, S);

environment + = A;
diffuse + = D;
spec + = S;

litColor = texColor * (ambient + diffuse) + spec;

if (gReflectionEnabled)
float3 incident = -toEye;
float3 reflectionVector = reflect (incident, normalMapSample);
float4 reflectionColor = gCubeMap.Sample (samLinear, reflectionVector);

litColor + = gMaterial.Reflect * reflectionColor;

// fogging

yes (gFogEnabled)
float fogLerp = saturate ((distToEye - gFogStart) / gFogRange);

// Mix the color of the fog and the color on.
litColor = lerp (litColor, gFogColor, fogLerp);

// Common to take alpha of diffuse material and texture.
litColor.a = gMaterial.Diffuse.a * texColor.a;

return litColor;

And here are the functions. SampledNormal2Normal, World2TangentSpace Y ComputeDirectionalLightInTangent:

float3 SampledNormal2Normal (float3 sampledNormal)
float3 normalT = 2.0f * sampledNormal - 1.0f;
return normalT;

float3x3 World2TangentSpace (float3 unitNormalW, float3 tangentW, float4x4 texTransform)
// Build orthonormal bases.
float3 N = unitNormalW;
float3 T = normalize (tangentW - point (tangentW, N) * N);
float3 B = cross (N, T);

float3x3 TBN = float3x3 (T, B, N);
/ * float3x3 invTBN = float3x3 (T.x, T.y, T.z, B.x, B.y, B.z, N.x, N.y, N.z);
returns invTBN; * /

float3 T_ = T - point (N, T) * N;
float3 B_ = B - point (N, B) * N - (point (T_, B) * T_) / point (T_, T_);
float3x3 invT_B_N = float3x3 (T_.x, T_.y, T_.z, B_.x, B_.y, B_.z, N.x, N.y, N.z);
returns invT_B_N;

void ComputeDirectionalLightInTangent (Material mat, DirectionalLight L,
float3 normalT, float3x3 toTS, float3 toEye,
outside float4 environment,
outside float4 diffuse,
outside float4 spec)
// Initialize outputs.
environment = float4 (0.0f, 0.0f, 0.0f, 0.0f);
diffuse = float4 (0.0f, 0.0f, 0.0f, 0.0f);
spec = float4 (0.0f, 0.0f, 0.0f, 0.0f);

// The light vector points in the opposite direction to the direction in which the light rays travel.
float3 lightVec = -L.Direction;
lightVec = mul (lightVec, toTS);
lightVec = normalize (lightVec);

// toEye to Tangent Space
toEye = mul (toEye, toTS);
toEye = normalize (toEye);

// Add environmental term.
ambient = mat.Ambient * L.Ambient;

// Add fuzzy and specular term, provided the surface is in
// The line of light site.

float diffuseFactor = dot (lightVec, normalT);

// Flatten to avoid dynamic branching.
if (diffuseFactor> 0.0f)
float3 v = mirror (-lightVec, normalT);
float specFactor = pow (max (point (v, toEye), 0.0f), mat.Specular.w);

diffuse = diffuse Factor * mat.Diffuse * L.Diffuse;
spec = specFactor * mat.Specular * L.Specular;

The result I got seems to be much darker in most places and too bright in several highlighted areas. I wonder if someone can help me with my code or give me advice on how to debug a hlsl shader. Thank you!

rdbms: Where is MySQL delaying reading or calculating the disk?

From the SQl case study

The system configuration is

Software: Percona 5.6.15-63.0. Hardware: Supermicro; X8DTG-D; 48G of RAM; 24xIntel (R) Xeon (R) CPU L5639 @ 2.13GHz, 1xSSD unit (250G)

Consultation is select yeard, count (*) of ontime group by yeard where yeard is the indexed column

The query is simple, however, you will have to scan 150M rows. Here are the results of the query (in cache):
The query took 54 seconds and used only 1 CPU core.

As I understand it: according to my calculation, it should have finished in much less time based on the shared configuration of the previous system and the data to scan.
I know I'm wrong and I'm missing something, but what is that?

Here is my calculation by seconds

  1. For HDD, the average time it takes to read 100 MB of data from the disk is approximately 1 sec. For SSD it is 5 to 10X faster. But still conservatively if I assume the speed of
    100MB per second, the time to read the data will be Size of the data in MB / 100. seconds . Based on this data size is 150 * 10 ^ 6 * 4/10 ^ 6 = 600 MB
    Assuming that each year is 4 bytes long. So the total time to read the data from the disk should be 600/100 = 6 seconds

  2. It is now a 2.13 GHz CPU, which means 2 billion cycles per second, which on average means 2 billion instructions per second per core. Now current
    The time required to execute the query was 54 seconds, which means that the time needed to calculate the instruction was approximately 54-6 = 48 seconds. Does it mean that it has to be executed around? 48 * 2 = 96 billion instructions just to calculate
    The count (group per year) or do I lack something?

Can you spend more time reading or counting the disk seems simple but internally involves a number of instructions?

informix – calculating the elapsed time

The following code compares recv.rcpt_dtim (which is a type of date and time) with the current date / time. Calculate an elapsed time that results in hours and minutes formatted as: "04:22". It took me a while to get it up and running, which it is, but it seems careless. Does anyone have any advice to clean it?

TRIM ((((CURRENT YEAR TO SECOND - recv.rcpt_dtim) :: INTERVAL SECOND (9) to
SECOND) / 3600) :: VARCHAR (12) || & # 39;: & # 39; || CASE WHEN (MOD (MOD (((CURRENT YEAR TO
MINUTE - recv.rcpt_dtim) :: INTERVAL MINUTE (9) a
MINUTE) :: VARCHAR (12) :: INT, 60), 60)) <10 THEN "0" MORE "" FINAL ||
to MINUTE) :: VARCHAR (12) :: INT, 60), 60)) :: VARCHAR (12))

database design – Stroring vs Calculating Aggregate Values ​​in DyanmoDb

I have a table of the format:

shipperId, date, city, account

In this shipperId is PrimaryKey and Date is rangeKey.

Currently we have specific queries from the sender, so the above scheme serves us well.

However, we now have a request to report data at a city date level. We will need to read this information at a very low frequency. [2-3 times a day]. I see the following solutions to this:

  1. Scan the entire table and then add at the city level. [Highly inefficient approach].

  2. Have another table of the format. [city, date, count] and make use of dynamo flows to update this. Maybe this is not real time but it works for us.

Is there any standard practice for such use cases?