get output as a vector in R during a loop - vba

How can I get the output as a vector in R?
For example, if I want to have
for (i in 1:1000) {if i mod 123345 = 0, a = list(i)}
a
but I would want to find all i that divide evenly into 123345 (i.e., factors), and not just the largest one.

There may be a more concise way to do this, but I would do it this way:
i <- 1:1000
j <- i[12345 %% i == 0 ]
The resulting vector j contains a vector of the values in i which are factors of 12345. In R the modulo operator is %% and it's a bit of a bitch to find when searching on your own. It's buried in the help document for arithmetic operators and you can find it by searching for + which must be in quotes like: ?"+" and then you have to read down a bit.
You better add a VBA tag if you want to find a VBA answer. But I suspect it will involve the VBA modulo operator ;)

JD Long's method is really the first that came to mind, but another:
Filter(function(x) !(12345 %% x), 1:1000)
I think it's kind of fun to avoid any need for an explicit assignment. (Kind of too bad to create a new function each time.) (In this case, "!" converts a non-zero value to FALSE and zero to TRUE. "Filter" picks out each element evaluating to TRUE.)
Also avoiding the need for a separate allocation and not creating a new function:
which(!(12345 %% 1:1000))
Timing:
> y <- 1:1000
> system.time(replicate(1e5, y[12345 %% y == 0 ]))
user system elapsed
8.486 0.058 8.589
> system.time(replicate(1e5, Filter(function(x) !(12345 %% x), y)))
Timing stopped at: 90.691 0.798 96.118 # I got impatient and killed it
# Even pulling the definition of the predicate outside,
# it's still too slow for me want to wait for it to finish.
# I'm surprised Filter is so slow.
> system.time(replicate(1e5, which(!12345 %% y)))
user system elapsed
11.618 0.095 11.792
So, looks like JD Long's method is the winner.

You wrote:
for (i in 1:1000) {if i mod 123345 = 0, a = list(i)} a
JD Long's code is much better, but if you wanted this loopy strategy to work try instead:
a <- vector(mode="list"); for (i in 1:1000) {if (123345 %% i == 0){ a <-c(a,i) } }
as.vector(unlist(a))

Related

How can I break out of a Kotlin `repeat` loop?

How do I break out of a Kotlin repeat loop?
(I see plenty of answers about forEach, but I want to see a repeat-specific answer.)
You can't use a naked return, because that will return from what contains the repeat.
You can't use break, because:
if the repeat is inside a loop, you'll break that loop
if the repeat is not in a loop, you'll get 'break' and 'continue' are only allowed inside a loop
These don't work (they are functionally identical):
repeat(5) { idx ->
println(">> $idx")
if(idx >= 2)
return#repeat // use implicit label
}
repeat(5) #foo{ idx ->
println(">> $idx")
if(idx >= 2)
return#foo // use explicit label
}
In both those cases, you get:
>> 0
>> 1
>> 2
>> 3
>> 4
(The return# in both those blocks actually acts like a continue, which you can see yourself if you add a println after the if-block.)
So how can I break out of a repeat?
It turns out that repeat (as well as forEach) are not actually loops. They're higher-order functions, that is, they are functions that take functions as parameters.
(I find this frustrating: They look and act like loops, and feature prominently in the Kotlin docs. Why not just go all the way and promote them to proper loops in the language?)
To break out of a repeat loop, this is the best answer I can devise:
run repeatBlock# { // need to make a label outside of the repeat!
repeat(20) { idx ->
println(">> $idx")
if(idx >= 2)
return#repeatBlock
}
}
This is the result of that:
>> 0
>> 1
>> 2
I wish I could do it without introducing a new indent-level, but I don't think it's possible.
That seems like quite an abuse of the repeat function. My understanding is that if you write repeat, you intend it to repeat for that number of times. Any fewer is surprising.
For your example, I would use a for loop:
for (idx in 0 until 20) {
println(">> $idx")
if (idx >= 2)
break
}
I think using the right tool is better than trying to coerce the wrong one (repeat) to do what you want.
repeat itself is implemented as a for loop:
for (index in 0 until times) {
action(index)
}
Trying to use it for anything more than that and you may as well write your own version, rather than wrap up extra behaviour on top of it.

Conditional Statement with Decision variables and Multiple relations

This is from CPLEX.
I tried doing this but getting no results. Basically my model need a forall statement with these two conditions using decision variables and multiple relations under that. All the equality constraints. Can anyone explain what is the problem in my syntax.
Error : Function operator<(dvar float+,float) not available in context CPLEX.
Some of the screenshots and actual equation from the document is provided alongwith the problem.
Regards,
Debtirthaenter image description here
// code from the model.
enter image description here
forall (a in A, j in Ji[a], n in N: j==jbreak)
{Ts[a][j][n] < tbreak && Tf[a][j][n] > tbreak} => (yvr1[j][n] == yv[j][n]);// && wvr1[a][n] == wv[a][n] && Balr1[a][j][n] == Bal[a][j][n] && Tsr1[a][j][n] == Ts[a][j][n] &&Tfr1[a][j][n] == Tf[a][j][n]);
forall (b in B: b==jbreak,i in Ij[b], n in N) ctTBRD[i][b][n]:
Tsr1[i][b][n] >= tbreak + tmaint;
}
strict inequality is not allowed so can you change
Tf[a][j][n] > tbreak
into
Tf[a][j][n] >= tbreak+1
?
Expanding on Alex's answer: the problem is indeed that strict inequality is not supported. However, Alex's solution will only work if tbreak is an integer variable. According to your error message, tbreak is a float+ variable, though. So the fix should be something like this:
Ts[a][j][n] <= tbreak - eps
where eps is a small constant, like 1e-6.
However, working with these tolerances is always a bit shaky, so you may want to double-check whether you can get around this. For example, by making tbreak an integer variable or by reverting the condition so that a strict less-than becomes a greater-than-or-equal (not sure this can be done but it is worth thinking about).

Discrete Binary Search in Topcoder Tutorial

I went through this code given in Topcoder binary search tutorial.
binary_search(lo, hi, p):
while lo < hi:
mid = lo + (hi-lo)/2
if p(mid) == true:
hi = mid
else:
lo = mid+1
if p(lo) == false:
complain // p(x) is false for all x in S!
return lo // lo is the least x for which p(x) is true
I am not able to reason as to why always low is going to point to what we want i.e. lo is the least x for which p(x) is true ?
I have tried this on examples and this comes out to be true but I am not able to think about it logically.
Some sort of proof using some invariant which is maintained in the loop will be helpful .
Thanks.
My understanding is more of a logical one:
If the while loop has to terminate then lo should become equal to or greater than hi. Assuming we work with integers, then lo will be equal to hi and hi will be mid.
In your language, the loop invariant is, lo is the least x in the search space that p(x) can be true. The loop makes progress by cutting the search space in half while maintaining the invariant. When the loop exits, search space has only one value, lo (which equals hi). We perform the last check, if p(lo) equals false, then we didn't find any x that makes p(x) true. Otherwise, it's the least x we look for.

howmany() Macro Objective C

While using Xcode, I accidentally auto completed to the macro howmany(x,y) and traced it to types.h. The entire line reads as follows:
#define howmany(x, y) __DARWIN_howmany(x, y) /* # y's == x bits? */
This didn't really make much sense, so I followed the path a little more and found __DARWIN_howmany(x, y) in _fd_def.h. The entire line reads as follows:
#define __DARWIN_howmany(x, y) ((((x) % (y)) == 0) ? ((x) / (y)) : (((x) / (y)) + 1)) /* # y's == x bits? */
I have no idea what __DARWIN_howmany(x, y) does. Does the comment at the end of the line shed any light on the intended function of this macro? Could someone please explain what this macro does, how it is used, and its relevance in _fd_def.h
This is a fairly commonly used macro to help programmers quickly answer the question, if I have some number of things, and my containers can each hold y of them, how many containers do I need to hold x things?
So if your containers can hold five things each, and you have 18 of them:
n = howmany(18, 5);
will tell you that you will need four containers. Or, if my buffers are allocated in words, but I need to put n characters into them, and words are 8 characters long, then:
n = howmanu(n, 8);
returns the number of words needed. This sort of computation is ubiquitous in buffer allocation code.
This is frequently computed:
#define howmany(x, y) (((x)+(y)-1)/(y))
Also related is roundup(x, y), which rounds x up to the next multiple of y:
#define roundup(x, y) (howmany(x, y)*(y))
Based on what you've posted, the macro seems to be intended to answer a question like, "How many chars does it take to hold 18 bits?" That question could be answered with this line of code
int count = howmany( 18, CHAR_BIT );
which will set count to 3.
The macro works by first checking if y divides evenly into x. If so, it returns x/y, otherwise it divides x by y and rounds up.

What are the practical uses of modulus (%) in programming? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Recognizing when to use the mod operator
What are the practical uses of modulus? I know what modulo division is. The first scenario which comes to my mind is to use it to find odd and even numbers, and clock arithmetic. But where else I could use it?
The most common use I've found is for "wrapping round" your array indices.
For example, if you just want to cycle through an array repeatedly, you could use:
int a[10];
for (int i = 0; true; i = (i + 1) % 10)
{
// ... use a[i] ...
}
The modulo ensures that i stays in the [0, 10) range.
I usually use them in tight loops, when I have to do something every X loops as opposed to on every iteration..
Example:
int i;
for (i = 1; i <= 1000000; i++)
{
do_something(i);
if (i % 1000 == 0)
printf("%d processed\n", i);
}
One use for the modulus operation is when making a hash table. It's used to convert the value out of the hash function into an index into the array. (If the hash table size is a power of two, the modulus could be done with a bit-mask, but it's still a modulus operation.)
To print a number as string, you need the modulus to find the value of a digit.
string number_to_string(uint number) {
string result = "";
while (number != 0) {
result = cast(char)((number % 10) + '0') ~ result;
// ^^^^^^^^^^^
number /= 10;
}
return result;
}
For the control number of international bank account numbers, the mod97 technique.
Also in large batches to do something after n iterations. Here is an example for NHibernate:
ISession session = sessionFactory.openSession();
ITransaction tx = session.BeginTransaction();
for ( int i=0; i<100000; i++ ) {
Customer customer = new Customer(.....);
session.Save(customer);
if ( i % 20 == 0 ) { //20, same as the ADO batch size
//Flush a batch of inserts and release memory:
session.Flush();
session.Clear();
}
}
tx.Commit();
session.Close();
The usual implementation of buffered communications uses circular buffers, and you manage them with modulus arithmetic.
For languages that don't have bitwise operators, modulus can be used to get the lowest n bits of a number. For example, to get the lowest 8 bits of x:
x % 256
which is equivalent to:
x & 255
Cryptography. That alone would account for an obscene percentage of modulus (I exaggerate, but you get the point).
Try the Wikipedia page too:
Modular arithmetic is referenced in number theory, group theory, ring theory, knot theory, abstract algebra, cryptography, computer science, chemistry and the visual and musical arts.
In my experience, any sufficiently advanced algorithm is probably going to touch on one more of the above topics.
Well, there are many perspectives you can look at it. If you are looking at it as a mathematical operation then it's just a modulo division. Even we don't need this as whatever % do, we can achieve using subtraction as well, but every programming language implement it in very optimized way.
And modulu division is not limited to finding odd and even numbers or clock arithmetic. There are hundreds of algorithms which need this module operation, for example, cryptography algorithms, etc. So it's a general mathematical operation like other +, -, *, /, etc.
Except the mathematical perspective, different languages use this symbol for defining built-in data structures, like in Perl %hash is used to show that the programmer declared a hash. So it all varies based on the programing language design.
So still there are a lot of other perspectives which one can do add to the list of use of %.