Multiple increments in Swift style for loops - swift

I have the following loop in my Swift code:
for var i:Int = 0, j:Int = 0; i < rawDataOut.count; i += 4, ++j {
maskPixels[j] = rawDataOut[i + 3]
}
I'm getting two warnings in Xcode:
C-style for statement is deprecated and will be removed in a future version of Swift
'++' is deprecated: it will be removed in Swift 3
I cannot see how to rewrite this in Swift's For In Loops to take into account the two variables and the 4-stride without it getting messy. Is there a simple elegant translation?

Preconditions to answering this: looking over your example
I will assume that you intended to limit i by i < rawDataOut.count-3 rather than i < rawDataOut.count, otherwise the rawDataOut[i + 3] element access by index wouldn't make much sense w.r.t. runtime safety. Anyway, without you showing us rawDataOut, this is an assumption we shall have to make.
Hence, your original loop (including a verifiable example) looks as follows
/* example data */
var rawDataOut = Array(1...40)
var maskPixels = [Int](count: 10, repeatedValue: 0)
/* your pre-Swift 2.2/3.0 loop */
for var i: Int = 0, j: Int = 0; i < rawDataOut.count-3; i += 4, ++j {
maskPixels[j] = rawDataOut[i + 3]
}
print(maskPixels) //[4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
Using for in ... where
In your specific example case, the multiple increments have a simple relation (j=4*i) so we could solve this without even making use of an explicit j iterate, e.g.
/* example data */
var rawDataOut = Array(1...40)
var maskPixels = [Int](count: 10, repeatedValue: 0)
/* your pre-Swift 2.2/3.0 loop */
for i in 0..<(rawDataOut.count-3) where i%4 == 0 {
maskPixels[i/4] = rawDataOut[i + 3]
}
print(maskPixels) // [4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
but this is possibly not really of interest for the general discussion of two iterates. We move on to a 2-iterate method combining stride and enumerate.
Combining stride and enumerate
One solution is to enumerate the stride described by iterate i in your loop above, and use the enumeration index to construct the second iterate (j above). In your example, the enumerate index exactly corresponds to j, i.e.
/* example data */
var rawDataOut = Array(1...40)
var maskPixels = [Int](count: 10, repeatedValue: 0)
/* Swift >= 2.2 loop */
for (j, i) in 0.stride(to: rawDataOut.count-3, by: 4).enumerate() {
maskPixels[j] = rawDataOut[i + 3]
}
print(maskPixels) // [4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
Note that in Swift 3 (as compared to 2.2), it seems as if the default implementations of stride(to:by:) and stride(through:by:) to protocol Strideable (as non-blueprinted extension methods) will be depracated, and that we're back to (as in Swift 1.2) using the global functions stride(from:to:by:) and stride(from:through:by:), see e.g. the current master branch of swift/stdlib/public/core/Stride.swift
Trickier cases: resort to while
For trickier cases, say a signature in your pre-Swift 2.2 loop as
for var i: Int = 0, j: Int = 0; i < rawDataOut.count-3; i += 4, j += i { ... }
you're probably best of simply using a while loop with one iterate associated with the loop invariant, and a trailing iterate as a free variable; whether this is considered messy or not is a matter of taste, I suppose.
var i = 0, j = 0
while i < rawDataOut.count-3 {
// ...
// increase iterates
i += 4
j += i
}
I assume the reason for removing the C-style loop is that it's, in most cases, directly covered by for in, stride etc, and for cases where these don't suffice, a good old' while, most likely, will.

In Swift 4
for index in stride(from: 0, to: 10, by: 2){
print(index)
}

Related

Efficient way to get a subsequence with a precondition in Swift

I have an ordered sequence of numbers, let's say something like
0, 1, 2, 3, 5, 6, 11, 12, 15, 20
Given a number N, how could I get a sequence that starts from the last number that is smaller than N? For example, if N = 7, I'd like to get back
6, 11, 12, 15, 20
Please note that this sequence will get very big and new numbers will be appended.
drop(while:) seemed like a good candidate, but in the example above it would also drop 6 so I can't use it.
For huge sorted arrays the most efficient way is binary search. It cuts the array in half until the index was found.
extension RandomAccessCollection where Element : Comparable {
func lastIndex(before value: Element) -> Index {
var slice : SubSequence = self[...]
while !slice.isEmpty {
let middle = slice.index(slice.startIndex, offsetBy: slice.count / 2)
if value < slice[middle] {
slice = slice[..<middle]
} else {
slice = slice[index(after: middle)...]
}
}
return slice.startIndex == self.startIndex ? startIndex : index(before: slice.startIndex)
}
}
let array = [0, 1, 2, 3, 5, 6, 11, 12, 15, 20]
let index = array.lastIndex(before: 7)
print(array[index...])

Best way to find the largest amount of consecutive integers in a sorted array in swift, preferably not using a for loop

Given an array of integers for example let array = [1, 3, 4, 7, 8, 9, 12, 14, 15]
What is the best way of finding the largest amount of consecutive integers preferably without using a for-in loop. If we would pass this array into a function it would return 3 as '7, 8, 9' is the largest amount of consecutive integers.
let array = [1, 3, 4, 7, 8, 9, 12, 14, 15]
func getMaxConsecutives(from array: [Int]) -> Int {
var maxCount = 1
var tempMaxCount = 1
var currentNumber = array[0]
for number in array {
if currentNumber == number - 1 {
tempMaxCount += 1
maxCount = tempMaxCount > maxCount ? tempMaxCount : maxCount
currentNumber = number
} else {
tempMaxCount = 1
currentNumber = number
}
}
return maxCount
}
getMaxConsecutives(from: array)
This works as intended but I would like a more efficient solution something that is not O(n).
I appreciate any creative answers.
You can do it like this:
let array = [1, 3, 4, 7, 8, 9, 12, 14, 15]
if let maxCount = IndexSet(array).rangeView.max(by: {$0.count < $1.count})?.count {
print("The largest amount of consecutive integers: \(maxCount)")
//prints 3
}
I think I can write it more tightly (basically as a one-liner):
let array = [1, 3, 4, 7, 8, 9, 12, 14, 15]
let (_,_,result) = array.reduce((-1000,1,0)) {
$1 == $0.0+1 ? ($1,$0.1+1,max($0.2,$0.1+1)) : ($1,1,$0.2)
}
print(result) // 3
But we are still looping through the entire array — so that we are O(n) — and there is no way to avoid that. After all, think about what your eye does as it scans the array looking for the answer: it scans the whole array.
(One way to achieve some savings: You could short-circuit the loop when we are not in the middle of a run and the maximum run so far is longer than what remains of the array! But the gain might not be significant.)

Swift 3.0 multiple conditions in c-style for loop

I understand how to write a for loop using swift syntax (using .enumerate() and .revers()), however how would I re-write (in swift) the following javascript version of for loop, considering I have multiple conditions to adhere to:
for(var j = 10; j >= 0 && array[j] > value; j--) {
array[j + 1] = array[j];
}
What about this?
for j in (0...10).reversed() {
guard array[j] > value else { break }
array[j + 1] = array[j]
}
I'm not sure that produces exactly the same result, but this is one of the approaches in Swift 3
for j in stride(from:10, through:0, by: -1) {
if array[j] <= value { break }
array[j + 1] = array[j]
}
For the sake of completion (I would personally prefer to use a for loop with a check for an early break, as others have already suggested) – in Swift 3.1 you could use Sequence's prefix(while:) method in order to get the suffix of the array's indices where the elements meet a given predicate.
var array = [2, 3, 6, 19, 20, 45, 100, 125, 7, 9, 21, 22]
let value = 6
for i in array.indices // the array's indices.
.dropLast() // exclude the last index as we'll be accessing index + 1 in the loop.
.reversed() // reversed so we can get the suffix that meets the predicate.
.prefix(while: {array[$0] > value}) // the subsequence from the start of the
{ // collection where elements meet the predicate.
array[i + 1] = array[i]
}
print(array) // [2, 3, 6, 19, 19, 20, 45, 100, 125, 7, 9, 21]
This is assuming that you're looking to begin iterating at the penultimate index of the array. If you want to start at a particular index, you can say:
for i in (0...10).reversed().prefix(while: {array[$0] > value}) {
array[i + 1] = array[i]
}
This will start at the index 10 and iterate down to 0, giving you the same behaviour to the code in your question.
It's worth noting that both of the above variants will first iterate through the reversed indices (until the predicate isn't met), and then through the array's elements. Although, in Swift 3.1, there is a version of prefix(while:) which operates on a lazy sequence – which would allow for just a single iteration through the elements until the predicate isn't met.
Until Swift 3.1, you can use the below extension to get prefix(while:) on a Collection:
extension Collection {
func prefix(while predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Self.SubSequence {
var index = startIndex
while try index < endIndex && predicate(self[index]) {
formIndex(after: &index)
}
return self[startIndex..<index]
}
}

Simple Swift Fibonacci program crashing (Project Euler 2)

I am trying to solve the second problem on Project Euler. The problem is as follows:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
I think I've written a solution, but when I try to run my code it crashes my Swift playground and gives me this error message:
Playground execution aborted: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
var prev = 0
var next = 1
var num = 0
var sum = 0
for var i = 1; i < 400; i++ {
num = prev + next
if next % 2 == 0 {
sum += next
}
prev = next
next = num
}
print(sum)
The weird thing is, if I set the counter on my loop to less than 93, it works fine. Explicitly setting the variable names to Double does not help. Anyone know what's going on here?
There is nothing weird about this at all. Do you know how large the 400 fibonacci number is?
176023680645013966468226945392411250770384383304492191886725992896575345044216019675
Swift Int64 or UInt64 simply cannot handle that large of a number. The later can go up to 18446744073709551615 at max - not even close.
If you change your variables to be doubles it works but will be inaccurate:
var prev : Double = 0
var next : Double = 1
var num : Double = 0
var sum : Double = 0
will yield
2.84812298108489e+83
which is kind of close to the actual value of
1.76e+83
Luckily you do not need to get values that big. I would recommend not writing a for loop but a while loop that calculates the next fibonacci number until the break condition is met whose values do not exceed four million.
The Fibonacci numbers become very large quickly. To compute large Fibonacci numbers, you need to implement some kind of BigNum. Here is a version the makes a BigNum that is implemented internally as an array of digits. For example, 12345 is implemented internally as [1, 2, 3, 4, 5]. This makes it easy to represent arbitrarily large numbers.
Addition is implemented by making the two arrays the same size, then map is used to add the elements, finally the carryAll function restores the array to single digits.
For example 12345 + 67:
[1, 2, 3, 4, 5] + [6, 7] // numbers represented as arrays
[1, 2, 3, 4, 5] + [0, 0, 0, 6, 7] // pad the shorter array with 0's
[1, 2, 3, 10, 12] // add the arrays element-wise
[1, 2, 4, 1, 2] // perform carry operation
Here is the implementation of BigNum. It is also CustomStringConvertible which makes it possible to print the result as a String.
struct BigNum: CustomStringConvertible {
var arr = [Int]()
// Return BigNum value as a String so it can be printed
var description: String { return arr.map(String.init).joined() }
init(_ arr: [Int]) {
self.arr = carryAll(arr)
}
// Allow BigNum to be initialized with an `Int`
init(_ i: Int = 0) {
self.init([i])
}
// Perform the carry operation to restore the array to single
// digits
func carryAll(_ arr: [Int]) -> [Int] {
var result = [Int]()
var carry = 0
for val in arr.reversed() {
let total = val + carry
let digit = total % 10
carry = total / 10
result.append(digit)
}
while carry > 0 {
let digit = carry % 10
carry = carry / 10
result.append(digit)
}
return result.reversed()
}
// Enable two BigNums to be added with +
static func +(_ lhs: BigNum, _ rhs: BigNum) -> BigNum {
var arr1 = lhs.arr
var arr2 = rhs.arr
let diff = arr1.count - arr2.count
// Pad the arrays to the same length
if diff < 0 {
arr1 = Array(repeating: 0, count: -diff) + arr1
} else if diff > 0 {
arr2 = Array(repeating: 0, count: diff) + arr2
}
return BigNum(zip(arr1, arr2).map { $0 + $1 })
}
}
// This function is based upon this question:
// https://stackoverflow.com/q/52975875/1630618
func fibonacci(to n: Int) {
guard n >= 2 else { return }
var array = [BigNum(0), BigNum(1)]
for i in 2...n {
array.append(BigNum())
array[i] = array[i - 1] + array[i - 2]
print(array[i])
}
}
fibonacci(to: 400)
Output:
1
2
3
5
8
...
67235063181538321178464953103361505925388677826679492786974790147181418684399715449
108788617463475645289761992289049744844995705477812699099751202749393926359816304226
176023680645013966468226945392411250770384383304492191886725992896575345044216019675

How to check if a number can be represented as a sum of some given numbers

I've got a list of some integers, e.g. [1, 2, 3, 4, 5, 10]
And I've another integer (N). For example, N = 19.
I want to check if my integer can be represented as a sum of any amount of numbers in my list:
19 = 10 + 5 + 4
or
19 = 10 + 4 + 3 + 2
Every number from the list can be used only once. N can raise up to 2 thousand or more. Size of the list can reach 200 integers.
Is there a good way to solve this problem?
4 years and a half later, this question is answered by Jonathan.
I want to post two implementations (bruteforce and Jonathan's) in Python and their performance comparison.
def check_sum_bruteforce(numbers, n):
# This bruteforce approach can be improved (for some cases) by
# returning True as soon as the needed sum is found;
sums = []
for number in numbers:
for sum_ in sums[:]:
sums.append(sum_ + number)
sums.append(number)
return n in sums
def check_sum_optimized(numbers, n):
sums1, sums2 = [], []
numbers1 = numbers[:len(numbers) // 2]
numbers2 = numbers[len(numbers) // 2:]
for sums, numbers_ in ((sums1, numbers1), (sums2, numbers2)):
for number in numbers_:
for sum_ in sums[:]:
sums.append(sum_ + number)
sums.append(number)
for sum_ in sums1:
if n - sum_ in sums2:
return True
return False
assert check_sum_bruteforce([1, 2, 3, 4, 5, 10], 19)
assert check_sum_optimized([1, 2, 3, 4, 5, 10], 19)
import timeit
print(
"Bruteforce approach (10000 times):",
timeit.timeit(
'check_sum_bruteforce([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 200)',
number=10000,
globals=globals()
)
)
print(
"Optimized approach by Jonathan (10000 times):",
timeit.timeit(
'check_sum_optimized([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 200)',
number=10000,
globals=globals()
)
)
Output (the float numbers are seconds):
Bruteforce approach (10000 times): 1.830944365834205
Optimized approach by Jonathan (10000 times): 0.34162875449254027
The brute force approach requires generating 2^(array_size)-1 subsets to be summed and compared against target N.
The run time can be dramatically improved by simply splitting the problem in two. Store, in sets, all of the possible sums for one half of the array and the other half separately. It can now be determined by checking for every number n in one set if the complementN-n exists in the other set.
This optimization brings the complexity down to approximately: 2^(array_size/2)-1+2^(array_size/2)-1=2^(array_size/2 + 1)-2
Half of the original.
Here is a c++ implementation using this idea.
#include <bits/stdc++.h>
using namespace std;
bool sum_search(vector<int> myarray, int N) {
//values for splitting the array in two
int right=myarray.size()-1,middle=(myarray.size()-1)/2;
set<int> all_possible_sums1,all_possible_sums2;
//iterate over the first half of the array
for(int i=0;i<middle;i++) {
//buffer set that will hold new possible sums
set<int> buffer_set;
//every value currently in the set is used to make new possible sums
for(set<int>::iterator set_iterator=all_possible_sums1.begin();set_iterator!=all_possible_sums1.end();set_iterator++)
buffer_set.insert(myarray[i]+*set_iterator);
all_possible_sums1.insert(myarray[i]);
//transfer buffer into the main set
for(set<int>::iterator set_iterator=buffer_set.begin();set_iterator!=buffer_set.end();set_iterator++)
all_possible_sums1.insert(*set_iterator);
}
//iterator over the second half of the array
for(int i=middle;i<right+1;i++) {
set<int> buffer_set;
for(set<int>::iterator set_iterator=all_possible_sums2.begin();set_iterator!=all_possible_sums2.end();set_iterator++)
buffer_set.insert(myarray[i]+*set_iterator);
all_possible_sums2.insert(myarray[i]);
for(set<int>::iterator set_iterator=buffer_set.begin();set_iterator!=buffer_set.end();set_iterator++)
all_possible_sums2.insert(*set_iterator);
}
//for every element in the first set, check if the the second set has the complemenent to make N
for(set<int>::iterator set_iterator=all_possible_sums1.begin();set_iterator!=all_possible_sums1.end();set_iterator++)
if(all_possible_sums2.find(N-*set_iterator)!=all_possible_sums2.end())
return true;
return false;
}
Ugly and brute force approach:
a = [1, 2, 3, 4, 5, 10]
b = []
a.size.times do |c|
b << a.combination(c).select{|d| d.reduce(&:+) == 19 }
end
puts b.flatten(1).inspect