An algorithm that determines if a function f from the finite set A to the finite set B is an onto function. - discrete-mathematics

How can I write an algorithm that determines if a function f from the finite set A to the finite set B is an onto function.
This is what I have so far:
A: array ( members of set A )
B: array ( members of set B )
Mapped: associative array of Boolean variables.
for each b in B:
Mapped[b] = false
for each a in A:
Mapped[f(a)] = true
Onto = true;
for each b in B:
Onto = Onto AND Mapped[b]
return Onto
Is this correct?

Yeah, that'll work. A potentially easier approach would be
for each a in A:
remove f(a) from B
return (is B empty?)
And then of course you should sort B first, so you can remove more quickly.

Related

Is destructuring assignment guaranteed to be parallel assignment in Swift?

I'm looking at the description of the assignment operator in the Swift language reference. Is it guaranteed that destructuring assignment is made in parallel? As opposed to serial assignment. I don't see that point addressed in the description of the assignment operator.
Just to be clear, is it guaranteed that (a, b) = (b, a) (where a and b are var) is equivalent to foo = a, a = b, b = foo, where foo is a variable which is guaranteed not to exist yet, and not a = b, b = a (which would yield a and b both with the same value). I tried (a, b) = (b, a) and it appears to work in parallel, but that's not the same as a documented description of the behavior.
Tuples are value types, and once constructed they are independent of the values that are part of them.
var a = 2
var b = 3
var t1 = (a, b)
print(t1) // (2, 3)
a = 4
print(t1) // (2, 3)
Thus the tuple (a, b) carries the actual values of the two variables, which is why the (b, a) = (a, b) assignment works without problems. Behind the scenes, the actual assigment is (b, a) = (2, 3) (assuming a and b have the values from the above code snippet).

Assign same value to multiple variables in Scala

I have 3 variables that have already been initialized, and I want to assign a new value to all three of them. e.g.
var a = 1
var b = 2
var c = 3
and I want to reassign them to the same value e.g.
a = b = c = 4
But the above expression is invalid. Is there a right way to do this in Scala?
It is possible to slightly shorten the var definition code as follows
var (a, b, c) = (1, 2, 3)
This works because of extractor objects in scala. A tuple of 3 is extracted into 3 components it was created with.
But following does not work becase the extraction is applied on val or var definitions.
(a, b, c) = (4, 4, 4)
You can do this:
var Seq(a, b, c) = Seq.fill(3)(4)
As with Ivan's solution, this only works when declaring vars or vals, not when reassigning. Since the second parameter is computed for each element, it even works well for mutable objects:
import scala.collection.mutable.ListBuffer
var Seq(a, b, c) = Seq.fill(3)(ListBuffer[Int]())
a += 1 // Only modifies a, not b or c.
By contrast, something like a = b = c = [] will only create one list in most programming languages (e.g. Python, JavaScript, Java). If you don't want to create your object each time (perhaps because it is immutable and creation is expensive), declare it as val first to prevent this behavior:
val largeObject = ???
var Seq(a, b, c) = Seq.fill(3)(largeObject)

How to group items from an unsorted sequence with custom logic?

Having trouble with this... I'm not even sure where to start.
I have an unsorted list of objects:
myList = (A, Z, T, J, D, L, W...)
These objects have different types, but all share the same parent type.
Some of the objects "match" each other through custom business logic:
A.matches(B) = True
A.matches(C) = False
(Edit: Matching is commutative. X.matches(Y) = Y.matches(X))
I'm looking for a way in Scala to group those objects that match, so I end up with something like:
myMatches = [ [A,B,C], [D,Z,X], [H], ...]
Here's the catch -- matching is not transitive.
A.matches(B) = True
B.matches(C) = True
A.matches(C) = False <---- A and C can only be associated through their matches to B
I still want [A,B,C] to be grouped even though A and C don't directly match.
Is there an easy way to group together all the things that match each other? Is there a name for this kind of problem so I can Google more about it?
Under the assumptions, that
matching is commutative, that is if A matches B, then B matches A
if A matches B, B matches C and C matches D, all of them should be in the same group.
you just need to do a search (DFS or BFS) through the graph of matches starting with every element, that is not yet in a group. The elements you find in one search form exactly one group.
Here is some example code:
import scala.collection.mutable
case class Element(name: Char) {
def matches(other: Element): Boolean = {
val a = name - 'A'
val b = other.name - 'A'
a * 2 == b || b * 2 == a
}
override def toString: String = s"$name (${name - 'A'})"
}
def matchingGroups(elements: Seq[Element]): Seq[Seq[Element]] = {
val notInGroup: mutable.Set[Element] = elements.to[mutable.Set]
val groups: mutable.ArrayBuilder[Seq[Element]] = mutable.ArrayBuilder.make()
val currentGroup: mutable.ArrayBuilder[Element] = mutable.ArrayBuilder.make()
def fillCurrentGroup(element: Element): Unit = {
notInGroup -= element
currentGroup += element
for (candidate <- notInGroup) {
if (element matches candidate) {
fillCurrentGroup(candidate)
}
}
}
while (notInGroup.nonEmpty) {
currentGroup.clear()
fillCurrentGroup(notInGroup.head)
groups += currentGroup.result()
}
groups.result()
}
matchingGroups('A' to 'Z' map Element) foreach println
This finds the following groups:
WrappedArray(M (12), G (6), D (3), Y (24))
WrappedArray(R (17))
WrappedArray(K (10), F (5), U (20))
WrappedArray(X (23))
WrappedArray(V (21))
WrappedArray(B (1), C (2), E (4), I (8), Q (16))
WrappedArray(H (7), O (14))
WrappedArray(L (11), W (22))
WrappedArray(N (13))
WrappedArray(J (9), S (18))
WrappedArray(A (0))
WrappedArray(Z (25))
WrappedArray(P (15))
WrappedArray(T (19))
If matches relationship is non-commutative, this problem is a bit more complex. In this case during a search you may run into several different groups, you've discovered during previous searches, and you'll have to merge these groups into one. It may be useful to represent the groups with the disjoint-set data structure for faster merging.
Here is a functional solution based on Scala Sets. It assumes that the unsorted list of objects does not contain duplicates, and that they all inherit from some type MatchT that contains an appropriate matches method.
This solution first groups all objects into sets that contain directly matching objects. It then checks each set in turn and combines it with any other sets that have any elements in common (non-empty intersection).
def groupByMatch[T <: MatchT](elems: Set[T]): Set[Set[T]] = {
#tailrec
def loop(sets: Set[Set[T]], res: Set[Set[T]]): Set[Set[T]] =
sets.headOption match {
case None =>
res
case Some(h) =>
val (matches, noMatches) = res.partition(_.intersect(h).nonEmpty)
val newMatches = h ++ matches.flatten
loop(sets.tail, noMatches + newMatches)
}
val matchSets = objs.map(x => objs.filter(_.matches(x)) + x)
loop(matchSets, Set.empty[Set[T]])
}
There are a number of inefficiencies here, so if performance is an issue then a non-functional version based on mutable Maps is likely to be faster.

Unsure how this union function on Sets works

I'm trying to understand this def method :
def union(a: Set, b: Set): Set = i => a(i) || b(i)
Which is referred to at question : Scala set function
This is my understanding :
The method takes two parameters of type Set - a & b
A Set is returned which the union of the two sets a & b.
Here is where I am particularly confused : Set = i => a(i) || b(i)
The returned Set itself contains the 'or' of Set a & b . Is the Set 'i' being populated by an implicit for loop ?
Since 'i' is a Set why is it possible to or a 'set of sets', is this something like whats being generated in the background :
a(i) || b(i)
becomes
SetA(Set) || SetB(Set)
Maybe what's confusing you is the syntax. We can rewrite this as:
type Set = (Int => Boolean)
def union(a: Set, b: Set): Set = {
(i: Int) => a(i) || b(i)
}
So this might be easier to sort out. We are defining a method union that takes to Sets and returns a new Set. In our implementation, Set is just another name for a function from Int to Boolean (ie, a function telling us if the argument is "in the set").
The body of the the union method creates an anonymous function from Int to Boolean (which is a Set as we have defined it). This anonymous function accepts a parameter i, an Int, and returns true if, and only if, i is in set a (a(i)) OR i is in set b (b(i)).
If you look carefully, that question defines a type Set = Int => Boolean. So we're not talking about scala.collection.Set here; we're talking Int => Booleans.
To write a function literal, you use the => keyword, e.g.
x => someOp(x)
You don't need to annotate the type if it's already known. So if we know that the r.h.s. is Int => Boolean, we know that x is type Int.
No the set is not populated by a for loop.
The return type of union(a: Set, b: Set): Set is a function. The code of the declaration a(i) || b(i) is not executed when you call union; it will only be executed when you call the result of union.
And i is not a set it is an integer. It is the single argument of the function returned by union.
What happens here is that by using the set and union function you construct a binary tree of functions by combining them with the logical-or-operator (||). The set function lets you build leafs and the union lets you combine them into bigger function trees.
Example:
def set_one = set(1)
def set_two = set(2)
def set_three = set(2)
def set_one_or_two = union(set_one, set_two)
def set_one_two_three = union(set_three, set_one_or_two)
The set_one_two_three will be a function tree which contains two nodes: the left is a function checking if the passed parameter is equal to 3; the right is a node that contains two functions itself, checking if the parameter is equal to 1 and 2 respectively.

Defining multiple-type container classes in haskell, trouble binding variables

I'm having trouble with classes in haskell.
Basically, I have an algorithm (a weird sort of graph-traversal algorithm) that takes as input, among other things, a container to store the already-seen nodes (I'm keen on avoiding monads, so let's move on. :)). The thing is, the function takes the container as a parameter, and calls just one function: "set_contains", which asks if the container... contains node v. (If you're curious, another function passed in as a parameter does the actual node-adding).
Basically, I want to try a variety of data structures as parameters. Yet, as there is no overloading, I cannot have more than one data structure work with the all-important contains function!
So, I wanted to make a "Set" class (I shouldn't roll my own, I know). I already have a pretty nifty Red-Black tree set up, thanks to Chris Okasaki's book, and now all that's left is simply making the Set class and declaring RBT, among others, as instances of it.
Here is the following code:
(Note: code heavily updated -- e.g., contains now does not call a helper function, but is the class function itself!)
data Color = Red | Black
data (Ord a) => RBT a = Leaf | Tree Color (RBT a) a (RBT a)
instance Show Color where
show Red = "r"
show Black = "b"
class Set t where
contains :: (Ord a) => t-> a-> Bool
-- I know this is nonesense, just showing it can compile.
instance (Ord a) => Eq (RBT a) where
Leaf == Leaf = True
(Tree _ _ x _) == (Tree _ _ y _) = x == y
instance (Ord a) => Set (RBT a) where
contains Leaf b = False
contains t#(Tree c l x r) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b
Note how I have a pretty stupidly-defined Eq instance of RBT. That is intentional --- I copied it (but cut corners) from the gentle tutorial.
Basically, my question boils down to this: If I comment out the instantiation statement for Set (RBT a), everything compiles. If I add it back in, I get the following error:
RBTree.hs:21:15:
Couldn't match expected type `a' against inferred type `a1'
`a' is a rigid type variable bound by
the type signature for `contains' at RBTree.hs:11:21
`a1' is a rigid type variable bound by
the instance declaration at RBTree.hs:18:14
In the second argument of `(==)', namely `x'
In a pattern guard for
the definition of `contains':
b == x
In the definition of `contains':
contains (t#(Tree c l x r)) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b
And I simply cannot, for the life of me, figure out why that isn't working. (As a side note, the "contains" function is defined elsewhere, and basically has the actual set_contains logic for the RBT data type.)
Thanks! - Agor
Third edit: removed the previous edits, consolidated above.
You could also use higher-kinded polyphormism. The way your class is defined it sort of expects a type t which has kind *. What you probably want is that your Set class takes a container type, like your RBT which has kind * -> *.
You can easily modify your class to give your type t a kind * -> * by applying t to a type variable, like this:
class Set t where
contains :: (Ord a) => t a -> a -> Bool
and then modify your instance declaration to remove the type variable a:
instance Set RBT where
contains Leaf b = False
contains t#(Tree c l x r) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b
So, here is the full modified code with a small example at the end:
data Color = Red | Black
data (Ord a) => RBT a = Leaf | Tree Color (RBT a) a (RBT a)
instance Show Color where
show Red = "r"
show Black = "b"
class Set t where
contains :: (Ord a) => t a -> a -> Bool
-- I know this is nonesense, just showing it can compile.
instance (Ord a) => Eq (RBT a) where
Leaf == Leaf = True
(Tree _ _ x _) == (Tree _ _ y _) = x == y
instance Set RBT where
contains Leaf b = False
contains t#(Tree c l x r) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b
tree = Tree Black (Tree Red Leaf 3 Leaf) 5 (Tree Red Leaf 8 (Tree Black Leaf 12 Leaf))
main =
putStrLn ("tree contains 3: " ++ test1) >>
putStrLn ("tree contains 12: " ++ test2) >>
putStrLn ("tree contains 7: " ++ test3)
where test1 = f 3
test2 = f 12
test3 = f 7
f = show . contains tree
If you compile this, the output is
tree contains 3: True
tree contains 12: True
tree contains 7: False
You need a multi-parameter type class. Your current definition of Set t doesn't mention the contained type in the class definition, so the member contains has to work for any a. Try this:
class Set t a | t -> a where
contains :: (Ord a) => t-> a-> Bool
instance (Ord a) => Set (RBT a) a where
contains Leaf b = False
contains t#(Tree c l x r) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b
The | t -> a bit of the definition is a functional dependency, saying that for any given t there is only one possible a. It's useful to have (when it makes sense) since it helps the compiler figure out types and reduces the number of ambiguous type problems you often otherwise get with multi-parameter type classes.
You'll also need to enable the language extensions MultiParamTypeClasses and FunctionalDependencies at the top of your source file:
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
The error means that the types don't match. What is the type of contains? (If its type is not something like t -> a -> Bool as set_contains is, something is wrong.)
Why do you think you shouldn't roll your own classes?
When you write the instance for Set (RBT a), you define contains for the specific type a only. I.e. RBT Int is a set of Ints, RBT Bool is a set of Bools, etc.
But your definition of Set t requires that t be a set of all ordered a's at the same time!
That is, this should typecheck, given the type of contains:
tree :: RBT Bool
tree = ...
foo = contains tree 1
and it obviously won't.
There are three solutions:
Make t a type constructor variable:
class Set t where
contains :: (Ord a) => t a -> a-> Bool
instance Set RBT where
...
This will work for RBT, but not for many other cases (for example, you may want to use a bitset as a set of Ints.
Functional dependency:
class (Ord a) => Set t a | t -> a where
contains :: t -> a -> Bool
instance (Ord a) => Set (RBT a) a where
...
See GHC User's Guide for details.
Associated types:
class Set t where
type Element t :: *
contains :: t -> Element t -> Bool
instance (Ord a) => Set (RBT a) where
type Element (RBT a) = a
...
See GHC User's Guide for details.
To expand on Ganesh's answer, you can use Type Families instead of Functional Dependencies. Imho they are nicer. And they also change your code less.
{-# LANGUAGE FlexibleContexts, TypeFamilies #-}
class Set t where
type Elem t
contains :: (Ord (Elem t)) => t -> Elem t -> Bool
instance (Ord a) => Set (RBT a) where
type Elem (RBT a) = a
contains Leaf b = False
contains (Tree c l x r) b
| b == x = True
| b < x = contains l b
| otherwise = contains r b