Flatten all values of multiple arrays in Swift - arrays

I have a Dictionary of Integer Arrays like below:
let numbers = [1: [2, 3], 4: [5, 6, 7], 8: [9]]
What I really want is a single flattened Array of all of the values (which themselves are arrays), like so:
[2, 3, 5, 6, 7, 9]
Now, I have been able to call numbers.values.array to get:
[[2, 3], [5, 6, 7], [9]]
But what I'm looking for is to merge these one step further, flattening them.
Does Swift (1.1, or 1.2) offer a convenience method for this?

With a combination of numbers.values.array and a reduce function you can simplify this down in one line of code.
numbers.values.array.reduce([], combine: +) // [5,6,7,2,3,9]
However, I would like to note that since you are using a dictionary, you cannot guarantee that the values will be sorted, so you can use the sorted function to accomplish this:
sorted(numbers.values.array.reduce([], combine: +), <) // [2,3,5,6,7,9]
As #Jeffery Thomas stated, you can also use flatmap which was just added in Swift 1.2:
sorted(numbers.values.array.flatMap { $0 }, <)
And to take it a step further, using the global sorted function, the < is extraneous because it is the default and using the global reduce and flatMap functions, you can remove the array property as pointed out by Martin R, so it can be reduced down to:
sorted(reduce(numbers.values, [], +))
sorted(flatMap(numbers.values) { $0 })

Another possible solution is
[].join(numbers.values)
And if you want the values in the order corresponding to the sorted
dictionary keys then it would be
flatMap(sorted(numbers.keys)) { numbers[$0]! }

This is called flattening, and it's a relatively common operation. There are a number of ways to do it, so pick one that suits your needs.
numbers.values.array.reduce([], combine: +) // As stated by #Bluehound
reduce(numbers.values, [], +)
numbers.values.array.flatMap { $0 } // Swift 1.2 (Xcode 6.3)
flatMap(numbers.values) { $0 } // Swift 1.2 (Xcode 6.3)
flatMap may be the most useful, if the next step after flattening is mapping.
NOTE: Thanks #MartinR for the syntax tip.

Related

collect all elements and indices of an array in two separate arrays in Ruby

Suppose I have an array array = [1,2,3,4,5]
I want to collect all the elements and indices of the array in 2 separate arrays like
[[1,2,3,4,5], [0,1,2,3,4]]
How do I do this using a single Ruby collect statement?
I am trying to do it using this code
array.each_with_index.collect do |v,k|
# code
end
What should go in the code section to get the desired output?
Or even simpler:
[array, array.each_index.to_a]
I like the first answer that was posted a while ago. Don't know why the guy deleted it.
array.each_with_index.collect { |value, index| [value,index] }.transpose
Actually I am using an custom vector class on which I am calling the each_with_index method.
Here's one simple way:
array = [1,2,3,4,5]
indexes = *array.size.times
p [ array, indexes ]
# => [[1, 2, 3, 4, 5], [0, 1, 2, 3, 4]]
See it on repl.it: https://repl.it/FmWg

comparing two numpy arrays and adding same rows

I have two large data files, one with two columns and one with three columns. I want to select all the rows from the second file that are contained in the fist array. My idea was to compare the numpy arrays.
Let's say I have:
a = np.array([[1, 2, 3], [3, 4, 5], [1, 4, 6]])
b = np.array([[1, 2], [3, 4]])
and the result should look like this:
[[1, 2, 3], [3, 4, 5]]
Any advice on that?
EDIT:
So in the end this works. Not very handy but it works.
for ii in range(a.shape[0]):
u, v, w = a[ii,:]
for jj in range(b.shape[0]):
if (u == b[jj, 0] and v == b[jj, 1]):
print [u, v, w]
The numpy_indexed package (disclaimer: I am its author) contains functionality to solve such problems efficiently, without using any python loops:
import numpy_indexed as npi
a[npi.contains(b, a[:, :2])]
If you prefer to not use another library but want to do this in numpy only, you can do something similar to what is suggested here and here, namely to use np.in1d (see docs) which does provide you with a mask indicating if an element in one 1D array exists in another 1D array. As the name indicates, this function only works for 1D arrays. But you can use a structured array view (using np.view) to cheat numpy into thinking you have 1D arrays. One caveat is though, that you need a deep copy of the first array a since np.view doesn't mix with slices, well. But if that is not too big of an issue for you, something along the lines of:
a_cp = a[:, :2].copy()
a[np.in1d(a_cp.view((np.void, a_cp.dtype.itemsize*a_cp.shape[1])).ravel(),
b.view((np.void, b.dtype.itemsize*b.shape[1])).ravel())]
might work for you.
This directly uses the masked array to return the correct values from your array a.
Check this, #Ernie. It may help you to get to the solution. ;D
http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.in1d.html

Recursively count items in a multidimensional array in generic and idiomatic Swift

I have a multi-dimensional array and I need a count of all of the items within all of the arrays, excluding container arrays themselves from the count.
What would be the most generic and idiomatic solution in Swift? I'm guessing it's going to be something functional (a reduce() operation?), but not sure on the best overall approach.
The obvious non-functional approach would be to simply iterate over the array and tally up the number of items.
With the latest Swift 2.0 beta 6 you can use flatten()
let array = [[1, 2, 3], [4, 5], [6]]
array.flatten().count
EDIT: Just tested it: Lazy is not needed, the values are never evaluated, it just calculates endIndex - startIndex of every subcollection.
You can do the following :
let array = [[1, 2, 3], [4, 5], [6]]
let countOfAll = array.map { (nested) -> Int in
return nested.count
}.reduce(0, combine: +) // 6
For Swift 2 you can use flatMap.
var anArray = [[1,0,0], ["asdf","df","lef"], [0,0,1]]
var flatArray = anArray.flatMap { $0 }
print(flatArray.count) // 9

How to calculate the sum of each position of subarrays?

Now my array is:
[[1,2,3],[4,5,6],[]]
I want to calculate this array and return a result as:
[5,7,9]
If there is a null array, remove it. Then plus every position for each sub array.
If use array's each method, maybe I can get the result. But is there a better way just use ruby's array method?
Another one liner
arr.reject(&:empty?).transpose.map{|x| x.reduce(:+)}
first get rid of the []
reject(&:empty?) # equivalent to reject{|x| x.empty?}
now .transpose to obtain
[[1, 4], [2, 5], [3, 6]]
Add up each sublist with
.map{|x| x.reduce(:+)}
Here's a one-liner that uses a lot of nice Ruby Array methods like reject, reduce, zip, and map.
array.reject(&:empty?).reduce { |result, e| result.zip(e).map { |x,y| x+y } }
See Ruby Array documentation for more details, and to see what other slick things you can do with them.
array = [[1,2,3],[4,5,6],[]]
require 'matrix'
Matrix[*array.reject { |a| a.empty? }].row_vectors.reduce(:+).to_a
#=> [5, 7, 9]

Difference between two arrays in Angular JS

Consider following arrays:
array1 = ['a','b'];
array2 = ['a','b','c','d'];
I need to extract the difference. So my resulting array should look something like,
array3 = ['c','d'];
If an element is present in array1 then it should be poped from array2.
I am looking for solutions more angular way,is there any directive available?
In my opinion you can use underscore or lodash library for such tasks.
for example in underscore you can done it through this simple code :
difference_.difference(array, *others)
Similar to without, but returns the values from array that are not present in the other arrays.
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
underscore annotated source

Resources