Using Prolog:
Write a predicate dispnth to display the nth element of a list. You may assume that the input list always has n or more elements.
For Example:
?- dispnth([1, [2, 3], 4, 5], 2, X). should return X = [2, 3]
I have this so far:
dispnth([X|_], 0, X).
dispnth([_|Xs], N, X) :-
dispnth(N1, X, Xs),
N is N1 + 1.
First let's give the predicate a more descriptive name, say list_nth_element/3. Next you might like to consider an auxiliary predicate list_nth_element_/4 with an additional argument, that holds the current position. From your given example I assume that you start counting at 1, so that's going to be the start value for the fourth argument. Then the predicates might look something like this:
list_nth_element(L,N,E) :-
list_nth_element_(L,N,E,1).
list_nth_element_([X|Xs],N,X,N). % if the 2nd and 4th elements are equal X is the nth element
list_nth_element_([_X|Xs],N,E,P0) :- % if the 2nd and 4th arguments
dif(P0,N), % differ
P1 is P0+1, % increment current position
list_nth_element_(Xs,N,E,P1). % and recurse
So essentially the fourth argument is used as a position indicator that is being incremented until you reached the desired position. However, there is no need to have this additional argument in the actual predicates interface, so it is "hidden" in the auxiliary predicate's interface.
Querying this predicate yields your desired result:
?- list_nth_element([1, [2, 3], 4, 5], 2, X).
X = [2,3] ? ;
no
You can also ask things like Which element is at what position?
?- list_nth_element([1, [2, 3], 4, 5], N, X).
N = X = 1 ? ;
N = 2,
X = [2,3] ? ;
N = 3,
X = 4 ? ;
N = 4,
X = 5 ? ;
no
Related
Let's say I have a vector of unique integers, for example [1, 2, 6, 4] (sorting doesn't really matter).
Given some n, I want to get all possible values of summing n elements of the set, including summing an element with itself. It is important that the list I get is exhaustive.
For example, for n = 1 I get the original set.
For n = 2 I should get all values of summing 1 with all other elements, 2 with all others etc. Some kind of memory is also required, in the sense that I have to know from which entries of the original set did the sum I am facing come from.
For a given, specific n, I know how to solve the problem. I want a concise way of being able to solve it for any n.
EDIT: This question is for Julia 0.7 and above...
This is a typical task where you can use a dictionary in a recursive function (I am annotating types for clarity):
function nsum!(x::Vector{Int}, n::Int, d=Dict{Int,Set{Vector{Int}}},
prefix::Vector{Int}=Int[])
if n == 1
for v in x
seq = [prefix; v]
s = sum(seq)
if haskey(d, s)
push!(d[s], sort!(seq))
else
d[s] = Set([sort!(seq)])
end
end
else
for v in x
nsum!(x, n-1, d, [prefix; v])
end
end
end
function genres(x::Vector{Int}, n::Int)
n < 1 && error("n must be positive")
d = Dict{Int, Set{Vector{Int}}}()
nsum!(x, n, d)
d
end
Now you can use it e.g.
julia> genres([1, 2, 4, 6], 3)
Dict{Int64,Set{Array{Int64,1}}} with 14 entries:
16 => Set(Array{Int64,1}[[4, 6, 6]])
11 => Set(Array{Int64,1}[[1, 4, 6]])
7 => Set(Array{Int64,1}[[1, 2, 4]])
9 => Set(Array{Int64,1}[[1, 4, 4], [1, 2, 6]])
10 => Set(Array{Int64,1}[[2, 4, 4], [2, 2, 6]])
8 => Set(Array{Int64,1}[[2, 2, 4], [1, 1, 6]])
6 => Set(Array{Int64,1}[[2, 2, 2], [1, 1, 4]])
4 => Set(Array{Int64,1}[[1, 1, 2]])
3 => Set(Array{Int64,1}[[1, 1, 1]])
5 => Set(Array{Int64,1}[[1, 2, 2]])
13 => Set(Array{Int64,1}[[1, 6, 6]])
14 => Set(Array{Int64,1}[[4, 4, 6], [2, 6, 6]])
12 => Set(Array{Int64,1}[[4, 4, 4], [2, 4, 6]])
18 => Set(Array{Int64,1}[[6, 6, 6]])
EDIT: In the code I use sort! and Set to avoid duplicate entries (remove them if you want duplicates). Also you could keep track how far in the index on vector x in the loop you reached in outer recursive calls to avoid generating duplicates at all, which would speed up the procedure.
I want a concise way of being able to solve it for any n.
Here is a concise solution using IterTools.jl:
Julia 0.6
using IterTools
n = 3
summands = [1, 2, 6, 4]
myresult = map(x -> (sum(x), x), reduce((x1, x2) -> vcat(x1, collect(product(fill(summands, x2)...))), [], 1:n))
(IterTools.jl is required for product())
Julia 0.7
using Iterators
n = 3
summands = [1, 2, 6, 4]
map(x -> (sum(x), x), reduce((x1, x2) -> vcat(x1, vec(collect(product(fill(summands, x2)...)))), 1:n; init = Vector{Tuple{Int, NTuple{n, Int}}}[]))
(In Julia 0.7, the parameter position of the neutral element changed from 2nd to 3rd argument.)
How does this work?
Let's indent the one-liner (using the Julia 0.6 version, the idea is the same for the Julia 0.7 version):
map(
# Map the possible combinations of `1:n` entries of `summands` to a tuple containing their sum and the summands used.
x -> (sum(x), x),
# Generate all possible combinations of `1:n`summands of `summands`.
reduce(
# Concatenate previously generated combinations with the new ones
(x1, x2) -> vcat(
x1,
vec(
collect(
# Cartesian product of all arguments.
product(
# Use `summands` for `x2` arguments.
fill(
summands,
x2)...)))),
# Specify for what lengths we want to generate combinations.
1:n;
# Neutral element (empty array).
init = Vector{Tuple{Int, NTuple{n, Int}}}[]))
Julia 0.6
This is really just to get a free critique from the experts as to why my method is inferior to theirs!
using Combinatorics, BenchmarkTools
function nsum(a::Vector{Int}, n::Int)::Vector{Tuple{Int, Vector{Int}}}
r = Vector{Tuple{Int, Vector{Int}}}()
s = with_replacement_combinations(a, n)
for i in s
push!(r, (sum(i), i))
end
return sort!(r, by = x -> x[1])
end
#btime nsum([1, 2, 6, 4], 3)
It runs in circa 4.154 μs on my 1.8 GHz processor for n = 3. It produces a sorted array showing the sum (which may appear more than once) and how it is made up (which is unique to each instance of the sum).
I'm new to Prolog and I'm having trouble with the first part of my programming assignment:
Create a predicate split that that takes as input three parameters. The first and third parameters are lists and the second parameter is an element. You can think of the first parameter as being the input and the last two parameters being the output. The method computes all possible way of splitting a list into an element and the rest of the list. Here is an example run.
?- split([1,2,3,4,5],X,Y).
X = 1,
Y = [2, 3, 4, 5] ;
X = 2,
Y = [1, 3, 4, 5] ;
X = 3,
Y = [1, 2, 4, 5] ;
X = 4,
Y = [1, 2, 3, 5] ;
X = 5,
Y = [1, 2, 3, 4] ;
There are two rules in defining the predicate. The first rule simply gets the first element of the list and returns it as the second parameter and the rest of the list as the third parameter. The second rule generates the list by copying the first element of the list in the result (i.e., third parameter) and then recursively applying the method to the rest of the elements.
split([H|T], H, T).
split([H|T], X, [H|Y]) :-
split(T, X, Y).
There are two ways to take an element out of a list:
Take the head (the first element)
Set the head aside and take an element out of the tail (the rest of the list)
Notice that the predicate can run both ways; if the second and the third parameters are defined, it will yield all possible ways these two can be combined to form a list.
split(List,Elem,Rest) :- select(Elem,List,Rest).
| ?- select(X,[1,2,3],Y).
X = 1,
Y = [2,3] ? ;
X = 2,
Y = [1,3] ? ;
X = 3,
Y = [1,2] ? ;
no
and with split/3 ;
| ?- split([1,2,3,4],X,Y).
X = 1,
Y = [2,3,4] ? ;
X = 2,
Y = [1,3,4] ? ;
X = 3,
Y = [1,2,4] ? ;
X = 4,
Y = [1,2,3] ? ;
no
with Sicstus-prolog u need to export select from library/lists
:- use_module(library(lists)).
My book has the following definition of inorder traversal (it computes a list with the elements of the tree in the inorder order within a list:
fun trav Empty = []
| trav(Node(t_1, x, t_2)) = trav t_1 # (x::trav t_2);
What's the convention / standard for simplifying the calls in the second line (namely, trav t_1 and x::trav t_2)? I know I simplify both of them before making use of the # operator but I'd like to know whether the first trav call evaluates completely before the other call, vice versa (unlikely), or both simultaneously.
Thanks
bclayman
Your intuition is correct, trav t_1 gets evaluated first as function arguments are evaluated in left to right order. This might seem a little strange, since # is an infix operator, but [1, 2, 3] # [4, 5, 6] can actually be rewritten as (op #)([1, 2, 3], [4, 5, 6]). You can verify that # evaluates its left argument first by doing:
Standard ML of New Jersey v110.78 [built: Sun Jun 7 20:21:33 2015]
- (print "test1\n"; [1, 2, 3]) # (print "test2\n"; [4, 5, 6]);
test1
test2
val it = [1,2,3,4,5,6] : int list
-
Essentially what you have is equivalent to:
fun trav Empty = []
| trav(Node(t_1, x, t_2)) =
let val l = trav t_1
val r = trav t_2
in l # (x::r) end
Define a Prolog predicate makelist/3 such that makelist(Start, End, List) is true if
List is a list of all integers from the integer Start to the integer End. For example:
makelist(3, 7, [3, 4, 5, 6, 7]) should be true.
Can't understand why my code doesn't work
makelist(H, L, _) :-
L is H+1.
makelist(H, L, List) :-
append([], [H], List), H1 is H+1.
makelist(H1, L, List) :-
append(List, [H1], List1), last(List1, R),
R \= L+1, makelist(N, L, List1), N is H1+1.
You can simplify your code, let's take your predicate and examine what is what you really need to do:
% makelist(X,Y,L)
Since your recursive call is increasing by 1 the first parameter, let's call it X, then your base case would be when X is the same than Y:
makelist(X,X,[X]) .
and your recursive call: it will be when X is smaller than Y, you need to increase X and add the value to the list:
makelist(X,Y,[X|L]) :- X < Y ,
X1 is X + 1 ,
makelist(X1, Y, L).
I'm trying to come up with a non brute-force solution to the following problem. Given a matrix of arbitrary size:
[6 0 3 5]
[3 7 1 4]
[1 4 8 2]
[0 2 5 9]
Transform its diagonals to a list of vectors, like so:
(0)
(1, 2)
(3, 4, 5)
(6, 7, 8, 9)
(0, 1, 2)
(3, 4)
(5)
(Working from bottom left to top right in this example)
Is there an elegant way to do this short of iterating up the left column and across the top row?
I would just write a little function to transform the vector indices into matrix indices.
Say the matrix is NxN square, then there will be 2N-1 vectors; if we number the vectors from 0 to 2N-2, element k of vector n will be at row max(N-1-n+k,k) and column max(n+k-N+1,k) (or in reverse, the matrix element at row i, column j will be element min(i,j) of vector N-1+j-i). Then whenever you need to access an element of a vector, just convert the coordinates from k,n to i,j (that is, convert vector indices to matrix indices) and access the appropriate element of the matrix. Instead of actually having a list of vectors, you'll wind up with something that emulates a list of vectors, in the sense that it can give you any desired element of any vector in the list - which is really just as good. (Welcome to duck typing ;-)
If you're going to access every element of the matrix, though, it might just be quicker to iterate, rather than doing this computation every time.
(non-checked code)
Something like this (java code):
// suppose m is the matrix, so basically an int[][] array with r rows and c columns
// m is an int[rows][cols];
List result = new ArrayList(rows + cols - 1);
for (int i = 0; i < (rows + cols - 1))
{
int y;
int x;
if (i < rows)
{
x = 0;
y = rows - i - 1;
}
else
{
x = i - rows + 1;
y = 0;
}
Vector v = new Vector();
while (y < rows && x < cols)
{
y++;
x++;
v.add(new Integer(m[y][c]));
}
result.add(v);
}
// result now contains the vectors you wanted
Edit: i had x and y mixed up, corrected now.
Mathematica:
m = {{6, 0, 3, 5},
{3, 7, 1, 4},
{1, 4, 8, 2},
{0, 2, 5, 9}};
Table[Diagonal[m, i], {i, 1 - Length#m, Length#m[[1]] - 1}]
Which gives a list of the i'th diagonals where the 0th diagonal is the main diagonal, i = -1 gives the one below it, etc. In other words, it returns:
{{0}, {1, 2}, {3, 4, 5}, {6, 7, 8, 9}, {0, 1, 2}, {3, 4}, {5}}
Of course using the built-in Diagonal function is kind of cheating. Here's an implementation of Diagonal from scratch:
(* Grab the diagonal starting from element (i,j). *)
diag0[m_,i_,j_] := Table[m[[i+k, j+k]], {k, 0, Min[Length[m]-i, Length#m[[1]]-j]}]
(* The i'th diagonal -- negative means below the main diagonal, positive above. *)
Diagonal[m_, i_] := If[i < 0, diag0[m, 1-i, 1], diag0[m, 1, i+1]]
The Table function is basically a for loop that collects into a list. For example,
Table[2*i, {i, 1, 5}]
returns {2,4,6,8,10}.