I'm trying to solve this problem:
We define objects called (p.q) numbers. In R the (p,q) numbers are lists with four elements. The first element of the list is either the integer +1+1 or the integer −1−1. It gives the sign of the number. The second and third element are p and q, each a non-negative integer. And the fourth element is a vector of p+q+1 integers between zero and nine.
Write a function which takes the four arguments sign, p, q, and nums. Then check if the arguments satisfy all requirements for a (p,q) number. If not, stop with an error message. If yes, return the (p.q) number as a list with attribute pqNumber using the structure() function.
Here's my code so far. I'm not sure what's wrong or what I need to do.
`pqNumber <- function(sign, p, q, nums) {
nums <- c()
if (sign != 1 && sign != -1) stop ("sign must be 1 or -1")
if (round != p) stop ("p must be an integer")
if (round != q) stop ("q must be an integer")
if (p < 0) stop ("p cannot be negative")
if (q < 0) stop ("q cannot be negative")
if (length(nums) != p + q + 1) stop ("nums must be a vector of p+q+1 integers")
structure(list(sign = sign, p = p, q = q, nums = nums), class = "pqNumber")
}`
Related
I'm trying to implement this algorithm to numerically compute pi.
n2 <- 100
k <- 0
for (k in 1:n2) {
x2 <- runif(n2, 0.0, 1.0)
y2 <- runif(n2, 0.0, 1.0)
if ((x2^2 + y2^2) < 1)
k <- k+1
return (4*k/n)
}
I get the message 'the condition has length > 1 and only the first element will be used' and i'm not sure where I'm making an error
Like was mentioned, n isn't defined which is why it will be breaking.
The reason you get the additional warning message:
"the condition has length > 1 and only the first element will be used"
Is in relation to your if() statement, as (x2^2 + y2^2) returns a vector of length 100 so only the first element is used in the comparison < 1.
You also don't use return statements in for loops.
Problem Statement: The Fibonacci word sequence of bit strings is defined as:
F(0) = 0, F(1) = 1
F(n − 1) + F(n − 2) if n ≥ 2
For example : F(2) = F(1) + F(0) = 10, F(3) = F(2) + F(1) = 101, etc.
Given a bit pattern p and a number n, how often does p occur in F(n)?
Input:
The first line of each test case contains the integer n (0 ≤ n ≤ 100). The second line contains the bit
pattern p. The pattern p is nonempty and has a length of at most 100 000 characters.
Output:
For each test case, display its case number followed by the number of occurrences of the bit pattern p in
F(n). Occurrences may overlap. The number of occurrences will be less than 2^63.
Sample input: 6 10 Sample output: Case 1: 5
I implemented a divide and conquer algorithm to solve this problem, based on the hints that I found on the internet: We can think of the process of going from F(n-1) to F(n) as a string replacement rule: every '1' becomes '10' and '0' becomes '1'. Here is my code:
#include <string>
#include <iostream>
using namespace std;
#define LL long long int
LL count = 0;
string F[40];
void find(LL n, char ch1,char ch2 ){//Find occurences of eiher "11" / "01" / "10" in F[n]
LL n1 = F[n].length();
for (int i = 0;i+1 <n1;++i){
if (F[n].at(i)==ch1&&F[n].at(i+1)==ch2) ++ count;
}
}
void find(char ch, LL n){
LL n1 = F[n].length();
for (int i = 0;i<n1;++i){
if (F[n].at(i)==ch) ++count;
}
}
void solve(string p, LL n){//Recursion
// cout << p << endl;
LL n1 = p.length();
if (n<=1&&n1>=2) return;//return if string pattern p's size is larger than F(n)
//When p's size is reduced to 2 or 1, it's small enough now that we can search for p directly in F(n)
if (n1<=2){
if (n1 == 2){
if (p=="00") return;//Return since there can't be two subsequent '0' in F(n) for any n
else find(n,p.at(0),p.at(1));
return;
}
if (n1 == 1){
if (p=="1") find('1',n);
else find('0',n);
return;
}
}
string p1, p2;//if the last character in p is 1, we can replace it with either '1' or '0'
//p1 stores the substring ending in '1' and p2 stores the substring ending in '0'
for (LL i = 0;i<n1;++i){//We replace every "10" with 1, "1" with 0.
if (p[i]=='1'){
if (p[i+1]=='0'&&(i+1)!= n1){
if (p[i+2]=='0'&&(i+2)!= n1) return;//Return if there are two subsequent '0'
p1.append("1");//Replace "10" with "1"
++i;
}
else {
p1.append("0");//Replace "1" with "0"
}
}
else {
if (p[i+1]=='0'&&(i+1)!= n1){//Return if there are two subsequent '0'
return;
}
p1.append("1");
}
}
solve(p1,n-1);
if (p[n1-1]=='1'){
p2 = p1;
p2.back() = '1';
solve(p2,n-1);
}
}
main(){
F[0] = "0";F[1] = "1";
for (int i = 2;i<38;++i){
F[i].append(F[i-1]);
F[i].append(F[i-2]);
}//precalculate F(0) to F(37)
LL t = 0;//NumofTestcases
int n; string p;
while (cin >> n >> p) {
count = 0;
solve(p,n);
cout << "Case " << ++t << ": " << count << endl;
}
}
The above program works fine, but with small inputs only. When i submitted the above program to codeforces i got an answer wrong because although i shortened the pattern string p and reduces n to n', the size of F[n'] is still very large (n'>=50). How can i modify my code to make it works in this case, or is there another approach (such as dynamic programming?). Many thanks for any advice.
More details about the problem can be found here: https://codeforces.com/group/Ir5CI6f3FD/contest/273369/problem/B
I don't have time now to try to code this up myself, but I have a suggested approach.
First, I should note, that while that hint you used is certainly accurate, I don't see any straightforward way to solve the problem. Perhaps the correct follow-up to that would be simpler than what I'm suggesting.
My approach:
Find the first two ns such that length(F(n)) >= length(pattern). Calculating these is a simple recursion. The important insight is that every subsequent value will start with one of these two values, and will also end with one of them. (This is true for all adjacent values -- for any m > n, F(m) will begin either with F(n) or with F(n - 1). It's not hard to see why.)
Calculate and cache the number of occurrences of the pattern in this these two Fs, but whatever index shifting technique makes sense.
For F(n+1) (and all subsequent values) calculate by adding together
The count for F(n)
The count for F(n - 1)
The count for those spanning both F(n) and F(n - 1). We can achieve that by testing every breakdown of pattern into (nonempty) prefix and suffix values (i.e., splitting at every internal index) and counting those where F(n) ends in prefix and F(n - 1) starts with suffix. But we don't have to have all of F(n) and F(n - 1) to do this. We just need the tail of F(n) and the head of F(n - 1) of the length of the pattern. So we don't need to calculate all of F(n). We just need to know which of those two initial values our current one ends with. But the start is always the predecessor, and the end oscillates between the previous two. It should be easy to keep track.
The time complexity then should be proportional to the product of n and the length of the pattern.
If I find time tomorrow, I'll see if I can code this up. But it won't be in C -- those years were short and long gone.
Collecting the list of prefix/suffix pairs can be done once ahead of time
To get another point (r) on the line that passes through point p in the direction v we can use the following formula, and substitute any value for a:
To test if r is on the line, we must only find a value for a that satisfies. In my current implementation, I check if a is the same for each component of the vectors by reorganizing the equation for r to:
In code terms, this looks like the following:
boolean isPointOnLine(Vector2f r, Vector2f p, Vector2f v) {
return (p.x - r.x) / v.x == (p.y - r.y) / v.y;
}
However, this method does not work: If any component of v is 0, the fraction will evaluate to infinity. Hence we get an incorrect result.
How do I check if r is on the line correctly?
In 3D you do the following:
If a point r=(x,y,z) is on the line with p=(px,py,pz) another point on the line and v=(vx,vy,vz) the direction calculate the following
CROSS(v,r-p)=0
or by component
(py-ry)*vz - (pz-rz)*vy==0
(pz-rz)*vx - (px-rx)*vz==0
(px-rx)*vy - (py-ry)*vx==0
For the 2D version, make all z-components zero
(px-rx)*vy - (py-ry)*vx == 0
No division needed, no edge cases and simple fast multiplication.
Of course due to round-off the result will be never be exactly zero. So what you need is a formula for the minimum distance, and a check if the distance is within some tolerance
d = ((px-rx)*vy-(py-ry)*vx)/sqrt(vx*vx+vy*vy) <= tol
It turns out that the equation I had was in fact correct, the division by 0 is just an edge case that must be handled beforehand. The final function looks like this:
boolean isPointOnLine(Vector2f r, Vector2f p, Vector2f v) {
if (v.x == 0) {
return r.x == p.x;
}
if (v.y == 0) {
return r.y == p.y;
}
return (p.x - r.x) / v.x == (p.y - r.y) / v.y;
}
Is it safe to replace a/(b*c) with a/b/c when using integer-division on positive integers a,b,c, or am I at risk losing information?
I did some random tests and couldn't find an example of a/(b*c) != a/b/c, so I'm pretty sure it's safe but not quite sure how to prove it.
Thank you.
Mathematics
As mathematical expressions, ⌊a/(bc)⌋ and ⌊⌊a/b⌋/c⌋ are equivalent whenever b is nonzero and c is a positive integer (and in particular for positive integers a, b, c). The standard reference for these sorts of things is the delightful book Concrete Mathematics: A Foundation for Computer Science by Graham, Knuth and Patashnik. In it, Chapter 3 is mostly on floors and ceilings, and this is proved on page 71 as a part of a far more general result:
In the 3.10 above, you can define x = a/b (mathematical, i.e. real division), and f(x) = x/c (exact division again), and plug those into the result on the left ⌊f(x)⌋ = ⌊f(⌊x⌋)⌋ (after verifying that the conditions on f hold here) to get ⌊a/(bc)⌋ on the LHS equal to ⌊⌊a/b⌋/c⌋ on the RHS.
If we don't want to rely on a reference in a book, we can prove ⌊a/(bc)⌋ = ⌊⌊a/b⌋/c⌋ directly using their methods. Note that with x = a/b (the real number), what we're trying to prove is that ⌊x/c⌋ = ⌊⌊x⌋/c⌋. So:
if x is an integer, then there is nothing to prove, as x = ⌊x⌋.
Otherwise, ⌊x⌋ < x, so ⌊x⌋/c < x/c which means that ⌊⌊x⌋/c⌋ ≤ ⌊x/c⌋. (We want to show it's equal.) Suppose, for the sake of contradiction, that ⌊⌊x⌋/c⌋ < ⌊x/c⌋ then there must be a number y such that ⌊x⌋ < y ≤ x and y/c = ⌊x/c⌋. (As we increase a number from ⌊x⌋ to x and consider division by c, somewhere we must hit the exact value ⌊x/c⌋.) But this means that y = c*⌊x/c⌋ is an integer between ⌊x⌋ and x, which is a contradiction!
This proves the result.
Programming
#include <stdio.h>
int main() {
unsigned int a = 142857;
unsigned int b = 65537;
unsigned int c = 65537;
printf("a/(b*c) = %d\n", a/(b*c));
printf("a/b/c = %d\n", a/b/c);
}
prints (with 32-bit integers),
a/(b*c) = 1
a/b/c = 0
(I used unsigned integers as overflow behaviour for them is well-defined, so the above output is guaranteed. With signed integers, overflow is undefined behaviour, so the program can in fact print (or do) anything, which only reinforces the point that the results can be different.)
But if you don't have overflow, then the values you get in your program are equal to their mathematical values (that is, a/(b*c) in your code is equal to the mathematical value ⌊a/(bc)⌋, and a/b/c in code is equal to the mathematical value ⌊⌊a/b⌋/c⌋), which we've proved are equal. So it is safe to replace a/(b*c) in code by a/b/c when b*c is small enough not to overflow.
While b*c could overflow (in C) for the original computation, a/b/c can't overflow, so we don't need to worry about overflow for the forward replacement a/(b*c) -> a/b/c. We would need to worry about it the other way around, though.
Let x = a/b/c. Then a/b == x*c + y for some y < c, and a == (x*c + y)*b + z for some z < b.
Thus, a == x*b*c + y*b + z. y*b + z is at most b*c-1, so x*b*c <= a <= (x+1)*b*c, and a/(b*c) == x.
Thus, a/b/c == a/(b*c), and replacing a/(b*c) by a/b/c is safe.
Nested floor division can be reordered as long as you keep track of your divisors and dividends.
#python3.x
x // m // n = x // (m * n)
#python2.x
x / m / n = x / (m * n)
Proof (sucks without LaTeX :( ) in python3.x:
Let k = x // m
then k - 1 < x / m <= k
and (k - 1) / n < x / (m * n) <= k / n
In addition, (x // m) // n = k // n
and because x // m <= x / m and (x // m) // n <= (x / m) // n
k // n <= x // (m * n)
Now, if k // n < x // (m * n)
then k / n < x / (m * n)
and this contradicts the above statement that x / (m * n) <= k / n
so if k // n <= x // (m * n) and k // n !< x // (m * n)
then k // n = x // (m * n)
and (x // m) // n = x // (m * n)
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions#Nested_divisions
I am trying to minimize an objective function that has three parameters: i, p, j like this:
param mlu{i in I, p in P, j in out[p]} := traffic[i,p]/capacity[j];
minimize MAXLU{i in I, p in P, j in out[p]}: mlu[i,p,j] * x[i,p,j];
but the objective function has to be greater than 0, otherwise it is defeating my purpose of minimization.
And I am trying to ensure this by adding a constraint on the objective function like this:
s.t. constraint1{i in I, p in P, j in out[p]} : MAXLU[i,p,j] != 0;
But I get the following error:
LP.mod:66: invalid reference to status, primal value, or dual value of objective MAXLU above solve statement
Context: i in I , p in P , j in out [ p ] } : MAXLU [ i , p , j ] !=
glp_mpl_generate: invalid call sequence
Error detected in file glpapi14.c at line 79
Aborted
Is it even possible to do this? Thank you for any help/suggestions!
You can refer to variables and parameters, but not objectives (MAXLU) in a constraint. A simple way to fix this is to replace MAXLU in constraint1 with the actual objective expression:
s.t. constraint1{i in I, p in P, j in out[p]} : mlu[i,p,j] * x[i,p,j] ...;
Moreover, you cannot define a constraint with expression != 0. You can have >= epsilon or <= epsilon instead where epsilon is a small number:
s.t. constraint1{i in I, p in P, j in out[p]} : mlu[i,p,j] * x[i,p,j] >= epsilon;