Prolog help | how come 'tony' is true when it should be false? - list

From the facts I have, 'tony' should not be true for pass(tony), but I am unsure what I am doing wrong.
I have an atom pass(Student) that passes if a Student has the following: their mark in programming > 29, they haven't failed an exam/none of their exam scores < 30, and if their average score for all their exams > 39
I also have an ERROR No permission to modify static procedure 'length/2'. I don't know what this is referring to but I would appreciate it if you could point me in the right direction.
I won't include all the facts, but here is an example of a student's:
coursework(tony, 57).
programming(tony, 65).
e1(tony, 20).
e2(tony, 80).
e3(tony, 90).
marks(tony, [20, 80, 90]).
length([], 0).
length([_|Tail], List + 1):-
length(Tail, List).
sum([], 0).
sum([X|Tail], Sum):-
sum(Tail, Temp),
Sum = Temp + X.
avg(List, Avg):-
sum(List, Sum),
length(List, Length),
Length > 0,
Avg is Sum / Length.
examFail(Student):-
e1(Student, Mark),
Mark < 30;
e2(Student, Mark),
Mark < 30;
e3(Student, Mark),
Mark < 30.
pass(Student):-
programming(Student, Mark),
Mark > 29,
\+ examFail(Mark),
marks(Student, List),
avg(List, Avg),
Avg > 39.
Is there something I am doing wrong?

As written in the title, Tony can neither be true nor false, Tony is a variable because it starts with a capital letter.
I have an atom pass(Student)
pass(Student) is a predicate, not an atom. An atom is a stringy thing like a or tony. A predicate can indeed yield true or false.
I also have an ERROR No permission to modify static procedure 'length/2'.
This is because you try to define
length([], 0).
length([_|Tail], List + 1):-
length(Tail, List).
But length/2 is a predicate that is built-in, to determine/set/check the length of a list No redefining allowed!
Evaluation is not done like this:
Sum = Temp + X.
This is unification ("The syntactic structures left and right shall be the same"). You want is:
Sum is Temp + X.
Which is correctly use here btw:
Avg is Sum / Length.
For example:
sum_list(L,Out) :-
sum_list(L,0,Out).
sum_list([],R,R).
sum_list([X|Xs],Rrun,Rfin) :-
Rnex is Rrun + X,
sum_list(Xs,Rnex,Rfin).
This ain't gonna work:
examFail(Student):-
e1(Student, Mark),
Mark < 30;
e2(Student, Mark),
Mark < 30;
e3(Student, Mark),
Mark < 30.
Mark is always the same "thing" in this whole clause. The above says that the Student must have the same Mark in all exams, and that Mark must be less than 30. This inequality is redundantly tested 2 more times. Use different variable names:
examFail(Student):-
(e1(Student, MarkE1), MarkE1 < 30);
(e2(Student, MarkE2), MarkE2 < 30);
(e3(Student, MarkE3), MarkE3 < 30).
Or even better, if data were stored in a more "normal form" (as in RDBMS):
marks(e1, tony, 20).
marks(e2, tony, 80).
marks(e3, tony, 90).
then one can use library(aggregate)
examFail(Student):- aggregate(min(M), marks(_,tony,M), Min), Min<20.
(I think, need to test)
This ain't gonna work either:
pass(Student):-
programming(Student, Mark),
Mark > 29,
\+ examFail(Mark),
marks(Student, List),
avg(List, Avg),
Avg > 39.
You call examFail(Mark). That should be examFail(Student).

Related

I don't understand ++ operators in c++

when I compile this, I get
j is: 28 k is: 50
V H
What I do not understand is, why is the j++ and k++ 28 and 50 and not 27 and 48, respectively? I don't understand why it adds 3+, and not 1+.
The condition (txt[j] == txt[k]) is true for 3 values, '-', 'I', and '-'. So you add three to 25, and add 3 to 47. The before/after increment is only different on the line it happens.
If you had:
int x = 10;
int y = 10;
cout << x++;
cout << ++y;
you would see that x's value would be 10 at the time it was printed, and y's value would be 11.
if you then just printed them again without changing them a second time they should both be 11.
===========================
With your values it works like this:
Txt [25] is letter '-' in the string. It's like the 4th '-' in. Text[47] is also the letter '-', it's like the 8th '-' in the string. The condition of the loop says to continue running the increment opperators on these two indexes while they are the same value. So they are the same, both get incremented. Now we look at letters 26, and 48. These are both 'I', which is the same again. So we increment a third time, 27, and 49 Are both '-' again, so we increment again. Now 28 is at 'V' (the start of 'VAAR'), and 50 is at 'H' the start of 'HOST'. 'H' is not equal to 'V' so we stop looping here.
You're starting your compare at "-I-V" and "-I-H". So there are three characters that match.
Preincrement ++k and postincrement j++ both increment the variables. The difference in how they behave as right hand side arguments, e.g. int z = ++k; vs int z = k++;. The former increments k and assigns its new value to z. The latter assigns the current value of k to z and then increments k;

Mathematica solution?

I am new with Mathematica and I have one more task to figure out, but I can't find the answer. I have two lists of numbers ("b","u"):
b = {8.734059001373602`, 8.330508824111284`, 5.620669156438947`,
1.4722145583571766`, 1.797504620275392`, 7.045821078656974`,
2.1437334927375247`, 2.295629405840401`, 9.749038328921163`,
5.9928406294151095`, 5.710839663259195`, 7.6983109942364365`,
1.02781847368645`, 4.909108426318685`, 2.5860897177525572`,
9.56334726886076`, 5.661774934433563`, 3.4927397824800384`,
0.4570000499566351`, 6.240122061193738`, 8.371962670138991`,
4.593105388706549`, 7.653068139076581`, 2.2715973346475877`,
7.6234743784167875`, 0.9177107503732636`, 3.182296027902268`,
6.196168580445633`, 0.1486794884986935`, 1.2920960388213274`,
7.478757220079665`, 9.610332785387424`, 0.05088141346751485`,
3.940557901075696`, 5.21881311050797`, 7.489624788199514`,
8.773397599406234`, 3.397275198258715`, 1.4847171141876618`,
0.06574278834161795`, 0.620801320529969`, 2.075457888143216`,
5.244608900551409`, 4.54384757203616`, 7.114276285060143`,
2.8878711430358344`, 5.70657733453041`, 8.759173986432632`,
1.9392596667256967`, 7.419234634325729`, 8.258205508179927`,
1.185315253730261`, 3.907753644335596`, 7.168561412289151`,
9.919881985898002`, 3.169835543867407`, 8.352858871046699`,
7.959492335118693`, 7.772764587074317`, 7.091413185764939`,
1.433673058797801`};
and
u={5.1929, 3.95756, 5.55276, 3.97068, 5.67986, 4.57951, 4.12308,
2.52284, 6.58678, 4.32735, 7.08465, 4.65308, 3.82025, 5.01325,
1.17007, 6.43412, 4.67273, 3.7701, 4.10398, 2.90585, 3.75596,
5.12365, 4.78612, 7.20375, 3.19926, 8.10662};
This is the LinePlot of "b" and "u";
I need to compare first 5 numbers from "b" to 1st number in "u" and always leave the maximum (replace "b"<"u" with "u"). Then I need to shift by 2 numbers and compare 3rd, 4th, 5th, 6th and 7th "b" with 2nd "u" and so on (shift always => 2 steps). But the overlapping numbers need to be "remembered" and compared in the next step, so that always the maximum is picked (e.g. 3rd, 4th and 5th "b" has to be > than 1st and 2nd "u").
Possibly the easiest way would be to cover the maximums showed in the image throughout the whole function, but I am new to this software and I don't have the experience to do that. Still It would be awesome if someone would figure out how to do this with a function that would do what I have described above.
I believe this does what you want:
With[{n = Length # u},
Array[b[[#]] ~Max~ Take[u, ⌊{#-2, #+1}/2⌋ ~Clip~ {1, n}] &, 2 n + 3]
]
{8.73406, 8.33051, 5.62067, 5.1929, 5.55276, 7.04582, 5.55276, 5.55276, 9.74904,--
Or if the length of u and v are appropriately matched:
With[{n = Length # u},
MapIndexed[# ~Max~ Take[u, ⌊(#2[[1]] + {-2, 1})/2⌋ ~Clip~ {1, n}] &, b]
]
These are quite a lot faster than Mark's solution. With the following data:
u = RandomReal[{1, 1000}, 1500];
b = RandomReal[{1, 1000}, 3004];
Mark's code takes 2.8 seconds, while mine take 0.014 and 0.015 seconds.
Please ask your future questions on the dedicated Mathematica StackExchange site:
I think that there's a small problem with your data, u doesn't have as many elements as Partition[b,5,2]. Leaving that to one side, the best I could do was:
Max /# Transpose[
Table[Map[If[# > 0, Max[#, u[[i]]], 0] &,
RotateRight[PadRight[Partition[b, 5, 2][[i]], Length[b]],
2 (i - 1)]], {i, 1, Length[u]}]]
which starts producing the same numbers as in your comment.
As ever, pick this apart from the innermost expression and work outwards.

Which language understands 'variable a = 0 , 20, ..., 300'?

Which language is smart so that it could understand variable a = 0 , 20, ..., 300 ? so you could easily create arrays with it giving step start var last var (or, better no last variable (a la infinite array)) and not only for numbers (but even complex numbers and custom structures like Sedenion's which you would probably define on your own as a class or whatever...)
Point is, find a language or algorithm usable in a language that can cach the law of how array of variables you've given (or params of that variables) change. And compose using that law a structure from which you would be able to get any variable(s).
To everyone - examples you provide are very helpful for all beginners out there. And at the same time are the basic knowledge required to build such 'Smart Array' class. So thank you wary much for your enthusiastic help.
As JeffSahol noticed
all possible rules might include some
that require evaluation of some/all
existing members to generate the nth
member.
So it is a hard Question. And I think language that would do it 'Naturally' would be great to play\work with, hopefully not only for mathematicians.
Haskell:
Prelude> let a=[0,20..300]
Prelude> a
[0,20,40,60,80,100,120,140,160,180,200,220,240,260,280,300]
btw: infinite lists are possible, too:
Prelude> let a=[0,20..]
Prelude> take 20 a
[0,20,40,60,80,100,120,140,160,180,200,220,240,260,280,300,320,340,360,380]
Excel:
Write 0 in A1
Write 20 in A2
Select A1:2
Drag the corner downwards
MatLab:
a = [0:20:300]
F#:
> let a = [|0..20..300|];;
val a : int [] =
[|0; 20; 40; 60; 80; 100; 120; 140; 160; 180; 200; 220; 240; 260; 280; 300|]
With complex numbers:
let c1 = Complex.Create( 0.0, 0.0)
let c2 = Complex.Create(10.0, 10.0)
let a = [|c1..c2|]
val a : Complex [] =
[|0r+0i; 1r+0i; 2r+0i; 3r+0i; 4r+0i; 5r+0i; 6r+0i; 7r+0i; 8r+0i; 9r+0i; 10r+0i|]
As you can see it increments only the real part.
If the step is a complex number too, it will increment the real part AND the imaginary part, till the last var real part has been reached:
let step = Complex.Create(2.0, 1.0)
let a = [|c1..step..c2|]
val a: Complex [] =
[|0r+0i; 2r+1i; 4r+2i; 6r+3i; 8r+4i; 10r+5i|]
Note that if this behavior doesn't match your needs you still can overload (..) and (.. ..) operators. E.g. you want that it increments the imaginary part instead of the real part:
let (..) (c1:Complex) (c2:Complex) =
seq {
for i in 0..int(c2.i-c1.i) do
yield Complex.Create(c1.r, c1.i + float i)
}
let a = [|c1..c2|]
val a : Complex [] =
[|0r+0i; 0r+1i; 0r+2i; 0r+3i; 0r+4i; 0r+5i; 0r+6i; 0r+7i; 0r+8i; 0r+9i; 0r+10i|]
And PHP:
$a = range(1,300,20);
Wait...
Python:
print range(0, 320, 20)
gives
[0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300]
Props to the comments (I knew there was a more succinct way :P)
Scala:
scala> val a = 0 to 100 by 20
a: scala.collection.immutable.Range = Range(0, 20, 40, 60, 80, 100)
scala> a foreach println
0
20
40
60
80
100
Infinite Lists:
scala> val b = Stream from 1
b: scala.collection.immutable.Stream[Int] = Stream(1, ?)
scala> b take 5 foreach println
1
2
3
4
5
In python you have
a = xrange(start, stop, step)
(or simply range in python 3)
This gives you an iterator from start to stop. It can be infinite since it is built lazily.
>>> a = xrange(0, 300, 20)
>>> for item in a: print item
...
0
20
40
60
80
100
120
140
160
180
200
220
240
260
280
And C++ too [use FC++ library]:
// List is different from STL list
List<int> integers = enumFrom(1); // Lazy list of all numbers starting from 1
// filter and ptr_to_fun definitions provided by FC++
// The idea is to _filter_ prime numbers in this case
// prime is user provided routine that checks if a number is prime
// So the end result is a list of infinite primes :)
List<int> filtered_nums = filter( ptr_to_fun(&prime), integers );
FC++ lazy list implementation: http://www.cc.gatech.edu/~yannis/fc++/New/new_list_implementation.html
More details: http://www.cc.gatech.edu/~yannis/fc++/
Arpan
Groovy,
assert [ 1, *3..5, 7, *9..<12 ] == [1,3,4,5,7,9,10,11]
The SWYM language, which appears to no longer be online, could infer arithmetic and geometric progressions from a few example items and generate an appropriate list.
I believe the syntax in perl6 is start ... *+increment_value, end
You should instead use math.
- (int) infiniteList: (int)x
{
return (x*20);
}
The "smart" arrays use this format since I seriously doubt Haskel could let you do this:
a[1] = 15
after defining a.
C# for example does implement Enumerable.Range(int start, int count), PHP offers the function range(mixed low, mixed high, number step), ... There are programming languages that are "smart" enough.
Beside that, an infinite array is pretty much useless - it's not infinite at all but all-memory-consuming.
You cannot do this enumerating simply with complex numbers as there is no direct successor or predecessor for a given number. Edit: This does not mean that you cannot compare complex numbers or create an array with a specified step!
I may be misunderstanding the question, but the answers that specify way to code the specific example you gave (counting by 20's) don't really meet the requirement that the array "cache" an arbitrary rule for generating array members...it seems that almost any complete solution would require a custom collection class that allows generation of the members with a delegated function/method, especially since all possible rules might include some that require evaluation of some/all existing members to generate the nth member.
Just about any program language can give you this sequence. The question is what syntax you want to use to express it. For example, in C# you can write:
Enumerable.Range(0, 300).Where(x => (x % 20) == 0)
or
for (int i = 0; i < 300; i += 20) yield return i;
or encapsulated in a class:
new ArithmaticSequence(0, 301, 20);
or in a method in a static class:
Enumerable2.ArithmaticSequence(0, 301, 20);
So, what is your criteria?
Assembly:
Assuming edi contains the address of the desired array:
xor eax, eax
loop_location:
mov [edi], eax
add edi, #4
add eax, #20
cmp eax, #300
jl loop_location
MATLAB
it is not a Programming language itself but its a tool but still u can use it like a programming language.
It is built for such Mathematics operations to easily arrays are a breeze there :)
a = 0:1:20;
creates an array from 0 to 20 with an increment of 1.
instead of the number 1 you can also provide any value/operation for the increment
Php always does things much simpler, and sometimes dangerously simple too :)
Well… Java is the only language I've ever seriously used that couldn't do that (although I believe using a Vector instead of an Array allowed that).

Mathematica: Determine if all integers in a list are less than a number?

Is there a way in Mathematica to determine if all the integers in a list are less than a set number. For example if I want to know if all the numbers in a list are less than 10:
theList = {1, 2, 3, 10};
magicFunction[theList, 10]; --> returns False
Thanks for your help.
Look into the Max function for lists, which returns the largest number in the list. From there, you can check if this value is less than a certain number.
Before offering my solution let me comment the previous two solutions. Lets call Joey Robert's solution magicFunction1 and Eric's solution magicFunction2.
magicFunction1 is very short and elegant. What I don't like about it is that if I have an very large list of numbers and the first one is already bigger than 10 it still will do all the work of figuring out the largest number which is not needed. This also applies to magicFunction2
I developed the following two solutions:
magicFunction3[lst_, val_] :=
Position[# < val & /# lst, False, 1, 1] == {}
and
magicFunction4[lst_, val_] :=
Cases[lst, x_ /; x >= val, 1, 1] == {}
Doing a benchmark I found
In[1]:= data = Table[RandomInteger[{1, 10}], {10000000}];
In[2]:= Timing[magicFunction1[data, 10]]
Out[2]= {0.017551, False}
In[2]:= Timing[magicFunction2[data, 10]]
Out[2]= {10.0173, False}
In[2]:= Timing[magicFunction3[data, 10]]
Out[2]= {7.10192, False}
In[2]:= Timing[magicFunction4[data, 10]]
Out[2]= {0.402562, False}
So my best answer is magicFunction4, but I still don't know why it is slower than magicFunction1. I also ignore why there is such a large performance difference between magicFunction3 and magicFunction4.
This kind of test is easy to construct using 'Fold':
magicFunction[ lst_, val_ ] :=
Fold[ ((#2 < val) && #1) &, True, lst ]
The phrase '(#2 < val)' is the test of each list element ('#2'). You could put any test you wanted here, so you can do more powerful tests than you can with a listable function like Max.
The ' && #1' then combines the result for your current element with the result for all prior elements.
And 'True' is the base case -- the result for an empty list.
To see how it works, you can pass in some undefined values and see what the expression expands to:
In[10]:= magicFunction[ {a, b, c}, 10 ]
Out[10]= c < 10 && b < 10 && a < 10

How do I build this finite automaton?

I'm studying for a Discrete Mathematics test and I found this exercise which I can't figure out.
"Build a basic finite automaton (DFA,NFA,NFA-lambda) for the language in the alphabet Sigma = {0,1,2} where the sum of the elements in the string is even AND this sum is more than 3"
I have tried using Kleene's Theorem concatenating two languages like concatenating the one associated with this regular expression:
(00 U 11 U 22 U 02 U 20)* - the even elements
with this one
(22 U 1111 U 222 U 2222)* - the ones whose sum is greater than 3
Does this make any sense?? I think my regex are flabby.
I find your notation a bit fuzzy, so perhaps I'm completely misunderstanding. If so, disregard the following. It seems you're not there yet:
I assume the * means '0 or more times'. However, one of the strings with sum >= 3 must occur. It's say you need a + ('1 or more times').
112 and 211 are missing in the list of strings with sum >= 3.
222 and 2222 in that list are superfluous.
All of these strings may be arbitraryly interspersed with 0s.
The sum of 00 is no more even than the sum of 0.
Edit: how about this (acc is the only accepting state, dot-source):
automaton http://student.science.uva.nl/~sschroev/so/885411.png
At states a and c the string sum is always odd. At states start, b and acc the sum is always even. Furthermore, at start the sum is 0, at b it is 2 and at d it is >= 4. This can be proved rather easily. Hence the accepting state acc meets all criteria.
Edit 2: I'd say this is a regex which accepts the requested language:
0*(2|(1(0|2)*1))(0*(2|(1(0|2)*1))+
Not sure if this is answering your question, but: do you need to submit a regular expression? or will an FSM do?
At any rate, it might be helpful to draw the FSM first, and I think this is a correct DFA:
FSM http://img254.imageshack.us/img254/5324/fsm.png
If that is the case, when constructing your regular expression (which, remember, has different syntax than programming "regex"):
0* to indicate "0 as many times as you want". This makes sense, since 0 in your string doesn't change the state of the machine. (See, in the FSM, 0 just loops back to itself)
You'd need to account for the different combinations of "112" or "22" etc - until you reach at least 4 in your sum.
If your sum is greater than 3, and even, then (0|2)* would keep you at a final state. Otherwise (sum > 3, and odd) you'd need something like 1(0|2)* in order to put you at an accepting state.
(don't know if this helps, or if its right - but it might be a start!)
Each expression, as guided by Stephan, may be:
(0*U 2* U 11)* - the even sums
with this one
(22 U 11 U 222 U 112 U 211 U 121)+ - the ones whose sum is greater than 3
I don't know if it could be simplfied more, it would help designing the automaton.
I find it easier just to think in terms of states. Use five states: 0, 1, 2, EVEN, ODD
Transitions:
State, Input -> New State
(0, 0) -> 0
(0, 1) -> 1
(0, 2) -> 2
(1, 0) -> 1
(1, 1) -> 2
(1, 2) -> ODD
(2, 0) -> 2
(2, 1) -> ODD
(2, 2) -> EVEN
(ODD, 0) -> ODD
(ODD, 1) -> EVEN
(ODD, 2) -> ODD
(EVEN, 0) -> EVEN
(EVEN, 1) -> ODD
(EVEN, 2) -> EVEN
Only EVEN is an accepting state.