How to assign more than one value to UInt32 - xcode

I am trying to set the bird group as two numbers so that when I assign a variable I can use multiple "else if" statements with that one group later on
Code:
Xcode doesn't let me do this I'm in Swift
Let birdgroup: UInt32 = 2, 3

You can use Array, Set, or a tuple to store multiple values in a single variable. If order matters, go with Array or tuple, but if the order doesn't matter, you can use Set. Array and Set both allow you to vary the number of values stored in your variable, while a tuple variable must always be the same length. Also, you can loop over the items in an array or set, but not over a tuple.
Array is the most often used of the three, so if you aren't sure which to use, it's a good first choice.
In summary, this table shows the possibilities and their properties:
Loopable Unloopable
Ordered Array Tuple
Unordered Set (none)
Finally, all the items in an array or set must be of the same type (or derived from the same type, if the array or set is defined with the base class). This is called homogeneous. A tuple can contain different types, also known as heterogeneous.
Homogeneous Heterogeneous
Ordered Array Tuple
Unordered Set (none)
Collection Types in the Swift documentation describes how to use Array and Set.
Array
Create an array with
var birdgroup: [UInt32] = [2, 3]
birdgroup[0] is equal to 2, and birdgroup[1] is equal to 3. You can also access the items by looping:
for bird in birdgroup {
println("\(bird)")
}
Set
You can declare a set with
var birdgroup: Set<UInt32> = [2, 3]
Because sets have no order (imagine every item is tossed together in a bag), you can't request the "first" or "second" item. Instead, loop over each item of the set:
for bird in birdgroup {
println("\(bird)")
}
Tuple
let birdgroup: (UInt32, UInt32) = (2, 3)
Tuples also retain the order of their items. birdgroup.0 is equal to 2, and birdgroup.1 to 3. You can also give each item of the tuple a name if you prefer that to a number:
let birdgroup: (UInt32, UInt32) = (foo: 2, bar: 3)
birdgroup.foo is 2, and birdgroup.bar is 3.
Additionally, the values in a tuple do not all need to be the same type. You can combine different types, such as
let heterogeneousTuple: (UInt32, String) = (2, "three")

Related

Best way to reduce a matcher

I have a matcher like so:
type matcher struct {
all []int
none []int
any [][]int
}
For an array of integers to match, it must contain all of the integers in all, none of the integers in none, and must contain at least one integer from each array of integers in any. I have a factory to make the construction of such a matcher easy, but once I have the factory fields I need to "flatten" the structure to make sure none of the terms are contradictory. Right now, what I have is (pseudocode):
all = [0, 1, 2, 3] // means all of these numbers must be present for the matcher to match
any = [[4, 5], [6, 7, 8]] // means one number from each of these groups must be present
none = [9,10] // means none of these may be present
sort(all)
sort(none)
if len(intersections(all, none)) != 0 {
panic("All and none are contradictory!")
}
for gIndex, group in any {
sort(group)
for index, integer in group {
// If all contains the integer...
if binarySearch(all, integer) {
swap(group[len(group)-1], group[index]) // swap the last item with the integer...
group = group[:len(all)-1] // and truncate the group by one; most efficient way to delete an item.
}
// If none contains the integer...
if binarySearch(none, integer) {
panic("item in any is also found in none; possible contradiction")
}
}
if len(group) < 1 {
// delete group from any
} else if len(group) == 1 {
// put group[0] (only integer in it) into all, since it must be met
} else {
sort(group) // Re-sort the group
any[gIndex] = group // Update the group
}
}
removeDuplicates(all)
removeDuplicates(none)
sort2D(any) // Sort by their greatest member
removeDuplicates2D(any) // Go through and remove any duplicate arrays.
all, any, and none should now be reduced to their simplest form, so that checking if an integer array matches should be more efficient and without contradictions.
Is there a better way to do this, and am I missing anything here?
There are at least two flaws in your solution.
You are removing integers in all from the any groups. In fact you have to remove the whole group instead of removing an item if there is an intersection with all. any groups containing items from all are just redundant.
Having overlaps with the none group is not necessarily a problem. These items could in fact just be removed from the any groups. But then you might want to throw an error when this leads to an empty any group. A matcher with an empty any group won't match anything. Anyway, don't just quietly remove empty any groups!
Something similar applies for any groups subsuming other any groups. Consider this choice of any:
any = [[4, 5], [4, 5, 6]]
Let's assume that all and none are empty. Then this would remain unchanged by your algorithm. However, the second group is clearly redundant. Any array containing at least one element of the first group will also match the second.
This means that at least you have to remove all any arrays containing a superset of others.
I'm confident that this leads to a canonical form that you can use to compare matchers. However, I may be wrong.

Generate pairs having the same attributes from list

Assume you have a list of items, each with a set of attributes.
What is an efficient algorithm for generating all pairs from the list having the same attributes?
For example, given a list:
[('item1', {'a','b'}), ('item2', {'a'}), ('item3', {'c','b'}), ('item4', {'b'})]
We should return the following list of four pairs, out of the total possible six:
('item1', 'item2') # both have attribute 'a'
('item1', 'item3') # both have attribute 'b'
('item1', 'item4') # both have attribute 'b'
('item3', 'item4') # both have attribute 'b'
Now, the trivial approach would be to first generate the list of all possible n(n+1)/2 pairs, and then filter out those without similar attributes, but I suspect this approach is inefficient, especially if the number of pairs is very large.
Any suggestions?
I would suggest a two phase algorithm:
arr = [('item1', {'a','b'}), ('item2', {'a'}), ('item3', {'c','b'}), ('item4', {'b'})]
# 1. create map with for each attribute the list of items that have it
mp = {}
for lst in arr:
for prop in lst[1]:
if prop not in mp: mp[prop] = []
mp[prop].append(lst[0])
# 2. for each attribute: add the pairs of items to the result set
result = set()
for prop in mp:
items = mp[prop]
# collect all pairs in items list
for p1 in range(len(items)):
for p2 in range(p1+1,len(items)):
result.add((items[p1],items[p2]))
print (result)
Output:
{('item1', 'item4'), ('item1', 'item2'), ('item3', 'item4'), ('item1', 'item3')}

Parse.com query objects where the key's array value contains any of the elements

on https://parse.com/docs/js_guide#queries-arrays there is an example how to find objects where the key's array value contains each of the elements 2, 3, and 4 with the following:
// Find objects where the array in arrayKey contains all of the elements 2, 3, and 4.
query.containsAll("arrayKey", [2, 3, 4]);
However, I would like to find objects where the key's array value contains at least one (not necessarily all) of the elements 2,3, and 4.
Is that possible?
I'm not positive, but what happens if you try containedIn?
I think if you pass an array, it checks to see if any are contained.
query.containedIn("arrayKey", [2,3,4]);
I know that if you use equalTo with an array key and a singular value, it checks if the value is in the array and returns TRUE. I think this will do something similar and should work. I think it will check if any value in "arrayKey" is in the passed array. If any key object does, it will return the object.
swift 3.0
let Query:PFQuery = PFQuery(className: “className”)
Query.whereKey(“Field Name”, containedIn: array)// [“1”,”2”,”3”];

Most efficient way to compile unique values in a massive text file?

I have a set of large text files that in total contain about 3 million rows.
What I want to do is pluck a value from a given column from each row and add it to an array in memory. If the value already exists in the array, then ignore it.
I'm assuming the fastest way is NOT:
Read a value
if exists (using array's native index or what-have-you method), then push it to the array
Should I be inserting the value in alphabetical order to speed up the match/search?
OR should I keep multiple arrays...for example, one for each letter of the alphabet?
Use Set:
Set implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup.
Example usage:
require 'set'
set = Set.new
set << 1 << 2 << 3 # => #<Set: {1, 2, 3}>
set << 2 # => #<Set: {1, 2, 3}>
You could add the values as keys to a hash map, that would take care of removing duplicates automatically. You could even count the number of times each value occurs this way (with the hash value).

Can't sort table with associative indexes

Why I can't use table.sort to sort tables with associative indexes?
In general, Lua tables are pure associative arrays. There is no "natural" order other than the as a side effect of the particular hash table implementation used in the Lua core. This makes sense because values of any Lua data type (other than nil) can be used as both keys and values; but only strings and numbers have any kind of sensible ordering, and then only between values of like type.
For example, what should the sorted order of this table be:
unsortable = {
answer=42,
true="Beauty",
[function() return 17 end] = function() return 42 end,
[math.pi] = "pi",
[ {} ] = {},
12, 11, 10, 9, 8
}
It has one string key, one boolean key, one function key, one non-integral key, one table key, and five integer keys. Should the function sort ahead of the string? How do you compare the string to a number? Where should the table sort? And what about userdata and thread values which don't happen to appear in this table?
By convention, values indexed by sequential integers beginning with 1 are commonly used as lists. Several functions and common idioms follow this convention, and table.sort is one example. Functions that operate over lists usually ignore any values stored at keys that are not part of the list. Again, table.sort is an example: it sorts only those elements that are stored at keys that are part of the list.
Another example is the # operator. For the above table, #unsortable is 5 because unsortable[5] ~= nil and unsortable[6] == nil. Notice that the value stored at the numeric index math.pi is not counted even though pi is between 3 and 4 because it is not an integer. Furthermore, none of the other non-integer keys are counted either. This means that a simple for loop can iterate over the entire list:
for i in 1,#unsortable do
print(i,unsortable[i])
end
Although that is often written as
for i,v in ipairs(unsortable) do
print(i,v)
end
In short, Lua tables are unordered collections of values, each indexed by a key; but there is a special convention for sequential integer keys beginning at 1.
Edit: For the special case of non-integral keys with a suitable partial ordering, there is a work-around involving a separate index table. The described content of tables keyed by string values is a suitable example for this trick.
First, collect the keys in a new table, in the form of a list. That is, make a table indexed by consecutive integers beginning at 1 with keys as values and sort that. Then, use that index to iterate over the original table in the desired order.
For example, here is foreachinorder(), which uses this technique to iterate over all values of a table, calling a function for each key/value pair, in an order determined by a comparison function.
function foreachinorder(t, f, cmp)
-- first extract a list of the keys from t
local keys = {}
for k,_ in pairs(t) do
keys[#keys+1] = k
end
-- sort the keys according to the function cmp. If cmp
-- is omitted, table.sort() defaults to the < operator
table.sort(keys,cmp)
-- finally, loop over the keys in sorted order, and operate
-- on elements of t
for _,k in ipairs(keys) do
f(k,t[k])
end
end
It constructs an index, sorts it with table.sort(), then loops over each element in the sorted index and calls the function f for each one. The function f is passed the key and value. The sort order is determined by an optional comparison function which is passed to table.sort. It is called with two elements to compare (the keys to the table t in this case) and must return true if the first is less than the second. If omitted, table.sort uses the built-in < operator.
For example, given the following table:
t1 = {
a = 1,
b = 2,
c = 3,
}
then foreachinorder(t1,print) prints:
a 1
b 2
c 3
and foreachinorder(t1,print,function(a,b) return a>b end) prints:
c 3
b 2
a 1
You can only sort tables with consecutive integer keys starting at 1, i.e., lists. If you have another table of key-value pairs, you can make a list of pairs and sort that:
function sortpairs(t, lt)
local u = { }
for k, v in pairs(t) do table.insert(u, { key = k, value = v }) end
table.sort(u, lt)
return u
end
Of course this is useful only if you provide a custom ordering (lt) which expects as arguments key/value pairs.
This issue is discussed at greater length in a related question about sorting Lua tables.
Because they don't have any order in the first place. It's like trying to sort a garbage bag full of bananas.

Resources