I'm trying to implement quicksort for my library based on this post Delphi : Sorted List
I am not 100% sure how to implement a sort order ascending/descending into this.
Do I just switch the comperator in if Lo<=Hi then begin and until Lo>Hi;?
I admit I don't quite understand this.
You only need to reverse the comparison in these two lines
while List[Lo] < Mid do Inc(Lo) ;
while List[Hi] > Mid do Dec(Hi) ;
So make that
while List[Lo] > Mid do Inc(Lo) ;
while List[Hi] < Mid do Dec(Hi) ;
Related
I'm trying to use Dafny with (unsigned) bitvectors (following this post).
The following simplified example (permalink) works fine, but when I change to bv32, I get:
Unexpected prover response: timeout
Is it a bug? or an expected performance gap between the two?
Here is the code to make this post self contained:
method bitvectors()
{
var a : bv16 := 0;
// var a : bv32 := 0;
ghost var atag := a;
while (a<0xFFFF)
// while (a<0xFFFFFFFF)
invariant atag < 0xFFFF
//invariant atag < 0xFFFFFFFF
{
atag := a;
a := a+1;
}
}
I'm hoping someone else has a better answer... but basically this is why I stay away from bitvectors :)
I did a little bit of digging, and it seems that on this particular example Dafny gets stuck in the termination check for the loop. At the Boogie level, comparing bitvectors involves converting them to mathematical integers, and then to real numbers, and then comparing those. It's pretty common for solvers to have trouble with these conversion functions, because they cut across different theories.
Sorry I couldn't be more helpful.
I would like to rearrange an equation in a way that certain variables only appear on the left side using wxMaxima.
%i: eq: term1 = term2 ;
%i: fun(eq,[v]);
%o: term3 = term4
Where the allowed symbols for the terms would be something like this:
term1 = all
term2 = all
term3 = only [v] and operators
term4 = all but [v]
[v] = the variable (or list) that I want to be on the left side
I tried to get something done with matchdeclare and defrule but I couldn't even get the b of a=b+c to the left side. I am not even sure if defrule is the correct approach as term 1 and 2 have nothing to do with 3 and 4. Is there a way to solve for lists?
UPDATE:
I came up with "something". It is not yet what I initially wanted, but at least closer.
It is basically a substitution. I can provide a left hand side and the function tries to solve for it. Of course this exact left side might not be possible so that some variables remain on the right side. But one can specify one variable that should be eliminated on the right.
expr: a=b+c*d+e $
left: log(a+b) $
notright: b $
solve_form( expr, left, notright);
results in:
[log(b+a)=log(-e-c*d+2*a)]
Now, if I instead choose log(a-b) for the left side the output is:
[log(a-b)=log(e+c*d)]
which is pretty much what I wanted. Variables a and b are on the left side, but not on the right.
But I have to give an explicit left side. I would love to have a function that would find an arbitrary left side on its own so that neither a nor b are on the right side.
The obvious solution would have been:[a-b=e+c*d]
Function:
solve_form(expr,lterm,substvar) := block(
[z],
lterm: z = lterm,
solve(lterm,substvar),
ev(expr,%%),
solve(%%,z),
ev(%%,lterm)
)$
Alternative function that does not need the notright input.
solveform(expr,zz_term) := block(
[z,zz_term_vars,slist],
zz_term: zz = zz_term,
zz_term_vars: listofvars(rhs(zz_term)),
slist:[],
for i:1 thru length(zz_term_vars) do block(
solve(zz_term,zz_term_vars[i]),
ev(expr,%%),
slist: append(slist,solve(%%,zz))
),
listify(setify(ev(slist,zz_term)))
)$
I think solve, linsolve, algsys, and eliminate have more or less the effect you are looking for.
I need a help with following:
flatten ([]) -> [];
flatten([H|T]) -> H ++ flatten(T).
Input List contain other lists with a different length
For example:
flatten([[1,2,3],[4,7],[9,9,9,9,9,9]]).
What is the time complexity of this function?
And why?
I got it to O(n) where n is a number of elements in the Input list.
For example:
flatten([[1,2,3],[4,7],[9,9,9,9,9,9]]) n=3
flatten([[1,2,3],[4,7],[9,9,9,9,9,9],[3,2,4],[1,4,6]]) n=5
Thanks for help.
First of all I'm not sure your code will work, at least not in the way standard library works. You could compare your function with lists:flatten/1 and maybe improve on your implementation. Try lists such as [a, [b, c]] and [[a], [b, [c]], [d]] as input and verify if you return what you expected.
Regarding complexity it is little tricky due to ++ operator and functional (immutable) nature of the language. All lists in Erlang are linked lists (not arrays like in C++), and you can not just add something to end of one without modifying it; before it was pointing to end of list, now you would like it to link to something else. And again, since it is not mutable language you have to make copy of whole list left of ++ operator, which increases complexity of this operator.
You could say that complexity of A ++ B is length(A), and it makes complexity of your function little bit greater. It would go something like length(FirstElement) + (lenght(FirstElement) + length(SecondElement)) + .... up to (without) last, which after some math magic could be simplified to (n -1) * 1/2 * k * k where n is number of elements, and k is average length of element. Or O(n^3).
If you are new to this it might seem little bit odd, but with some practice you can get hang of it. I would recommend going through few resources:
Good explanation of lists and how they are created
Documentation on list handling with DO and DO NOT parts
Short description of ++ operator myths and best practices
Chapter about recursion and tail-recursion with examples using ++ operator
I'd like to write a while() loop in Gforth. Unfortunately, the only tutorial online isn't useful due to a lack of examples, and examples on counted loops (what I'm not looking for) appear fundamentally different.
What are some concrete examples of how to represent something like this?
while (x > 3) { print(x); x--; }
Or really, just some concrete way to represent anything of the form:
while (predicate) { expression(s) }
Your first piece of code translates to:
\ Assuming x is on the top of the stack.
begin dup 3 > while dup . 1- repeat
\ Or if x is in memory.
begin x # 3 > while x ? -1 x +! repeat
And the second:
begin predicate while expressions repeat
I cannot find "do...while..."
I have to code like this:
let bubbleSort a=
let n = Array.length a
let mutable swapped = true
let mutable i = 0
while swapped do
swapped <- false
for j = 0 to n-i-2 do
if a.[j] > a.[j+1] then
let t = a.[j]
a.[j] <- a.[j+1]
a.[j+1] <- t
swapped <- true
i <- i+1
The code is bad without "do...while".
Sadly, "break/continue" are also not available.
F# is very much suitable for non-functional programming. In fact, being able to fine-tune parts of an algorithm in an imperative style is one of the major strong points of the language for me.
For example, in tackling a project euler problem, I started out with a clean functional solution using immutable sets and folds. It took 150 seconds to complete. Now having the framework of my algorithm in place allowed me to pick apart the data structures and folds operations one at a time until I managed to get the run time down to 5 seconds. My final solution was very much an imperative one (and even slightly faster than an equivalent C# version).
As you can see I solved it by coding a solution in functional style first and then rewrite small parts to an imperative style. Not having to deal with indices and other loop conditions explicitly kept the code more understandable for me.
Once you learn how to think like a functional programmer you'll find that you'll rarely want breaks and continues. That's what I experienced. But if you do need them, knowing how to think in a functional way helps in coming up with work-arounds, usually involving a tail-recursive version of what used to be a loop.
By the time you start thinking more in an idiomatic F# way, you'll probably see more and more (tail-)recursive code replacing what you used to do with looping constructs. Heck, writing F# for 2 years now has warped my mind so far that I'm more likely to pick recursion and folds over loops.
Whenever I think I need break/continue, I usually don't because there's a cleaner version of the algorithm hidden and waiting to get out. The biggest challenge is learning how to find that cleaner version. I'm afraid that lots of practice and good examples are the only way to get better at thinking functionally, but I believe that it's an effort well spent.
Edit: ironically, bubble sort is an algorithm which is actually designed for arrays with mutable contents. Any recursive bubble sort is likely to be harder to understand than an imperative version. I think I just killed my own post here.
It turns out to be quite easy to write a good enough do-while in F# as a higher-order function:
let doWhile f c =
f ()
while c () do
f ()
break and continue would be a really useful feature additions; they're reserved words, and maybe we'll see them in a future version of the language. The lack of them is an occasional minor annoyance, but hardly makes the language 'unsuitable'. In the mean time, a mutable sentinel works, as you have in your example.
See also
http://tomasp.net/blog/imperative-ii-break.aspx/
do/while is not available because F# is a functional language and this kind of construct is specific to imperative languages.
break/continue is also not available for the same reasons.
However, you can still write do/while in F#. The following code blocks are equivalent :
in C#
do
{
System.Console.WriteLine("processing something...");
System.Console.WriteLine("doing something complicated");
System.Console.Write("continue?");
} while (Console.ReadLine() == "y");
in F#
let doSomethingAndContinue() =
printfn "processing something..."
printfn "doing something complicated"
printf "continue?"
System.Console.ReadLine()="y"
while doSomethingAndContinue() do ignore None
Although a bit more verbose, you can use recursive functions to avoid the "do while" as in :
let swap (a:int[]) i j =
let t = a.[i]
a.[i] <- a.[j]
a.[j] <- t
let rec bubbleSortAux a nMax j swapped =
if j >= 0 && j <= nMax then
if a.[j] > a.[j+1] then
swap a j (j+1)
bubbleSortAux a nMax (j+1) true
else
bubbleSortAux a nMax (j+1) false
else
swapped
let rec bubbleSortLoop a nMax =
if bubbleSortAux a nMax 0 false then
bubbleSortLoop a (nMax - 1)
let bubbleSort a =
bubbleSortLoop a (a.Length - 2)
let bubbleSort (a: _ []) =
let mutable fin = false
while not fin do
fin <- true
for i=0 to a.Length-2 do
if a.[i] > a.[i+1] then
let t = a.[i]
a.[i] <- a.[i+1]
a.[i+1] <- t
fin <- false
I do not know about F# very well, but F# is a functional language. Usually, there is no such thing as "for" or "while" loops in functional programming languages.
Functional languages define functions in a mathematical sense (like f(x) => ...). Writing a program comes down to defining and combining a set of mathematical functions. This means that the only way of coding loops is using recursion.
In Mathematics, there is no way of saying:
f(x) => "do 5 times this"
What you'd do is define f like:
count > 0 : f(x, count-1)
f(x, count) => {
count <= 0 : ...
And then use this function as in:
y = f(x, 5)
This would be exactly how you implement functions in functional languages.
At least, this is true for purely functional languages like Haskell...
You can do something like
let mutable ind = 0
while (
//Do your stuff here
//Now condition part return some boolean value
ind < 10
) do ind <- ind +1
I just recently found this way. It feels a bit hacky but what I like is that you can build something more complex what usually caused issues in C#, C++.
let mutable ind = 0
while (
(some condition) && (
//do something
let someValue = Eval ....
//Now more complex condition
ind + someValue < 10
)
) do ind <- ind +1