I am trying to use GraphPlot function to build a Graph, where each node is an image. I wanted to display the image as my vertex. Does anybody know how to do this?
I tried something like this:
GraphPlot[ Map[If[# > 2.0 , 0, 1] &,
imgDistT, {2}],
VertexRenderingFunction -> (Inset[imgs[[#2]], #1, Center] &) ]
But this does not work.
imgs is my list of images corresponding to each vertex number.
As a sanity check, if i do this:
GraphPlot[
Map[If[# > 2.0 , 0, 1] &, imgDistT, {2}],
VertexRenderingFunction -> (Inset[Text[#2], #1, Center] &) ]
then that works and it shows me the vertex number at each node.
imgs = ExampleData /# ExampleData["TestImage"];
GraphPlot[{1 -> 4, 1 -> 5, 2 -> 3, 2 -> 4, 2 -> 5, 3 -> 4, 3 -> 5},
VertexRenderingFunction -> (Inset[Image[imgs[[#2]], ImageSize -> 100], #1] &)]
Edit
-- Infix notation joke removed --
Two possible issues:
It looks like your graph, Map[If[# > 2.0 , 0, 1] &, imgDistT, {2}], will contain zeroes and ones—but zeroes are invalid indices for the imgs array
The images may not appear properly due to scaling issues—for example, they might be really big only the white portion might be visible. Try specifying an explicit image size.
What is the output of
GraphPlot[Map[If[# > 2.0 , 0, 1] &, imgDistT, {2}],
VertexRenderingFunction -> (Module[{tmp =
Inset[Image[imgs[[#2]], ImageSize -> 10], #1, Center]},
Print[tmp]; tmp] &)]
?
Related
I'm working on a school project in a functional programming class. The project is about determining if a set of dominos (represented as a list of tuples of two numbers from 1-6) can be put end to end. I'm ok on the problem, but I'm running into an issue where lists:filter is returning the string "\n\f" instead of a list like it says in the documentation.
I couldn't find anything online, and was wondering if any of you had any ideas.
Thanks!
Here is my code. The issue is in the check_dominos() function.
-module(challenge).
-export([test/0, check_dominos/1]).
% If there is an even number of each number, true
% else, false
extract_numbers([]) -> [];
extract_numbers([{First, Second} | T]) -> [First] ++ [Second] ++ extract_numbers(T).
add_matching_numbers(_Previous, []) -> [];
add_matching_numbers(Previous, [First | T]) when Previous =:= First-> [Previous + First | add_matching_numbers(First, T)];
add_matching_numbers(_Previous, [First | T]) -> add_matching_numbers(First, T).
check_dominos(Dominos) ->
All_Numbers = extract_numbers(Dominos),
Sorted_Numbers = lists:sort(All_Numbers),
Accumulated_Numbers = add_matching_numbers(0, Sorted_Numbers) ,
Filter_Lambda = fun(Num) -> Num rem 2 == 0 end,
Result = lists:filter(Filter_Lambda, Accumulated_Numbers),
Result.
% Still working on the logic of this part
%case length(Accumulated_Numbers) =:= length(Result) of
% true -> true;
% _ -> false
%end.
test() ->
Test_1 = [{1, 3}, {3, 2}, {2, 1}], % Already in order
Test_2 = [{5, 2}, {5, 6}, {6, 3}, {1, 4}], % Shouldn't work
Test_3 = [{2, 6}, {3, 5}, {1, 4}, {3, 4}, {6, 1}, {2, 5}], % Should work
true = check_dominos(Test_1),
false = check_dominos(Test_2),
true = check_dominos(Test_3).
Erlang strings are lists of character codes, and by default Erlang shell tries to display lists of integers as strings. To change this behaviour call shell:strings(false). before running your program.
The previous answerer is correct. Any list containing only numbers that correspond to printable characters, will display as a string. The result of your
Accumulated_Numbers = add_matching_numbers(0, Sorted_Numbers)
on Test_2 is "\n\f", but displayed as a list it is [10, 12]. Try typing [10, 12]. in an interactive erlang shell and you will indeed see it displays "\n\f".
Try:
[7].
in an interactive Erlang shell. For me it displays:
[7]
Try:
[8].
Displays:
"\t"
N.B. The numbers 8 through 13 are printable characters, as are (some of?) the numbers 32 to 255. Might be some gaps in there. If you want to see the numeric value of a printable character, use a dollar sign, e.g. $\n. prints 10.
That said, with your current way of going about things, you won't be able to get an answer with add_matching_numbers as it stands. It drops a value whenever it doesn't match the next item in the sorted list, which doesn't tell you if you had any unmatched items. The result of [10,12] on List_2 tells of this: it is a list of even numbers, like the other results.
Good luck on finding your solution.
I'm trying to solve this problem:
There is a grid with with r rows and c columns. A robot sitting in top left cell can only move in 2 directions, right and down. But certain cells have to be avoided and the robot cannot step on them. Find a path for the robot from the top left to the bottom right.
The problem specifically asks for a single path, and that seems straight forward:
Having the grid as boolean[][], the pseudocode I have is
List<String> path = new ArrayList<String>()
boolean found = false
void getPath(r, c){
if (!found) {
if ( (r or c is outofbounds) || (!grid[r][c]) )
return
if (r==0 AND c==0) // we reached
found = true
getPath(r-1, c)
getPath(r, c-1)
String cell = "(" + r + ", " + c + ")"
path.add(cell)
}
}
Though I was wondering how can I get all the possible paths (NOT just the count, but the path values as well). Note that it has r rows and c columns, so its not a nxn grid. I'm trying to think of a DP/recursive solution but unable to come up with any and stuck. It's hard to think when the recursion goes in two ways.
Any pointers? And also any general help on how to "think" about such problems would be appreciated :).
Any pointers? And also any general help on how to "think" about such problems would be appreciated :).
Approach to the problem:
Mentally construct graph G of the problem. In this case the vertices are cells in the grid and directed edges are created where a valid robot move exist.
Search for properties of G. In this case G is a DAG (Directed Acyclic Graph).
Use such properties to come up with a solution. In this case (G is a DAG) its common to use topological sort and dynamic programming to find the amount of valid paths.
Actually you don't need to construct the graph since the set of edges is pretty clear or to do topological sort as usual iteration of the matrix (incremental row index and incremental column index) is a topological sort of this implicit graph.
The dynamic programming part can be solved by storing in each cell [x][y] the amount of valid paths from [0][0] to [x][y] and checking where to move next.
Recurrence:
After computations the answer is stored in dp[n - 1][m - 1] where n is amount of rows and m is amount of columns. Overall runtime is O(nm).
How about find all possible valid paths:
Usual backtracking works and we can speed it up by applying early pruning. In fact, if we calculate dp matrix and then we do backtracking from cell [n - 1][m - 1] we can avoid invalid paths as soon the robot enters at a cell whose dp value is zero.
Python code with dp matrix calculated beforehand:
n, m = 3, 4
bad = [[False, False, False, False],
[ True, True, False, False],
[False, False, False, False]]
dp = [[1, 1, 1, 1],
[0, 0, 1, 2],
[0, 0, 1, 3]]
paths = []
curpath = []
def getPath(r, c):
if dp[r][c] == 0 or r < 0 or c < 0:
return
curpath.append((r, c))
if r == 0 and c == 0:
paths.append(list(reversed(curpath)))
getPath(r - 1, c)
getPath(r, c - 1)
curpath.pop()
getPath(n - 1, m - 1)
print(paths)
# valid paths are [[(0, 0), (0, 1), (0, 2), (0, 3), (1, 3), (2, 3)],
# [(0, 0), (0, 1), (0, 2), (1, 2), (1, 3), (2, 3)],
# [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 3)]]
Notice that is very similar to your code, there is a need to store all valid paths together and take care that appended lists are a copy of curpath to avoid ending up with an list of empty lists.
Runtime: O((n + m) * (amount of valid paths)) since simulated robot moves belong to valid paths or first step into an invalid path detected using foresight (dp). Warning: This method is exponential as amount of valid paths can be .
I've been practicing using recursion to define the index in Erlang. Here I need to implement a function to return the index for a list from a list.
eg.
([2, 4, 4], [1, 1, 2, 4, 4, 3, 4 ]) ----> 2
([1, 3], [5, 2, 2, 3, 1, 3, 5]) ----> 4
([1], [3, 2, a, {1, 1}, 1] ----> 4
Here is my code:
-module(project).
-export([index/2]).
index([X|XS],[_]) -> index([X|XS],[_],1).
index(_,[],_) -> [];
index([X|XS],[X|_], ACC) -> ACC;
index([X|XS],[_|rest],ACC) ->index([X|XS],rest,ACC+1).
I modified and coded logically but it still can not being compiled. I hope someone who can help me with it. Thanks!
Just for fun, here is an implementation that is not written a very clean way, but illustrates the techniques I think you are looking for. Note there are two basic states: "checking" and "matching".
-module(sublistmatch).
-export([check/2]).
check(Segment, List) ->
SegLen = length(Segment),
ListLen = length(List),
Index = 1,
check(Segment, List, SegLen, ListLen, Index).
check(S, S, _, _, I) ->
{ok, I};
check(_, _, SL, LL, _) when SL >= LL ->
nomatch;
check(S = [H|Ss], [H|Ls], SL, LL, I) ->
case matches(Ss, Ls) of
true -> {ok, I};
false -> check(S, Ls, SL, LL - 1, I + 1)
end;
check(S, [_|L], SL, LL, I) ->
check(S, L, SL, LL - 1, I + 1).
matches([H|S], [H|L]) -> matches(S, L);
matches([], _) -> true;
matches(_, _) -> false.
Note that this depends on knowing the lengths of both the segment you are checking for, and the current length of the remaining list to check. Consider why this is necessary. Also consider how using the utility function matches/2 gives us a natural place to explore whether an option matches, and backtracks if it does not.
In real programs you would use the standard library functions such as lists:prefix/2, lists:suffix/2, or sets:is_subset/2, or maybe some key or member operation over a gb_tree, dict, map or array depending on the situation.
To Compile the code you have to change it to:
-module(project).
-export([index/2]).
%%index([X|XS],[_]) -> index([X|XS],[_],1).
index([X|XS],List) -> index([X|XS],List,1).
%% you shuld not pass '_' as parameter it's will be marked as unbound
index(_,[],_) -> [];
index([X|XS],[X|_], ACC) -> ACC;
%%index([X|XS],[_|rest],ACC) ->index([X|XS],rest,ACC+1).
index([X|XS],[_|Rest],ACC) ->index([X|XS],Rest,ACC+1).
%% rest is an atom, it's not the case you need to use here.
%%Variables should start with upper case letter.
This code will compiled but wrong results as some cases.
I'm doing an independent study on Elm, and I feel like I'm learning to program all over again! As a learn-the-language project, I'm trying to get an easy blackjack up and running, but once I started I realized how much I still don't grasp. I have as far as drawing cards from a deck and adding them to a list:
import Random
import Mouse
import Array
--Build the deck
faces = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
suits = ['H', 'D', 'C', 'S']
allCards faces suits =
case suits of
x :: xs -> family faces x ++ allCards faces xs
_ -> []
family faces suit =
case faces of
x :: xs -> (,) x suit :: family xs suit
_ -> []
deck = allCards faces suits
rand : Signal Int
rand = Random.range 0 (length deck-1) Mouse.clicks
pickCard n = head <| drop n deck
nextCard = lift pickCard rand
yourHand = foldp (::) [] nextCard
main = lift asText yourHand
My questions are mostly on how to continue. Looking at completed Elm projects helps a little, but many of them are hard for me to parse as a beginner. Any kind of direction helps!
One of the first problems I had was trying to figure out how to remove cards from the deck once they're drawn, using something like dropCard deck card = filter (\card /= nextCard) deck to filter out the drawn card from the list. But my understanding of Elm is that every time a signal changes, the program re-evaluates, meaning that the deck is recreated in full every time a card is drawn. Would I need to foldp the original deck as well?
What's the proper way to remove an element from one list and add it to another in functional programming? Function composition, like toHand . dropCard card?
For adding card faces to determine winning/losing, I'm not sure how to get the integer value out of the list. I tried doing fst (head deck), but I got type errors, probably because deck is itself a signal of some kind. Is there something I'm not seeing?
That said, I've really enjoyed Elm thus far!
Questions
For simple programs, the easiest way to think about signals is by thinking about what kinds of things in your program can change. In your case that would be the deck and the hand. Then you take these things and make a datastructure in which to store them. Then you do a foldp over that whole datastructure, so instead of just keeping track of the hand you also keep track of the deck.
You can write a function that takes a list and an index, and returns the item at that index in the list and the list with that item removed. Then you add the item to the other list and you're done.
fst (head deck) should work. Perhaps you forgot to remove lift in the main definition when you tried it?
Example code
-- This first part is your code:
import Random
import Mouse
import Array
--Build the deck
faces = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
suits = ['H', 'D', 'C', 'S']
allCards faces suits =
case suits of
x :: xs -> family faces x ++ allCards faces xs
_ -> []
family faces suit =
case faces of
x :: xs -> (,) x suit :: family xs suit
_ -> []
-- Here come my additions/changes:
-- Naming some types for clarity
type Card = (Int,Char)
type ProgramState = { deck : [Card], hand : [Card] }
getFromList : Int -> [a] -> (a,[a])
getFromList index list =
let prefix = take index list
(item :: postfix) = drop index list
in (item, prefix ++ postfix)
startState : ProgramState
startState = { deck = allCards faces suits, hand = [] }
rand : Signal Float
rand = Random.float Mouse.clicks
rFloatToInt : Float -> Int -> Int -> Int
rFloatToInt rnd lo hi = round ((rnd + toFloat lo) * toFloat hi)
pickCard : Float -> ProgramState -> ProgramState
pickCard rnd {deck,hand} =
let index = rFloatToInt rnd 0 (length deck - 1)
(item, newDeck) = getFromList index deck
in { deck = newDeck, hand = item :: hand }
programState : Signal ProgramState
programState = foldp pickCard startState rand
main : Signal Element
main = lift asText programState
If anything is unclear, let me know.
I need to make a nested loop with an arbitrary depth. Recursive loops seem the right way, but I don't know how to use the loop variables in side the loop. For example, once I specify the depth to 3, it should work like
count = 1
for i=1, Nmax-2
for j=i+1, Nmax-1
for k=j+1,Nmax
function(i,j,k,0,0,0,0....) // a function having Nmax arguments
count += 1
end
end
end
I want to make a subroutine which takes the depth of the loops as an argument.
UPDATE:
I implemented the scheme proposed by Zoltan. I wrote it in python for simplicity.
count = 0;
def f(CurrentDepth, ArgSoFar, MaxDepth, Nmax):
global count;
if CurrentDepth > MaxDepth:
count += 1;
print count, ArgSoFar;
else:
if CurrentDepth == 1:
for i in range(1, Nmax + 2 - MaxDepth):
NewArgs = ArgSoFar;
NewArgs[1-1] = i;
f(2, NewArgs, MaxDepth, Nmax);
else:
for i in range(ArgSoFar[CurrentDepth-1-1] + 1, Nmax + CurrentDepth - MaxDepth +1):
NewArgs = ArgSoFar;
NewArgs[CurrentDepth-1] = i;
f(CurrentDepth + 1, NewArgs, MaxDepth, Nmax);
f(1,[0,0,0,0,0],3,5)
and the results are
1 [1, 2, 3, 0, 0]
2 [1, 2, 4, 0, 0]
3 [1, 2, 5, 0, 0]
4 [1, 3, 4, 0, 0]
5 [1, 3, 5, 0, 0]
6 [1, 4, 5, 0, 0]
7 [2, 3, 4, 0, 0]
8 [2, 3, 5, 0, 0]
9 [2, 4, 5, 0, 0]
10 [3, 4, 5, 0, 0]
There may be a better way to do this, but so far this one works fine. It seems easy to do this in fortran. Thank you so much for your help!!!
Here's one way you could do what you want. This is pseudo-code, I haven't written enough to compile and test it but you should get the picture.
Define a function, let's call it fun1 which takes inter alia an integer array argument, perhaps like this
<type> function fun1(indices, other_arguments)
integer, dimension(:), intent(in) :: indices
...
which you might call like this
fun1([4,5,6],...)
and the interpretation of this is that the function is to use a loop-nest 3 levels deep like this:
do ix = 1,4
do jx = 1,5
do kx = 1,6
...
Of course, you can't write a loop nest whose depth is determined at run-time (not in Fortran anyway) so you would flatten this into a single loop along the lines of
do ix = 1, product(indices)
If you need the values of the individual indices inside the loop you'll need to unflatten the linearised index. Note that all you are doing is writing the code to transform array indices from N-D into 1-D and vice versa; this is what the compiler does for you when you can specify the rank of an array at compile time. If the inner loops aren't to run over the whole range of the indices you'll have to do something more complicated, careful coding required but not difficult.
Depending on what you are actually trying to do this may or may not be either a good or even satisfactory approach. If you are trying to write a function to compute a value at each element in an array whose rank is not known when you write the function then the preceding suggestion is dead flat wrong, in this case you would want to write an elemental function. Update your question if you want further information.
you can define your function to have a List argument, which is initially empty
void f(int num,List argumentsSoFar){
// call f() for num+1..Nmax
for(i = num+1 ; i < Nmax ; i++){
List newArgs=argumentsSoFar.clone();
newArgs.add(i);
f(i,newArgs);
}
if (num+1==Nmax){
// do the work with your argument list...i think you wanted to arrive here ;)
}
}
caveat: the stack should be able to handle Nmax depth function calls
Yet another way to achieve what you desire is based on the answer by High Performance Mark, but can be made more general:
subroutine nestedLoop(indicesIn)
! Input indices, of arbitrary rank
integer,dimension(:),intent(in) :: indicesIn
! Internal indices, here set to length 5 for brevity, but set as many as you'd like
integer,dimension(5) :: indices = 0
integer :: i1,i2,i3,i4,i5
indices(1:size(indicesIn)) = indicesIn
do i1 = 0,indices(1)
do i2 = 0,indices(2)
do i3 = 0,indices(3)
do i4 = 0,indices(4)
do i5 = 0,indices(5)
! Do calculations here:
! myFunc(i1,i2,i3,i4,i5)
enddo
enddo
enddo
enddo
enddo
endsubroutine nestedLoop
You now have nested loops explicitly coded, but these are 1-trip loops unless otherwise desired. Note that if you intend to construct arrays of rank that depends on the nested loop depth, you can go up to rank of 7, or 15 if you have a compiler that supports it (Fortran 2008). You can now try:
call nestedLoop([1])
call nestedLoop([2,3])
call nestedLoop([1,2,3,2,1])
You can modify this routine to your liking and desired applicability, add exception handling etc.
From an OOP approach, each loop could be represented by a "Loop" object - this object would have the ability to be constructed while containing another instance of itself. You could then theoretically nest these as deep as you need to.
Loop1 would execute Loop2 would execute Loop3.. and onwards.