Swift 3 sorting an array of tuples - arrays

I found these answers:
Sort an array of tuples in swift 3
How to sort an Array of Tuples?
But I'm still having issues. Here is my code:
var countsForLetter:[(count:Int, letter:Character)] = []
...
countsForLetter.sorted(by: {$0.count < $1.count})
Swift 3 wanted me to add the by: and now it says that the result of the call to sorted:by is unused.
I'm new to swift 3. Sorry if this is a basic question.

You are getting that warning because sorted(by... returns a new, sorted version of the array you call it on. So the warning is pointing out the fact that you're not assigning it to a variable or anything. You could say:
countsForLetter = countsForLetter.sorted(by: {$0.count < $1.count})
I suspect that you're trying to "sort in place", so in that case you could change sorted(by to sort(by and it would just sort countsForLetter and leave it assigned to the same variable.

Sorted() returns a new array, it does not sort in place.
you can use :
countsForLetter = countsForLetter.sorted(by: {$0.count < $1.count})
or
countsForLetter.sort(by: {$0.count < $1.count})

Related

How to merge 2 arrays of equal length into a single dictionary with key:value pairs in Godot?

I have been trying to randomize the values in an ordered array (ex:[0,1,2,3]) in Godot. There is supposed to be a shuffle() method for arrays, but it seems to be broken and always returns "null". I have found a workaround that uses a Fisher-Yates shuffle, but the resulting array is considered "unsorted" by the engine, and therefore when I try to use methods such as bsearch() to find a value by it's position, the results are unreliable at best.
My solution was to create a dictionary, comprised of an array containing the random values I have obtained, merged with a second array of equal length with (sorted) numbers (in numerical order) which I can then use as keys to access specific array positions when needed.
Question made simple...
In GDScript, how would you take 2 arrays..
ex: ARRAY1 = [0,1,2,3]
ARRAY2 = [a,b,c,d]
..and merge them to form a dictionary that looks like this:
MergedDictionary = {0:a, 1:b, 2:c, 3:d}
Any help would be greatly appreciated.
Godot does not support "zip" methodology for merging arrays such as Python does, so I am stuck merging them manually. However... there is little to no documentation about how to do this in GDScript, despite my many hours of searching.
Try this:
var a = [1, 2, 3]
var b = ["a", "b", "c"]
var c = {}
if a.size() == b.size():
var i = 0
for element in a:
c[element] = b[i]
i += 1
print("Dictionary c: ", c)
If you want to add elements to a dictionary, you can assign values to the keys like existing keys.

Determine Size of Multidimensional Array in Swift

I am new to Swift and am struggling to work out how to determine the size of a multidimensional array.
I can use the count function for single arrays, however when i create a matrix/multidimensional array, the output for the count call just gives a single value.
var a = [[1,2,3],[3,4,5]]
var c: Int
c = a.count
print(c)
2
The above matrix 'a' clearly has 2 rows and 3 columns, is there any way to output this correct size.
In Matlab this is a simple task with the following line of code,
a = [1,2,3;3,4,5]
size(a)
ans =
2 3
Is there a simple equivalent in Swift
I have looked high and low for a solution and cant seem to find exactly what i am after.
Thanks
- HB
Because 2D arrays in swift can have subarrays with different lengths. There is no "matrix" type.
let arr = [
[1,2,3,4,5],
[1,2,3],
[2,3,4,5],
]
So the concept of "rows" and "columns" does not exist. There's only count.
If you want to count all the elements in the subarrays, (in the above case, 12), you can flat map it and then count:
arr.flatMap { $0 }.count
If you are sure that your array is a matrix, you can do this:
let rows = arr.count
let columns = arr[0].count // 0 is an arbitrary value
You must ask the size of a specific row of your array to get column sizes :
print("\(a.count) \(a[0].count)")
If you are trying to find the length of 2D array which in this case the number of rows (or # of subarrays Ex.[1,2,3]) you may use this trick: # of total elements that can be found using:
a.flatMap { $0 }.count //a is the array name
over # of elements in one row using:
a[0].count //so elemints has to be equal in each subarray
so your code to get the length of 2D array with equal number of element in each subarray and store it in constant arrayLength is:
let arrayLength = (((a.flatMap { $0 }.count ) / (a[0].count))) //a is the array name

Get the base array of an enumerated array

I need to sort an array based on the value as well as the index of each element, so I'd like to do something like this:
let a = [4,9,5,7].enumerate()
let b = a.sort { ... }
But then I need to convert b back to an array without the indices. My current solution is
let c = b.map { $0.1 }
But I was wondering, if there's a simpler way, since b is of the type EnumerateSequence<Array<Int>> and has a property base which holds the array that I want. Unfortunately base is internal and I don't know if there is any method that returns what I want.
Note: You might have noticed that this is Swift 2. While I need a solution in Swift 2 (if there is any), I am of course interested if there's a difference between Swift 2 and Swift 3.
But I was wondering, if there's a simpler way
No. let c = b.map { $0.1 } is simple.
This is slightly (2 characters) simpler:
let c = b.map { $1 }
map receives a tuple of two values, so you can either refer to the two values as $0.0 and $0.1, or as $0, and $1. When your closure uses only $0, then $0 is the entire tuple, so .0 and .1 refers to the individual items. When your closure mentions $1, then $0 is the first item of the tuple and $1 is the second item of the tuple.

Add value to empty Swift array

I cannot figure out how to add values to an empty array in Swift. I have tried started with empty array in two different ways:
var emptyArray : Int[]?
emptyArray = Int[]()
and
var emptyArray = []
(by the way, what is the difference with these two ways of creating empty arrays?)
I have tried to add an integer to the array with emptyArray.append(1), emptyArray += [1] but none works nor it is in the guide book (or maybe, it is hidden some where that I couldn't figure out). Both of these work if there is one or more values in it and this is driving me crazy! Please let me know how to if you know how to do it. Thank you!
First, create empty Int array:
var emptyArray : Int[] = []
or:
var emptyArray = Int[]()
Add number to that array (two ways):
emptyArray += [1]
emptyArray.append(2)
Array now contains [1, 2]
You need to first declare the empty array in Swift like this:
var emptyArray = [Int]()
You can then append that array with whatever value/variable you so choose like this:
emptyArray.append(6)
just be sure you keep in mind that trying to append a type that mismatches your array declaration will give you a compile error. For example, trying to append a string would error since this array was declared using the Int type.
Playgrounds in XCode are an excellent resource for testing things like this.
Swift
var arrName = [String]()
arrName = ["Deep", "Hemant", "Yash"]
print("old array--> ", arrName)
arrName.append("Jay")
print("new array--> ", arrName)
Output:-
old array--> ["Deep", "Hemant", "Yash"]
new array--> ["Deep", "Hemant", "Yash", "Jay"]

Getting the first and last element of an array in CoffeeScript

If say I have an array and I would to iterate through the array, but do something different to the first and last element. How should I do that?
Taking the below code as example, how do I alert element a and e?
array = [a,b,c,d,e]
for element in array
console.log(element)
Thanks.
You can retrieve the first and last elements by using array destructuring with a splat:
[first, ..., last] = array
This splat usage is supported in CoffeeScript >= 1.7.0.
The vanilla way of accessing the first and last element of an array is the same as in JS really: using the index 0 and length - 1:
console.log array[0], array[array.length - 1]
CoffeeScript lets you write some nice array destructuring expressions:
[first, mid..., last] = array
console.log first, last
But i don't think it's worth it if you're not going to use the middle elements.
Underscore.js has some helper first and last methods that can make this more English-like (i don't want to use the phrase "self-explanatory" as i think any programmer would understand array indexing). They are easy to add to the Array objects if you don't want to use Underscore and you don't mind polluting the global namespace (this is what other libraries, like Sugar.js, do):
Array::first ?= (n) ->
if n? then #[0...(Math.max 0, n)] else #[0]
Array::last ?= (n) ->
if n? then #[(Math.max #length - n, 0)...] else #[#length - 1]
console.log array.first(), array.last()
Update
This functions also allow you to get the n first or last elements in an array. If you don't need that functionality then the implementation would be much simpler (just the else branch basically).
Update 2
CoffeeScript >= 1.7 lets you write:
[first, ..., last] = array
without generating an unnecessary array with the middle elements :D
The shortest way is here
array[-1..]
See this thread
https://github.com/jashkenas/coffee-script/issues/156
You can use just:
[..., last] = array
You can use slice to get last element. In javascript, slice can pass negative number like -1 as arguments.
For example:
array = [1, 2, 3 ]
console.log "first: #{array[0]}"
console.log "last: #{array[-1..][0]}"
be compiled into
var array;
array = [1, 2, 3];
console.log("first: " + array[0]);
console.log("last: " + array.slice(-1)[0]);
You can get the element and the index of the current element when iterating through the array using Coffeescript's for...in. See the following code, replace the special_process_for_element and normal_process_for_element with your code.
array = [a, b, c, d]
FIRST_INDEX = 0
LAST_INDEX = array.length - 1
for element, index in array
switch index
when FIRST_INDEX, LAST_INDEX
special_process_for_element
else
normal_process_for_element
sample
Here's a working code

Resources