i have a really simple CountUp from 0 to 10 Code-Line here, but I want it to CountDown 3 Seconds after it has reached 10 back to 0 again. And this in an interval. Somebody knows what I'm doing wrong?
Thanks for your help!
Utils.interval 3, ->
zahlValue = 0
Utils.interval 0.05, ->
if zahlValue < 10
zahlValue++
zahl.html = zahlValue
Utils.delay 3, ->
Utils.interval 0.05, ->
if zahlValue = 10
zahlValue = 0
zahl.html = "0"
Related
I would like to be able to obtain a (non-convergent) sequence of numbers by a simple calculation that would look like this: 0, 1, -1, 2, -2, 3, -3, 4, -4 ...
By simple calculation I mean being able to do it with a single variable that would start from 1 (or 0) without having to rearrange this sequence.
I made several (unsuccessful) attempts in Lua, here is what it should look like in principle (this example only alternates 0s and 1s):
do
local n = 0
for i = 1, 10 do print(n)
n = n==0 and 1 or -n + (n/n)
end
end
Is this possible and how?
Update:
I just succeeded like this:
local n, j = 0, 2
for i = 1, 10 do print(n)
n = n==0 and 1 or j%2==0 and -(n+(n/math.abs(n))) or -n
j = j + 1
end
But I have to help myself with a second variable, I would have liked to know if with only n it would be possible to do it?
The whole numbers are enumerable. Thus there exists a mapping from the natural numbers to whole numbers. You'll now have to use a loop to loop over natural numbers, then compute a function that gives you a whole number:
-- 0, 1...10, -1...-10 -> 21 numbers total
for n = 1, 21 do
local last_bit = n % 2
local sign = 1 - (2 * last_bit)
local abs = (n - last_bit) / 2
print(sign * abs)
end
prints
-0
1
-1
2
-2
...
10
-10
on Lua 5.1; on newer Lua versions, you can use n // 2 instead of (n - last_bit) / 2 to (1) use ints and (2) make extracting the abs cheaper.
Simply "emit" both n and -n in each iteration:
for n = 0, 10 do
print(n)
print(-n)
end
My problem was solved by #EgorSkriptunoff in comment of my question, his approach is:
n = (n > 0 and 0 or 1) - n
The output of:
local n = 0
for i=1,10 do io.write(n..", ")
n = (n > 0 and 0 or 1) - n
end
Actually gives:
0, 1, -1, 2, -2, 3, -3, 4, -4, 5,
I have a plot whose y min starts well above 0. But I want to include 0 as the min of the y-axis and still have Stata automatically create evenly-spaced y-axis labels.
Here is the baseline:
sysuse auto2, clear
scatter turn displacement
This produces:
This is almost what I want, except that the y range does not start at 0.
Based on this answer by Nick Cox (https://www.statalist.org/forums/forum/general-stata-discussion/general/1598753-force-chart-y-axis-to-start-at-0), I modify the code to be:
scatter turn displacement, yscale(range(0 .)) ylabel(0)
This succeeds in starting the y-axis at 0, but the labeling besides 0 goes away:
I proceed to remove `ylabel(0):
scatter turn displacement, yscale(range(0 .))
This produces the opposite problem - the y-axis labels are the same as in the first plot.
How can I have Stata automatically produce the y-axis labels from 0 to the max? For instance, 0, 10, 20, 30, 40, 50 - importantly, though, I have many plots and need a solution that determines the exact values automatically, without needing me to input the y max, etc. So it would not be me who chooses 10, 20, ..., 50, but Stata.
By coincidence, I have been working on a command in this territory. Here is a reproducible example.
sysuse auto, clear
summarize turn, meanonly
local max = r(max)
nicelabels 0 `max', local(yla)
* shows 0 20 40 60
scatter turn displacement, yla(`yla', ang(h))
nicelabels 0 `max', local(yla) nvals(10)
* shows 0 10 20 30 40 50 60
scatter turn displacement, yla(`yla', ang(h))
where nicelabels is at present this code.
*! 1.0.0 NJC 25 April 2022
program nicelabels
/// fudge() undocumented
version 9
gettoken first 0 : 0, parse(" ,")
capture confirm numeric variable `first'
if _rc == 0 {
// syntax varname(numeric), Local(str) [ nvals(int 5) tight Fudge(real 0) ]
syntax [if] [in] , Local(str) [ nvals(int 5) tight Fudge(real 0) ]
local varlist `first'
marksample touse
quietly count if `touse'
if r(N) == 0 exit 2000
}
else {
// syntax #1 #2 , Local(str) [ nvals(int 5) tight Fudge(real 0) ]
confirm number `first'
gettoken second 0 : 0, parse(" ,")
syntax , Local(str) [ nvals(int 5) tight Fudge(real 0) ]
if _N < 2 {
preserve
quietly set obs 2
}
tempvar varlist touse
gen double `varlist' = cond(_n == 1, `first', `second')
gen byte `touse' = _n <= 2
}
su `varlist' if `touse', meanonly
local min = r(min) - (r(max) - r(min)) * `fudge'/100
local max = r(max) + (r(max) - r(min)) * `fudge'/100
local tight = "`tight'" == "tight"
mata: nicelabels(`min', `max', `nvals', `tight')
di "`results'"
c_local `local' "`results'"
end
mata :
void nicelabels(real min, real max, real nvals, real tight) {
if (min == max) {
st_local("results", min)
exit(0)
}
real range, d, newmin, newmax
colvector nicevals
range = nicenum(max - min, 0)
d = nicenum(range / (nvals - 1), 1)
newmin = tight == 0 ? d * floor(min / d) : d * ceil(min / d)
newmax = tight == 0 ? d * ceil(max / d) : d * floor(max / d)
nvals = 1 + (newmax - newmin) / d
nicevals = newmin :+ (0 :: nvals - 1) :* d
st_local("results", invtokens(strofreal(nicevals')))
}
real nicenum(real x, real round) {
real expt, f, nf
expt = floor(log10(x))
f = x / (10^expt)
if (round) {
if (f < 1.5) nf = 1
else if (f < 3) nf = 2
else if (f < 7) nf = 5
else nf = 10
}
else {
if (f <= 1) nf = 1
else if (f <= 2) nf = 2
else if (f <= 5) nf = 5
else nf = 10
}
return(nf * 10^expt)
}
end
EDIT
If you go
sysuse auto, clear
summarize turn, meanonly
local max = r(max)
scatter turn displacement, yla(0(10)`max', ang(h))
scatter turn displacement, yla(0(20)`max', ang(h))
you get good solutions. Clearly in this case we need to know that 10 or 20 is a step size to use. There would be scope to calculate a good width programmatically using your own recipe.
EDIT 10 May 2022
A revised and documented nicelabels is now downloadable from SSC.
For the CLRS algorithm for QuickSort,
I am having trouble with following all the calls for the input A = [2,1,3].
QuickSort(A,p,r)
if p < r
q = Partition(A,p,r)
QuickSort(A,p,q-1)
QuickSort(A,q+1,r)
Partition(A,p,r)
x = A[r]
i = p - 1
for j = p to r - 1
if A[j] <= x
i = i + 1
swap (A[i], A[j])
swap(A[i+1], A[r])
return i+1
Here are my function calls for array A:
QuickSort(A,1,3)
Partition(A,1,3)
QuickSort(A,1,2)
Partition(A,1,2)
QuickSort(A,1,0)
QuickSort(A,2,3)
Partition(A,2,3)
QuickSort(A,1,2)
Why does it loop from 8 on?
Assuming indexes start at 1 and not 0, I get:
quicksort A 1 3
partition A 1 3
quicksort A 1 2
partition A 1 2
quicksort A 1 0
quicksort A 2 2
quicksort A 4 3
If indexes starts at 0, then the initial call should be QuickSort(A, 0, 2)
Hello r masters.
I need to calculate Denominators of Farey tree fractions up to 2**30.
I came up with this C++ solution using this approach:
struct FareySB {
int num, den;
FareySB() : den(0) {}
int sum() {
return num + den;
}
};
const int LGMAX = 30;
const int MAX = 1 << LGMAX;
FareySB FTF[MAX];
void get_FTF() {
FTF[0].num = 0; FTF[0].den = 1;
FTF[1].num = 1; FTF[1].den = 1;
FTF[2].num = 1; FTF[2].den = 2;
int k = 3;
for (int i = 1; i < LGMAX; i++) {
int len = 1 << i;
int hlen = len >> 1;
for (int j=0; j<hlen; j++) {
FTF[k].num = FTF[k-hlen].num;
FTF[k].den = FTF[k-hlen].sum();
k++;
}
for (int j=0; j<hlen; j++) {
FTF[k].num = FTF[k-len].den;
FTF[k].den = FTF[k-1-(j<<1)].den;
k++;
}
}
}
To know the n-th term I need to know all [0..n-1] terms. Ok so far.
This has a problem: memory just explodes after about 2**27.
The denominators of Farey Tree Fractions are the OEIS-A007306:
1, 1, 2, 3, 3, 4, 5, 5, 4, 5, 7, 8, 7, 7, 8, 7, ...
In that OEIS page I found a code which seems to return the n-th term of the sequence in constant time. If thats true it would solve my Memory Limit Exceeded issue.
But the code is in R language:
(R)
# Given n, compute directly a(n)
# by taking into account the binary representation of n-1
aa <- function(n){
b <- as.numeric(intToBits(n))
l <- sum(b)
m <- which(b == 1)-1
d <- 1
if(l > 1) for(j in 1:(l-1)) d[j] <- m[j+1]-m[j]+1
f <- c(1, m[1]+2) # In A002487: f <- c(0, 1)
if(l > 1) for(j in 3:(l+1)) f[j] <- d[j-2]*f[j-1]-f[j-2]
return(f[l+1])
}
# a(0) = 1, a(1) = 1, a(n) = aa(n-1) n > 1
It may be really simple to you, but I don't know R language, and can't understand the above code.
Is it really a constant function? How does that function works?
If you could show me for a given n whats happening inside this function, then I could be able to code it in C++ myself.
Thanks in advance.
I'm not sure quite how it works, but here is what the R code is doing. Assume n=100.
b <- as.numeric(intToBits(n)) this produces a 32-element vector of a (reversed) binary representation of n. For n=100, b is 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
l <- sum(b) is the sum of the elements of b (i.e. the number of 1s). In this case l=3
m <- which(b == 1)-1 is a vector of the indices of the elements of b that are equal to 1, each reduced by 1. So for n=100, m= 2 5 6
d <- 1 just setting d equal to 1
if(l > 1) for(j in 1:(l-1)) d[j] <- m[j+1]-m[j]+1. If l is bigger than one, then d becomes a vector of length l-1, where each d is the differences between successive values of m, plus one. So for n=100, d= 4 2
f <- c(1, m[1]+2) sets f as a vector with the first value 1, second value the first element of m, plus 2. Here f is 1 4
if(l > 1) for(j in 3:(l+1)) f[j] <- d[j-2]*f[j-1]-f[j-2]. If l is bigger than one, this adds elements onto the end of f, according to that formula - e.g. f[3] is d[1]*f[2]-f[1] or 4*4-1=15. For n=100, f is 1 4 15 26.
return(f[l+1]) This returns the last element of f as the result.
I'm not sure whether it is constant, but it looks pretty quick as n increases. Good luck!
So this is the code:
int test ( int n)
{
if (n ≤2) return 1;
else return test(n-2) * test(n-2);
}
I'm not confident in how to reason about this recursive function. I tried mapping the N value to the recursion depth like so:
N = 2 -> 0 recursions
N = 4 -> 2
N = 8 -> 14
But to be honest I'm not sure this gets me anywhere (and just thinking about test(16) hurts my head.
Let's start by writing out a recurrence relation for the total number of calls made:
T(0) = T(1) = T(2) 1, since there's one total call (the initial call).
T(n+2) = 2T(n) + 1, since there's one call for the initial call, plus two recursive calls to problems of size n.
Let's start by looking at the case where n is even. Then
T(0) = 1
T(2) = 1
T(4) = 2T(2) + 1 = 3
T(6) = 2T(4) + 1 = 7
T(8) = 2T(6) + 1 = 15
T(9) = 2T(8) + 1 = 31
Except for the 0 case, it looks like these values take on the pattern 1, 3, 7, 15, 31, etc. Notice that each of these is one less than a power of two: 1 = 2 - 1, 3 = 4 - 1, 7 = 8 - 1, etc. We can guess that what we're looking at has something to do with powers of two.
Going back to our sequence, we might make a guess that
T(2) = 1 = 21 - 1
T(4) = 3 = 22 - 1
T(6) = 7 = 23 - 1
...
T(2n) = 2n - 1
So if n is even, we have T(n) = 2n/2 - 1 = (√2)n - 1. You can formalize this using a proof by induction.
For the odd case, we basically get the same thing:
T(1) = 1
T(3) = 2T(1) + 1 = 3
T(5) = 2T(3) + 1 = 7
T(7) = 2T(5) + 1 = 15
T(9) = 2T(7) + 1 = 31
...
T(2n+1) = 2n - 1
So if n is even, then T(n) = 2(n-1)/2 - 1. Again, you can prove this by induction to formalize things if you'd like.