Swift way to C-style for loop that alters initial variable? [duplicate] - swift

This question already has answers here:
is there anyway to increment exponentially in swift?
(4 answers)
Closed 2 years ago.
In many languages a for loop is able to alter i like the below. This for loop will double i each loop around.
for(int i = 0; i < total; i = i + i){}
Swift has for var i in stride(from: 0, to: total, by: N)
and for i in 0..<total
but neither allows us to alter i like the C style for loop above.
Is there a Swifty way to do this?
The goal is to change the pace each loop around instead of in a constant way like the N in stride.

You're looking for the sequence global function. The equivalent of your
for(int i = 0; i < total; i = i + i)
(I assume you meant 1, not 0, since otherwise you'd just get 0 forever, eh?) is:
let total = 100 // let's say
let seq = sequence(first:1) {$0 >= 100 ? nil : $0 + $0}
for i in seq {
print(i)
}
Output:
1
2
4
8
16
32
64
128

Related

Where a Number Occur More than or equal to N/3 Times [duplicate]

This question already has answers here:
Find the majority element in array
(26 answers)
Closed last month.
This post was edited and submitted for review 18 days ago.
Find number which is occur more than N/3 times in array. not N/2 times? just look at question first.
Without Using Moore's Algorithms.
You will need to take into account the maximum (What is your worst scenario).
Unless you have not checked all elements in your array, 2 can compete till the end.
Lets assume you have the following array:
[1,2,3,1,2,2,1,2]
when you are at element 4, 1 is the winner with a count of 2.
at element 5, 1 & 2 are equal represented.
at element 6, 2 is the winner with a count of 3.
etc.
Based on this example you can see you will need to run over all of teh elements one time: O(n)
int majorityElement(int a[], int size){
// your code here
//Moore Voting Algorithm
//Finding the candidate element
int count = 1, res = 0;
for(int i=1;i<size;i++){
if(a[i]==a[res]) count++;
else count--;
if(count==0){
res = i;
count = 1;
}
}
//Checking
count = 0;
for(int i=0;i<size;i++){
if(a[i]==a[res]) count++;
}
return count>size/2? a[res]: -1;
}

How can I traverse an array with stride? [duplicate]

This question already has an answer here:
How can I do a Swift for-in loop with a step?
(1 answer)
Closed 3 years ago.
I want to traverse an array with a stride. For example, I have an array [0,1,2,3,4,5,6,7,8,9].And I want to traverse this array with a stride of 3. The oc code likes below:
for (int i = 0; i < array.count; i += 3) {
}
How can I do that with swift.
You can use a for loop with stride to traverse the array
let testarray = [0,1,2,3,4,5,6,7,8,9]
for i in stride(from: 0, to: testarray.count, by: 3) {
print(testarray[i])
}

Swift C-style loop [duplicate]

This question already has answers here:
How can I do a Swift for-in loop with a step?
(1 answer)
Express for loops in swift with dynamic range
(2 answers)
Closed 6 years ago.
for (var i = 1; i < 1024; i *= 2) {
print(i)
}
How can this be done with for in loop?
The given solution is for += operator not *= operator. Please provide a solution for *= thanks.
In Swift 3 you can do
for f in sequence(first: 1, next: { $0 < (1024 / 2) ? $0 * 2 : nil }) {
print(f)
}
The concept of the sequence function is described in the documentation.
Printing an infinite list is easy, the code would just be
for f in sequence(first: 1, next: {$0 * 2}) {
print(f)
}
Since we want the program to stop at some point, we us the ternary operator ? to terminate the list once we reach the maximum value.
Since the last value we want to print is 512, the last value we have to double is 256. For 512 which does not satisfy the condition < (1024 / 2) we have nil and thereby stop.

Struggling to understand the code - which tries to return the decimal digit 'n' places in from the right of the number

I'm new to Swift and is trying to learn the concept of extension. I saw this code in "the swift programming language", which tries to return the decimal digit 'n' places in from the right of the number. The code work fine, but I am struggling to understand how the code actually works.
Could someone explain it to me?
extension Int {
subscript(var digitIndex: Int) -> Int {
var decimalBase = 1
while digitIndex > 0 {
decimalBase *= 10
--digitIndex
}
return (self / decimalBase) % 10
}
}
746381295[0]
// returns 5
746381295[1]
// returns 9
746381295[2]
// returns 2
746381295[8]
// returns 7
746381295[9]
Extensions work by adding capability to existing types, with the caveat that they cannot introduce their own storage. In the case in point:
/*1*/ extension Int {
/*2*/ subscript(var digitIndex: Int) -> Int {
/*3*/ var decimalBase = 1
/*4*/ while digitIndex > 0 {
/*5*/ decimalBase *= 10
/*6*/ --digitIndex
/*7*/ }
/*8*/ return (self / decimalBase) % 10
}
}
Line 1 defines the extension as applying to all Int types.
Line 2 is setting up a new subscript operator for an Int, which will allow you to have 12345[4] and produce 'something'. Lines 3-8 define that something.
The while in lines 4-8 is multiplying decimalBase by 10 for 'digitIndex' times. A bit of a weird way of doing it, but never mind. The upshot is if digitIndex is 1, decimalBase is 10; if it's 2, decimal base is 100; 3 it's 1000; etc.
The guts is in line 8. First it retrieves self. Since the extension applies to an Int, self will be that integer value. It then divides it by decimalBase, and because they're both integers, any fractional part will be lost. Therefore in the case of 746381295[2] decimalBase will be 100 so you get 7463812. Then it uses '%' to get the remainder of the division by 10. So 7463812 divided by 10 is 746381 with a remainder of 2. So the returned value is 2.
Hope that explains it.
Pre-empting your question, I might use for in this case, instead of the while:
for _ in 0..<digitIndex {
decimalBase *= 10
}
I haven't thought too much about how often the above loops, it might run once to often or once too few, but you get the idea.
Even better would be to use the 'raising to the power' operator (not really sure what it's called).
decimalBase = 10 ^^ digitIndex
Then the whole definition could boil down to:
return (self / (10 ^^ digitIndex)) % 10
I will leave it to you to decide whether that's better or not.
Either way, I wouldn't really create this extension, and I assume it was just done for the purpose of demonstration.
Simply put, decimalBase is calculated to be 1 with an index of 0, 10 with an index of 1, 100 with an index of 2, 1,000 with an index of 3, and so on. In other words, decimalBase ends up equal to 10 ^ digitIndex.
So look at the case where digitIndex is 3, for instance. decimalBase will end up being 1,000, so:
746381259 / 1000 == 746381
and then:
746381 % 10 == 1
so that's how you get from 746381259[3] to 1.

What does for i = 1 ; i <= power ; 1 += 1) { mean?

Sorry for pretty basic question.
Just starting out. Using flowgorithm to write code that gives out a calculation of exponential numbers.
The code to do it is:
function exponential(base, power) {
var answer;
answer = 1;
var i;
for (i = 1 ; i <= power ; i+= 1) {
answer = answer * base;
}
return answer;
f
then it loops up to the number of power. And i just understand that in the flowgorithm chart but i dont understand the code for it.
what does each section of the for statement mean?
i = 1 to power, i just need help understanding how it is written? What is the 1+= 1 bit?
Thanks.
The exponential function will take in 2 parameters, base and power.
You can create this function and call (fire) it when ever it is needed like so exponential(2,4).
The for (i = 1; 1 <= power; i+=1) is somewhat of an ugly for loop.
for loops traditionaly take three parameters. The first parameter in this case i =1 is the assignment parameter, the next one 1 <= power is the valadation parameter. So if we call the function like so...exponential(2,4) is i less than 4? The next parameter is an increment/decrement parameter. but this doesnt get executed until the code inside the for loop gets executed. Once the code inside the for loop is executed then this variable i adds 1 to itself so it is now 2. This is usefull because once i is no longer less than or equal to power it will exit the for loop. So in the case of exponential(2,4) once the code inside this for loop is ran 5 times it will exit the for loop because 6 > 5.
So if we look at a variable answer, we can see that before this for loop was called answer was equal to 1. After the first iteration of this for loop answer = answer times base. In the case of exponential(2,4) then answer equals 1 times 2, now answer =2. But we have only looped through the foor loop once , and like i said a for loop goes like (assignment, validator, "code inside the foor loop". then back up to increment/decrement). So since we to loop through this for loop 5 times in the case of exponential(2,4) it will look like so.
exponential(2,4)
answer = 1 * 2
now answer = 2
answer = 2 * 2
now answer = 4
answer = 4 * 2
now answer = 8
answer = 8 * 2
now answer = 16
answer = 16 * 2
now answer = 32
So if we could say... var int ans = exponential(2,4)
Then ans would equal 32 hence, the return answer; at the last line of your code.