What is wrong with my if statement 'if x + y = z' - ruby

I am trying to evaluate if a selected item meats a requirement. I am trying to evaluate the result of nominal + x against required.
I am using the following code:
if #weight.nominal + x = required
weights << #weight.id
end
However, it adds nominal + x together. Why is that, and how do I do what I want?

As #Pavan said in the comment, your conditional might be wrong. It should be == instead of =. = is the assignment.
if #weight.nominal + x == required ... end
Here what happens "behind the scene" with your original code:
required is assigned to x.
Add x to #weight.nominal (#weight.nominal + x)
Evaluate the result from step 2, which is always true.
Execute the code within if block, which is weights << #weight.id
Eventually, your x's value is lost, it will take required value instead and your conditional is useless since it always true.

Related

Check if numeral within bounds in one statement

Is there a way to check if a number x is greater than a number a and less than a number b, without specifying x twice?
I can do this:
x = 4
a = 1
b = 10
x > a && x < b
...but is there a way to do something like this:
# not valid ruby, is there another way?
a < x < b
This does not answer the question exactly, please read the Edit part of the answer.
Tested this to work for x being an Integer and a Float.
(a..b).include? x
Edit:
As #spickermann pointed out in comments the original question excludes the beginning and the end of the interval.
To exclude the end is easy, this is what ... is for. Therefore
(a...b).include? x # is the same as `a <= x && x < b`
To exclude the start of the interval is not that easy. One could use next_float:
(a.to_f.next_float...b).include? x
However even the (a...b) is something I would not use because it is not so common literal and in my opinion decreases readability of the code. With a.to_f.next_float we are making some really awkward code that may work for Integers and Floats but I would be afraid of other Numeric data types.
Unless someone brings completely different approach I would stick with x > a && x < b

Corrects sequences of parenthesis

Corrects sequences of parentesis can be defined recursively:
The empty string "" is a correct sequence.
If "X" and "Y" are correct sequences, then "XY" (the concatenation of
X and Y) is a correct sequence.
If "X" is a correct sequence, then "(X)" is a correct sequence.
Each correct parentheses sequence can be derived using the above
rules.
Given two strings s1 and s2. Each character in these strings is a parenthesis, but the strings themselves are not necessarily correct sequences of parentheses.
You would like to interleave the two sequences so that they will form a correct parentheses sequence. Note that sometimes two different ways of interleaving the two sequences will produce the same final sequence of characters. Even if that happens, we count each of the ways separately.
Compute and return the number of different ways to produce a correct parentheses sequence, modulo 10^9 + 7.
Example s1 = (() and s2 = ())
corrects sequences of parentheses, s1 (red) and s2(blue)
I don't understand the recursive algorithm, what does X and Y mean? And modulo 10^9 + 7?
First, I tried defining all permutations of s1 and s2 and then calculate the number of balanced parentheses. But that way is wrong, isn't it?
class InterleavingParenthesis:
def countWays(self, s1, s2):
sequences = list(self.__exchange(list(s1 + s2)))
corrects = 0
for sequence in sequences:
if self.__isCorrect(sequence):
corrects += 1
def __isCorrect(self, sequence):
s = Stack()
balanced = True
i = 0
while i < len(sequence) and balanced:
if '(' == sequence[i]:
s.stack(sequence[i])
elif s.isEmpty():
balanced = False
else: s.remove()
i += 1
if s.isEmpty() and balanced: return True
else: return False
def __exchange(self, s):
if len(s) <= 0: yield s
else:
for i in range(len(s)):
for p in self.__exchange(s[:i] + s[i + 1:]):
yield [s[i]] + p
class Stack:
def __init__(self):
self.items = []
def stack(self, data):
self.items.append(data)
def remove(self):
self.items.pop()
def isEmpty(self):
return self.items == []
Here's an example that shows how this recursive property works:
Start with:
X = "()()(())"
Through property 2, we break this into further X and Y:
X = "()" ; Y = "()(())"
For X, we can look at the insides with property 3.
X = ""
Because of property 1, we know this is valid.
For Y, we use property 2 again:
X = "()"
Y = "(())"
Using the same recursion as before (property 2, then property 1) we know that X is valid. Note that in code, you usually have to go through the same process, I'm just saving time for humans. For Y, you use property 3:
X = "()"
And again.. :
X = ""
And with property 1, you know this is valid.
Because all sub-parts of "()()(())" are valid, "()()(())" is valid. That's an example of recursion: You keep breaking things down into smaller problems until they are solvable. In code, you would have the function call itself with regards to a smaller part of it, in your case, X and Y.
As for the question you were given, there is a bit that doesn't make sense to me. I don't get how there is any room for doubt in any string of parentheses, like in the image you linked. In "((()())())" for example, there is no way these two parentheses do not match up: "((()())())". Therefore my answer would be that there is only one permutation for every valid string of parentheses, but this obviously is wrong somehow.
Could you or anyone else expand on this?

how does this checks surrounding cells in a 2D array

I am attempting to write a battleship game in ruby. I came across a code snippet that I think I grasp, but was hoping you all could maybe offer some clarification. The [-1,0,1] is what is throwing me. This is to check a 2D array. Thank you for your help as always.
def neighbors
#neighbors ||= [-1, 0, 1].repeated_permutation(2).map do |dx, dy|
#grid[x + dx, y + dy] unless dx.zero? && dy.zero?
end.compact
end
I think I may have figured it out finally. The repeated_permutation(2) takes to of the values in the [-1,0,1] to search around the "cell" in question.
What ||= means is if #neighbors responds to a nil (NilClass) object type or false (FalseClass) object value, it will take the value which you're assigning in the right side, that's to say the result of:
[-1, 0, 1].repeated_permutation(2).map do |dx, dy|
#grid[x + dx, y + dy] unless dx.zero? && dy.zero?
end.compact
To use ||= is like to use x || x = a or maybe x = a unless x, but in the Ruby way to be simple to read, simple to understand, simple to work with.
And what the [-1, 0, 1].repeated_permutation(2).map is trying to do is to map the result of a repeated_permutation over the [-1, 0, 1] array and to take the first and second value within the permutation, and to set your #grid variable probably (because I can't say what's #grid) as a range starting in the sum of dx plus x and then dy plus y unless the value of dx and dy are 0 at the same time (&&). Then compact the "mapped" result.
You might want to see Array#repeated_permutation and Array#permutation
Quick & dirty permutations are like minor changes to a series of numbers ([link to more indepth])1. What you're looking at is the array with being altered by the .repeated_permutations to find all options for each value & the results then being added to the original x & y coords...
The ||= & the unless parts are just checks to ensure the code doesn't run on 0's ...

For loop with flexible stop variable

I need to write a loop
for x in (1..y)
where the y variable can be changed somehow. How can I do that?
For example:
for x in (1..y/x)
But it does not work.
Normally we'd use a loop do with a guard clause:
x = 1
loop do
break if x >= y
x += 1
...
end
Make sure y is larger than x or it'll never do anything. y can change if necessary and as long as it's greater than x the loop will continue. As soon as y drops below x the loop will terminate on the next iteration.
Note: I use >= because testing for equality is a bug-in-waiting. Sometimes we try to compare where x starts out greater than y or we are incrementing a float and comparing it to an integer or another float and using == and never hit the magic "equal" causing the loop to run away. Instead always check for a greater-than-or-equal to end the loop.
I think you might be confused about return values. This actually works fine, it's just that the return value is equal to the original range.
y = 4
for x in (1..y)
puts x
end
# 1
# 2
# 3
# 4
#=> 1..4
Here's a code snippet to prove it.

Multiline conditionals in Ruby and other mysteries -- why won't this compile?

I'm learning Ruby, but I'm having trouble predicting what Ruby will behave under certain circumstances. For example, the following causes a syntax error:
[2, 3, 4].any? do |x|
(x > 1
and x < 4)
end
but this compiles fine:
[2, 3, 4].any? do |x|
(x > 1 and
x < 4)
end
(the difference is in the placement of the and)
Why does the former fail to compile, while the latter succeeds, and how would I have known that? i.e.: since the above seems totally unintuitive, where is the formal grammar for Ruby, like https://docs.python.org/3/reference/grammar.html , or a guide like this https://docs.python.org/3/reference/lexical_analysis.html so I don't have to just guess at Ruby's behavior and figure it out by trial & error?
You have to end the line with an operator if you want the statement to be continued on the next line.
I will try to see if I can re-find the doc on this.
This is documented in the following book , chapter 2.
The Ruby Programming Language
By David Flanagan, Yukihiro Matsumoto
To paraphrase :
With having semicolons as explicit end of statement indicators, the ruby interpreter must figure out when a statement ends. It does this by figuring out if a statement is complete or not, if not it continues parsing on the next line. So
total = x +
y
is the same as total = x + Y since total = x + is not a complete statement
but
total = x
+y
is the same as total = x followed by the statement +y, which is just y
so the same applies for a conditional , if you end with a && for example the interpreter will continue parsing on the next line
x = a &&
b
is the same as x = a && b
but
x = a
&& b
is assigns a to x and generates a syntax error for the next line
Your best friend: CLICK ME
If you would like to format your conditionals like your first example(I don't know why you would) you can use the \format. Try this
[2, 3, 4].any? do |x|
(x > 1 \
and x < 4)
end
Basically just add the slash after each Boolean except your last one!
However standard Ruby convention is to be as short, descriptive, and concise as possible. A similar conditional could be written as so
As johnson said it should be
[2, 3, 4].any? { |x| x > 1 && x < 4 }
Happy Coding!

Resources