All possible paths algorithm - algorithm

I'm not very comfortable with math algorithms, and would need to use one for a project I'm working on. I have found answers for point A to point B, but none that really match what I'm looking for. I am looking for the best time efficient algorithm to accomplish this task:
For an input :
Points {
In
Out
}
[Bridge]Points = {
"AB-1" = {"A", "B"}
"AB-2" = {"A", "B"}
"BA-1" = {"B", "A"}
"BA-2" = {"B", "A"}
"AC-1" = {"A", "C"}
"AC-2" = {"A", "C"}
"CA-1" = {"C", "A"}
"CA-2" = {"C", "A"}
"BC-1" = {"B", "C"}
"BC-2" = {"B", "C"}
"CB-1" = {"C", "B"}
"CB-2" = {"C", "B"}
}
Each "bridge" represent 2 "points" : First value is an "in" and the second in an "out".
Each path can use each unique bridge only once.
Different bridges can have the same in/out (like "BC-1","BC-2", ..), and each unique bridge must have a different in and out ("AA-1" = {"A", "A"} is not possible).
The goal is to obtain EVERY POSSIBLE paths given a start point and an end point, which can be the same points (A->A, B->B, ..).
For A to A expected output :
AB-1 -> BA-1
AB-1 -> BA-2
AB-2 -> BA-1
AC-1 -> CA-2
AB-1 -> BA-1 -> AB-2 -> BA-2
AB-1 -> BA-2 -> AC-1 -> CB-2 -> BA-1
AC-2 -> CA-1 -> AB-1 -> BA-2
AC-1 -> CA-1 -> AB-2 -> BC-1 -> CA-2
...
Also, the possibility of defining a maximum path length (to avoid subsequent processing within the algorithm) would be optional but very interesting.
Thanking you for your time, I would very much appreciate your advice.

One could use a recursion like this (pseudo code):
findPath(from, to, path_to_from) {
if from == to { output path_to_from }
for all bridges going out from 'from' that were not already used in path_to_from {
findPath(bridge.out, to, path_to_from + bridge)
}
}
and call it with findPath(A, B, empty_path) to output all paths from A to B.

Related

How do I add numbers to each subset in Wolfram mathematica?

Say I have a deck of 52 cards. I now remove two cards from the deck, say it is Diamond 2 and 4. I now create a subset {5} meaning I print every 5 card combination of the 50 cards I have left.
How do I now add back both the diamond 2 and 4 into each subset i.e. each set of 5 card combinations?
Update Use resource function PlayingCardGraphic to generate graphic
Converting to the right format is a bit messy, would have been easier if the ranks were generated in a different way.
newHands =
Subsets[deckPart, {5}] // Map[Join[#, cardsToRemove] & /* RandomSample];
hand = newHands // RandomChoice
(hand //
Map[StringSplit[#,
x : DigitCharacter .. | {"J", "Q", "K", "A"} :> x] &]) /. {v_,
s_} :> {If[MemberQ[{"J", "Q", "K", "A"}, v], v, ToExpression#v],
s} //
ResourceFunction["PlayingCardGraphic"][#, "CardSpreadAngle" -> .8] &
The number of 5 card subsets is
50!/(5! 45! = 2118760
it takes ~2.8s to compute and ~10s to display in the notebook on my machine.
suits = ToString /# {\[SpadeSuit], \[HeartSuit], \[DiamondSuit], \[ClubSuit]}
ranks = CharacterRange["2", "9"]~Join~{"10", "J", "Q", "K", "A"}
deck = Outer[StringJoin, ranks, suits] // Flatten // RandomSample
cardsToRemove = {"2\[DiamondSuit]", "4\[DiamondSuit]"}
deckPart = deck // DeleteCases[Alternatives ## cardsToRemove]
Subsets[deckPart, {5}] // Map[Join[#, cardsToRemove] & /* RandomSample]

Creating Map from a number of Sets with Map/Reduce

Suppose there are N sets of words and I would like to create a map from those sets so that it maps the words to the number of the words occurrences in all these sets.
For example:
N = 3
S1 = {"a", "b", "c"}, S2 = {"a", "b", "d"}, S3 = {"a", "c", "e"}
M = { "a" -> 3, "b" -> 2, "c" -> 2, "d" -> 1, "e" -> 1}
Now I have M computers to use. Thus, I can make each computer create a map from N/M sets. In the second (final) phase I can create a map from the M maps. Looks like a map/reduce. Does it make sense ? How would you improve this approach ?
This is the standard map reduce example.
For example here is Python code based on the mincemeat map/reduce library:
#!/usr/bin/env python
import mincemeat
S1 = {"a", "b", "c"}
S2 = {"a", "b", "d"}
S3 = {"a", "c", "e"}
datasource = dict(enumerate([S1,S2,S3]))
def mapfn(k, v):
for w in v:
yield w, 1
def reducefn(k, vs):
result = sum(vs)
return result
s = mincemeat.Server()
s.datasource = datasource
s.mapfn = mapfn
s.reducefn = reducefn
results = s.run_server(password="changeme")
print results
Prints
{'a': 3, 'c': 2, 'b': 2, 'e': 1, 'd': 1}
Note that the way that map/reduce is structured means that the server gives new tasks to clients as they complete their tasks.
This means that there is not necessarily a fixed partitioning of N/M tasks to each client.
If one client is faster than the others then it will end up being given more tasks in order to make best use of the available resources.

Using data returned form Tally command in Mathematica

I have a small piece of code to generate sequences, which is ok.
List = Reap[
For[i = 1, i <= 10000, i++,
Sow[RandomSample[Join[Table["a", {2}], Table["b", {2}]], 2]]];][[2, 1]];
Tally[List]
Giving the following output,
{{{"b", "b"}, 166302}, {{"b", "a"}, 333668}, {{"a", "b"}, 332964}, {{"a", "a"}, 167066}}
My problem is I have yet to find a way to extract the frequencies from the output ....?
Thanks in advance for any help
Note: Generally do not start user-created Symbol names with a capital letter as these may conflict with internal functions.
It is not clear to me how you wish to transform the output. One interpretation is that you just want:
{166302, 333668, 332964, 167066}
In your code you use [[2, 1]] so I presume you know how to use Part, of which this is a short form. The documentation for Part includes:
If any of the listi are All or ;;, all parts at that level are kept.
You could therefore use:
Tally[list][[All, 2]]
You could also use:
Last /# Tally[list]
As george comments you can use Sort, which due to the structure of the Tally data will sort first by the item because it appears first in each list, and each list has the same length.
tally =
{{{"b","b"},166302},{{"b","a"},333668},{{"a","b"},332964},{{"a","a"},167066}};
Sort[tally][[All, 2]]
{167066, 332964, 333668, 166302}
You could also convert your data into a list of Rule objects and then pull values from a predetermined list:
rules = Rule ### tally
{{"b", "b"} -> 166302, {"b", "a"} -> 333668, {"a", "b"} -> 332964, {"a", "a"} -> 167066}
These could be in any order you choose:
{{"a", "a"}, {"a", "b"}, {"b", "a"}, {"b", "b"}} /. rules
{167066, 332964, 333668, 166302}
Merely to illustrate another technique if you have a specific list of items you wish to count you may find value in this Sow and Reap construct. For example, with a random list of "a", "b", "c", "d":
SeedRandom[1];
dat = RandomChoice[{"a", "b", "c", "d"}, 50];
Counting the "a" and "c" elements:
Reap[Sow[1, dat], {"a", "c"}, Tr[#2] &][[2, All, 1]]
{19, 5}
This is not as fast as Tally but it is faster than doing a Count for each element, and sometimes the syntax is useful.

How to make selective drop down menu in Mathematica?

I am running out of space on the Manipulate interface. So, I am looking to see if I can overload a PopupMenu to serve more than one purpose.
Here is the problem:
I have a PopupMenu where I use to select an entry from it. But depending on another choice I make somewhere else, some of these entries in the menu will no longer make sense to select.
So, I was wondering, if I can make some of the entries in the PopupMenu 'selectable' based on a setting of a Dynamic? (may be disabled, or grayed out, or what would be best, have the whole list itself by dynamic, i.e. the whole popUp menu be dyanmic, so I can select different menus based on value of another dynamic. But I do not think this is possible)
Currently, the WHOLE PopupMenu can be enabled or disabled based on a dynamic setting. But I want to do this at the entry level inside the Popupmenu.
Here is an example to illustrate:
Manipulate[selection,
Grid[{
{"x", SetterBar[Dynamic[x], {1, 2}]},
{"selection", PopupMenu[Dynamic[selection],
{
"NONE", "SOR", "SSOR"
}, Enabled -> Dynamic[x == 1]], SpanFromLeft
}
}]
]
In the above, when X=1, the whole menu is enabled.
But what I want, if X=1, is to be able to select only say "NONE" (or the list just show "NONE"), and when X=2, then be able to select only "SOR" and "SSOR" (or the list just show these 2 choices).
i.e. the system will not let "SOR" be selected if x=2. Trying to select it will cause no change and the menu will remain on its previous setting and not change.
Again, I know I can break things into 2 popuMenus, and control each one based on X setting like this below, but I do not have more space to add more menus:
Manipulate[If[x == 1, selectionA, selectionB],
Grid[{
{"x", SetterBar[Dynamic[x], {1, 2}]},
{"selection", PopupMenu[Dynamic[selectionA],
{
"NONE"
}, Enabled -> Dynamic[x == 1]], SpanFromLeft
},
{"selection", PopupMenu[Dynamic[selectionB],
{
"SOR", "SSOR"
}, Enabled -> Dynamic[x == 2]], SpanFromLeft
}
}]
]
My question is: Is there a way to do the above in Mathematica? I am using 8.04.
Best solution would be to have the list of items for the menu itself by Dynamic (or the whole menu be dynamic), so I can tell it to use listA when X=1 or use listB when X=2, etc.. But I do not know how to do this and do not know if it is even possible.
ps. This is my current attempt at a solution
Manipulate[selection,
Grid[{
{"x", SetterBar[Dynamic[x], {1, 2}]},
{"selection", PopupMenu[Dynamic[selection],
{
Dynamic[If[x == 1, listA, listB]]
}
]
}
}
],
Initialization :>
(
listA = {"A", "B"};
listB = {"C", "D"};
)
]
But it is not working too well yet. Will keep at it....
thanks
Update:
Looking at Simon solution below inspired me a little more, so this is what I have so far:
Manipulate[selection,
Grid[{
{"x", SetterBar[Dynamic[x], {1, 2}]},
{"selection",
Dynamic[If[x == 1,
(
selection = "A";
PopupMenu[Dynamic[selection], {"A", "B"}]
),
(
selection = "C";
PopupMenu[Dynamic[selection], {"C", "D"}]
)
]
]
}
}
]
]
Is this the type of thing you're looking for?
Manipulate[
Switch[x,
1, If[selection =!= None, selection = None],
2, If[selection === None, selection = "SOR"]];
selection,
{x, {1, 2}, ControlType -> SetterBar},
{{selection, None}, Switch[x, 1, {None}, 2, {"SOR", "SSOR"}, _, {"huh"}],
ControlType -> PopupMenu}]
Note the Switch at the top that controls the defaults for selection when x is changed.
Edit:
Following your request to have the menu logic localised to the control Grid and stealing Heike's default mechanism, here's a new version:
Manipulate[selection,
Grid[With[{menu = {{None}, {"A", "B"}, {"emu", "num"}}},
{{"Which menu?", SetterBar[Dynamic[x], Range[Length[menu]]]},
{"Menu selection:", Dynamic[
If[MemberQ[menu[[x]], selection], selection = menu[[x, 1]]];
PopupMenu[Dynamic[selection], menu[[x]]]]}}]],
{{selection, None}, None}, {{x, 1}, None}]
Note that the menu list does not need to be localized with a With statement - it can be set elsewhere in the code.
This solution is similar to Simon's answer, but it doesn't explicitly use the number of lists so it should work for an arbitrary number of lists
choices = {{"a", "b", "c"}, {None}, {"e", "f"}};
Manipulate[
If[Not[MemberQ[x, selection]], selection = x[[1]]];
selection,
{{x, choices[[1]]}, MapIndexed[# -> #2[[1]] &, choices], SetterBar},
{selection, x, ControlType -> PopupMenu}]

Is there a functional programming concept equivalent to the flip-flop operator in Perl or Ruby?

Ruby (and Perl) has a concept of the flip flop:
file = File.open("ordinal")
while file.gets
print if ($_ =~ /third/) .. ($_ =~ /fifth/)
end
which given a list of ordinals, such as
first
second
third
fourth
fifth
sixth
would start printing when it reached "third" and stop when it reached "fifth":
third
fourth
fifth
Is there a functional programming concept analogous to this, or would this normally be described in terms of takewhiles? I'm not asking about a particular language, just what term you'd use to describe it.
In a functional language such as haskell, you would pass in the flip and flop conditions as predicates, and filter an input list based on it. For example, the following is a definition of flipflop in haskell (don't worry about the implementation if you don't know haskell - the key part is how it is used):
flipflop flip flop =
uncurry (++) . second (take 1) . break flop . dropWhile (not . flip)
This is how it can be used:
> flipflop (== 3) (== 5) [1..10]
[3,4,5]
It is an example of making an effectively new language construct just by using higher ordered function.
I don't know if there is a special name for that construct in functional languages.
Depends on functional language. How about this?
ff_gen =
lambda{ |first, *conditions|
flipflop = false
condition = first
lambda{ |v|
if condition && condition[v]
condition = conditions.shift
flipflop = !flipflop
true
else
flipflop
end
}
}
ff = ff_gen[lambda{|v| v == 3}, lambda{|v| v == 5}, lambda{|v| v == 7}, lambda{|v| v == 11}]
puts (0..20).select{ |i| ff[i] }.inspect # => [3, 4, 5, 7, 8, 9, 10, 11]
Added: Of course, Ruby is not a pure functional language, so I decided to rewrite it in Erlang:
#!/usr/bin/env escript
flipflop(E, {[H|T] = Conditions, FlipFlop}) ->
case H(E) of
true ->
{true, {T, not FlipFlop}};
false ->
{FlipFlop, {Conditions, FlipFlop}}
end;
flipflop(_, {[], FlipFlop}) ->
{FlipFlop, {[], FlipFlop}}.
flipflop_init(Conditions) ->
{[], {Conditions, false}}.
main([]) ->
{L, _} =
lists:foldl(
fun(E, {L2, FFState}) ->
case flipflop(E, FFState) of
{true, FFState2} ->
{[E|L2], FFState2};
{false, FFState2} ->
{L2, FFState2}
end
end,
flipflop_init([
fun(E) -> E == 3 end,
fun(E) -> E == 5 end,
fun(E) -> E == 7 end,
fun(E) -> E == 11 end
]),
lists:seq(0,20)
),
io:format("~p~n", [lists:reverse(L)]),
ok.
Note: In fact, classic flip-flop should work like dropwhile(!first) -> takewhile(!second), so Ruby's flip-flop is ad hoc one (compare with flip-flop in electronics).
Same as #nanothief's solution, but in Scala:
def flipFlop[A](flip: A => Boolean, flop: A => Boolean, seq: Seq[A]): Seq[A] = {
val (p, q) = seq.dropWhile(!flip(_)).span(!flop(_))
p ++ q.take(1)
}
Sample runs:
> flipFlop[Int](_ == 3, _ == 5, Nil)
List()
> flipFlop[Int](_ == 3, _ == 5, 1 to 19)
Vector(3, 4, 5)

Resources