Creating a list of players - list

I want to create a list of "players".
The user of the program can say how many players he wants.
Amount = io:get_line("how many players? \n"),
Int = string:to_integer(Amount),
List = Lists:seq(1,Int).
But now I want to create a list of players in the form [Player1, Player2...PlayerN].
Can someone tell me how to do so?

Remember that string:to_int/1 will return a tuple, not a single value. Also keep in mind that users do some pretty wild stuff in input, so you'll want to check that. (That said... when you're just trying to get a program written for yourself to test an idea, meh, whatever.)
{PlayerCount, _} = string:to_integer(io:get_line("How many players? ")),
Pretty simple. Mess around with this a bit. Input is its own world, and its good to think through this stuff a few times in toy programs (and give yourself insane input to see how the program reacts).
From here you can do a few things. If you just want a list of tuples that indicate you have a player whose serial number is a number, that's easy with a list comprehension:
Players = [{player, Number} || Number <- lists:seq(1, PlayerCount)],
You can write that as a map as well:
Players = lists:map(fun(N) -> {player, N} end, lists:seq(1, PlayerCount)),
I find the list comprehension more readable, though. Another alternative is to write your own custom recursive function. You almost never need to do this, but if you're new to programming it is good practice, and early on its way more readable because you see exactly what is happening each iteration:
player_list(Count) -> player_list(1, Count, []).
player_list(Max, Max, Players) ->
lists:reverse(Players);
player_list(Current, Max, Players) ->
player_list(Current + 1, Max, [make_new_player(Current) | Players]).
Note that the above is equivalent to, but more naturally stated than:
player_list(Current, Max, Players) ->
Next = Current + 1,
case Next == Max of
true -> lists:reverse(Players);
false -> player_list(Next, Max, [make_new_player(Current) | Players])
end.
Matching in function heads is much more clear and readable over the course of a program than a bunch of case and if statements. Over time, though, as I mentioned above, you will eventually stop writing recursive functions yourself (for the most part) and find yourself using a lot of list operations (map, fold, filter, list comprehensions, etc.) as you gain experience.
The details of make_new_player/0,1 are entirely up to you, of course -- you didn't indicate what sort of structure you wanted for their data, but you can do whatever you want there. Here are some other ways that might play out:
[make_new_player(Z) || Z <- lists:seq(1, PlayerCount)]
or
[#player{serial = Z} || Z <- lists:seq(1, PlayerCount)]

Related

Riddle puzzle in clingo

So in the tag prolog someone wanted to solve the "the giant cat army riddle" by Dan Finkel (see video / Link for description of the puzzle).
Since I want to improve in answer set programming I hereby challenge you to solve the puzzle more efficient than me. You will find my solution as answer. I'll accept the fastest running answer (except if it's using dirty hacks).
Rules:
hardcoding the length of the list (or something similar) counts as dirty hack.
The output has to be in the predicate r/2, where it's first argument is the index of the list and the second its entry.
Time measured is for the first valid answer.
num(0..59).
%valid operation pairs
op(N*N,N):- N=2..7.
% no need to add operations that start with 14
op(Ori,New):- num(Ori), New = Ori+7, num(New), Ori!=14.
op(Ori,New):- num(Ori), New = Ori+5, num(New), Ori!=14.
%iteratively create new numbers from old numbers
l(0,0).
{l(T+1,New) : op(Old,New)} = 1 :- l(T,Old), num(T+1), op(Old,_).
%no number twice
:- 2 #sum {1,T : l(T,Value)}, num(Value).
%2 before 10 before 14
%linear encoding
reached(T,10) :- l(T,10).
reached(T+1,10) :- reached(T,10), num(T+1).
:- reached(T,10), l(T,2).
:- l(T,14), l(T+1,_).
%looks nicer, but quadratic
%:- l(T2,2), l(T10,10), T10<T2.
%:- l(T14,14), l(T10,10), T14<T10.
%we must have these three numbers in the list somewhere
:- not l(_,2).
:- not l(_,10).
:- not l(_,14).
#show r(T,V) : l(T,V).
#show.
Having a slightly more ugly encoding improves grounding a lot (which was your main problem).
I restricted op/2 to not start with 14, as this should be the last element in the list
I do create the list iteratively, this may not be as nice, but at least for the start of the list it already removed impossible to reach values via grounding. So you will never have l(1,33) or l(2,45) etc...
Also list generation stops when reaching the value 14, as no more operation is possible/needed.
I also added a linear scaling version of the "before" section, although it is not really necessary for this short list (but a cool trick in general if you have long lists!) This is called "chaining".
Also note that your show statement is non-trivial and does create some constraints/variables.
I hope this helps, otherwise feel free to ask such questions also on our potassco mailing list ;)
My first attempt is to generate a permutation of numbers and force successor elements to be connected by one of the 3 operations (+5, +7 or sqrt). I predefine the operations to avoid choosing/counting problems. Testing for <60 is not necessary since the output of an operation has to be a number between 0 and 59. The generated List l/2 is forwarded to the output r/2 until the number 14 appears. I guess there is plenty of room to outrun my solution.
num(0..59).
%valid operation pairs
op(N*N,N):- N=2..7.
op(Ori,New):- num(Ori), New = Ori+7, num(New).
op(Ori,New):- num(Ori), New = Ori+5, num(New).
%for each position one number
l(0,0).
{l(T,N):num(N)}==1:-num(T).
{l(T,N):num(T)}==1:-num(N).
% following numbers are connected with an operation until 14
:- l(T,Ori), not op(Ori,New), l(T+1,New), l(End,14), T+1<=End.
% 2 before 10 before 14
:- l(T2,2), l(T10,10), T10<T2.
:- l(T14,14), l(T10,10), T14<T10.
% output
r(T,E):- l(T,E), l(End,14), T<=End.
#show r/2.
first Answer:
r(0,0) r(1,5) r(2,12) r(3,19) r(4,26) r(5,31) r(6,36) r(7,6)
r(8,11) r(9,16) r(10,4) r(11,2) r(12,9) r(13,3) r(14,10) r(15,15)
r(16,20) r(17,25) r(18,30) r(19,37) r(20,42) r(21,49) r(22,7) r(23,14)
There are multiple possible lists with different length.

Struggling to extract a section of a list in Haskell

I am trying to implement a basic function but I'm out of practice with Haskell and struggling so would really appreciate some help. My question is specifically how to select a section of a list by index. I know how to in other languages but have been struggling
[ x | x <- graph, x!! > 5 && x!! <10 ]
I have been fiddling around with basic list comprehension similar to what is above, and while I know that isn't right I was hoping a similarly simple solution would be available.
If anyone wants more information or felt like helping on the further question I have included more information below, thanks!
type Node = Int
type Branch = [Node]
type Graph= [Node]
next :: Branch -> Graph -> [Branch]
This is the individual question for the "next" function
This is the general set up information but most importantly that the graph is represented as a flattened adjacency matric
Apologies for the two pictures but it seemed the best way to convey the information.
As pointed out in the comments !! does not give you the index of a value in the way it seems you expect. It is just an infix for getting an element of a list.
There is no way to get the index of x like this in Haskell since the x object doesn't keep track of where it is.
To fix this we can make a list of objects that do keep track of where they were. This can be achieved with zip.
zip [0..] graph
This creates a list of tuples each containing their index and the value in graph.
So you can write your list comprehensions as
[ x | (index, x) <- zip [0..] graph, index > 5, index < 10 ]
Now this is not going to be terribly fast since it still needs to go through every element of the list despite the fact that we know no element after the 11th will be used. For speed we would want to use a combination of take and drop.
drop 5 (take 10 graph)
However if we wanted to do some other selections (e.g. all even indexes), we can still go back to the list comprehension.
In this case, you could drop 5 <&> take 4. As in drop 5 x & take 4. Drop skips the first few elements and take leaves out all but the first few left after the drop.

How to extract data to list in Prolog?

I have an array L of some type, I'm trying to extract the data to an array, for example:
L=[day(sunday),day(monday)]
to
Target=[sunday,monday]
Tried using forall and searched for related questions on Prolog lists.
extract_data_to_list(L,Target) :-
member(day(Day),L),
length(L, L1),
length(Target, L1),
member(Day,Target).
Current output:
?- extract_data_to_list([day(sunday),day(monday)],Target).
Target = [sunday, _5448] ;
Target = [_5442, sunday] ;
Target = [monday, _5448] ;
Target = [_5442, monday].
Desired output:
?- extract_data_to_list([day(sunday),day(monday)],Target).
Target=[sunday,monday]
This is an ideal problem for maplist:
day_name(day(DayName), DayName).
dates_daylist(Dates, DayList) :-
maplist(day_name, Dates, DayList).
Maplist applies day_name to each corresponding pair of elements in Dates and DayList.
This is an ideal problem for library(lambda) for SICStus|SWI:
maplist(\day(N)^N^true, Dates, Daylist).
I have a couple other ways you can do this, just in case you're wondering.
?- findall(D, member(day(D), [day(monday), day(tuesday)]), Days).
Days = [monday, tuesday].
The trick here is that you can use findall/3 to drive a simple loop, if the Goal (argument 2) uses member/2. In this case, we're unifying day(D) with each item in the list; no further work really needs to happen besides the unification, so we're able to "tear off the wrapping" just with member/2 but you could drive a more complex loop here by parenthesizing the arguments. Suppose you wanted to change day to day-of-week, for instance:
?- findall(DoW, (member(day(D),
[day(monday), day(tuesday)]), DoW=day_of_week(D)),
Days).
Days = [day_of_week(monday), day_of_week(tuesday)].
Making the goal more complex works, in other words, as long as you parenthesize it.
The second trick is specific to SWI-Prolog (or Logtalk, if you can use that), which is the new library(yall):
?- maplist([Wrapped,Day]>>(Wrapped=day(Day)),
[day(monday),day(tuesday)], X).
X = [monday, tuesday].
library(yall) enables you to write anonymous predicates. [Wrapped,Day]>>(Wrapped=day(Day)) is sort of like an inline predicate, doing here exactly what #lurker's day_name/2 predicate is doing, except right inside the maplist/3 call itself without needing to be a separate predicate. The general syntax looks something like [Variables...]>>Goal. This sort of thing was previously available as library(lambda) and has been a feature of Logtalk for many years.

Haskell List Monad State Dependance

I have to write a program in Haskell that will solve some nondeterministic problem.
I think i understand List Monad in 75% so it is oblivious choice but...
(My problem is filling n x m board with ships and water i am given sums of rows and colums every part of ship has its value etd its not important right now).
I want to guard as early as possible to make algoritm effective the problem is that possibility of insertion of ship is dependant from what i am given / what i have inserted in previus moves lets call it board state and i have no idea how to pass it cuz i can't generate a new state from board alone)
My Algoritm is:
1. Initialize First Board
2. Generate First Row trying applying every possible insertion (i can insert sheep verticaly so i need to remember to insert other parts of sheep in lower rows)
3. Solve the problem for smaller board (ofc after generating each 2 rows i check is everything ok)
But i have no idea how can I pass new states cuz as far as i have read about State Monad it generates new state from old state alone and this is impossible for me to do i would want to generate new state while doing operations on value).
I am sorry for my hatred towards Haskell but after few years of programing in imperative languages being forced to fight with those Monads to do things which in other languages i could write almost instantly makes me mad. (well other things in Haskell are fine for me and some of them are actually quite nice).
Combine StateT with the list monad to get your desired behavior.
Here's a simple example of using the non-determinism of the list monad while still keeping a history of previous choices made:
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.State
fill :: StateT [Int] [] [Int]
fill = do
history <- get
if (length history == 3)
then return history
else do
choice <- lift [0, 1, 2]
guard (choice `notElem` history)
put (choice:history)
fill
fill maintains a separate history for each path that it tries out. If it fills up the board it returns successfully, but if the current choice overlaps with a previous choice it abandons that solution and tries a different path.
You run it using evalStateT, supplying an initial empty history:
>>> evalStateT fill []
[[2,1,0],[1,2,0],[2,0,1],[0,2,1],[1,0,2],[0,1,2]]
It returns a list of all possible solutions. In this case, that just happens to be the list of all permutations in which we could have filled up the board.

Prolog - Recursive call

I am having trouble with recursive searching of list and creation of list of lists from the result..
The knowledge base contains team name, number of wins and zone they are in, all associated withe their team number. I am passing list of team numbers in Teams and I am searching for a matching pair with findMinMax/3. The result I need is...
List of lists of paired teams (ex. X = [[gonzaga, washington], [iowa, oklahoma], …])
And 1 unmatched team (resulted from odd number of teams) or 0 (in case of even)
I figured out everything else and can get up to the part [gonzaga, washington], but failing at recursive portion...
findPair(Teams,[HL|TL],Rest) :-
findMinMax(Teams,Min,Max),
delete(Teams,Min,TeamsNoMin),
delete(TeamsNoMin,Max,Rest),
createPair(Min,Max,Pair), %Pair = "["Min_team","Max_team"]"
append(HL,[Pair],TL),
findPair(Rest,TL,[]).
A general recursive scheme
Here I'll try to show you how we usually perform recursion in Prolog. It's not simple to get for beginners because the lists are built "backwards": nothing gets really built until we hit the end of the list.
The reason for this "build backwards" principle is that once a variable is set, you can't set it to another value, so for example it'd be hard to say that the result is [1] at the first step of the recursion and then becomes [1, 2]. Instead, what we say in Prolog is that the result head is 1 and that the result tail is the result of the recursive call (yeah read it twice if it got messy : d). So as long as we do not hit a base case (a case where no recursion is performed), we don't bind variables definitely (ie we always let a part of the term unbound).
For a predicate rec/2: rec(Input, Result) producing a result list from an input list by linking their elements with somepredicate/2, we'd write:
rec([InputHead|InputTail], [ResultHead|ResultTail]) :-
somepredicate(InputHead, ResultHead),
rec(InputTail, ResultTail).
to represent that.
Here you can see that we stated that the head of the result is ResultHead and that its tail is calculated thanks to the call rec(InputTail, ResultTail).
Now that's fine but we need to stop at some point, when the list is empty, for example. We'd write that as follows:
rec([], []).
which means: when the input list is empty, so is the result list.
An application to your predicate
Now, to fix your problem, you first have to fix the recursive clause:
findPair(Teams,[HL|TL],Rest) :-
findMinMax(Teams,Min,Max),
delete(Teams,Min,TeamsNoMin),
delete(TeamsNoMin,Max,Rest),
createPair(Min,Max,Pair), %Pair = "["Min_team","Max_team"]"
append(HL,[Pair],TL),
findPair(Rest,TL,[]).
would become
findPair(Teams, [Pair|Tail], LeftOver) :-
findMinMax(Teams, Min, Max),
delete(Teams, Min, TeamsNoMin),
delete(TeamsNoMin, Max, Rest),
createPair(Min, Max, Pair), %Pair = "["Min_team","Max_team"]"
findPair(Rest, Tail, LeftOver).
Important to note: now Rest has become two separate variables. The last argument of findPair/3 doesn't get changed anymore, since in the recursive call we do not know anything about it yet, so we can't bind it, and the in-predicate Rest is therefore now independant and just represents the teams that have not been handled yet and are therefore of interest for the tail of our result list (and for LeftOver).
Now we have to handle the base cases:
when there are no teams left
findPair([], [], []).
Here we say that when Teams is empty, so are the Result and LeftOver.
when there is one team left
findPair([Last], [], [Last]).
Here we say that when Teams has only one element, LeftOver is equal to Teams and Result is empty.
Resulting code is:
findPair([], [], []).
findPair([Last], [], [Last]).
findPair(Teams, [Pair|Tail], LeftOver) :-
findMinMax(Teams, Min, Max),
delete(Teams, Min, TeamsNoMin),
delete(TeamsNoMin, Max, Rest),
createPair(Min, Max, Pair), %Pair = "["Min_team","Max_team"]"
findPair(Rest, Tail, LeftOver).
To make your clauses exclusive you could replace Teams with [Not, Empty|AtAll] to ensure the last clause is used only with lists of length 2 or more, or just add a guard such as Teams = [_, _|_], at the start of the clause.
Hope it helped and do not hesitate to ask for clarifications in comments :)