I am learning javascript and data structures at the same time and struggling with my output for a graph. Can anyone help me fix my code to output all available paths between start and end node?
If I enter F to C I get the following:
F -> B C :3
F -> A D G :4
F -> A D E :3
F -> C B E F G :7
F -> C D :3
F -> D :1
F -> B D :3
F to C
F D B
F D C
F D
F D E
F
F D G
I'd like the first output to show all available paths from F to C. All its doing now is showing all available paths. The second output is showing all available paths but not correctly.
I'm trying to make the first output show the following when I enter F and C:
F -> D C: 2
F -> D E C: 4
F -> D B A C: 5
F -> D G B A C: 7
I've looked at these:
https://en.wikipedia.org/wiki/Depth-first_search
All the paths between 2 nodes in graph
http://www.quora.com/What-are-good-ways-to-find-all-the-possible-paths-between-two-nodes-in-a-directed-graph
Graph Algorithm To Find All Connections Between Two Arbitrary Vertices
https://mathematica.stackexchange.com/questions/25779/finding-all-simple-paths-between-two-vertices-in-a-graph
https://mathematica.stackexchange.com/questions/4128/finding-all-shortest-paths-between-two-vertices
and many others and I am still stuck.
My code is here:
https://jsfiddle.net/jtlindsey/584hh0vf/3/
My two outputs so far start at line number 116 and 209 in the code.
Related
I am trying to translate this JS fixed-point operator into Haskell.
JS:
const fix = F => {
const D = X => F(
t => X(X)(t)
)
return D(D)
};
My attempt is (Haskell):
fix' f = d d
where
d x = f (\t -> x x t)
However, I get the following error:
Couldn't match expected type ‘(t2 -> t3) -> t4’
with actual type ‘p’
because type variables ‘t2’, ‘t3’, ‘t4’ would escape their scope
These (rigid, skolem) type variables are bound by the inferred type of d :: (t1 -> t2 -> t3) -> t4
Does someone know what's happening here ?
In the self-application d d, d is both a function, of some type a -> r, and its argument, of type a. Thus the two types must be one and the same, a ~ (a -> r).
Haskell wants to know its types in full upfront so it keeps substituting one for another ending up with an infinite type.
Infinite types aren't allowed in Haskell, but recursive types are allowed.
All we need to do here is to name that recursive type:
newtype T r = D { app :: T r -> r }
Now T r is both a type of a function and its argument, for some result type r.
Here T is a type constructor, and D its data constructor, D :: (T r -> r) -> T r.
The above record syntax defines a new data type (here though with the keyword newtype, not data) and names its single field as app. It also defines app as an accessor function, app :: T r -> (T r -> r). (It's kind of an inverse of D, and oftentimes one sees such functions named with the prefix of "un", like app could have been named unD. But here app makes sense, as we will see later.)
For a value x of type T r, x :: T r, this means that x is / matches up with / some value D g where (g = app x) :: T r -> r, i.e. app simply unwraps the data constructor D to get to the underlying value (a function) g: x = D g ; app x = app (D g) = g. That's how the record syntax works in Haskell.
Now we can write
{- fix' f = d d
where
d x = f (\t -> x x t) -- applying x to x can't be typed!
-}
fix1 :: ((t1 -> t) -> t1 -> t) -> t1 -> t
fix1 f = d (D d)
where
d x = f (\t -> app x x t) -- `app`ing x to x is well-typed!
fix2 :: ((t1 -> t) -> t1 -> t) -> t1 -> t
fix2 f = d (D d)
where
d (D y) = f (\t -> y (D y) t)
fix3 :: ((t1 -> t) -> t1 -> t) -> t1 -> t
fix3 f = f (\t -> d (D d) t)
where
d (D y) = f (\t -> y (D y) t)
fix4 :: (t -> t) -> t
fix4 f = f (d (D d))
where
d (D y) = f (y (D y))
all work. The last one even has the same type as the built-in fix.
But Haskell doesn't only have recursive types. It also has recursion itself. An entity is allowed to refer to itself in its own definition.
Thus as the comments say we don't really need to emulate recursion by self-application of a value passed as an argument. We can just use recursively the function being defined, itself:
fix0 :: (t -> t) -> t
fix0 f = f (fix0 f)
Or we can use a recursively defined value:
y :: (t -> t) -> t
y f = x where { x = f x }
Regarding the error, the second type error you get,
prog.hs:3:22: error:
• Occurs check: cannot construct the infinite type:
t1 ~ t1 -> t2 -> t3
• In the first argument of ‘x’, namely ‘x’
In the expression: x x t
In the first argument of ‘f’, namely ‘(\ t -> x x t)’
• Relevant bindings include
t :: t2 (bound at prog.hs:3:15)
x :: t1 -> t2 -> t3 (bound at prog.hs:3:7)
d :: (t1 -> t2 -> t3) -> t4 (bound at prog.hs:3:5)
|
3 | d x = f (\t -> x x t)
| ^
seems more to-the-point / helpful / than the one you included.
I read that a functor's map is assocative and that it implies the following :
Functor.map(f).map(g) == Functor.map(x => g(f(x))
Shouldn't the above equation be written like this to demonstrate associativity?
Functor.map(f).map(g) == Functor.map(f.map(g))
(but it seams impossible because funcitons dont have a map method).
There is something that I am not grasping here.
This is an example in Haskell.
You can create two functions.
The first composeAndMap which will first compose f and g and then apply the map function.
composeAndMap :: Functor f => (b -> c) -> (a -> b) -> f a -> f c
composeAndMap f g = fmap (f . g)
The second will be called mapAndCompose which will compose two partial application functions using the map function. The first map will use the f and the second one will use the g like this:
mapAndCompose :: Functor f => (b -> c) -> (a -> b) -> f a -> f c
mapAndCompose f g = fmap f . fmap g
Eventually you can compare between the results of each function using a specific functor instance, the most obvious is the list functor.
list :: [Int]
list = [1..5]
main :: IO ()
main = print $ mapAndCompose (+1) (+2) list == composeAndMap (+1) (+2) list
You should not forget the identity law also.
identity :: Functor f => f a -> f a
identity = fmap id
composeAndMap :: Functor f => (b -> c) -> (a -> b) -> f a -> f c
composeAndMap f g = fmap (f . g)
mapAndCompose :: Functor f => (b -> c) -> (a -> b) -> f a -> f c
mapAndCompose f g = fmap f . fmap g
list :: [Int]
list = [1..5]
main :: IO ()
main = do
print $ identity list == list
print $ mapAndCompose (+1) (+2) list == composeAndMap (+1) (+2) list
This is an example in JavaScript:
Create two functions plusOne and plusTwo
function plusOne(val) {
return val + 1;
}
function plusTwo(val) {
return val + 2;
}
Create a compose function which composes two functions
function compose(f, g) {
return (val) => f(g(val));
}
Create a utility function sequenceEquals
function sequenceEquals(arr1, arr2) {
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
Now you can compare between the two implementations:
let list = [1,2,3,4,5];
let composed = compose(plusOne, plusTwo);
let composeAndMap = list.map(composed);
let mappedTwice = list.map(plusTwo).map(plusOne);
console.log(sequenceEquals(composeAndMap, mappedTwice));
And the identity law.
Create an identity function:
function identity(value) { return value; }
And compare the results:
console.log(sequenceEquals(list.map(identity), list));
I answered a question yesterday and it got my mind thinking about an interesting (to me) puzzle
With the restriction of using lambdas, numbers, and + only (no if, ?:, or other language features), the goal is to implement some f and some g such that
// contract
f(x) => f'
g(y) => g'
f'(g') == g'(f')
// or more simply:
m(n) == n(m)
Here's what I came up with so far - this code is in JavaScript for the purpose of being able to demonstrate the code in the browser but answers in any functional language are acceptable (racket, clojure, ocaml, lambda calc, etc)
// f
const f = x => k =>
k(y => y + x)
// g
const g = y => k =>
k(x => x + y)
// make instance of each
const a = f(1)
const b = g(2)
console.log(a(b))
// x => x + y1
// should be 3
console.log(b(a))
// y => y + x2
// should be 3
I was able to fix one half of relationship, but the other side remains broken due f and g now being asymmetrical
// f
const f = x => k =>
k(y => y(x))
// g
const g = y => k =>
k(x => x + y)
// make instance of each
const a = f(1)
const b = g(2)
console.log(a(b))
// 3
// should be 3 (OK)
console.log(b(a))
// y => y + x2
// should be 3
I know why it's not working but I'm having trouble trying to fix it. Most importantly, if it's not possible, I'd be interested in learning why.
If you come up with a solution that breaks the restrictions, I'm still interested in seeing it ^_^
This answer assumes a strong non-unit type system (eg. Haskell, but I try to stick to JS-like syntax here).
If we stay in the realm of parametricity, we don't need (and cannot even use) numbers or conditions. The constant functions don't change anything, so I'll leave them out and deal with f and g directly.
First, observe that the equation
f(g) == g(f)
implies that both f and g have function types. Assuming both have different inputs we get that f: A -> X and g: B -> X == (A -> X) -> X == ((B -> X) -> X) -> X == ..., ie., you get an infinite type. I remember having read a paper about this exact construction (one can represent it as a pair of types, and I think it forms a category), but unfortunately forgot its name -- maybe there's more to say here.
A simpler solution would be to require A == B. Then f, g: A -> X, but since X == A by the symmetry equation, it follows that f, g: A -> A -- for arbitrary A, that is. One possibilitity fulfilling this is the identity function:
id(id) == id(id)
The other solutions arise when we specialize A to A -> A; then we search for functions of type (A -> A) -> (A -> A). These are, for one, the (specialized) identity function, which has already been found, but also all functions of the shape h => h o ... o h -- compositions ((o) = h => x => h(h(x))) of a function for a number of types. These "add their repetitions" on application, e.g.
(h => h o h)(h => h o h) == (h => h o h) o (h => h o h)
== h => h o h o h o h.
From this we see that we can choose
f == g == h => h,
f == g == h => h o h,
f == g == h => h o h o h,
f == g == ...
which are, I think, all functions of type forall A. (A -> A) -> (A -> A) (excluding nontermination).
There also seems to be a relation of the limit of this construction (infinite composition) to the infinite case mentined above (now in real Haskell):
Prelude> let g = \h -> h . g
<interactive>:11:19:
Occurs check: cannot construct the infinite type: b ~ (b -> c) -> c
This is the closest I've been able to get but it does use a ternary (?:) expression
const f = x => g =>
g === undefined ? x : g() + x
const g = y => f =>
f === undefined ? y : f() + y
const a = f(1)
const b = g(2)
console.log(a(b)) // 3
console.log(b(a)) // 3
Here f is completely equivalent to g and we could easily just use one or the other
const f = x => g =>
g === undefined ? x : g() + x
const a = f(1)
const b = f(2)
console.log(a(b)) // 3
console.log(b(a)) // 3
For this to happen obviously both f and g has to accept a function as an argument and return a same type value. However after tinkering a while it quickly strike me that i am dealing with infinite types.
Well unless your functions are Haskell's id like JS's x => x. So in Haskell i would do;
f :: a -> a
g :: a -> a
f = id
g = id
*Main> f(g)(+3) 2
5
*Main> g(f)(+3) 2
5
Can simply be implemented in JS as well.
Consider the following multiple choice question:
What's the color of apples?
a. red
b. green
c. blue
d. black
Now, I want to calculate all it's possible answers and I could do it manually, like so...:
a
b
c
d
a, b
a, c
a, d
b, c
b, d
c, d
a, b, c
a, b, d
a, c, d
b, c, d
a, b, c, d
... but that's prone to human error. How could I do this programmatically with JavaScript?
My initial thought is to define the total number of choices (a,b,c,d = 4)...:
const TOTAL_CHOICES = 4;
// TO-DO
... but then I don't know what the next step should be. Any ideas?
With the help of #nenad-vracar's comment I found a solution:
function combinations(str) {
var fn = function(active, rest, a) {
if (!active && !rest)
return;
if (!rest) {
a.push(active);
} else {
fn(active + rest[0], rest.slice(1), a);
fn(active, rest.slice(1), a);
}
return a;
}
return fn("", str, []);
}
var result = combinations('abcd').sort();
for (combination of result) {
document.body.innerHTML += combination + '<br>';
}
This will output:
a
ab
abc
abcd
abd
ac
acd
ad
b
bc
bcd
bd
c
cd
d
This implements the way I suggested in my comment.
var choices = ['d','c','b','a'];
var numCombos=Math.pow(2,choices.length);
var binNum;
writeln('Combos are:');
for (i=0;i<numCombos;i++)
{
binNum=(i.toString(2));
while (binNum.length<choices.length)
binNum='0'+binNum;
for (j=choices.length-1;j>=0;j--){
if (binNum[j]=='1') write(choices[j]);}
writeln();
}
I'm using angularjs for my application and found this issue on google chrome, the problem is I have this URL:
http://127.0.0.1/#/fa/episode/1315019/برنامه-خوب
but when I click on this links it shows:
http://127.0.0.1/#/fa/episode/1315019/%D9%82%D8%B3%D9%85%D8%AA-%D8%A2%D8%AE%D8%B1
I'm using $routeProvider for my routing, it works fine in firefox but I have issue with that in google chrome.
why is that and how should I resolve this issue?
You cant fix this "problem" but it actually should not be a problem at all.
URLs can only contain these characters:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 - _ . ~
! * ' ( ) ; : # & = + $ , / ? % # [ ]
All other characters, like <, § and the characters contained in برنامه-خوب will get encoded.
Encoding means, that they get replaced by a combination of valid characters, in your case برنامه-خوب gets replaced by %D9%82%D8%B3%D9%85%D8%AA-%D8%A2%D8%AE%D8%B1 which is no issue, its the way how an URL works, you can not change it.