what's the use of .count command in repeat while loop? - ios

I recently began to study swift as my first programming language and there's a very simple term that i can't find an answer for it.
take a look at this code:
var a = [Int]()
repeat {
let randomNumbers = Int.random(in: 0...10)
if a.contains(randomNumbers) == false {
a.append(randomNumbers)
}
print(randomNumbers)
} while (a.count < 10)
so this code is supposed to add 10 numbers (no duplicates) from 0...10 into the array until all unique integers are listed. what I don't understand is the role of "while" here.
doesn't the last line mean the number of "generated numbers" must be less than 10? then why every time I run the code I get more than 10 numbers (say 30-40) in the console?
Also according to the code, this code must not generate dupes. then why do I get some numbers printed 2,3 times in the console?

you check if randomNumbers already added to array a, if yes, the loop will be executed again, until a.count < 10.
if you move the print statement inside the if statement, it will be printed exactly 10 times.

Related

I am looking for a Lua find and replace logic

enter image description here
I just started working on lua scripting since a week. I have a lua file where in the logic needs to be written for a certain condition.
The condition when gets triggered
it does an iteration on one of the fields to change value from
(ABC123-XYZ) to this value
(ABC123#1-XYZ) and it keeps increasing whenever iterations happens (ABC123#2-XYZ)
I need to run a function that removes the # followed by number to change it back to (ABC123-XYZ). Looking for any advice!
Edit 1:
Below is the updated code that is written Thanks to #Piglet
I have another scenario if therr are two hashes in the variable.
local x = 'BUS144611111-PNB_00#80901#1555-122TRNHUBUS'
local b = x:gsub("#%d+","")
function remove_char(a) a=a:gsub("#%d+","")
return a;
end if string.match(x,"#")
then print('function')
print(remove_char(x));
else print(x);
end
Expected output should be
x = 'BUS144611111-PNB_00#80901-122TRNHUBUS' for the aforesaid variable
local a = "ABC123#1-XYZ"
local b = a:gsub("#%d+", "")
this will remove any # followed by or one more digits from your string.

How do you use reduce(into:) in swift [duplicate]

This question already has answers here:
What is the reduce() function doing, in Swift
(4 answers)
Closed 9 months ago.
I am reading iOS 13 Programming Fundamentals with Swift, got to the part about reduce() and I think I understand it more or less, but then there is reduce(into:) and this piece of code:
let nums = [1,2,3,4,5]
let result = nums.reduce(into: [[],[]]) { temp, i in
temp[i%2].append(i)
}
// result is now [[2,4],[1,3,5]]
So this code takes an array of Int and splits it into 2 arrays, even and odd. The problem is that I have no idea what's happening inside the brackets {}.
In the case of reduce, the first parameter is the first one of the iteration and then the closure is supposed to process all the items one after the other, similar to map() but more powerful (here one loop is enough to get the two arrays but with map() I would need 2 loops, according to the book).
I cannot understand the syntax here anyway, especially what does "temp" stand for and that use of "in". And how is "append()" appending the value to the proper array??
Inside the closure, "temp" is the result format which is [[][]] and "i" is each number. As you said it processes all numbers in a loop. When % is used it returns the division remainder, so for the odd numbers like "1,3,5", it returns "1" and for the even numbers "0", which means that "temp" appends these values to the array in these respective indexes.
So if we debug and replace the variables for constants the results would be:
temp[1].append(1) //1%2 = 1/2 left 1 [[][1]]
temp[0].append(2) //2%2 = 2/2 left 0 [[2][1]]
temp[1].append(3) //3%2 = 3/2 = 1 left 1 [[2][1,3]]
temp[0].append(4) //4%2 = 4/2 left 0 [[2,4][1,3]]
temp[1].append(5) //5%2 = 5/2 = 2 left 1 [[2,4][1,3,5]]
According to the documentation the closure is called sequentially with a mutable accumulating value initialized that when exhausted, is returned to the caller.

Finding the number of digits in a number restricted number of tools since I am a Python beginner

def digits(n):
total=0
for i in range(0,n):
if n/(10**(i))<1 and n/(10**(i-1))=>1:
total+=i
else:
total+=0
return total
I want to find the number of digits in 13 so I do the below
print digits(13)
it gives me $\0$ for every number I input into the function.
there's nothing wrong with what I've written as far as I can see:
if a number has say 4 digits say 1234 then dividing by 10^4 will make it less than 1: 0.1234 and dividing by 10^3 will make it 1.234
and by 10^3 will make it 1.234>1. when i satisfies BOTH conditions you know you have the correct number of digits.
what's failing here? Please can you advise me on the specific method I've tried
and not a different one?
Remember for every n there can only be one i which satisfies that condition.
so when you add i to the total there will only be i added so total returning total will give you i
your loop makes no sense at all. It goes from 0 to exact number - not what you want.
It looks like python, so grab a solution that uses string:
def digits(n):
return len(str(int(n))) # make sure that it's integer, than conver to string and return number of characters == number of digits
EDIT:
If you REALLY want to use a loop to count number of digits, you can do this this way:
def digits(n):
i = 0
while (n > 1):
n = n / 10
++i
return i
EDIT2:
since you really want to make your solution work, here is your problem. Provided, that you call your function like digits(5), 5 is of type integer, so your division is integer-based. That means, that 6/100 = 0, not 0.06.
def digits(n):
for i in range(0,n):
if n/float(10**(i))<1 and n/float(10**(i-1))=>1:
return i # we don't need to check anything else, this is the solution
return null # we don't the answer. This should not happen, but still, nice to put it here. Throwing an exception would be even better
I fixed it. Thanks for your input though :)
def digits(n):
for i in range(0,n):
if n/(10**(i))<1 and n/(10**(i-1))>=1:
return i

Can't modify loop-variable in lua [duplicate]

This question already has answers here:
Lua for loop reduce i? Weird behavior [duplicate]
(3 answers)
Closed 7 years ago.
im trying this in lua:
for i = 1, 10,1 do
print(i)
i = i+2
end
I would expect the following output:
1,4,7,10
However, it seems like i is getting not affected, so it gives me:
1,2,3,4,5,6,7,8,9,10
Can someone tell my a bit about the background concept and what is the right way to modify the counter variable?
As Colonel Thirty Two said, there is no way to modify a loop variable in Lua. Or rather more to the point, the loop counter in Lua is hidden from you. The variable i in your case is merely a copy of the counter's current value. So changing it does nothing; it will be overwritten by the actual hidden counter every time the loop cycles.
When you write a for loop in Lua, it always means exactly what it says. This is good, since it makes it abundantly clear when you're doing looping over a fixed sequence (whether a count or a set of data) and when you're doing something more complicated.
for is for fixed loops; if you want dynamic looping, you must use a while loop. That way, the reader of the code is aware that looping is not fixed; that it's under your control.
When using a Numeric for loop, you can change the increment by the third value, in your example you set it to 1.
To see what I mean:
for i = 1,10,3 do
print(i)
end
However this isn't always a practical solution, because often times you'll only want to modify the loop variable under specific conditions. When you wish to do this, you can use a while loop (or if you want your code to run at least once, a repeat loop):
local i = 1
while i < 10 do
print(i)
i = i + 1
end
Using a while loop you have full control over the condition, and any variables (be they global or upvalues).
All answers / comments so far only suggested while loops; here's two more ways of working around this problem:
If you always have the same step size, which just isn't 1, you can explicitly give the step size as in for i =start,end,stepdo … end, e.g. for i = 1, 10, 3 do … or for i = 10, 1, -1 do …. If you need varying step sizes, that won't work.
A "problem" with while-loops is that you always have to manually increment your counter and forgetting this in a sub-branch easily leads to infinite loops. I've seen the following pattern a few times:
local diff = 0
for i = 1, n do
i = i+diff
if i > n then break end
-- code here
-- and to change i for the next round, do something like
if some_condition then
diff = diff + 1 -- skip 1 forward
end
end
This way, you cannot forget incrementing i, and you still have the adjusted i available in your code. The deltas are also kept in a separate variable, so scanning this for bugs is relatively easy. (i autoincrements so must work, any assignment to i below the loop body's first line is an error, check whether you are/n't assigning diff, check branches, …)

IOS: Get two digits of a double (€) NOT to display the value, just return it

I´ve read a lot of posts about this but all of them were to limit the number digits to show them(NSString) .In my case I have:
I compare two double values(wich are the "same"), each of them got from different mathematical operations. For example: (4.800000 and 4.800000)
double result1=4.800000, result2=4.800000
//compare the results:
if(result1==result2){
msg.text=#"well done!!";
}else if(result1>result2){
msg.text=#"continue your work";
}
"I´m working with money (4,80€)"
In the msg label i get "continue your work" message, not the "well done". I don´t even know if the comparison is done in a correct way.
I think that the best idea would be to limit 4.800000 to 4.80 in order to delete small values and get a exact comparison.(how could i do this?)
I DONT WANT to limit the number to two digits just to PRINT the solution, I want to WORK with that number.
You can do something like this:
double a = 2.55000, b = 2.55002;
if(fabs(a-b)<1e-3) {
// code here, a == b
} else {
// code here, a != b
}
use floor(<#double#>) to round down OR just subtract them and floor the result.
For a nice answer to this problem see:
https://stackoverflow.com/a/10335601/474896
Which could be summarized as a simple as:
if (fabs(x-y) < FLT_EPSILON) {/* ... */}
However since you you're working with money values you should check out NSDecimalNumber.
Or as Marcus Zarra puts it:
"If you are dealing with currency at all, then you should be using
NSDecimalNumber.".

Resources