Wonky results from basic IF AND OR Syntax in SPSS - spss

My SPSS Syntax code below does not produce the results intended. Even when reason is equal to 15 or 16, it will flag ped.crossing.with.signal to 1.
COMPUTE ped.crossing.with.signal = 0.
IF ((ped.action = 1 | ped.action = 2) AND (reason ~= 15 | reason ~= 16)) ped.crossing.with.signal = 1.
EXECUTE.
When I do it like this, it works... but why?
COMPUTE ped.crossing.with.signal = 0.
IF (ped.action = 1 | ped.action = 2) ped.crossing.with.signal = 1.
IF (reason = 15 | reason = 16) ped.crossing.with.signal = 0.
EXECUTE.

It's not a wonky result, but rather the correct application of boolean algebra which is explained by De Morgan's Laws.
The expression (reason ~= 15 | reason ~= 16) is equivalent to ~(reason = 15 and reason = 16) which in this case can never evaluate to false (because a single variable can't hold two values). Logically, the correct expression to use would be (reason ~= 15 & reason ~= 16) or ~(reason = 15 | reason = 16) although as pointed out already using the any function is more straightforward.

Your syntax looks good but in fact is logically not as you intend as Jay points out in his answer.
Also, you can simplify the syntax as follow to avoid complicated Boolean negations:
COMPUTE ped.crossing.with.signal = ANY(ped.action, 1, 2) AND ANY(reason, 15, 16)=0.
Using a single COMPUTE command in this way shall make your processing more efficient/faster, not to mention more parsimonious code also.

Related

What's the proper way to find the last parcel of an array?

I'm doing some codewars and arr[index] keeps returning nil. I've done this a few different ways, and I'm sure the array exists, as well as the index. What's wrong here, is it syntax?
As I've mentioned in the title, I want to find the last digit of the array.
if arr[index] <= 0 then
return -1
end
Full Code:
local solution = {}
function solution.newAvg(arr, navg)
local currentAverage = 0
local index = 0
for i, v in pairs(arr) do
index = i
currentAverage = currentAverage + v
end
if arr[index] <= 0 then
return -1
end
return math.ceil(((index+1) * navg) - currentAverage)
end
return solution
I see two issues with your code:
Edge case: Empty array
If arr = {}, the loop for i, v in pairs(arr) do won't execute at all and index will remain at 0. Since arr is empty, arr[0] will be nil and arr[index] <= 0 will fail with an "attempt to compare a nil value" error.
Lack of ordering guarantee
You use pairs rather than ipairs to loop over what I assume is a list. This means keys & values might be traversed in any order. In practice pairs usually (but not always!) traverses the list part of a table in the same order as ipairs, but the reference manual clearly states that you can't rely on no specific order. I don't think CodeWars is this advanced but consider the possibility that pairs may be overridden to deliberately shuffle the order of traversal in order to check whether you're relying on the dreaded "undefined behavior". If this is the case, your "last index" might actually be any index that happens to be visited last, obviously breaking your algorithm.
Fixes
I'll assume arr is an "array", that is, it only contains keys from 1 to n and all values are non-nil (i.e. there are no holes). Then you can (and should!) use ipairs to loop over the "array":
for i, v in ipairs(arr) do ... end
I don't know the problem statement so it's hard to tell how an empty array should be handled. I'll assume that it should probably return 0. You could add a simply early return at the top of the function for that: if arr[1] == nil then return 0 end. Nonempty arrays will always have arr[1] ~= nil.
I want to find the last digit of the array.
If you mean the last integer (or entry/item) of the array:
local last = array[#array]
If you mean the last digit (for example array = {10, 75, 44, 62} and you want 2), then you can get the last item and then get the last digit using modulo 10:
local last = array[#array] % 10
for i, v in pairs(arr) do
index = i
currentAverage = currentAverage + v
end
Just a reminder:
#array returns the number of items in a table.
In Lua, arrays are implemented using integer-indexed tables.
There's a difference between pairs() and ipairs().
Regarding point 3 above, the following code:
local array = {
[1] = 12,
[2] = 32,
[3] = 41,
[4] = 30,
[5] = 14,
[6] = 50,
[7] = 62,
[8] = 57
}
for key, value in pairs(array) do
print(key, value)
end
produces the following output (note that the order of keys is not respected):
8 57
1 12
2 32
3 41
4 30
5 14
6 50
7 62
while the same code above with pairs() replaced with ipairs() gives:
1 12
2 32
3 41
4 30
5 14
6 50
7 62
8 57
So, this might be the cause of your problem.

A better way on improving my roman numeral decoder

Quick explanation, I have recently started using codewars to further improve my programming skills and my first challenge was to make a roman numeral decoder, I went through many versions because I wasnt satisfied with what I had, So I am asking if there is an easier way of handling all the patterns that roman numerals have, for example I is 1 but if I is next to another number it takes it away for example V = 5 but IV = 4.
here is my CODE:
function Roman_Numerals_Decoder (roman)
local Dict = {I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000}
local number = 0
local i = 1
while i < #roman + 1 do
local letter = roman:sub(i,i) -- Gets the current character in the string roman
if roman:sub(i,i) == "I" and roman:sub(i + 1,i + 1) ~= "I" and roman:sub(i + 1,i + 1) ~= "" then -- Checks for the I pattern when I exists and next isnt I
number = number + (Dict[roman:sub(i +1,i + 1)] - Dict[roman:sub(i,i)]) -- Taking one away from the next number
i = i + 2 -- Increase the counter
else
number = number + Dict[letter] -- Adds the numbers together if no pattern is found, currently checking only I
i = i + 1
end
end
return number
end
print(Roman_Numerals_Decoder("MXLIX")) -- 1049 = MXLIX , 2008 = MMVIII
at the moment I am trying to get 1049 (MXLIX) to work but I am getting 1069, obviously I am not following a rule and I feel like its more wrong then it should be because usually if its not correct its 1 or 2 numbers wrong.
The algorithm is slightly different: you need to consider subtraction when the previous character has less weight than the next one.
function Roman_Numerals_Decoder (roman)
local Dict = {I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000}
local num = 0
local i = 1
for i=1, #roman-1 do
local letter = roman:sub(i,i) -- Gets the current character in the string roman
local letter_p = roman:sub(i+1,i+1)
if (Dict[letter] < Dict[letter_p]) then
num = num - Dict[letter] -- Taking one away from the next number
print("-",Dict[letter],num)
else
num = num + Dict[letter] -- Adds the numbers together if no pattern is found, currently checking only I
print("+",Dict[letter],num)
end
end
num = num + Dict[roman:sub(-1)];
print("+",Dict[roman:sub(-1)], num)
return num
end
print(Roman_Numerals_Decoder("MXLIX")) -- 1049 = MXLIX , 2008 = MMVIII

Postfix evaluating incorrectly

-2^2 (infix notation) should translate to -2 2 ^ (postfix notation). It does as expected however when evaluating that postfix it evaluates to 4 not -4 which is what is expected.
I'm using Lua and here's my precedence & associativity tables:
-- Precedence table for different operators
local PRECEDENCE = {
[Token.Type.MINUS] = 0,
[Token.Type.PLUS] = 0,
[Token.Type.ASTERIK] = 1,
[Token.Type.SLASH] = 1,
[Token.Type.CARET] = 2,
[Token.Type.UMINUS] = 3
}
-- Associativity table for different operators
-- 0 = LTR (Left To Right)
-- 1 = RTL (Right To Left)
local ASSOCIATIVITY = {
[Token.Type.MINUS] = 0,
[Token.Type.PLUS] = 0,
[Token.Type.ASTERIK] = 0,
[Token.Type.SLASH] = 0,
[Token.Type.CARET] = 1,
[Token.Type.UMINUS] = 1
}
When trying to evaluate -2^2 my output queue looks like this:
{
2,
UMINUS,
2,
CARET
}
Here's my parser. It's worth noting that queue and stack are "classes" with their respective functionality.
--[[
Parse tokens
]]
function Parser:parse()
self:preprocess() -- Convert valid MINUS tokens into UMINUS
while (self.token) do
local token = self.token
if (token.type == Token.Type.NUMBER) then
self.queue:enqueue(tonumber(token.value))
elseif (isOperator(token)) then -- PLUS, MINUS, SLASH, ASTERIK, UMINUS, CARET
while (not self.stack:isEmpty()
and ASSOCIATIVITY[token.type]
and PRECEDENCE[token.type]
and ASSOCIATIVITY[self.stack:top().type]
and PRECEDENCE[self.stack:top().type]
and ((ASSOCIATIVITY[token.type] == 0 and PRECEDENCE[token.type] <= PRECEDENCE[self.stack:top().type])
or (ASSOCIATIVITY[token.type] == 1 and PRECEDENCE[token.type] < PRECEDENCE[self.stack:top().type]))) do
self.queue:enqueue(self.stack:pop())
end
self.stack:push(token)
elseif (token.type == Token.Type.LPAREN) then
self.stack:push(token)
elseif (token.type == Token.Type.RPAREN) then
while (self.stack:top().type ~= Token.Type.LPAREN) do
self.queue:enqueue(self.stack:pop())
end
self.stack:pop()
end
self:next() -- Move to the next token
end
while (not self.stack:isEmpty()) do
self.queue:enqueue(self.stack:pop())
end
return self.queue
end
What am I doing wrong? I tried an online calculator here and I also get 4 yet I know the correct output should be -4 for that expression.
To get the result you expect, the carat must have a higher precedence than unary minus. That's how it works in Lua's operator precedence. The postfix notation for -2^2 should actually be 2 2 ^ UMINUS. Remember that the square of any real number is always positive. You could just swap the precedence levels:
[Token.Type.CARET] = 3,
[Token.Type.UMINUS] = 2,

Swift Range Operator with two unknown values

If I have two unknown values, lets say x and y, what is the best way loop through all of the values between between those values?
For example, given the values x = 0 and y = 5 I would like to do something with the values 0, 1, 2, 3, 4, and 5. The result could exclude 0 and 5 if this is simpler.
Using Swift's Range operator, I could do something like this:
for i in x...y {
// Do something with i
}
Except I do not know if x or y is the greater value.
The Swift documentation for Range Operators states:
The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.
There are a number of solutions here. A pretty straight forward one is:
let diff = y - x
for i in 0...abs(diff) {
let value = min(x, y) + i
// Do something with value
}
Is there a better, or more elegant way to achieve this?
I guess the most explicit way of writing it would be:
for i in min(a, b)...max(a, b) {
// Do something with i
}
To exclude the first and last value, you can increment your lower limit and use the Swift ..< syntax:
let lowerLimit = min(a, b) + 1
let upperLimit = max(a, b)
for i in lowerLimit..<upperLimit {
// Do something with i
}

Incrementation in Lua

I am playing a little bit with Lua.
I came across the following code snippet that have an unexpected behavior:
a = 3;
b = 5;
c = a-- * b++; // some computation
print(a, b, c);
Lua runs the program without any error but does not print 2 6 15 as expected. Why ?
-- starts a single line comment, like # or // in other languages.
So it's equivalent to:
a = 3;
b = 5;
c = a
LUA doesn't increment and decrement with ++ and --. -- will instead start a comment.
There isn't and -- and ++ in lua.
so you have to use a = a + 1 or a = a -1 or something like that
If you want 2 6 15 as the output, try this code:
a = 3
b = 5
c = a * b
a = a - 1
b = b + 1
print(a, b, c)
This will give
3 5 3
because the 3rd line will be evaluated as c = a.
Why? Because in Lua, comments starts with --. Therefore, c = a-- * b++; // some computation is evaluated as two parts:
expression: c = a
comment: * b++; //// some computation
There are 2 problems in your Lua code:
a = 3;
b = 5;
c = a-- * b++; // some computation
print(a, b, c);
One, Lua does not currently support incrementation. A way to do this is:
c = a - 1 * b + 1
print(a, b, c)
Two, -- in Lua is a comment, so using a-- just translates to a, and the comment is * b++; // some computation.
Three, // does not work in Lua, use -- for comments.
Also it's optional to use ; at the end of every line.
You can do the following:
local default = 0
local max = 100
while default < max do
default = default + 1
print(default)
end
EDIT: Using SharpLua in C# incrementing/decrementing in lua can be done in shorthand like so:
a+=1 --increment by some value
a-=1 --decrement by some value
In addition, multiplication/division can be done like so:
a*=2 --multiply by some value
a/=2 --divide by some value
The same method can be used if adding, subtracting, multiplying or dividing one variable by another, like so:
a+=b
a-=b
a/=b
a*=b
This is much simpler and tidier and I think a lot less complicated, but not everybody will share my view.
Hope this helps!

Resources