algorithms – How to check if \$x\$ equals a certain value \$y\$ with while loops, addition and substraction

Consider, we are only allowed to use loops ($$while$$), addition ($$+$$), substraction ($$-$$) and checking if a value is $$> 0$$. How can one find out, if a certain variable $$x$$ equals a value $$y$$? E.g. how can I find out if $$x=4$$ by only using the aforementioned methods? For $$x=0$$ I came up with the following:

``````y = 1
while x > 0:
y = y - 1
x = x - 1
while y > 0:
do something
``````

This way, $$something$$ gets only executed if $$x=0$$. But I have no clue about values above $$0$$.

graphics – I have some assembly code that makes the screen fade out on my MS-DOS game. It works, but it loops continuously

I am making a game with C and assembly for MS-DOS (I am planning to distribute the game with DOSBox or my own modification thereof). I large portions of the graphics code are in assembly, which is a language I am weaker in, but I saw it as something that was convenient to use due to its ability to change things to such a nitty-gritty level (down to things like the graphical palette and such).

However, I am basing my code off of a fade out function that I found from some old source code that was in 16 bit assembly, and I am trying to convert it to 32 bit assembly.

I got the code to work, but however, it keeps looping repeatedly instead of continuing the code.

``````AFObeg  equ (bp+4)
AFOcnt  equ (bp+4+2)

push    ebx
push    ecx
push    edx
mov ebp,esp
push    ds
push    esi
push    edi

push    ds        ; get data segment into es
pop es
mov edx, offset _WorkPalette
push    edx       ; save offset of opal
xor ebx, ebx
mov ecx, 100h
mov eax, 1017h    ; bios read dac registers function
int 10h       ; read the palette registers into opal
pop edi       ; offset of opal, was in dx!
mov eax, AFObeg   ; get offset of first palette byte to
mov ebx, 3        ; be processed
mul ebx
mov eax, AFOcnt   ; find the number of bytes to be processed
mov ebx, 3
mul ebx       ; leave it in ax
mov ecx, 64       ; 64 passes through fade loop
push    ecx       ; save the fade loop counter
push    edi       ; save offset of first byte processed in
mov bl, cl        ; we'll use the pass number as a threshold
mov ecx, eax          ; load number of bytes to process into cx
o_pal_cmp_loop:
cmp bl, es:(edi)      ; start decrementing when palette value
jnz o_no_dec      ; is equal loop count (it will stay equal
dec BYTE PTR es:(edi)  ; to loop count for the rest of this pass)
o_no_dec:
inc edi
loop    o_pal_cmp_loop      ; do the next byte

mov ebx, esp            ; need the stack pointer for a moment
mov di, ss:(ebx)        ; restore offset into pal without popping
mov ecx, AFOcnt     ; number of triplets to process
push    eax         ; need to use ax for port i/o

mov edx, 03DAh      ; CRT controller input status 1 register
o_vbi_1:
in al, dx           ; watch vertical blanking bit
test al,08h         ; wait for it to clear to make sure
jnz o_vbi_1         ; we're not in a blanking interval
o_vbi_2:
in al, dx           ; now wait for the start of the
test al,08h         ; next blanking interval
jz o_vbi_2

mov ah, AFObeg ; get first register to process into ah
mov dx, 03c8h       ; DAC palette index register
mov al, ah          ; get next palette number to write
out dx, al          ; write the register number to the dac
inc dx          ; address dac data register
mov al, BYTE PTR es:(di) ; get first byte of triplet
out dx, al           ; write it to the dac data register
inc edi          ; point to second byte
mov al, BYTE PTR es:(di) ; get second byte of triplet
out dx, al           ; write it to the dac data register
inc edi          ; point to third byte
mov al, BYTE PTR es:(di) ; get third byte of triplet
out dx, al           ; write it to the dac data register
inc edi          ; point to first byte of next triplet
dec edx          ; address the da21c index register
inc ah           ; point to next palette register
loop    o_pal_load_loop      ; process next triplet

pop eax       ; restore ax
pop edi       ; restore the offset into pal
pop ecx       ; restore the fade loop counter

pop edi
pop esi
pop ds
pop ebp
ret
endp ;end of the fade out function
``````

sql server – What does Nested Loops join operator has to do with a Scalar?

As far as I understand the docs, the Nested Loops operator is a join operator, i.e., it requires two tables as input.

If that’s correct, then why the Nested Loops operator is used with a Scalar input?

For example, take the following query (from Paul White’s website) and its execution plan.
You can see that the inputs for the Nested Loops operator are (1) a Scalar, and (2) a table (the result of the Index Seek).

I know that a scalar can’t be joined with a table, then what that actually means? What’s actually being joined?

``````USE AdventureWorks2019;
DECLARE @Like nvarchar(50) = N'D%';
SELECT p.(Name)
FROM   Production.Product AS p
WHERE  p.(Name) LIKE @Like;
``````

BTW, I presume that it’s a pretty basic question, but I couldn’t find a good resource that goes through such basics methodologically, so a recommendation would be much appreciated.

Get Each Digits of Number with Using Loops in C++

I need a program same as I wrote but using loops. (if else for etc.) . Program is that enter a number and get each digits of number like that: number is 123456. I’m beginner, I can’t create the logic and can’t combine loops. Can anybody help me about that situation?

``````1.digits is 6
2.digits is 5
3.digits is 4
4.digits is 3
5.digits is 2
6.digits is 1
7.digits is 0
8.digits is 0
9.digits is 0
``````

.

``````#include <iostream>
using namespace std;

int main()
{
int number,first,second,third,fourth,fifth,sixth,seventh,eighth,ninth;

cout<< "Enter a number (<999999999): " << endl;

cin>>number;

first = number%10;
second = number/10%10;
third = number/100%10;
fourth = number/1000%10;
fifth = number/10000%10;
sixth = number/100000%10;
seventh = number/1000000%10;
eighth = number/10000000%10;
ninth = number/100000000%10;

cout<<"1. digit is"<<" "<<first<<endl;
cout<<"2. digit is"<<" "<<second<<endl;
cout<<"3. digit is"<<" "<<third<<endl;
cout<<"4. digit is"<<" "<<fourth<<endl;
cout<<"5. digit is"<<" "<<fifth<<endl;
cout<<"6. digit is"<<" "<<sixth<<endl;
cout<<"7. digit is"<<" "<<seventh<<endl;
cout<<"8. digit is"<<" "<<eighth<<endl;
cout<<"9. digit is"<<" "<<ninth<<endl;

return 0;
}
``````

postgresql – How to limit tree traversal in case of loops?

So I want to limit tree depth traversal (as the simplest recursion killer tool). Example code that turns normalized records into tree:

``````CREATE TABLE items (
item_id     serial PRIMARY KEY,
title text
);
CREATE TABLE joins (
id          serial PRIMARY KEY,
item_id     int,
child_id    int
);
INSERT INTO items (item_id,title) VALUES
(1,'PARENT'),
(2,'LEVEL 2'),
(3,'LEVEL 3.1'),
(4,'LEVEL 4.1'),
(5,'LEVEL 4.2'),
(6,'LEVEL 3.2');
INSERT INTO joins (item_id, child_id) VALUES
(1,2),
(2,3),
(3,4),
(3,5),
(2,6);

WITH RECURSIVE t(item_id, json) AS (
SELECT item_id, to_jsonb(items)
FROM items
WHERE NOT EXISTS (
SELECT 1
FROM joins
WHERE items.item_id = joins.item_id
)
UNION ALL
SELECT parent.item_id, to_jsonb(parent) || jsonb_build_object( 'children', t.json )
FROM t
JOIN joins AS j
ON t.item_id = j.child_id
JOIN items AS parent
ON j.item_id = parent.item_id
)
SELECT item_id, jsonb_pretty(json)
FROM t
WHERE item_id = 1;
``````

``````INSERT INTO joins (item_id, child_id) VALUES
(1,2),
(2,3),
(3,1);
``````

So we get a loop `1->2->3->1` and I want to limit its output using limiters – I want all my trees to be no bigger than depth X set by a number I give to this tree constructing function. How to do such thing in postgres 13+?

memory access – How does changing cache size and/or block size affect the hit rate of the for loops in the following code?

I am working on practice problems to study for an upcoming exam. I am given the following piece of code:

``````#define LEAP 4
#define SIZE 64
int foo(SIZE);
// Assume foo has been initialized to contain values.
// Assume the cache starts empty at this point.
for (int i = 0; i < SIZE; i += LEAP) { // Loop 1
foo(i) = foo(i) + i * (i + 2);
}
for (int j = 1; j < SIZE; j += (LEAP * 2)) { // Loop 2
foo(j) = foo(j) + j * 5;
}
``````

I have a direct-mapped cache containing 128 bytes with a cache block size of 32 bytes. The cache uses LRU replacement and write-allocate and write-back policies. I also need to assume `i` and `j` are stored in registers, the array `foo` starts at address `0x0`, and the cache starts out empty. I already determined the hit rate for both Loop 1 and Loop 2, however, I am exploring more into this problem than what is asked as an exercise.

Assuming that all factors remain the same as shown in the original code, how would changing cache size (say from 128 bytes to 256 bytes) affect the hit rate of both loops? Similarly, how would changing the block size (say from 32 bytes to 16 bytes) affect the hit rate of both loops?

My initial assumption would be that if we increased the cache size, then that would increase the hit rate of both loop 1 and loop 2 because it would reduce misses. For decreasing block size, then the hit rate would increase for both loop 1 and loop 2 because if block size was increased, then there would be a decreased number of entries in the cache and it will take more time to fetch block size from memory.

Is my logic incorrect? If so, can someone explain what would happen in terms of the hit rate in both loops by implementing the changes I am suggesting. I am still a little unsure of what I claim would be true. Any feedback or suggestion in helping me answer this conceptual question would be greatly appreciated.

performance – How can I speed up a C++ code with several loops

I have recently started to work with C++ and I do consider myself quite basic in C++ coding.

I have made the following two functions and I was wondering whether someone could give me some hints on how to improve and speed up this code.

Please, note that the second function is then used in `R` through `Rcpp R` package.

``````#include <Rcpp.h>
using namespace Rcpp;
using namespace std;

double sumAll(double i, double j, int a, int b, double coeff) {

double pi = 2 * acos(0.0);

double total = 0;
int half_a =  a / 2;
int half_b =  b / 2;

for (int k = 0; k <= half_a; ++k) {

for (int l = 0; l <= half_b; ++l) {

double fkl;
if (k == 0 && l == 0) {
fkl = 0;
} else {
fkl = pow((1 - (coeff * (1 - cos(2.0 * pi * k / a)))), 2.0) *
pow((1 - (coeff * (1 - cos(2.0 * pi * l / b)))), 2.0);
}

double a1 = 1 - (cos(2.0 * pi * i * k / a) * cos(2.0 * pi * j * l / b));

double deltaa;
if (k == 0) {
deltaa = 1;
} else {
deltaa = 0.5;
}

double deltab;
if (l == 0) {
deltab = 1;
} else {
deltab = 0.5;
}

if (k == 0 && l == 0) {

total = total + 0;

} else {

double res = (fkl * a1) / (deltaa * deltab * (1 - fkl));

total = total + res;
}
}
}
}

// ((Rcpp::export))
NumericVector series_Sum(NumericVector xvec, NumericVector yvec, int a, int b,
double coeff) {

int size = xvec.length();
NumericVector series_res(size);
int half_a = a / 2;
int half_b = b / 2;

for (double i = 0; i < size; i++) {
series_res(i) = sumSij(half_a, half_b, xvec(i), yvec(i), a, b, coeff);
}

return series_res;
}

Consider that in `sumAll` :
- i and j: are integers, which can get values between 0 and a/2 or 0 and b/2, respectively.
- coeff: can be a value between 0 and 1.0.
- a and b: can be any integer values higher than 5 (arbitrary choice).

In `series_Sum` :
- xvec and yvec: are vectors of i and j values.

In other words, `series_Sum` use `sumAll` over several possible combinations of i and j.
``````

Postfix “loops back to myself” only when trying to send to fallback relay

I have a Postfix 2.11 server (`mail-server.example.com`) that is strictly for outgoing email. It works fine if it is able to send the email on the first try. However, for performance reasons, if it cannot send the email on the first try and instead wants to defer it, I have configured `smtp_fallback_relay` so that it forwards the email to another server (`deferred-mail.example.com`) that handles only deferred emails.

If, from my trusted IP (`mynetworks`), I send an email to either server destined for `someone@gmail.com`, either server will accept it and try to send it to Gmail. Because my server IP is new, Gmail rejects the email from either server with `421` (temporary deferral). As expected, the `deferred-mail` server simply puts the message in its deferred queue and tries again later.

The weird part is that while `mail-server` will send the message to Gmail to begin with, after receiving the `421`, it attempts to send the mail to `deferred-mail`, but gives up and instead bounces the message, saying “mail for gmail.com loops back to myself”. I see no logs on the `deferred-mail` server saying anything about what is going on.

So both servers are configured to accept mail and relay it to Gmail if the client is trusted, and the `deferred-mail` trusts `mail-server` (I can send to a Gmail address when directly connecting to `deferred-mail` from `mail-server), so how is Postfix coming up with this “loop” and why is it bouncing the email instead of relaying it?

Per request, here are redacted logs of the error:

``````postfix/smtpd(26668): 50F7C5B81: client=ip-10-111-7-75.us-west-2.compute.internal(10.111.7.75)
postfix/cleanup(26682): 50F7C5B81: message-id=<>
opendkim(36): 50F7C5B81: can't determine message sender; accepting
postfix/qmgr(143): 50F7C5B81: from=<REDACTED-SENDER>, size=279, nrcpt=1 (queue active)
postfix/smtp(26686): 50F7C5B81: host aspmx.l.google.com(74.125.197.26) said: 421-4.7.0 (REDACTED-PUBLIC-IPv4      15) Our system has detected that this message is 421-4.7.0 suspicious ...
postfix/smtp(26686): 50F7C5B81: host alt2.aspmx.l.google.com(142.250.152.27) said: 421-4.7.0 (REDACTED-PUBLIC-IPv4      15) Our system has detected that this message is 421-4.7.0 suspicious ...
postfix/smtp(26686): warning: host deferred-mail.example.com(10.111.14.181):25 greeted me with my own hostname mail-server.example.com
postfix/smtp(26686): warning: host deferred-mail.example.com(10.111.14.181):25 replied to HELO/EHLO with my own hostname mail-server.example.com
postfix/smtp(26686): 50F7C5B81: to=<someone@gmail.com>, relay=deferred-mail.example.com(10.111.14.181):25, delay=26, delays=24/0.01/1.5/0, dsn=5.4.6, status=bounced (mail for gmail.com loops back to myself)

log messages here about sending bounce email to sender
have been removed

postfix/bounce(26688): 50F7C5B81: sender non-delivery notification: AEA8A5B83
postfix/qmgr(143): 50F7C5B81: removed
``````

python – What is more efficient? using conditions before for loops? or vice versa?

I’d like to know what is more efficient and performant for the following two cases:

1. Using conditions before for loops:
``````if food == 'tomato':
for i in range(1,000,000):
<some logic>
elif food == 'banana':
for i in range(1,000,000):
<some other logic>
``````
1. OR to use one for loop before the conditions:
``````for i in range(1,000,000):
if food == 'tomato':
<some logic>
elif food == 'banana':
<some other logic>
``````

The first case checks the if condition just one time but uses repeated for loops

but the second case uses the same for loop but we need to check a million times!

which one di you think is better?

finance – Calculating Average Price and P&L Efficiently Without Loops

A very common task is stock portfolio evaluation is to calculate the average price of stock holdings for a sequence of trades and from there to calculate the (realized) profit or loss. Obviously one can easily accomplish the task using Do loops, but that’s a very inefficient (and inelegant) approach to take in Mathematica.

I am looking for an elegant, efficient solution that will likely make use of functions like PairFoldList and/or SequenceFoldList.

Here is a simple, toy example shown as an Excel table for simplicity:

There are five transactions in total. In the first three transactions a total of 625 shares are acquired at three different prices. The total value of the portfolio is calculated and the average price is simply this value divided by the total number of shares in the portfolio (e.g. $$1062.50 / 635 =$$1.70 after the third transaction).

In the fourth transaction we dispose of 400 shares of the portfolio and we now calculate a P&L, as this is a closing transaction, using the average price: 400 * ($$2.50 –$$1.70) = \$320.

Note that the average price remains at its previous value (i.e \$1.70).

If the fifth transaction the remainder of the shares (225) are sold giving a profit of 225 * ($$3.00 –$$1.70) = \$292.50.

The total PL from all transactions in this example is \$612.50.

I am looking for two functions, the first that will generate a list of average prices { $$1.00,$$1.32, $$1.70,$$1.70, $$0 } and the second a list of realized PLs: { 0, 0, 0, 320,$$292.50 }.

As I say, doing this with loops is trivial, but can be very slow if the number of transactions is large.

Important note: it is vital to take account of the possibility of going short. So, for instance, if in the fifth transaction we had sold 500 shares, instead of just the remaining 225 shares in the portfolio, we would now be net short 275 shares and the table would read as follows:

Note that:
(i) the realized P&L remains unchanged
(ii) the Av Price for the fifth transaction is no longer 0 (or #DIV/0! in Excel), but \$3.00, the price at which the excess of 275 shares were sold short.

In other words, a change of sign on the portfolio value restarts the computation of the average price sequence.

Not an easy challenge!