What will this display? - dart

This code was in a quiz of Dart course that I'm taking, please help me solve it.
I want to know what it should display.
I solved it as 6, but the answer was 1, but I don't know why.
int var1 = 5;
int var2 = 6;
if ((var2 = 1) == var1)
print(var2);
else
print(var2++);

In the if query, a new value is assigned to the var2 variable, so var2 is not equal to var1 with both its old value and its new value.
Then, when var2 value is wanted to be printed, there is var2++, which means use the var2 value as it is, then increase it.
If you want to see this add a print(var2) after the last print and see the output is 2

Related

Is it atomic operation when exchange std::atomic with itself?

Will following code be executed atomically?
const int oldId = id.exchange((id.load()+1) % maxId);
Where id is std::atomic<int>, and maxId is some integer value.
I searched google and stackoverflow for std::atomic modulo increment. And I found some topics but I can't find clear answer how to do that properly.
In my case even better would be to use:
const int newId = id.exchange((++id) % maxId);
But I am still not sure if it will be executed atomically.
No, this is not atomic, because the load() and the exchange() are separate operations, and nothing is preventing id from getting updated after the load, but before the exchange. In that case your exchange would write a value that has been calculated based on a stale input, so you end up with a missed update.
You can implement a modulo increment using a simple compare_exchange loop:
int val = id.load();
int newVal = (val + 1) % maxId;
while (!id.compare_exchange_weak(val, newVal) {
newVal = (val + 1) % maxId;
}
If the compare_exchange fails it performs a reload and populates val with the updated value. So we can re-calculate newVal and try again.
Edit:
The whole point of the compare-exchange-loop is to handle the case that between the load and the compare-exchange somebody might change id. The idea is to:
load the current value of id
calculate the new value
update id with our own value if and only if the value currently stored in id is the same one as we read in 1. If this is the case we are done, otherwise we restart at 1.
compare_exchange is allows us to perform the comparison and the conditional update in one atomic operation. The first argument to compare_exchange is the expected value (the one we use in our comparison). This value is passed by reference. So when the comparison fails, compare_exchange automatically reloads the current value and updates the provided variable (in our case val).
And since Peter Cordes pointed out correctly that this can be done in a do-while loop to avoid the code duplication, here it is:
int val = id.load();
int newVal;
do {
newVal = (val + 1) % maxId;
} while (!id.compare_exchange_weak(val, newVal);

Looping and adding chars to string in LUA

It's about Lua/Roblox. (Disclaimer: must be roblox compatible.) I have an array called "array1", and a number value "num" which is 0.
local array1 = {"1","2","3","etc."}
local num = 0
I do:
while 1 do
wait(1) -- just a little delay between loops
num = num + 1 -- every loop I'm increasing that "num" value with 1.
script.Parent.TextLabel.Text = array1[num] -- I'm setting Text to [num]th (in this case 1) of array1. (I get 1st, 2nd, 3rd, 4th etc. word every second)
end
And it works. Kinda. My problem is, it's setting it to:
"1" and then only "2", not "1" and then "12".
Here's some video of the problem: https://i.imgur.com/d63BoN5.gifv
And I don't want it that way. I want to it to be:
1, 12, 123.
Try this:
script.Parent.TextLabel.Text = script.Parent.TextLabel.Text .. array1[num]
This will concatenate the previous Text value with the next number.

Randoms in one Array

I have six variables, that these variables have different position on the screen, I wanna put different images in these variables, hence i have an Array with the images.
misImagenes = {[1] = "rec/ro.png",[2] ="rec/az.png",[3] ="rec/ros.png",[4] ="rec/ne.png",[5] ="rec/ve.png",[6] ="rec/am.png"}
I put the elements of this Array into another Array into that have 2 different randoms, like this:
randoms = {[1] = misImagenes[math.random(1,6)],[2] = misImagenes[math.random(1,6)] }
So, I wanna put this randoms of random form, hence, i create an random of the randoms.
randomRan = randoms[math.random(1,2)]
I put the randomRan into the 6 variables, but the images of the variables are always equals.
uno = display.newImageRect(randomRan,340,280)
dos = display.newImageRect(randomRan,340,280)
tres = display.newImageRect(randomRan,340,280)
cuatro = display.newImageRect(randomRan,340,280)
cinco = display.newImageRect(randomRan,340,280)
seis = display.newImageRect(randomRan,340,280)
This variables have the randomRan, but the images are alway equals, i need that the images are differents, 2 differents images in random variables.
Thanks
It looks like what you want to do is commonly called shuffling and filtering an array.
Once you assign randoms[math.random(1,2)] to the randomRan variable, it is going to stay the same no matter what. It isn't like randomRan is going to be random each time it's used. However, if it were a function call, like randomRan(), then that would be a different case, depending on what the function did. A variable, once assigned to, generally stays the same unless changed.
math.randomseed(os.time()) -- Make sure to seed the random number generator.
local function shuffle(t)
local n = #t
while n >= 2 do
-- n is now the last pertinent index
local k = math.random(n) -- 1 <= k <= n
-- Quick swap
t[n], t[k] = t[k], t[n]
n = n - 1
end
return t
end
local misImagenes = {"rec/ro.png", "rec/az.png", "rec/ros.png", "rec/ne.png", "rec/ve.png", "rec/am.png"}
local randomImages = {}
-- Make a copy of misImagenes for randomImages.
for i, v in ipairs(misImagenes) do randomImages[i] = v end
-- Shuffle the new array. This will randomize the order of its contents.
shuffle(randomImages)
-- Since you want only two unique images for a total of six rectangles,
-- we'll have to duplicate and overwrite the other four, randomly.
for i = 1+2, 6 do
randomImages[i] = randomImages[math.random(1, 2)]
end
-- Now to filter the array with newImageRect.
for i=1, #randomImages do
randomImages[i] = display.newImageRect(randomImages[i], 340, 280)
end
-- randomImages now contains all of your randomized image rectangles.
The shuffle algorithm was borrowed from here to show an example of how this could work.
If you are doing
var1 = randomRan
var2 = randomRan
then var1 and var2 will have the same value - randomRan does not get recomputed each time its evaluated. YIf that is what you want, you can repeat the expression you used to initialize randomRan:
var1 = randoms[math.random(1,2)]
var2 = randoms[math.random(1,2)]
and if you want to avoid retyping that ocmplex expression, you can encapsulate it in a function:
--Return a random image
local function randomRan()
return randoms[math.random(1,2)]
end
var1 = randomRan()
var2 = randomRan()

Lua: Is there a way to concatenate "nil" values?

I have the following function in Lua:
function iffunc(k,str,str1)
if k ~= 0 then
return str .. k .. (str1 or "")
end
end
This function allows me to check if value k is populated or not. I'm actually using it to determine if I want to display something that has zero value. My problem is this: I'm trying to concatenate a string of iffunc(), but since some of the values are 0, it returns an error of trying to concatenate a nil value. For instance:
levellbon = iffunc(levellrep["BonusStr"],"#wStr#r{#x111","#r}") .. iffunc(levellrep["BonusInt"],"#wInt#r{#x111","#r}") .. iffunc(levellrep["BonusWis"],"#wWis#r{#x111","#r}")
If any of the table values are 0, it'll return the error. I could easily put 'return 0' in the iffunc itself; however, I don't want a string of 000, either. So how can I work it where no matter which values are nil, I won't get that error? Ultimately, I'm going to do an iffunc on the levellbon variable to see if that's populated or not, but I've got that part figured out. I just need to get past this little hurdle right now. Thanks!
I'd do this:
function iffunc(k,str,str1)
if k == 0 then return "" end
return str .. k .. (str1 or "")
end
You should add an else statement in the function, where you return an empty string ("").

Strange table error in Lua

Okay, so I've got a strange problem with the following Lua code:
function quantizeNumber(i, step)
local d = i / step
d = round(d, 0)
return d*step
end
bar = {1, 2, 3, 4, 5}
local objects = {}
local foo = #bar * 3
for i=1, #foo do
objects[i] = bar[quantizeNumber(i, 3)]
end
print(#fontObjects)
After this code has been run, the length of objects should be 15, right? But no, it's 4. How is this working and what am I missing?
Thanks, Elliot Bonneville.
Yes it is 4.
From the Lua reference manual:
The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).
Let's modify the code to see what is in the table:
local objects = {}
local foo = #bar * 3
for i=1, foo do
objects[i] = bar[quantizeNumber(i, 3)]
print("At " .. i .. " the value is " .. (objects[i] and objects[i] or "nil"))
end
print(objects)
print(#objects)
When you run this you see that objects[4] is 3 but objects[5] is nil. Here is the output:
$ lua quantize.lua
At 1 the value is nil
At 2 the value is 3
At 3 the value is 3
At 4 the value is 3
At 5 the value is nil
At 6 the value is nil
At 7 the value is nil
At 8 the value is nil
At 9 the value is nil
At 10 the value is nil
At 11 the value is nil
At 12 the value is nil
At 13 the value is nil
At 14 the value is nil
At 15 the value is nil
table: 0x1001065f0
4
It is true that you filled in 15 slots of the table. However the # operator on tables, as defined by the reference manual, does not care about this. It simply looks for an index where the value is not nil, and whose following index is nil.
In this case, the index that satisfies this condition is 4.
That is why the answer is 4. It's just the way Lua is.
The nil can be seen as representing the end of an array. It's kind of like in C how a zero byte in the middle of a character array is actually the end of a string and the "string" is only those characters before it.
If your intent was to produce the table 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5 then you will need to rewrite your quantize function as follows:
function quantizeNumber(i, step)
return math.ceil(i / step)
end
The function quantizeNumber is wrong. The function you're looking for is math.fmod:
objects[i] = bar[math.fmod(i, 3)]

Resources