Answer the question
In order to leave comments, you need to log in
What is the best way to organize the structure of this code?
Advise how it is better to organize the given code. The task is essentially simple:
Given A, B, C - numeric variables. There can be the following relationships between them:
A > B > C
A < B < C
Also given a numeric variable X. This variable can be equal to A, B, C (3 options), can be in the intervals between them (2 options), and go beyond the boundaries (to be less than A, or greater than C (2 options)). A total of 7 options. Considering that there can be both A > B > C and A < B < C, we multiply the number of options by 2, for a total of 14 possible options for X.
I solved this problem only using if's:
if (A < B && B < C) {
if (X < A) {
// что-то делаем
}
if (X == A) {
// делаем другое
}
if (X > A && X < B) {
// делаем третье
}
// и так далее, все 14 вариантов вхождения для X
}
Answer the question
In order to leave comments, you need to log in
If the actions are symmetrical, i.e. for X > (C > B > A), the actions are the same as for X > (A > B > C),
you can bring the variables to a uniquely increasing option - swap A and C if A > C.
So there will be 7 options.
if (A > C) [A, C] = [C, A]; // поменять местами значения A и C
// теперь точно A < B < C
if (X < A) { // вар. 0
} else if (X == A) { // вар. 1
} else if (X < B) { // вар. 2
} else if (X == B) { // вар. 3
} else if (X < C) { // вар. 4
} else if (X == C) { // вар. 5
} else { // X > C // вар. 6
}
A > B > C
to A < B < C
have been confirmed, so I will leave the first step, where we swap A and C so that the sequence is definitely increasing. 0 1 2 3 4 5 6
---o-----o-----o---
A B C
0 1 0 1 0 1 0 1
0 0 1 1 0 0 1 1
0 0 0 0 1 1 1 1
if (A > C) [A, C] = [C, A]; // поменять местами значения A и C
// теперь точно A < B < C
if (X > B) {
if (X > C) { // вар. 6
} else {
if (X == C) { // вар. 5
} else { // вар. 4
}
}
} else {
if (X > A) {
if (X == B) { // вар. 3
} else { // вар. 2
}
} else {
if (X == A) { // вар. 1
} else { // вар. 0
}
}
}
So less visually and readable, but saved on matches - fewer checks. I will say right away that the answer of Sergey Sokolov is an extremely slow solution in terms of performance and, in general, his answer is illogical and even erroneous !
It has a lot of redundant conditions and checks that were simply incorrectly designed logically from the very beginning, which led to chaos in its code.
He tried to fix it using my answer, but unfortunately it didn't help the situation.
Do it right like this :
/* проверяем все центры */
1. X==A
2. X==B
3. X==C
/* проверяем левую ветку: X<B */
4. X<A
5. else ... //X>A
/* проверяем правую ветку: else */
6. X<C
7. else ... //X>C
If actions cannot be somehow grouped according to conditions, then if ... else is perhaps the best construction for js.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question