I was wondering if I simply cannot find a between method for numbers in Crystal.
In Ruby, there's the Comparable#between? method which can (among others) compare two numeric values (my specific case).
Background: I want to achieve a not-between solution without using
variable < 2 || variable > 5
I tried 5.between(2,5) and 5.between?(2,5) but all I got was a compilation error:
Error in line 1: undefined method 'between?' for Int32
I ended up with extending the number structure:
struct Number
def between?(a, b)
self <=> a >= 0 && self <=> b <= 0
end
end
Question 2: Is my solution above a feasible one? If not, suggestions are welcomed.
In crystal you can write 2 <= variable <= 5, which is easier to read and gives you greater control over inclusivity/exclusivity at each end of the range.
From a deleted answer but I still like it:
You can use a similar method Range#includes? (or #covers).
Related
I'm new to coding and I recently started to take my baby steps in LUA. I have a small problem so it would be very helpful if you can help me. In my code, I need to code that
If x ~= 1 and x~=2 and x~=3 and x~=4 then (do something) end
is there a faster way not to hardcode that part, not to type the whole thing from x~=1 to x~=4?
Thank you!
If you need something like if x ~= 1 and x~=2 and x~=3 and x~=4 then (do something) end x is usually an integer.
Then
if x < 1 or x > 4 then
-- do your stuff here
end
Is what you are looking for. If you want to explicitly check wether x is unquald 1,2,3,4 you can simply do something like Egor suggested.
But as you see unless you can describe your conditions in a shorter mathematical way you still have separate unique conditions and you won't come around writing them down.
If you have to check those conditions repeatedly you can use a truth table like in Egor's example or you write a function that returns if that condition is met for its argument.
I have a fortran code using a derived type as follows:
if(type%value(1).LT.0D0 OR type%value(1).GT.1D0) then
if(type%value(1).LT.0D0) then
do something
end if
deallocate(type%value)
end if
In this scenario the statement type%value(1).LT.0D0 is checked twice. Is there a way to avoid this? More generally, is there a better approach to validate this?
Well, you have three paths:
type % value(1) < 0
type % value(1) > 1
0 <= type % value(1) <= 1
In all three paths the statements will be different, so you need two if statements.
Do something then deallocate
Only deallocate
Nothing
How you branch between the three paths is up to you, and the specifics of your code. The way you describe above is totally reasonable. If the evaluation is more computational intensive than a simple floating point comparison, it might be useful to store the results of this comparison in a logical variable, but other than that, it's fine.
Other ways are:
if (type % value(1) .LT. 0D0) then
do something
deallocate(type % value)
elseif (type % value(1) .GT. 1D0) then
deallocate(type % value)
end if
In a sense, this repeats the deallocate statement, but it distinguishes the paths better. I'm testing this out, I don't know the exact Fortran Standard, but my understanding is that if the value is less than 0, then it is deallocated, but the elseif isn't even tested, so it doesn't matter that it's no longer allocated at that point.
Ultimately, your method is fine. Make sure that the code is easy to read for you or whoever has to read the code in the future. I don't see any performance reason to chose one over the other.
I'm working on my new project now and I'm facing a weird problem. The problem seems to have two solutions - the first one which would take me, let's say, about 5 minutes, and the second one which would require some copying and pasting and take a lot of time.
However, I am not sure if the first solution is possible or not, and mainly, how it's possible.
I wasn't even able to briefly describe my problem to Google, but I'll try to describe it to you.
Let's say I have an variable x. Then I have another variable $9$ (it's name is 9, for example). I want variable $9$ to change it's value, when the value of variable x is equal to 9. The code:
int x = 9
char $9$ = 0
$x$ = 1 //this in not correct. This is just my idea. This line should do; char variable with the name which is equal to the value of int x changes its value to 1..
I can't use if (if (x == 9) $9$ = 1;) or switch because there are actually 600 possible values for int x and therefore also 600 char $value of x$ variables.. (well, thats the second solution).
I hope atleast somebody understood my issue, any ideas? Thank you very much for any help. Also, I'm sorry for my beginner's english, for being new to C++ and for being unable to google it. :D
It sounds like you want some sort of key-value store. That is, you have a runtime determined key, and you want to lookup / change some value based on that key. There's a few options included in C++ that can do this relatively easily.
Because your key is an int that is relatively restricted in range, we can use an array. We can also use a std::unordered_map (a hash table) or a std::map (a binary tree).
So... given one of these objects:
std::array<int, 600> data;
std::unordered_map<int, int> data;
std::map<int, int> data;
We could do:
int x = 9;
data[x] = 1;
This question already has answers here:
How to change index of a for loop?
(5 answers)
Closed 4 months ago.
is it possible to break a for loop in Python, without break command?
I'm asking this question in order to compare it with C++ for loop, in which actually checks a condition each time.
i.e. it's possible to break a for loop in C++ like below:
for(int i=0; i<100; i++)
i = 1000; // equal to break;
is it possible to do the same in Python?
for i in range(0,100):
i = 10000 // not working
Python's for is really a "for each" and is used with iterables, not loop conditions.
Instead, use a while statement, which checks the loop condition on each pass:
i = 0
while i < 1000:
i = 1000
Or use an if statement paired with a break statement to exit the loop:
for i in range(1000):
if i == 10:
break
Use a while loop for that purpose:
i = 0
while i < 100:
i = 1000
No, for doesn't work like that in Python. for iterates over a list (in this case) or other container or iterable. for i in range(0, 100) doesn't mean "increment i until i is greater than or equal to 100", it means "set i to successive items from a list of these 100 items until the list is exhausted."
If i is 50, then the next item of the list is still 51, regardless of what you may set i to.
break is better anyway.
This won't work (as you've noticed). The reason is that, in principle, you are iterating the elements of a list of ascending numbers (whether that is really true depends on if you're using python 2 or 3). You can use the 'break' keyword to break out of a loop at any time, although using it in excess might make it hard to follow your code.
You might have to settle for the break statement:
http://docs.python.org/tutorial/controlflow.html
for i in range(0,100):
print i
if i == 10:
break
I recently read in Code Complete that the recommended way of handling expressions that involve numbers is to order them like a number line.
The book has 2 examples:
if ( (MIN_ELEMENTS <= i) && (i <= MAX_ELEMENTS) )
if ( (i < MIN_ELEMENTS) || (MAX_ELEMENTS < i ) )
With the first example showing that i is between the min and max elements, and the second example being that i falls outside the range between the elements.
I've been trying to adopt it, and I'm not sure if it's just the way I think, but I don't think it's making code any clearer.
Example:
if (m_Health > BOSS_HALF_HEALTH) // The way it was
if (BOSS_HALF_HEALTH <= m_Health) // The "number line" method
Is it just me, or does the number line method seem less clear? What are your thoughts regarding this practice?
It's also odd that he mentions putting constants on the left side of comparisons contradicts the number-line-method, but here it seems that the number line method leads to putting the constant on the left side.
I think the original motivation comes from having more than one comparison in the same logical expression. Both the quoted examples are comparing between both a lower and upper bound of a range. This ordering method may have value in those situations.
However, I don't think it's necessarily applicable if you're testing a single condition, such as m_Health > BOSS_HALF_HEALTH. In that case, the comparison you're making is whether something (a variable) is greater than something else. That's perfectly logical and doesn't need to be ordered in any particular way.
If you always ordered your comparisons in a "number line" way, you would never even need the > or >= comparison operators. They exist for good reasons.
I think it should be written the way you expect to read it.
Thus I would do:
if (i > MIN_ELEMENTS &&
i <= MAX_ELEMENTS)
instead of:
if ( (MIN_ELEMENTS <= i) && (i <= MAX_ELEMENTS) )
Because I read C alike english, like
if i is less than min and more than max
instead of
if min is less than is and is is less than max
because I care about i, not min.
I think this is not a method that is inherently superior. The advantage comes in having the expressions the same way throughout the code, making the code faster to read when you're used to it.
Steve McConnell's work is superb but there are little things I don't agree with him on. This may be one of those things with you.
If you feel it's making your code less clear, then don't do it just because Steve McConnell thinks it's the way to go.
I guess the original intention is to just make a habit.
Language is just a familiar arrangement of words. Once it becomes a habit,
you get accustomed to it.
If you can train your brain to read:
if ( CONST == i ) //[1]
in the same way as:
if ( i == CONST) //[2]
you will never fall prey to the bug of:
if ( i = CONST) //[3]
However, it should be noted that most modern compilers today give a warning on construct [3]
In conclusion, if you are fix all your compiler warnings, you can use either of the coding style.