Haskell: List Comprehensions [closed] - list

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am practicing for my exam and have problems solving the following list-comprehensions-exercises:
a) Create the infinite list of square numbers n^2, with n element of N,
which are even numbers, have the rest 2 when they are divided by 9 and have the rest 3 when divided by 35, which means:
[1444,446224,1684804,3717184,...]
b) Create a list of tupel (a, b, c, d) for all a ∈ {10, 34, 77, 180}, b ∈ {’p’,’r’,’g’}, c ∈ {False, True} and d ∈ {’Y’,’Z’}. The order of the elements should change numbers first, then lower letters, then boolean value and then upper letters, which means:
[(10,’p’,False,’Y’),(34,’p’,False,’Y’),(77,’p’,False,’Y’)
(180,’p’,False,’Y’),(10,’r’,False,’Y’),(34,’r’,False,’Y’),
(77,’r’,False,’Y’),(180,’r’,False,’Y’)...]
I am not quite sure how to implement this in actual haskell code.

a)
[n^2 | n <- [2, 4..],
n `mod` 9 == 2,
n `mod` 35 == 3]
For b) it's important to list the sets in reverse order.
[(a, b, c, d) | d <- ['Y', 'Z'],
c <- [True, False],
b <- ['p', 'r', 'g'],
a <- [10, 34, 77, 180]]

Related

Arithmetic in Prolog - Multiples of a number

I want to create a function multiples(X, N, R) where R is a list containing all multiples of X from X to X * N.
An example would be: multiples(3, 4, [12, 9, 6, 3]), which should give out true.
My code so far:
multiples(X, N, R) :- X >= 1, N >= 1, Z is X*N, contains(Z, R).
contains(Z, [Z|_]).
contains(Z, [W|V]) :- contains(Z,V), L is Z-X, L >= X, contains(L, V).
The output of the console for multiples(3,4,X). is X = [12|_xxxx] and when I type ; an error occurs.
How do I manage to receive the list that I want?
(Maybe my idea is completely wrong).
I found 4 issues with your code. Here is the fixed code, explanation below:
multiples(X, N, R) :-
X >= 1,
N >= 1,
Z is X*N,
contains(X, Z, R).
contains(X, Z, [Z|V]) :-
L is Z-X,
L >= X,
contains(X, L, V).
contains(_, Z, [Z]).
?- multiples(3,4,X).
X = [12, 9, 6, 3] ;
X = [12, 9, 6] ;
X = [12, 9] ;
X = [12] ;
false.
At first in your contains predicate you access X and W and never state their values. Solve X by adding another attribute to the predicate. Solve W by replacing it with Z.
Another problem is the order of your rules. The larger contains rule should be the "main" rule, only if this one fails the other one should "fire". By placing the default rule on top you get the right result.
Also the rule contains(_, Z, [Z]). marks the end, therefore it the return list has only the element Z in it and does not contain any other (unknown) elements.
The last point is that you don't need two contains calls in the main contains rule.
The example works for the first answer. However you can improve this with a cut (!), which prevents going to the second rule after successfully visiting the first rule:
contains(X, Z, [Z|V]) :-
L is Z-X,
L >= X,
!,
contains(X, L, V).
contains(_, Z, [Z]).
?- multiples(3,4,X).
X = [12, 9, 6, 3].
A slight modification to your code. contains predicate will collect the numbers in a list, and N will keep getting decreased till it satisfies the base predicate.
multiples(X, N, R) :- X >= 1, N >= 1, contains(X,N, R),!.
contains(_,0,[]).
contains(X,N,[Z|List]):-
Z is X*N,
N1 is N-1,
contains(X,N1,List).
Example:
?- multiples(3,4,R).
R = [12, 9, 6, 3]
?- multiples(2,5,R).
R = [10, 8, 6, 4, 2]
?- multiples(25,5,R).
R = [125, 100, 75, 50, 25]

What's the difference between a while loop in one or two statements? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I am confused understanding the difference between these two loops and their results :
State 1:
int n = 10;
while (n>0) {
cout << n << ", " << --n;
}
State 2 :
int n = 10;
while (n>0) {
cout << n << ", ";
--n;
}
I do not understand why should the result differentiate?
State 1 shows : 10, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0
while
State 2 shows : 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
what is happening? and what makes this difference?
There is no difference in the values, just in the number of times they are occurring because of being printed a different number of times.
The first one outputs, with "()" added for clarity:
(10, 9)(9, 8)(8, 7)(7, 6)(6, 5)(5, 4)(4, 3)(3, 2)(2, 1)(1, 0)
Note that there are pairs of numbers without a "," in between, created by the start and the end of the ouput.
The second one outputs:
(10, )(9, )(8, )(7, )(6, )(5, )(4, )(3, )(2, )(1,)
Note that I do not discuss in this question the topic of unreliable order of evaluation caused by using ++ on a value and outputting it in the same statement. This is only about the difference of behaviour you observe in your environment.

Find unique quadruplets in C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
So, I need to find unique quadruples in C++. Any idea would help
Input 1 : [1, 0, 2, 3], [2, 0, 1, 3], [4, 5, 6, 7], [8, 9, 10, 11]
Output 1 : [2, 0, 1, 3], [4, 5, 6, ,7], [8, 9, 10, 11]
As [1,0,2,3] and [2,0,1,3] both contain same elements so either one can be in the output
Input 2 : [2, 0, 1, 3], [4, 5, 6, ,7], [8, 9, 10, 11], [15,16,17,18]
Output 2 : [2, 0, 1, 3], [4, 5, 6, ,7], [8, 9, 10, 11], [15,16,17,18]
I cannot initalize set (int,int,int,int). Any idea on how to get unique ones?
Update for people who asked for defining the question more:
A quadruple is a combination of 4 integers for the problem. Problem states to find unique quadruples from all the given quadruples. A quadruple (a,b,c,d) is unique , if no other quadruple exists with all the elements same as this one, i.e. any quadruple formed from the permutation of (a,b,c,d) is not unique. Quadruples (a,b,c,d) and (a,d,b,c) are the same, where as quadruples (a,b,c,d) and (a,e,f,b) are not. Quadruples are unique if they contain atleast 1 element which is not common to both.
Write a comparator that sorts the integers in the quadruples before comparing them.
struct CompareQuads
{
bool operator()(Quad x, Quad y) const
{
// sort x integers
...
// sort y integers
...
// return true if x < y (lexicographically)
...
}
};
Use the comparator in std::set to eliminate duplicates.
std::set<Quad, CompareQuads> s;
Add all the quads to s and the duplicates will be removed. Iterate through s and print the ones that remain.

Recursive function call - Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I have a list of integers larger than zero. I need to identify the one with the highest number of dividers. For this I created two functions: one that gives me all the divisors of all the elements of a list and another that filters which element that has more divisors. The problem is that I can not make the maisDivisores function directly receive a list of only the elements (without dividers), you know? If I call the function 1 (listaDivisores) within the function 2 (maisDivisores) always crashes. However if I call manually, it works good. I've tried all the possibilities and nothing. How do I call the first function in the second for this to work getting the gross list?
def listaDivisores(lista):
if lista == []:
return []
else:
lista=qs(lista)
resultado=[]
resultado.append((lista[0],[y for y in range(1,((lista[0])+1)) if (int(lista[0]))%y==0]))
return resultado+listaDivisores(lista[1:])
return listaDivisores(lista)
def maisDivisores(lista):
if len(lista)==[]:
return "Nenhum número."
else:
**lista=listaDivisores(lista)**
if int(len(lista))==1:
return lista[0]
elif int(len(lista[0][1]))<int(len(lista[1][1])):
lista.pop(0)
elif int(len(lista[0][1]))==int(len(lista[1][1])):
if lista[0]<lista[1]:
lista.pop(0)
else:
lista.pop(1)
else:
lista.pop(1)
return maisDivisores(lista)
return lista
functions working separately; error log when working together.
you can easily get the divisor of a number with list comprehension like this
def divisores(n):
if n <= 0:
raise ValueError("n must be positive")
return [x for x in range(1,n+1) if n%x==0 ]
then you can use the build in max with a key function to get the desire result
>>> test=[24, 5, 9, 42]
>>> max( test, key=lambda x:len(divisores(x)))
24
>>>
if you also want to get the divisor in the same step, you can use a generator or list comprehension to build a intermediary result from which get the max
for example
>>> max( ( (x,divisores(x)) for x in test), key=lambda y:len(y[1]))
(24, [1, 2, 3, 4, 6, 8, 12, 24])
here ( (x,divisores(x)) for x in test) is the generator, which create a tuple with the number and the list of its divisors
or
>>> test2 = [ (x,divisores(x)) for x in test ]
>>> test2
[(24, [1, 2, 3, 4, 6, 8, 12, 24]), (5, [1, 5]), (9, [1, 3, 9]), (42, [1, 2, 3, 6, 7, 14, 21, 42])]
>>> max(test2,key=lambda x:len(x[1]))
(24, [1, 2, 3, 4, 6, 8, 12, 24])
>>>
and any of those can be made into a simple function.
Your implementation is just too convoluted for what you want and frankly I have a hard time understanding it

Sorting sequence based on greatest common division [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a question. I write this comparator:
bool cmp(int a, int b)
{
return __gcd(a, b) > 1;
}
and, for example:
if I have these numbers:
2 5 6 7 8 12 15 19 20
my code outputs:
20 15 12 8 6 2 5 7 19
it's okay..
but for example:
1 2 3 4 5 6 7 8 9
my code outputs
1 2 3 4 5 6 7 8 9
How can I do this?
this sequence should be something like this:
9 6 3 (...)
Your comparator does not establish strict weak ordering, so results are undefined.
To make proper comparator you must make sure that following is true:
cmp(a, a) == false — your comparator does not pass the test on cmp(2, 2)
cmp(a, b) == true → cmp(b, a) == false — your comparator does not pass the test on cmp(2, 4)
cmp(a, b) == true and cmp(b, c) == true → cmp(a, c) == true — your comparator does not pass the test on cmp(2, 6) and cmp(6, 3)