Two variables in for loop using Swift - swift

How to use two variables in for loop?
for j,k in zip(range(x,0,-1),range(y,-1,-1)
I want to implement this in Swift.

If your range is a python function, then the Swift-y solution will be:
let x = 100
let y = 99
let rx = reverse(0...x)
let ry = reverse(-1...y)
for (j,k) in zip(rx, ry) {
println(j, k)
}

if you're looping over a dictionary you can loop like this
for (key,value) in dictionary {
}
if an array etc. you're going to have to use a c style for loop
just sub in whatever start and end indices you need
for var j = 0 , k = 0; j < 10 && k < 10; j++ , k++ {
}
EDIT
missed the zip in there. You can loop like this
for (j,k) in zip(range1, range2) {
}

Related

How to print ONCE if there are multiple correct answers? (MATLAB)

So I have arr = randi([0,20],20,1). I want to show: If there are numbers less than 5, fprintf('Yes\n') only once. Im using a for loop (for i = 1 : length(arr)) and indexing it.
As your description, maybe you need if statement within for loop like below
for i = 1:length(arr)
if arr(i) < 5
fprintf('Yes\n');
break
end
end
If you want to print Yes once, you can try
if any(arr < 5)
fprintf('Yes\n')
endif
If you don't want to use break, the code below might be an option
for i = 1:min(find(arr <5))
if (arr(i) < 5)
fprintf('Yes\n');
end
end
You can use a break statement upon finding the first value under 5 and printing the Yes statement.
Using a break Statement:
arr = randi([0,20],20,1);
for i = 1: length(arr)
if arr(i) < 5
fprintf("Yes\n");
break;
end
end
Extension:
By Using any() Function:
Alternatively, if you'd like to concise it down without the need for a for-loop the any() function can be used to determine if any values within the array meet a condition in this case arr < 5.
arr = randi([0,20],20,1);
if(any(arr < 5))
fprintf("Yes\n");
end
By Using a While Loop:
Check = 0;
arr = randi([0,20],20,1);
i = 1;
while (Check == 0 && i < length(arr))
if arr(i) < 5
fprintf("Yes\n");
Check = 1;
end
i = i + 1;
end

for-in loop swift 4 two variables and increments

I want to ask a question regarding for-in loops in swift 4. I want to set two variables and their increments:
j = 1, f = 87.5; j < numberOfGrids && f > (-90) ; j++, f -= 2.5 { }
How can you convert this to Swift 4? I hope to hear back from you folks soon!
You're trying to iterate over two sequences, stopping when the shortest is exhausted. The first sequence is 1..<numberOfGrids. The second is "values from 87.5 to -90 by -2.5" which is stride(from: 87.5, to: -90, by: -2.5).
To iterate over two sequences, stopping when the shortest is exhausted, you use zip:
let grids = 1..<numberOfGrids
let fs = stride(from: 87.5, to: -90, by: -2.5) // not sure what "f" represents
for (j, f) in zip(grids, fs) {
print(j, f)
}
You could try this code:
let numberOfGrid = 100
var j = 1
var f = 87.5
repeat {
// Do something here
j += 1
f -= 2.5
// Do something here
} while j < numberOfGrid && f > -90

for loop over odd numbers in swift

I am trying to solve the task
Using a standard for-in loop add all odd numbers less than or equal to 100 to the oddNumbers array
I tried the following:
var oddNumbers = [Int]()
var numbt = 0
for newNumt in 0..<100 {
var newNumt = numbt + 1; numbt += 2; oddNumbers.append(newNumt)
}
print(oddNumbers)
This results in:
1,3,5,7,9,...199
My question is: Why does it print numbers above 100 although I specify the range between 0 and <100?
You're doing a mistake:
for newNumt in 0..<100 {
var newNumt = numbt + 1; numbt += 2; oddNumbers.append(newNumt)
}
The variable newNumt defined inside the loop does not affect the variable newNumt declared in the for statement. So the for loop prints out the first 100 odd numbers, not the odd numbers between 0 and 100.
If you need to use a for loop:
var odds = [Int]()
for number in 0...100 where number % 2 == 1 {
odds.append(number)
}
Alternatively:
let odds = (0...100).filter { $0 % 2 == 1 }
will filter the odd numbers from an array with items from 0 to 100. For an even better implementation use the stride operator:
let odds = Array(stride(from: 1, to: 100, by: 2))
If you want all the odd numbers between 0 and 100 you can write
let oddNums = (0...100).filter { $0 % 2 == 1 }
or
let oddNums = Array(stride(from: 1, to: 100, by: 2))
Why does it print numbers above 100 although I specify the range between 0 and <100?
Look again at your code:
for newNumt in 0..<100 {
var newNumt = numbt + 1; numbt += 2; oddNumbers.append(newNumt)
}
The newNumt used inside the loop is different from the loop variable; the var newNumt declares a new variable whose scope is the body of the loop, so it gets created and destroyed each time through the loop. Meanwhile, numbt is declared outside the loop, so it keeps being incremented by 2 each time through the loop.
I see that this is an old question, but none of the answers specifically address looping over odd numbers, so I'll add another. The stride() function that Luca Angeletti pointed to is the right way to go, but you can use it directly in a for loop like this:
for oddNumber in stride(from:1, to:100, by:2) {
// your code here
}
stride(from:,to:,by:) creates a list of any strideable type up to but not including the from: parameter, in increments of the by: parameter, so in this case oddNumber starts at 1 and includes 3, 5, 7, 9...99. If you want to include the upper limit, there's a stride(from:,through:,by:) form where the through: parameter is included.
If you want all the odd numbers between 0 and 100 you can write
for i in 1...100 {
if i % 2 == 1 {
continue
}
print(i - 1)
}
For Swift 4.2
extension Collection {
func everyOther(_ body: (Element) -> Void) {
let start = self.startIndex
let end = self.endIndex
var iter = start
while iter != end {
body(self[iter])
let next = index(after: iter)
if next == end { break }
iter = index(after: next)
}
}
}
And then you can use it like this:
class OddsEvent: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
(1...900000).everyOther{ print($0) } //Even
(0...100000).everyOther{ print($0) } //Odds
}
}
This is more efficient than:
let oddNums = (0...100).filter { $0 % 2 == 1 } or
let oddNums = Array(stride(from: 1, to: 100, by: 2))
because supports larger Collections
Source: https://developer.apple.com/videos/play/wwdc2018/229/

How to break/escape from inner loop in Swift

I'm looking for a way to stop iterating the just inner loop once a condition is met. I thought of using "continue" but it's not doing what i wanted.
"break" seems to break the entire loop including the outer loop.
So in my code, once the condition is met. I want to stop iterating j but i want to start iterating i again. Thank you,
for i in 0..<sortedArray.count{
for j in 1..<sortedArray.count{
if sortedArray[j] == sortedArray[i]{
//I want to skip iterating inner loop j from now. and back to iterating i
}
}
}
Break just breaks the inner loop.
e.g.
for var i in 0...2
{
for var j in 10...15
{
print("i = \(i) & j = \(j)")
if j == 12
{
break;
}
}
}
Output -->
i = 0 & j = 10
i = 0 & j = 11
i = 0 & j = 12
i = 1 & j = 10
i = 1 & j = 11
i = 1 & j = 12
i = 2 & j = 10
i = 2 & j = 11
i = 2 & j = 12
The nested index loop and subsequent element access by index approach (anArray[accessByThisIndex]) is kind of C++'ish rather than Swifty. Depending on you application, you can make good use of neat features in Swift to achieve your goal.
E.g., assuming (based on the anme of your array) your array is sorted,
let sortedArray = [2, 5, 7, 9]
for i in sortedArray {
for j in sortedArray where j <= i {
print(j)
}
print("-----")
}
/* 2
-----
2
5
-----
2
5
7
-----
2
5
7
9
----- */
Note that we don't care about the indices of the array above, instead accessing the elements of the array directly in the for ... in (... where ...) loop(s).
Another alternatively coulkd make use of prefixUpTo(:_)
for i in 1...sortedArray.count {
sortedArray.prefixUpTo(i).forEach {
print($0)
}
print("-----")
}
/* same printout as above */

How to write a non-C-like for-loop in Swift 2.2+?

I have updated Xcode (7.3) and there are a lot of changes; C-like for expressions will be deprecated. For a simple example,
for var i = 0; i <= array.count - 1; i++
{
//something with array[i]
}
How do I write this clear and simple C-like for-loop to be compliant with the new changes?
for var i = 0, j = 1; i <= array.count - 2 && j <= array.count - 1; i++, j++
{
//something with array[i] and array[j]
}
Update.
One more variant
for var i = 0; i <= <array.count - 1; i++
{
for var j = i + 1; j <= array.count - 1; j++
{
//something with array[i] and array[j]
}
}
And more ...
for var i = 0, j = 1, g = 2; i <= array.count - 3 && j <= array.count - 2 && g <= array.count - 1; i++, j++, g++
{
//something with array[i] and array[j] and array[g]
}
Update2 After several suggestions for me while loop is preferable universal substitution for all cases more complicated than the simple example of C-like for-loop (suitable for for in expression). No need every time to search for new approach.
For instance: Instead of
for var i = 0; i <= <array.count - 1; i++
{
for var j = i + 1; j <= array.count - 1; j++
{
//something with array[i] and array[j]
}
}
I can use
var i = 0
while i < array.count
{
var j = i + 1
while j < array.count
{
//something with array[i] and array[j]
j += 1
}
i += 1
}
charl's (old) answer will crash. You want 0..<array.count:
for index in 0..<array.count {
// ...
}
If you want something like your i/j loop you can use stride and get i's successor:
for i in 0.stride(through: array.count, by: 1) {
let j = i.successor()
// ...
}
Just make sure to check i.successor() in case you go out of bounds.
for var i = 0; i <= array.count - 1; i++ {
//something with array[i]
}
Here you don't need the element index at all, so you can simply
enumerate the array elements:
for elem in array {
// Do something with elem ...
}
for var i = 0, j = 1; i <= array.count - 2 && j <= array.count - 1; i++, j++ {
//something with array[i] and array[j]
}
To iterate over pairs of adjacent elements, use zip()
and dropFirst():
for (x, y) in zip(array, array.dropFirst()) {
// Do something with x and y ...
print(x, y)
}
Output:
1 2
2 3
3 4
4 5
For other distances, use dropFirst(n):
for (x, y) in zip(array, array.dropFirst(3)) {
// Do something with x and y ...
print(x, y)
}
Output:
1 4
2 5
There are probably many solutions to do
for var i = 0; i <= <array.count - 1; i++ {
for var j = i + 1; j <= array.count - 1; j++ {
//something with array[i] and array[j]
}
}
without a C-style for-loop, here is one:
for (index, x) in array.enumerate() {
for y in array.dropFirst(index + 1) {
print(x, y)
}
}
If you want to do something with subsequent pairs there are many other ways to do it.
Something like this would work...
var previousItem = array.first
for index in 1..<array.count {
let currentItem = array[index]
// do something with current and previous items
previousItem = currentItem
}
for (i, j) in zip(array.dropLast(), array.dropFirst())
{
// something
}
What you're really doing here is enumerating two parallel sequences. So, create those sequences and use zip to turn them into a single sequence.
Do enumeration
let suits = ["♠︎", "♥︎", "♣︎", "♦︎"]
for (i, suite) in suits.enumerate() {
// ...
}
or to compare neighbors
import Foundation
let suits = ["♠︎", "♥︎", "♣︎", "♦︎"]
for (i, suite1) in suits.enumerate() {
let j = i.successor()
if j < suits.count {
let suite2 = suits[j]
// ...
}
}
or zipping and enumerating
let suits = ["♠︎", "♥︎", "♣︎", "♦︎"]
let combination = zip(suits, suits.dropFirst())
for (i, (s1,s2)) in combination.enumerate() {
print("\(i): \(s1) \(s2)")
}
result
0: ♠︎ ♥︎
1: ♥︎ ♣︎
2: ♣︎ ♦︎
Worst case, you can convert it to a while loop.
var i = 0
var j = 1
while i <= array.count -2 && j <= array.count - 1 {
// something
i += 1
j += 1
}
-- EDIT --
Because you said, "while loop is preferable universal substitution for all cases more complicated than the simple example of C-like for-loop"... I feel the need to expand on my answer. I don't want to be responsible for a bunch of bad code...
In most cases, there is a simple for-in loop that can handle the situation:
for item in array {
// do something with item
}
for (item1, item2) in zip(array, array[1 ..< array.count]) {
// do something with item1 and item2
}
for (index, item1) in array.enumerate() {
for item2 in array[index + 1 ..< array.count] {
// do soemthing with item1 and item2
}
}
For your last case, you might be justified using a for look, but that is an extremely rare edge case.
Don't litter your code with for loops.
to compare neighbouring elements from the same array you can use
let arr = [1,2,2,5,2,2,3,3]
arr.reduce(nil) { (i, j)->Int? in
if let i = i {
print(i,"==",j,"is",i == j)
}
return j
}
it prints
1 == 2 is false
2 == 2 is true
2 == 5 is false
5 == 2 is false
2 == 2 is true
2 == 3 is false
3 == 3 is true
more 'generic' approach without using subscript but separate generators
let arr1 = [1,2,3,4,5,6,7,8,9,0]
var g1 = arr1.generate()
var g2 = (arr1.dropFirst(5) as AnySequence).generate()
var g3 = (arr1.dropFirst(6) as AnySequence).generate()
while true {
if let a1 = g1.next(),
let a2 = g2.next(),
let a3 = g3.next() {
print(a1,a2,a3)
} else {
break
}
}
/* prints
1 6 7
2 7 8
3 8 9
4 9 0
*/