Swift, How to make an Array of UIBezierPaths? - ios

I can make 1 just fine, and in Objective-C I would just slap a "[10]" on my first declaration and be good to go. But swift arrays are so foreign to me, I don't understand at all. I need a 10x10 grid of squares (UIBezierPaths) Iv tried looking at many posts but I can't understand. Could someone please help out and explain the nature of swift arrays, am I missing something?
thank you

Does this help?
var paths: [[UIBezierPath]] = [[UIBezierPath]]()
for index in 0 ... 9 {
paths.append([UIBezierPath]())
for kdx in 0 ... 19 {
paths[index].append(UIBezierPath())
}
}
Creates a 2d array of UIBezierPath and then iterates over two loops. In the first loop we add a new list of paths and in the second loop we add new paths to these lists.
For a single list of paths just use the inner loop.
var paths: [UIBezierPath] = [UIBezierPath]()
for kdx in 0 ... 9 {
paths.append(UIBezierPath())
}

Related

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.

How to share the same index among multiple dask arrays

I'm trying to build a dask-based ipython application, that holds a meta-class which consists of some sub-dask-arrays (which are all shaped (n_samples, dim_1, dim_2 ...)) and should be able to sector the sub-dask-arrays by its getitem operator.
In the getitem method, I call the da.Array.compute method (the code is still in it's very early state), so I would be able to iterate batches of the sub-arrays.
def MetaClass(object):
...
def __getitem__(self, inds):
new_m = MetaClass()
inds = inds.compute()
for name,var in vars(self).items():
if isinstance(var,da.Array):
try:
setattr(new_m, name, var[inds])
except Exception as e:
print(e)
else:
setattr(new_m, name, var)
return new_m
# Here I construct the meta-class to work with some directory.
m = MetaClass('/my/data/...')
# m.type is one of the sub-dask-arrays
m2 = m[m.type==2]
It works as expected, and I get the sliced arrays, but as a result I get a huge memory consumption, and I assume that in the background the mechanism of dask is copying the index for each sub-dask-array.
My question is, how do I achieve the same results, without using so much memory?
(I tried not to "compute" the "inds" in getitem, but then I get nan shaped arrays, which can not be iterated, which is a must for the application)
I have been thinking about three possible solutions that I'd be happy to be advised which of them is the "right" one for me. (or to get another solution which I haven't thought of):
To use a Dask DataFrame, which I'm not sure how to fit multidimensional-dask-arrays in (would really appreciate some help or even a link that explains how to deal with multidimensional arrays in dd).
To forget about the entire MetaClass, and to use one dask-array with a nasty dtype (something like [("type",int,(1,)),("images",np.uint8,(1000,1000))]), again, I'm not familiar with this and would really appreciate some help with that (tried to google it.. it's a bit complicated..)
To share the index as a global inside the calling function (getitem) with property and its get-function-mechanism (https://docs.python.org/2/library/functions.html#property). But the big downside here is that I lose the types of the arrays (big down for representation and everything that needs anything but the data itself).
Thanks in advance!!!
One can use the sub-arrays.map_blocks with a shared function that holds the indices in its memory.
Here is an example:
def bool_mask(arr, block_info=None):
from_ind,to_ind = block_info[0]["array-location"][0]
return arr[inds[from_ind:to_ind]]
def getitem(var):
original_chunks = var.chunks[0]
tmp_inds = np.cumsum([0]+list(original_chunks))
from_inds = tmp_inds[:-1]
to_inds = tmp_inds[1:]
new_chunks_0 = np.array(list(map(lambda f,t:inds[f:t].sum(),from_inds,to_inds)))
new_chunks = tuple([tuple(new_chunks_0.tolist())] + list(var.chunks[1:]))
return var.map_blocks(bool_mask,dtype=var.dtype,chunks=new_chunks)

Swift - compare words and filtering

i just started learning Swift and trying to make an assignment for iOS.
what i have is 4 categories of keywords, for example:
CategoryX: hello, bye, good, bad
CategoryY: rain, sun
CategoryZ: sun, hello, what, rain
CategoryV: yes, no, bad, music, song, note
what i want is to compare this categories with each other and the result will give me the keywords that are in the choosen categories.
for example if i choose to compare all the categories, the results will be: null
(because there is no keyword that appear in all categories)
but if i choose X and Z, then the result will be: hello
if Y and Z then its: sun, rain
I’m not asking from anyone to write me the code (but ofc would be nice if someone gave me a headstart), i just want little explanation of how to deal with this problem and what to use to do it the right way, can someone shed some light?
thank you
I’m not asking from anyone to write me the code (but ofc would be nice if someone gave me a headstart), i just want little explanation of how to deal with this problem and what to use to do it the right way, can someone shed some light?
Okay, without giving the answer away, here’s a hint about how to deal with the problem., to give you a head start.
Doesn't this assignment make you think about sets? Remember those Venn diagrams you had to make in high school? Remember the idea of the intersection of sets? Think about that. Think about sets. Hmmm... Swift has a Set struct...
If you follow up that idea, and research what a Set is in Swift, you’ll see what to do.
Had fun writing it so I post it here. If you aren’t finished by now then look at the result and learn from it(my motto).
I expect you to learn .forEach, .map, .filter, guard let and optional subscript, since you skipped the easy answer with Sets. Oh don’t forget closures and how they strongly capture.
func compare(dicts: [[String]]) -> [String] {
var result = [String: Int]()
dicts.forEach { arg0 in
guard let priorResult = result[arg0.key] else {
result[arg0.key] = arg0.value
return
}
result[arg0.key] = priorResult + arg0.value
}
return result.filter{ arg0 in return arg0.value == dicts.count }.map{ return $0.key }
}
.map, forEach and .filter call for every item in the collection(for every key-value pair in a dictionary) thegiven closure.
.map returns an array of what is returned inside map.
.filter returns an array of items for which the closure returned true and so filtering out the items for which the closure returned false.
.forEach is an alternative to a for-loop.
result counts every occurance of a string.
.filter returns true for the strings which occured inside every dict.
.map maps the dictionary’s keys to a simple [String] array.
You can try
let set1 = Set(["123","456","789"])
let set2 = Set(["123","456"])
let set3 = Set(["123"])
let res12 = set1.intersection(set2) // ["123","456"]
let res123 = set1.intersection(set2).intersection(set3) // ["123"]

Why does Swift 2.2 not support fixed sized arrays, maybe swift 3.0 support?

I'm trying to create a game for iPhone (it's simple, just to sharpen my skills), and I've noticed that Apple has yet to show any support for fixed sized arrays (i had a huge issue with keeping track of my enemies I'm spawning and it would have helped a lot to have a fixed array). Does anyone know why they're not supported? Or if they will be supported in Swift 3.0?
You are not writing C, don't carry the C's baggage with you. Arrays in Swift falls into 2 types: constant array, which is fixed-length and fixed value, you can't modify anything; or variable-length and variable value. Each array knows its length (arr.count), so you don't need a separate variable to keep track of it.
As for for loop, the more I write Swift, the less I used this:
for var i = 0; i < arr.count; i++ { ... }
And the more I used these:
for item in arr { ... }
for (index, item) in arr.enumerate() { ... }
arr.forEach { ... }
arr.map { ... }

Is there a difference between foreach and map?

Ok this is more of a computer science question, than a question based on a particular language, but is there a difference between a map operation and a foreach operation? Or are they simply different names for the same thing?
Different.
foreach iterates over a list and performs some operation with side effects to each list member (such as saving each one to the database for example)
map iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (such as converting a list of strings to uppercase)
The important difference between them is that map accumulates all of the results into a collection, whereas foreach returns nothing. map is usually used when you want to transform a collection of elements with a function, whereas foreach simply executes an action for each element.
In short, foreach is for applying an operation on each element of a collection of elements, whereas map is for transforming one collection into another.
There are two significant differences between foreach and map.
foreach has no conceptual restrictions on the operation it applies, other than perhaps accept an element as argument. That is, the operation may do nothing, may have a side-effect, may return a value or may not return a value. All foreach cares about is to iterate over a collection of elements, and apply the operation on each element.
map, on the other hand, does have a restriction on the operation: it expects the operation to return an element, and probably also accept an element as argument. The map operation iterates over a collection of elements, applying the operation on each element, and finally storing the result of each invocation of the operation into another collection. In other words, the map transforms one collection into another.
foreach works with a single collection of elements. This is the input collection.
map works with two collections of elements: the input collection and the output collection.
It is not a mistake to relate the two algorithms: in fact, you may view the two hierarchically, where map is a specialization of foreach. That is, you could use foreach and have the operation transform its argument and insert it into another collection. So, the foreach algorithm is an abstraction, a generalization, of the map algorithm. In fact, because foreach has no restriction on its operation we can safely say that foreach is the simplest looping mechanism out there, and it can do anything a loop can do. map, as well as other more specialized algorithms, is there for expressiveness: if you wish to map (or transform) one collection into another, your intention is clearer if you use map than if you use foreach.
We can extend this discussion further, and consider the copy algorithm: a loop which clones a collection. This algorithm too is a specialization of the foreach algorithm. You could define an operation that, given an element, will insert that same element into another collection. If you use foreach with that operation you in effect performed the copy algorithm, albeit with reduced clarity, expressiveness or explicitness. Let's take it even further: We can say that map is a specialization of copy, itself a specialization of foreach. map may change any of the elements it iterates over. If map doesn't change any of the elements then it merely copied the elements, and using copy would express the intent more clearly.
The foreach algorithm itself may or may not have a return value, depending on the language. In C++, for example, foreach returns the operation it originally received. The idea is that the operation might have a state, and you may want that operation back to inspect how it evolved over the elements. map, too, may or may not return a value. In C++ transform (the equivalent for map here) happens to return an iterator to the end of the output container (collection). In Ruby, the return value of map is the output sequence (collection). So, the return value of the algorithms is really an implementation detail; their effect may or may not be what they return.
Array.protototype.map method & Array.protototype.forEach are both quite similar.
Run the following code: http://labs.codecademy.com/bw1/6#:workspace
var arr = [1, 2, 3, 4, 5];
arr.map(function(val, ind, arr){
console.log("arr[" + ind + "]: " + Math.pow(val,2));
});
console.log();
arr.forEach(function(val, ind, arr){
console.log("arr[" + ind + "]: " + Math.pow(val,2));
});
They give the exact ditto result.
arr[0]: 1
arr[1]: 4
arr[2]: 9
arr[3]: 16
arr[4]: 25
arr[0]: 1
arr[1]: 4
arr[2]: 9
arr[3]: 16
arr[4]: 25
But the twist comes when you run the following code:-
Here I've simply assigned the result of the return value from the map and forEach methods.
var arr = [1, 2, 3, 4, 5];
var ar1 = arr.map(function(val, ind, arr){
console.log("arr[" + ind + "]: " + Math.pow(val,2));
return val;
});
console.log();
console.log(ar1);
console.log();
var ar2 = arr.forEach(function(val, ind, arr){
console.log("arr[" + ind + "]: " + Math.pow(val,2));
return val;
});
console.log();
console.log(ar2);
console.log();
Now the result is something tricky!
arr[0]: 1
arr[1]: 4
arr[2]: 9
arr[3]: 16
arr[4]: 25
[ 1, 2, 3, 4, 5 ]
arr[0]: 1
arr[1]: 4
arr[2]: 9
arr[3]: 16
arr[4]: 25
undefined
Conclusion
Array.prototype.map returns an array but Array.prototype.forEach doesn't. So you can manipulate the returned array inside the callback function passed to the map method and then return it.
Array.prototype.forEach only walks through the given array so you can do your stuff while walking the array.
the most 'visible' difference is that map accumulates the result in a new collection, while foreach is done only for the execution itself.
but there are a couple of extra assumptions: since the 'purpose' of map is the new list of values, it doesn't really matters the order of execution. in fact, some execution environments generate parallel code, or even introduce some memoizing to avoid calling for repeated values, or lazyness, to avoid calling some at all.
foreach, on the other hand, is called specifically for the side effects; therefore the order is important, and usually can't be parallelised.
Short answer: map and forEach are different. Also, informally speaking, map is a strict superset of forEach.
Long answer: First, let's come up with one line descriptions of forEach and map:
forEach iterates over all elements, calling the supplied function on each.
map iterates over all elements, calling the supplied function on each, and produces a transformed array by remembering the result of each function call.
In many languages, forEach is often called just each. The following discussion uses JavaScript only for reference. It could really be any other language.
Now, let's use each of these functions.
Using forEach:
Task 1: Write a function printSquares, which accepts an array of numbers arr, and prints the square of each element in it.
Solution 1:
var printSquares = function (arr) {
arr.forEach(function (n) {
console.log(n * n);
});
};
Using map:
Task 2: Write a function selfDot, which accepts an array of numbers arr, and returns an array wherein each element is the square of the corresponding element in arr.
Aside: Here, in slang terms, we are trying to square the input array. Formally put, we are trying to compute it's dot product with itself.
Solution 2:
var selfDot = function (arr) {
return arr.map(function (n) {
return n * n;
});
};
How is map a superset of forEach?
You can use map to solve both tasks, Task 1 and Task 2. However, you cannot use forEach to solve the Task 2.
In Solution 1, if you simply replace forEach by map, the solution will still be valid. In Solution 2 however, replacing map by forEach will break your previously working solution.
Implementing forEach in terms of map:
Another way of realizing map's superiority is to implement forEach in terms of map. As we are good programmers, we'll won't indulge in namespace pollution. We'll call our forEach, just each.
Array.prototype.each = function (func) {
this.map(func);
};
Now, if you don't like the prototype nonsense, here you go:
var each = function (arr, func) {
arr.map(func); // Or map(arr, func);
};
So, umm.. Why's does forEach even exist?
The answer is efficiency. If you are not interested in transforming an array into another array, why should you compute the transformed array? Only to dump it? Of course not! If you don't want a transformation, you shouldn't do a transformation.
So while map can be used to solve Task 1, it probably shouldn't. For each is the right candidate for that.
Original answer:
While I largely agree with #madlep 's answer, I'd like to point out that map() is a strict super-set of forEach().
Yes, map() is usually used to create a new array. However, it may also be used to change the current array.
Here's an example:
var a = [0, 1, 2, 3, 4], b = null;
b = a.map(function (x) { a[x] = 'What!!'; return x*x; });
console.log(b); // logs [0, 1, 4, 9, 16]
console.log(a); // logs ["What!!", "What!!", "What!!", "What!!", "What!!"]
In the above example, a was conveniently set such that a[i] === i for i < a.length. Even so, it demonstrates the power of map().
Here's the official description of map(). Note that map() may even change the array on which it is called! Hail map().
Hope this helped.
Edited 10-Nov-2015: Added elaboration.
Here is an example in Scala using lists: map returns list, foreach returns nothing.
def map(f: Int ⇒ Int): List[Int]
def foreach(f: Int ⇒ Unit): Unit
So map returns the list resulting from applying the function f to each list element:
scala> val list = List(1, 2, 3)
list: List[Int] = List(1, 2, 3)
scala> list map (x => x * 2)
res0: List[Int] = List(2, 4, 6)
Foreach just applies f to each element:
scala> var sum = 0
sum: Int = 0
scala> list foreach (sum += _)
scala> sum
res2: Int = 6 // res1 is empty
If you're talking about Javascript in particular, the difference is that map is a loop function while forEach is an iterator.
Use map when you want to apply an operation to each member of the list and get the results back as a new list, without affecting the original list.
Use forEach when you want to do something on the basis of each element of the list. You might be adding things to the page, for example. Essentially, it's great for when you want "side effects".
Other differences: forEach returns nothing (since it is really a control flow function), and the passed-in function gets references to the index and the whole list, whereas map returns the new list and only passes in the current element.
ForEach tries to apply a function such as writing to db etc on each element of the RDD without returning anything back.
But the map() applies some function over the elements of rdd and returns the rdd. So when you run the below method it won't fail at line3 but while collecting the rdd after applying foreach it will fail and throw an error which says
File "<stdin>", line 5, in <module>
AttributeError: 'NoneType' object has no attribute 'collect'
nums = sc.parallelize([1,2,3,4,5,6,7,8,9,10])
num2 = nums.map(lambda x: x+2)
print ("num2",num2.collect())
num3 = nums.foreach(lambda x : x*x)
print ("num3",num3.collect())

Resources