I have been asked to make a simple sort aglorithm to sort a random series of 6 numbers into numerical order. However, I have been asked to do this using Barebones-a theoretical language put forward in the book Computer Science, an Overview.
Some information on the language can be found here.
Just to clarify, I am a student teacher and have been doing anaysis on "mini-programing languages" and their uses in a teaching environment. I suggested to my tutor that I look at barebones (the language) and asked what sort of exmaple program I should write. He suggested a simple sort algorithm. Now since looking at the language I can't understand how I can do this without using arrays and if statements.
The code to swap the value of variables would be
while a not 0 do;
incr Aux1;
decr a;
end;
while b not 0 do;
incr Aux2
decr b
end;
while Aux1 not 0 do;
incr a;
decr Aux1;
end;
while Aux2 not 0 do;
incr b;
decr Aux2;
end;
However, the language does not provide < or > operators. What could I use as a workaround?
Oh, come on, start thinking about the problem!
What's an array? A list of variables.
So Barebones doesn't have an if statement? It's got while loops.
Get on with your homework.
Interesting exercise.
I would suggest you try to first implement the following:
Swap values of two variables
Set a variable (say z) to zero if value of variable x >= value of variable y.
Since the program is supposed to sort exactly 6 integers, I suppose you can assume they are in the variables x1, x2, .., x6.
In the end we need: x1 <= x2 <= ... <= x6.
Related
Suppose that we have a Lua table called t, defined as follows:
t = {4, 5, 6, 7}
Suppose we wish further to know what the product of the numbers in t is. (Aside: the answer is 840.) I can think of two methods.
First, a basic for loop:
answer = 1
for i = 1, #t do
answer = answer * t[i]
end
print ( answer )
Second, an ipairs iterator:
answer = 1
for i, j in ipairs ( t ) do
answer = answer * j
end
print ( answer )
(I suppose one could also use a pairs iterator.)
My questions:
Does either of the two methods shown above suffer from any real drawbacks?
Are there methods for obtaining the desired value of answer that are more efficient and/or robust than the methods shown above?
ipairs involves a function call. This makes generic for-loop slower tiny bit. If the inner task is anything complex, the function call overhead will be negligible, in comparison to a few arithmetic operations it may be notable in some extreme cases. Try it:
a={}
for i=1,2e8 do a[i]=math.random() end
t=os.time()
q=1
for i=1,#a do q=q*a[i] end
print(os.time()-t)
w=1
t=os.time()
for i,v in ipairs(a) do w=w*v end
print(os.time()-t)
For me results were 15 and 18.
It is more impactful when the calculation is repeated multiple times (nested loops):
a={} for i=1,1e4 do a[i]=math.random() end
t=os.time() q=1; for i=1,1e5 do for j=1,1e4 do q=q*a[j] end end print(os.time()-t)
t=os.time() q=1; for i=1,1e5 do for _,v in ipairs(a) do q=q*v end end print(os.time()-t)
But still not a lot.
If you really need to squeeze out even that bit of performance, you probably should take a look at luajit and various numeric frameworks based on it: 1, 2, 3.
Also, there's article on optimization by the language author.
Some one ask a this question from me. I am confuse how it is possible to multiply two numbers without using multiplication operator? Plz share you idea.
Its so simple. see this code:
int multiplication(int a, int b){
if(b==1|| b==0)
return a;
else
return a+multiplication(a,--b);
}
I have not tested it. Just share it for idea.
Assuming the terms you are multiplying are non-negative integers, you don't even need full addition, just a successor function (i.e. the ability to add one). That's because ...
a*b is the same as add together b lots of a
a+b is the same as add 1 to a, b times
So you could program a*b that with nested loops like this:
answer = 0
for iMultiply from 1 to b
for iAdd from 1 to a
answer++
next iAdd
next iMultiply
return answer
On math.SE, a question about math notation enerated a discussion of how programming languages interpret the set {1,...,n} when n=0
The question asked for a mathematical notation to represent the R code 1:n
According to the comments, the mathematical interpretation of {1,...,n} when n=0 is that this is an empty set. A subsequent comment suggested that C is consistent with this interpretation, because for (int i = 1; i < n; i++) returns a empty set because it iterates 0 times.
It is not clear to me what the equivalent statement in R is, but 1:0 returns the vector [1,0]
Thus, for (i in 1:0) print(i) iterates over 1 and 0 (I interpret as analogous to the C code above)
Is this because {1,...,n} is not the correct notation for 1:n?
Does this mean R violates a universal rule?
Is there a consistent interpretation for this set among programming languages?
Each mathematical formalism has its own notation. To suggest that there is a "universal notation" is very "un-mathematical". Look at the notation associated with tensors or groups if you want examples of mathematical domains where multiple notational systems exist.
In R the code x <- 1:0 returns the ordered vector c(1,0). Just as the code x <- 2:-2 returns c(2,1,0,-1,-2). The code x <- seq(1, length=0) returns a sequence of length 0 which is printed in console sessions as integer(0). R is not really designed to mimic set notation but it does have some set functions and it also has packages that more fully implement set notation.
C has no concept of a set that a for loop runs over. A for loop for(a;b;c) d; is simply syntactic sugar for:
a;
loop: if (!b) goto done;
d;
c;
goto loop;
done: ;
See also my response at: Sequence construction that creates an empty sequence if lower is greater than upper bound - in R, seq_len(n) should be used in preference to 1:n for exactly this reason (the latter fails misbehaves when n=0).
some languages support the concept of ranges, in C it is arbitary what you make a for loop do, you could make it mean 0 or you could make it count backwards. In other languages a range that has the second number less that the first often produces a number sequence that is decreasing. But its arbitrary, and there is no universal rule.
Days ago, my teacher told me it was possible to check if a given point is inside a given rectangle using only bit operators. Is it true? If so, how can I do that?
This might not answer your question but what you are looking for could be this.
These are the tricks compiled by Sean Eron Anderson and he even put a bounty of $10 for those who can find a single bug. The closest thing I found here is a macro that finds if any integer X has a word which is between M and N
Determine if a word has a byte between m and n
When m < n, this technique tests if a word x contains an unsigned byte value, such that m < value < n. It uses 7 arithmetic/logical operations when n and m are constant.
Note: Bytes that equal n can be reported by likelyhasbetween as false positives, so this should be checked by character if a certain result is needed.
Requirements: x>=0; 0<=m<=127; 0<=n<=128
#define likelyhasbetween(x,m,n) \
((((x)-~0UL/255*(n))&~(x)&((x)&~0UL/255*127)+~0UL/255*(127-(m)))&~0UL/255*128)
This technique would be suitable for a fast pretest. A variation that takes one more operation (8 total for constant m and n) but provides the exact answer is:
#define hasbetween(x,m,n) \
((~0UL/255*(127+(n))-((x)&~0UL/255*127)&~(x)&((x)&~0UL/255*127)+~0UL/255*(127-(m)))&~0UL/255*128)
It is possible if the number is a finite positive integer.
Suppose we have a rectangle represented by the (a1,b1) and (a2,b2). Given a point (x,y), we only need to evaluate the expression (a1<x) & (x<a2) & (b1<y) & (y<b2). So the problems now is to find the corresponding bit operation for the expression c
Let ci be the i-th bit of the number c (which can be obtained by masking ci and bit shift). We prove that for numbers with at most n bit, c<d is equivalent to r_(n-1), where
r_i = ((ci^di) & ((!ci)&di)) | (!(ci^di) & r_(i-1))
Prove: When the ci and di are different, the left expression might be true (depends on ((!ci)&di)), otherwise the right expression might be true (depends on r_(i-1) which is the comparison of next bit).
The expression ((!ci)&di) is actually equivalent to the bit comparison ci < di. Hence, this recursive relation return true that it compares the bit by bit from left to right until we can decide c is smaller than d.
Hence there is an purely bit operation expression corresponding to the comparison operator, and so it is possible to find a point inside a rectangle with pure bitwise operation.
Edit: There is actually no need for condition statement, just expands the r_(n+1), then done.
x,y is in the rectangle {x0<x<x1 and y0<y<y1} if {x0<x and x<x1 and y0<y and y<y1}
If we can simulate < with bit operators, then we're good to go.
What does it mean to say something is < in binary? Consider
a: 0 0 0 0 1 1 0 1
b: 0 0 0 0 1 0 1 1
In the above, a>b, because it contains the first 1 whose counterpart in b is 0. We are those seeking the leftmost bit such that myBit!=otherBit. (== or equiv is a bitwise operator which can be represented with and/or/not)
However we need some way through to propagate information in one bit to many bits. So we ask ourselves this: can we "code" a function using only "bit" operators, which is equivalent to if(q,k,a,b) = if q[k] then a else b. The answer is yes:
We create a bit-word consisting of replicating q[k] onto every bit. There are two ways I can think of to do this:
1) Left-shift by k, then right-shift by wordsize (efficient, but only works if you have shift operators which duplicate the last bit)
2) Inefficient but theoretically correct way:
We left-shift q by k bits
We take this result and and it with 10000...0
We right-shift this by 1 bit, and or it with the non-right-shifted version. This copies the bit in the first place to the second place. We repeat this process until the entire word is the same as the first bit (e.g. 64 times)
Calling this result mask, our function is (mask and a) or (!mask and b): the result will be a if the kth bit of q is true, other the result will be b
Taking the bit-vector c=a!=b and a==1111..1 and b==0000..0, we use our if function to successively test whether the first bit is 1, then the second bit is 1, etc:
a<b :=
if(c,0,
if(a,0, B_LESSTHAN_A, A_LESSTHAN_B),
if(c,1,
if(a,1, B_LESSTHAN_A, A_LESSTHAN_B),
if(c,2,
if(a,2, B_LESSTHAN_A, A_LESSTHAN_B),
if(c,3,
if(a,3, B_LESSTHAN_A, A_LESSTHAN_B),
if(...
if(c,64,
if(a,64, B_LESSTHAN_A, A_LESSTHAN_B),
A_EQUAL_B)
)
...)
)
)
)
)
This takes wordsize steps. It can however be written in 3 lines by using a recursively-defined function, or a fixed-point combinator if recursion is not allowed.
Then we just turn that into an even larger function: xMin<x and x<xMax and yMin<y and y<yMax
I want to calculate whether a point, (x,y), is inside a rectangle which is determined by two points, (a,b) and (c,d).
If a<=c and b<=d, then it is simple:
a<=x&&x<=c&&b<=y&&y<=d
However, since it is unknown whether a<=c or b<=d, the code should be
(a<=x&&x<=c||c<=x&&x<=a)&&(b<=y&&y<=d||d<=y&&y<=b)
This code may work, but it is too long. I can write a function and use it, but I wonder if there's shorter way (and should be executed very fast - the code is called a lot) to write it.
One I can imagine is:
((c-x)*(x-a)>=0)&&((d-y)*(y-b)>=0)
Is there more clever way to do this?
(And, is there any good way to iterate from a from c?)
Swap the variables as needed so that a = xmin and b = ymin:
if a > c: swap(a,c)
if b > d: swap(b,d)
a <= x <= c and b <= y <= d
Shorter but slightly less efficient:
min(a,c) <= x <= max(a,c) and min(b,d) <= y <= max(b,d)
As always when optimizing you should profile the different options and compare hard numbers. Pipelining, instruction reordering, branch prediction, and other modern day compiler/processor optimization techniques make it non-obvious whether programmer-level micro-optimizations are worthwhile. For instance it used to be significantly more expensive to do a multiply than a branch, but this is no longer always the case.
I like the this:
((c-x)*(x-a)>=0)&&((d-y)*(y-b)>=0)
but with more whitespace and more symmetry:
(c-x)*(a-x) <= 0 && (d-y)*(b-y) <= 0
It's mathematically elegant, and probably the fastest too. You will need to measure to really determine which is the fastest. With modern pipelined processors, I would expect that straight-line code with the minimum number of operators will run fastest.
While sorting the (a, b) and (c, d) pairs as suggested in the accepted answer is probably the best solution in this case, an even better application of this method would probably be to elevate the a < b and c < d requirement to the level of the program-wide invariant. I.e. require that all rectangles in your program are created and maintained in this "normalized" form from the very beginning. Thus, inside your point-in-rectangle test function you should simply assert that a < b and c < d instead of wasting CPU resources on actually sorting them in every call.
Define intermediary variables i = min(a,b), j = min(c,d), k = max(a,b), l = max(c,d)
Then you only need i<=x && x<=k && j<=y && y<=l.
EDIT: Mind you, efficiency-wise it's probably better to use your "too long" code in a function.