why is l { xy | x,y in {a, b}* ,where |x| = |y| } regular? Supposedly it is just even length strings? - regular-language

So can someone explain {xy | x,y \in {a, b}* , |x| = |y|} regular. Apparently the answer is it is just even length strings but I can't see why this is the case?

The language L = {xy | x,y in {a, b}* , |x| = |y|} is exactly the language of words of even length:
Every word of even length is in L: If w in {a,b}* is even, then there is some natural number k, such that |w| = 2*k. Therefore, w can be split into two words of length k, so there are x,y in {a,b}* such that w = xy and |x| = |y| = k. Therefore, w is in L.
Every word in L is of even length: Consider w in L. Then by definition of L, there are x,y in {a,b}* , such that |x| = |y| and w = xy. Therefore |w| = |xy| = |x| + |y| = 2*|x|. Therefore, w is of even length.
Next, you have to show L is regular. You could do this by constructing a DFA with two states q0 and q1, where q0 is the starting state and also accepting. From q0, reading a or b takes you to q1, and from q1, reading a or b takes you back to q0. Then the words for which a run of the automaton ends in q0 are exactly the words of even length.

Related

Understanding implementation of Extended Euclidean algorithm

After some experimentation and search, I came up with the following definition:
emcd' :: Integer -> Integer -> (Integer,Integer,Integer)
emcd' a 0 = (a, 1, 0)
emcd' a b =
let (g, t, s) = emcd' b r
in (g, s, t - (q * s))
where
(q, r) = divMod a b
What's the meaning behind this expression t - (q * s) ?
I've tried to evaluate it by hand; even though I arrived at the correct result (1, -4, 15), I can't see why that expression returns the value of t.
There is a famous method for calculating s and t in as + bt = gcd(a, b). In the process of finding the gcd, I get several equations.
By reversing the steps in the Euclidean Algorithm, it is possible to find these integers a and b. Those resulting equations look like the expression t - (q * s); however, I can't figure out the exact process.
Since (q, r) = divMod a b, we have the equation
a = qb + r
and because of the recursive call, we have:
tb + sr = g
Substituting a-qb for r in the second equation, that means
tb + s(a-qb) = g
tb + sa - qsb = g
sa + (t-qs)b = g
This explains why s and t - q*s are good choices to return.

How can I invert? a coordinate space?

Here's a problem that's been wrecking my brain for a while.
Given:
I have two coordinate spaces:
the global space G, and
a local space A, and
I know the position and rotation of A relative to G.
Question:
How can I programmatically calculate the position and rotation of G relative to A?
On graph paper, I can calculate this by hand:
if A relative to G is (4, 1) 90deg, then G relative to A is (-1, -4) -90deg
if A relative to G is (5, 0) 0deg, then G relative to A is (-5, 0) 0deg
... but I'm having trouble transferring this calculation to software.
In matrix form,
y = R x + t
where R is the rotation matrix and t the translation of the origin.
The reverse way,
x = R' (y - t) = R' y + (- R' t)
where R' is the inverse of R, and also its transpose.

python3 - create list of strings elliptically

EDIT: I do not want your code! just help me think of a nice way to do it :)
I have a string with 25 characters:
ABCDEFGHIKLMNOPQRSTUVWXYZ
and I want to create a matrix5*5 given a position and a direction,
position can be one of the corners and direction can be clock or counter clock.
so if I gave this arguments:
create((0,0), clock)
I want to recive:
["ABCDE", "QRSTF", "PYZUG", "OXWVH", "NMLKI"]
and I could then print it and recieve:
A B C D E
Q R S T F
P Y Z U G
O X W V H
N M L K I

Create all the '' small'' matrix from a bigger one - Haskell

I have a rectangular matrix with cases containing B or N. An example of matrix:
g0 = [[B,B,B,B,B,B,N],
[B,B,N,B,N,B,B],
[N,B,N,N,N,N,N],
[B,B,B,N,N,B,N],
[N,N,N,B,B,B,B],
[B,B,B,N,N,B,N]]
I have a type rectangle like [Int,Int,Int,Int] and a function that gets a smaller rectangular matrix from my matrix with this type. Here's the function but that's not the most important part:
getRectangle :: Rectangle -> Grille -> Grille -- cette fonction récupère la grille qui correspond au rectangle donné
getRectangle (i,j,l,c) g = transpose (getLigne (j,c,(nbLigne (transpose g0))) (transpose (getLigne (i,l,(nbLigne g0)) g0)))
--transpose get create a matrix with (n,m) = (lines,columns) in a matrix (m,n) and nbLigne return the number of lines (or columns when used with transpose) of a matrix.
getLigne :: (Int,Int,Int) -> Grille -> Grille
getLigne (i,l,0) g = []
getLigne (1,l,1) g = [head g]
getLigne (i,l,indice) [] = []
getLigne (i,l,indice) g
| indice == (i+l) = getLigne (i,l,(indice-1)) (init g) ++ [last g]
| indice == i = [last g]
| i < indice && indice < (i+l) = getLigne (i,l,(indice-1)) (init g) ++ [last g]
| otherwise = getLigne (i,l,(indice-1)) (init g)
Here's an example:
*Main> affiche (getRectangle (1,2,2,3) g0)
[B,B,B,B]
[B,N,B,N]
[B,N,N,N]
So, I have a tuple with (i,j,l,c). Knowing that 1<=i<i+l<=n and 1<=j<j+c<=m with n the number of lines of the matrix and m the number of columns.
To be clear, with a tuple (i,j,l,c), my function create a rectangle, from my matrix, formed with these cases: (i,j), (i+l,j), (i,j+c) and (i+l,j+c).
Now that I can create a single rectangle, I need to create all the possibles rectangles in any matrix. I don't have any clue on how I can do this since I feel like there is so many rectangles in a single matrix and cover all the cases seems very hard and long to me.
Maybe that I wasn't clear on some points, feel free to ask.
Salut :),
For combinations, I often work with the list monad.
Note that using the do notation like this is equivalent to working with list comprehensions
From a position you can deduce all the rectangles that can originate from a given point:
allRectsOriginatingFrom :: Point -> Grille -> [Rectangle]
allRectsOriginatingFrom (x, y) g
-- Si le point est dans ta grille...
| (x >= 1 && x <= width g) && (y >= 1 && y <= height g) = do
w <- [0 .. width g - x]
h <- [0 .. height g - y]
return (x, y, w, h)
-- Sinon y'a pas de rectangle possible
| otherwise = []
From there, your just have to map the function over all the possible positions on your grid:
allPointsOf :: Grille -> [Point]
allPointsOf g = do
x <- [1 .. width g]
y <- [1 .. height g]
return (x, y)
allRectsOf :: Grille -> [Rectangle]
allRectsOf g = do
pos <- allPointsOf g
allRectsOriginatingFrom pos g
And finally, mapping it with your getLigne function will get you every rectangle in your grid.
PS: Try to create datatypes instead of type aliases, it's better in my opinion (e.g. create a datatype like data Rectangle = Rectangle Int Int Int Int instead of type Rectangle = (Int, Int, Int, Int)).

Mutating data with immutable data structures

I would like to implement a particular algorithm, but I'm having trouble finding a good data structure for the job. A simpler version of the algorithm works like the following:
Input: A set of points.
Output: A new set of points.
Step 1: For each point, calculate the closest points in a radius.
Step 2: For each point, calculate a value "v" from the closest points subset.
Step 3: For each point, calculate a new value "w" from the closest points and
the values "v" from the previous step, i.e, "w" depends on the neighbors
and "v" of each neighbor.
Step 4: Update points.
In C++, I can solve this like this:
struct Point {
Vector position;
double v, w;
std::vector<Point *> neighbors;
};
std::vector<Point> points = initializePoints();
calculateNeighbors(points);
calculateV(points); // points[0].v = value; for example.
calculateW(points);
With a naive structure such as a list of points, I cannot update the value "v" into the original set of points, and would need to calculate the neighbors twice. How can I avoid this and keep the functions pure, since calculating the neighbors is the most expensive part of the algorithm (over 30% of the time)?
PS.: For those experienced in numerical methods and CFD, this is a simplified version of the Smoothed Particle Hydrodynamics method.
Update: Changed step 3 so it is clearer.
It is a common myth that Haskell doesn't offer mutation at all. In reality, it offers a very special kind of mutation: a value can mutate exactly once, from un-evaluated to evaluated. The art of taking advantage of this special kind of mutation is called tying the knot. We will start with a data structure just like your one from C++:
data Vector -- held abstract
data Point = Point
{ position :: Vector
, v, w :: Double
, neighbors :: [Point]
}
Now, what we're going to do is build an Array Point whose neighbors contain pointers to other elements within the same array. The key features of Array in the following code are that it's spine-lazy (it doesn't force its elements too soon) and has fast random-access; you can substitute your favorite alternate data structure with these properties if you prefer.
There's lots of choices for the interface of the neighbor-finding function. For concreteness and to make my own job simple, I will assume you have a function that takes a Vector and a list of Vectors and gives the indices of neighbors.
findNeighbors :: Vector -> [Vector] -> [Int]
findNeighbors = undefined
Let's also put in place some types for computeV and computeW. For the nonce, we will ask that computeV live up to the informal contract you stated, namely, that it can look at the position and neighbors fields of any Point, but not the v or w fields. (Similarly, computeW may look at anything but the w fields of any Point it can get its hands on.) It is actually possible to enforce this at the type level without too many gymnastics, but for now let's skip that.
computeV, computeW :: Point -> Double
(computeV, computeW) = undefined
Now we are ready to build our (labeled) in-memory graph.
buildGraph :: [Vector] -> Array Int Point
buildGraph vs = answer where
answer = listArray (0, length vs-1) [point pos | pos <- vs]
point pos = this where
this = Point
{ position = pos
, v = computeV this
, w = computeW this
, neighbors = map (answer!) (findNeighbors pos vs)
}
And that's it, really. Now you can write your
newPositions :: Point -> [Vector]
newPositions = undefined
where newPositions is perfectly free to inspect any of the fields of the Point it's handed, and put all the functions together:
update :: [Vector] -> [Vector]
update = newPositions <=< elems . buildGraph
edit: ...to explain the "special kind of mutation" comment at the beginning: during evaluation, you can expect when you demand the w field of a Point that things will happen in this order: computeW will force the v field; then computeV will force the neighbors field; then the neighbors field will mutate from unevaluated to evaluated; then the v field will mutate from unevaluated to evaluated; then the w field will mutate from unevaluated to evaluated. These last three steps look very similar to the three mutation steps of your C++ algorithm!
double edit: I decided I wanted to see this thing run, so I instantiated all the things held abstract above with dummy implementations. I also wanted to see it evaluate things only once, since I wasn't even sure I'd done it right! So I threw in some trace calls. Here's a complete file:
import Control.Monad
import Data.Array
import Debug.Trace
announce s (Vector pos) = trace $ "computing " ++ s ++ " for position " ++ show pos
data Vector = Vector Double deriving Show
data Point = Point
{ position :: Vector
, v, w :: Double
, neighbors :: [Point]
}
findNeighbors :: Vector -> [Vector] -> [Int]
findNeighbors (Vector n) vs = [i | (i, Vector n') <- zip [0..] vs, abs (n - n') < 1]
computeV, computeW :: Point -> Double
computeV (Point pos _ _ neighbors) = sum [n | Point { position = Vector n } <- neighbors]
computeW (Point pos v _ neighbors) = sum [v | Point { v = v } <- neighbors]
buildGraph :: [Vector] -> Array Int Point
buildGraph vs = answer where
answer = listArray (0, length vs-1) [point pos | pos <- vs]
point pos = this where { this = Point
{ position = announce "position" pos $ pos
, v = announce "v" pos $ computeV this
, w = announce "w" pos $ computeW this
, neighbors = announce "neighbors" pos $ map (answer!) (findNeighbors pos vs)
} }
newPositions :: Point -> [Vector]
newPositions (Point { position = Vector n, v = v, w = w }) = [Vector (n*v), Vector w]
update :: [Vector] -> [Vector]
update = newPositions <=< elems . buildGraph
and a run in ghci:
*Main> length . show . update . map Vector $ [0, 0.25, 0.75, 1.25, 35]
computing position for position 0.0
computing v for position 0.0
computing neighbors for position 0.0
computing position for position 0.25
computing position for position 0.75
computing w for position 0.0
computing v for position 0.25
computing neighbors for position 0.25
computing v for position 0.75
computing neighbors for position 0.75
computing position for position 1.25
computing w for position 0.25
computing w for position 0.75
computing v for position 1.25
computing neighbors for position 1.25
computing w for position 1.25
computing position for position 35.0
computing v for position 35.0
computing neighbors for position 35.0
computing w for position 35.0
123
As you can see, each field is computed at most once for each position.
Can you do something like this? Given the following type signatures
calculateNeighbours :: [Point] -> [[Point]]
calculateV :: [Point] -> Double
calculateW :: [Point] -> Double -> Double
you can write
algorithm :: [Point] -> [(Point, Double, Double)]
algorithm pts = -- pts :: [Point]
let nbrs = calculateNeighbours pts -- nbrs :: [[Point]]
vs = map calculateV nbrs -- vs :: [Double]
ws = zipWith calculateW nbrs vs -- ws :: [Double]
in zip3 pts vs ws -- :: [(Point,Double,Double)]
This calculates the lists of neighbours only once, and re-uses the value in the computations for v and w.
If this isn't what you want, can you elaborate a little more?
I think you should either use Map (HashMap) to separately store v's (and w's) counted from your Point's, or use mutable variables to reflect your C++ algorithm. First method is more "functional", e.g. you may easily add parralelism into it, since all data is immutable, but it should be little slower, since you'll have to count hash each time you need to get v by point.

Resources