What does % mean in this statement in kotlin? [duplicate] - kotlin

This question already has answers here:
Understanding The Modulus Operator %
(10 answers)
Closed 2 years ago.
I am learning kotlin and in a snipped of code iterating through a list i have this line:
currentIndex = (currentIndex + 1) % myList.size
I am confused by the % sign. Does it mean that you should increment currentIndex by 1 until you get to the size of myList?
I couldnt find anything in documentation about it and the text book just seems to assume I should know!

Modulus operator. Take a look to the next links:
https://kotlinlang.org/docs/reference/operator-overloading.html
https://www.programiz.com/kotlin-programming/operators
EDIT 1: Sorry, I forgot to answer your question really.
What it makes that statement is to increment the currentIndex by 1 at each iteration, until it ranges the whole list. When that happens, the currentIndex is initialized to 0 again. When currentIndex = 9, the next iteration will be set to zero again.
Cheers.

Related

getBytes exceeds data length, but the range is obviously less than the length [duplicate]

This question already has an answer here:
Out of bounds Problem with attributedSubstringFromRange
(1 answer)
Closed 6 years ago.
I am getting this output:
[NSConcreteData getBytes:range:]: range {2605022, 2605022} exceeds data length 3907534'
From this statement:
for(uint i = data.length*2/3; i<data.length; i++){
// NSLog(#"i: %u",i);
[data getBytes:buffer range:NSMakeRange(i,i)];
}
What I am doing wrong? I have never used Objective-C before, so I really don't know what I'm doing.
For those in my shoes, NSMakeRange is not start and end. It is start and length. A similar question was posed here: http://idevapps.com/forum/showthread.php?tid=181

What does a square-bracketed index after an NSArray mean? [duplicate]

This question already has answers here:
What are the details of "Objective-C Literals" mentioned in the Xcode 4.4 release notes?
(4 answers)
Closed 8 years ago.
Going through iTunes U Developing iOS 7 Apps for iPhone and iPad and in Lecture 3 slides, on page 120, there's a Quiz question that asks what the following line of code does. Frankly, I'm a bit stumped, and hoped someone could break it down.
cardA.contents = #[cardB.contents,cardC.contents][[cardB match:#[cardC]] ? 1 : 0];
So, I get the first part, cardA.contents = a new array with cardB.contents and cardC.contents in the array. But, next comes (I guess??) an index that returns either 1 or 0 depending if cardB matches an array that includes cardC.
Here's what I don't "get", and maybe it's just a syntax issue.... is what this does?
How is
cardA.contents = #[cardB.contents,cardC.contents][0];
or
cardA.contents = #[cardB.contents,cardC.contents][1];
Valid? Or, did I miss something?
Your understanding is completely correct; you're just missing one bit of syntax. Subscripted access of NSArrays with the array[index] form is part of the "collection literals" feature introduced by Clang a little while back.
It's transformed by the compiler into a call to [array objectAtIndexedSubscript:index].
As usual, in writing this out, it makes sense. It's literally saying, that if cardB matched cardC, use an index of [1] (cardC), if not, use an index of [0] (cardB)
So,
cardA.contents = cardB.contents // if does NOT match
cardA.contents = cardC.contents // if matches
(based on the index).
Duh.. Sorry for a silly question...

Why use `i` as the index variable in iterations? [duplicate]

This question already has answers here:
Why are variables "i" and "j" used for counters?
(23 answers)
Closed 9 years ago.
I assume there is some historical/mathematical reason that whenever I write I for loop, I use i:
for (var i=0; i<10; i++) {
// do something 10 times
}
I know i is used in mathematics for summations (Σ) and products (∏). Does it just mean "index", or is there some more significant meaning?
I believe it does just mean "index" in the example mentioned.
I know it's not answering your question and probably stating the obvious but I personally would always try to give the variable name some meaning for readability and avoid this confusion when reading others code e.g.
for (int productCounter = 0; productCounter<10; productCounter++){
// do something 10 times
}
In Fortran, variables starting with letters I through M were automatically of type INTEGER, so people could write:
DO 10 J = 1, 10
...do something 10 times...
10 CONTINUE
Labels were numeric in columns 1-5; column 6 was for the continuation character (if needed), and the code started in column 7 (originally up to column 72; column 73-80 on the punched card were for the card's sequence number in the deck).
Single letter names are convenient. In Fortran, you didn't have to declare the variables before you used them.

Objective-C Random Number [duplicate]

This question already has answers here:
Generating random numbers in Objective-C
(13 answers)
Closed 9 years ago.
I have one piece of code that is giving me some trouble and is confusing.
Here is the piece of code...
int r = rand() % 100;
printf("Random number: %u", r);
Why does it print 7 every time? According to the book it should print any number 0-100 I believe... am I wrong with this?
You have to seed it first:
srandom(time(NULL));
It is actually better to just use arc4random:
int r = arc4random() % 100;
printf("Random number: %u", r);
Random numbers are pseudo-random. To make them seem random, they are seeded at arbitrary times based on your design. If you want seeding and "random" number generation to happen simultaneously, use arc4random instead, which also provides other benefits.

binary search middle value calculation

The following is the pseudocode I got from a TopCoder tutorial about binary search
binary_search(A, target):
lo = 1, hi = size(A)
while lo <= hi:
mid = lo + (hi-lo)/2
if A[mid] == target:
return mid
else if A[mid] < target:
lo = mid+1
else:
hi = mid-1
// target was not found
Why do we calculate the middle value as mid = lo + (hi - lo) / 2 ? Whats wrong with (hi + lo) / 2
I have a slight idea that it might be to prevent overflows but I'm not sure, perhaps someone can explain it to me and if there are other reasons behind this.
Although this question is 5 years old, but there is a great article in googleblog which explains the problem and the solution in detail which is worth to share.
It's needed to mention that in current implementation of binary search in Java mid = lo + (hi - lo) / 2 calculation is not used, instead the faster and more clear alternative is used with zero fill right shift operator
int mid = (low + high) >>> 1;
Yes, (hi + lo) / 2 may overflow. This was an actual bug in Java binary search implementation.
No, there are no other reasons for this.
From later on in the same tutorial:
"You may also wonder as to why mid is calculated using mid = lo + (hi-lo)/2 instead of the usual mid = (lo+hi)/2. This is to avoid another potential rounding bug: in the first case, we want the division to always round down, towards the lower bound. But division truncates, so when lo+hi would be negative, it would start rounding towards the higher bound. Coding the calculation this way ensures that the number divided is always positive and hence always rounds as we want it to. Although the bug doesn't surface when the search space consists only of positive integers or real numbers, I've decided to code it this way throughout the article for consistency."
It is indeed possible for (hi+lo) to overflow integer. In the improved version, it may seem that subtracting lo from hi and then adding it again is pointless, but there is a reason: performing this operation will not overflow integer and it will result in a number with the same parity as hi+lo, so that the remainder of (hi+lo)/2 will be the same as (hi-lo)/2. lo can then be safely added after the division to reach the same result.
Let us assume that the array we're searching in, is of length INT_MAX.
Hence initially:
high = INT_MAX
low = 0
In the first iteration, we notice that the target element is greater than the middle element and so we shift the start index to mid as
low = mid + 1
In the next iteration, when mid is calculated, it is calculated as (high + low)/2
which essentially translates to
INT_MAX + low(which is half of INT_MAX + 1) / 2
Now, the first part of this operation i.e. (high + low) would lead to an overflow since we're going over the max Int range i.e. INT_MAX
Because Unsigned right shift is not present in Go programming, To avoid integer overflow while calculating middle value in Go Programming language we can write like this.
mid := int(uint(lo+hi) >> 1)
Why question is answered but it is not easy to understand why solution works.
So let's assume 10 is high and 5 is low. Assume 10 is highest value integer can have ( 10+1 will cause overflow ).
So instead of doing (10+5)/2 ≈ 7 ( because 10 + anything will lead overflow).
We do 5+(10-5)/2=> 5 + 2.5 ≈ 7