Bspline Basis Function In C - c

I am trying to calculate Bspline Curves with the given Control Points. I've researched about Bplsines and the Bspline I am trying to draw is Uniform Quadratic Bspline. But I am not sure if i get it correct. Please help me with my confusion. If I am right the degree of the every single bspline curve is under my decision. So I want them to be quadratic. And the number of knots depends on the number of control points.
(number of knots = number of control points - 2).Because every single control polygon will be including three control points. The function I am calculating the knot vector is:
for(int i = 0; i < numOfPoints-2; i++)
{
if(1<=i && i <= k)
knotArray[i] = 0;
else if(k + 1 <= i && i <= n + 1)
knotArray[i] = i-k;
else if(n + 2 <= i && i <= n + k + 1)
knotArray[i] = n - k + 2;
}
I don't know if this is correct. According the documention I read, the formula for calculating the knot vector is something like this.
And the method I am using for calculating the basis function is:
t: funciton parameter
i: the basis function I am calculating
k: (degree of the curve) + 1. (in this case it is 3 at the beginning)
x[]: knot vector
float N(float t, float i, float k, float x[])
{
if(k == 1) //k = n + 1 (n is the degree of the curve)
{
if(x[i] <= t && t <= x[i+1])
return 1;
else
return 0;
}
return (t - x[i] / x[i+k-1] - x[i]) * N(t, i, k-1, x) + (x[i+k] - t / x[i+k] - x[i+1])* N(t, i+1, k-1, x);
}
It doesn't even compile the code and I am looking for the bug atleast 3 hours.
If someone patient can teach me the basics of the Bspline Curve, i will be very thankful.

Related

Find the frequency of number repeates (r-l+1)/2 times in range [l:r]

Given the array: A[N]. There are some queries including Li and Ri. We must Find the number that appears more than (Ri-Li+1)/2 times in range [Li:Ri].
For example:
INPUT:
N=7
1 1 3 2 3 4 3
OUTPUT:
Ranges:
[1:3] ans is :>1
[1:4] no answer
[1:7] ans is :>3
[2:7] no answer
First, I think we can use map to store the times that A[i] appears from 1 to j
And it's take up a lot of memories if N up to 5e5.
Then I sort(Increasing order) the queries so that Ri, and no more idea.
Suggestions:
Is there any efficient algorithm to this problem or any data structure to stores the frequency of A[i]: from 1 to j?
I have no idea about such data structure, but I find an solution for this problem.
If Ri - Li + 1 is odd, there may have two elements appear (Ri - Li + 1) / 2 times. Which one do you want to get? We can use the algorithm beblow to get one of them and the algorithm can get all of these two if you want.
If there are just few queries satisfy \sum (Ri - Li) are small enough, get the answer for each [Li, Ri] separately.
For each [Li, Ri],we can use a O(Ri - Li) time, O(1) auxiliary memory algorithm to get the answer. If there is a x appears exactly (Ri - Li + 1) / 2 times, at least one of three case below must happend (suppose Ri > Li).
x appears (Ri - Li + 1) / 2 times in [Li, Ri - 1].
x appears (Ri - Li + 1) / 2 times in [Li + 1, Ri].
A[Li] == A[Ri] == x.
For case 1,2 we can use 'Heavy Hitters' algorithm to find the candidate x.
So can get three candidate x for one travese, and check each of them to find the answer(see cpp code below).
int getCandidateX(int L, int R) {
int x = A[L], count = 1;
for(int i = L + 1; i <= R; ++i){
if(A[i] == x) ++count;
else if(--count == 0){
x = A[i];
count = 1;
}
}
return x;
}
int getFrequency(int L, int R, int x) {
int count = 0;
for(int i = L; i <= R; ++i) {
if(A[i] == x) ++count;
}
return count;
}
/**
* if Ri == Li, no answer
* suppose Ri > Li
* return {x, 0} and {-1,-1} if no such element
*/
pair<int,int> getAnswer(int Li, int Ri) {
int t = (Ri - Li + 1) / 2;
int x;
if((Ri - Li) & 1) {
x = getCandidateX(Li, Ri);
if(getFrequency(Li, Ri, x) == t) return {x, 0};
return {-1, -1}
}
x = getCandidateX(Li, Ri - 1);
if(getFrequency(Li, Ri, x) == t) return {x, 0};
x = getCandidateX(Li + 1, Ri);
if(getFrequency(Li, Ri, x) == t) return {x, 0};
if(A[Li] == A[Ri] && getFrequency(Li, Ri, A[Li]) == t)
return {Li, 0};
return {-1,-1}
}
When \sum (Ri - Li) is large, I found an O((m + n)logn) online solution, but it also cost a lot of memory. I conduct it as a RMQ(Range Maximum Query) problem and solve it by ST(sparse table) algorithm.
First, we can get the frequency in [L, R] of any x with O(logn) time.
We can store all the position of x in map[x] where map maps x to its position array.(we can use treemap or hashmap)
Then we can get the frequency of x in [L, R] by binary search which cost O(logn) time.
Define num[L][R] be a set of elements appear more than (R - L + 1) / 4 times in interavl [L,R]. Let val[i][k] = num[L][L + 2^k - 1], k >= 2.
Every val[i][k] has at most 4 elements, and we can calculate all val[i][k] for 0 <= i <= n and i + 2^k <= n in O(nlogn) time and O(nlogn) memory.
Because for every interval [L,R] and M1, M2 such that L <= M < R it is obvious to see that num[L][R] \subset num[L][M] \cup num[M + 1][R]. Then val[i][k] \subset val[i][k - 1] \cup val[i + 2^{k - 1} - 1][k - 1]`.
Let t as the greatest number such that 2^t <= R - L + 1 we can draw a conclusion that if x \in [L,R] appears not less than (R - L + 1) / 2 times,x must in val[L][t] or val[R - 2^t + 1][R]。
This means it is sufficient to check the frequency of every element in val[L][t] \cup val[R - 2^t - 1][t].
For every query [L,R] we can check every element in O(logn) time, so the total time is O((m + n)logn) where n is the element number of A and m is the query number.
If the question is to get the element appears exactly (Ri-Li+1)/2 + 1 times (or more), it can be solve in a more simply way.

How does run time for quick select, comes out to be, CN = 2 N + 2 k ln (N / k) + 2 (N – k) ln (N / (N – k))?

When selecting the kth, largest element from a unsorted array, the run time comes out to be CN = 2 N + 2 k ln (N / k) + 2 (N – k) ln (N / (N – k)) (preposition taken from ALgorithms1 by Prof Robert Sedgewick). The implementation is a randomized quick select.
public static Comparable select(Comparable[] a, int k)
{
StdRandom.shuffle(a);
int lo = 0, hi = a.length - 1;
while (hi > lo)
{
int j = partition(a, lo, hi);
if (j < k) lo = j + 1;
else if (j > k) hi = j - 1;
else return a[k];
}
return a[k];
}
The partition subroutine is the quick sort partition implementation where the lo element is used as pivot to partition. shown below
private static int partition(Comparable[] a, int lo, int hi)
{
int i = lo, j = hi+1;
while (true)
{
while (less(a[++i], a[lo]))
if (i == hi) break;
while (less(a[lo], a[--j]))
if (j == lo) break;
if (i >= j) break;
exch(a, i, j);
}
exch(a, lo, j);
return j;
}
I see the run time for partition would be (N+1), and speculating the distribution is shuffled and each run would decrease the array to half the recurrence would come out to be (N+N/2+N/4..) so O(N) time can be assumed. This being a very optimistic scenario.
More likely the distribution can be slpit into halfs such as (C0,Cn-1) or (c1, cn-2)..probability of each being 1/n times. Now depending upon the k from either of the above split left side or right side could be selected. (That is either c0 or cn-1 if first case ocurred, with probability of 1/2N). Now cn would be changed to new length and the same steps would be repeated until j==k.
Could someone help in deriving the recurrence relation and the limits it would run under, and ultimately come to the above equation of Cn.
Note:- i see others answers on SO but they consider the rosy picture of splitting into half, which is very unlikely to happen. like this one Average Runtime of Quickselect

Nested loops for creating a spiral shape pattern in c

I need to make a spiral pattern made of stars '*' using nested for loops. I managed to make outter lines, now I don't know how to repeat smaller swirls in the same place.
What I should have:
*********
*
******* *
* * *
* *** * *
* * * *
* ***** *
* *
*********
Any help would be greatly appreciated.
After being thoroughly nerd-sniped, I came up with this:
#include <stdio.h>
void print_spiral(int size)
{
for (int y = 0; y < size; ++y)
{
for (int x = 0; x < size; ++x)
{
// reflect (x, y) to the top left quadrant as (a, b)
int a = x;
int b = y;
if (a >= size / 2) a = size - a - 1;
if (b >= size / 2) b = size - b - 1;
// calculate distance from center ring
int u = abs(a - size / 2);
int v = abs(b - size / 2);
int d = u > v ? u : v;
int L = size / 2;
if (size % 4 == 0) L--;
// fix the top-left-to-bottom-right diagonal
if (y == x + 1 && y <= L) d++;
printf((d + size / 2) % 2 == 0 ? "X" : " ");
}
printf("\n");
}
}
As others mentioned, it might be more intuitive to allocate an array representing the grid, and draw the spiral into the array (within which you can move freely), then print the array. But, this solution uses O(1) memory.
It could almost certainly be optimized and simplified a bit, but I'll "leave that as an exercise for the reader" as I've already spent too much time on this ;-)
Update
I'm not going to spend any more time on this, but I had an idea for a second attempt that might result in simpler code. If you check the output at increasingly large sizes, a pattern emerges:
Within each quadrant, the pattern is regular and can be easily coded. I think you would just have to carefully classify the (x, y) coordinates into one of the four quadrants and then apply the appropriate pattern.
The most sensible approach is to create a 2d array, then fill it with the * that you want.
Alternatively, you can try to come up with some "just in time" logic to avoid a buffer. This is more complicated.
I came up with an approach by thinking of the spiral as four different triangles that form a square. Here I have printed "a,b,c,d" for each of the four triangles to show what I mean:
aaaaaaaaaac
c
baaaaaac c
b c c
b baac c c
b b dd c c
b b c c
b dddddd c
b c
dddddddddd
There are two tricky parts to this. One is to align the diagonals correctly. Not so hard with with trial and error. The other tricky party is that not all squares divide into alternating lines the same way. You can see in the example above a square n=11, the left side is shifted by one. Perhaps there is a better solution, but this attempts to create alternating rows and columns.
n = 11;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// top
if (j > i - 2 && j < n - i && i % 2 == (n&1)) printf("a");
// left
else if (j < i - 1 && j < n - i && j % 2 == (n & 1)) printf("b");
// right
else if (j > n - i -1&& j > i && j % 2 == ((n+1) & 1)) printf("c");
// bottom
else if (j < i + 1 && j > n - i - 1 && i % 2 == ((n + 1) & 1)) printf("d");
else printf(" ");
}
printf("\n");
}
I would recommend taking a look at the NCurses library. It contains many methods for moving the cursor in the terminal window, such as mvaddch() and curs_set().
Here is a document that contains everything you'd need to know on how to use NCurses.
However, if you don't want to use external libraries, then you could define a 2D array of ints or bools and then print a * where an index is 1 or true, respectively.
Example of the latter:
#include <stdbool.h> //You need to include this header file if you want to use 'bool's
...
//Using a 10x10 array for this example
bool stars[10][10] = { /* initialize the 2D array here */ };
...
//Get the length of a row
int rowLength = (sizeof stars[0]) / (sizeof stars[0][0]);
//Get the amount of rows
int rowAmount = (sizeof stars) / (sizeof stars[0]));
//Print the spiral using the array "stars"
for(int r = 0; r < rowAmount; r++){
for(int c = 0; c < rowLength; c++){
if(stars[r][c])
printf("*");
else
printf(" ");
}
printf("\n");
}
...

C Language - General algorithm to read a square matrix, based on the square number of it's side?

So we're reading a matrix and saving it in an array sequentially. We read the matrix from a starting [x,y] point which is provided. Here's an example of some code I wrote to get the values of [x-1,y] [x+1,y] [x,y-1] [x,y+1], which is a cross.
for(i = 0, n = -1, m = 0, array_pos = 0; i < 4; i++, n++, array_pos++) {
if(x+n < filter_matrix.src.columns && x+n >= 0 )
if(y+m < filter_matrix.src.lines && y+m >= 0){
for(k = 0; k < numpixels; k++) {
arrayToProcess[array_pos].rgb[h] = filter_matrix.src.points[x+n][y+m].rgb[h];
}
}
m = n;
m++;
}
(The if's are meant to avoid reading null positions, since it's an image we're reading the origin pixel can be located in a corner. Not relevant to the issue here.)
Now is there a similar generic algorithm which can read ALL the elements around as a square (not just a cross) based on a single parameter, which is the size of the square's side squared?
If it helps, the only values we're dealing with are 9, 25 and 49 (a 3x3 5x5 and 7x7 square).
Here is a generalized code for reading the square centered at (x,y) of size n
int startx = x-n/2;
int starty = y-n/2;
for(int u=0;u<n;u++) {
for(int v=0;v<n;v++) {
int i = startx + u;
int j = starty + v;
if(i>=0 && j>=0 && i<N && j<M) {
printf(Matrix[i][j]);
}
}
}
Explanation: Start from top left value which is (x - n/2, y-n/2) now consider that you are read a normal square matrix from where i and j are indices of Matrix[i][j]. So we just added startx & starty to shift the matrix at (0,0) to (x-n/2,y-n/2).
Given:
static inline int min(int x, int y) { return (x < y) ? x : y; }
static inline int max(int x, int y) { return (x > y) ? x : y; }
or equivalent macros, and given that:
the x-coordinates range from 0 to x_max (inclusive),
the y-coordinates range from 0 to y_max (inclusive),
the centre of the square (x,y) is within the bounds,
the square you are creating has sides of (2 * size + 1) (so size is 1, 2, or 3 for the 3x3, 5x5, and 7x7 cases; or if you prefer to have sq_side = one of 3, 5, 7, then size = sq_side / 2),
the integer types are all signed (so x - size can produce a negative value; if they're unsigned, you will get the wrong result using the expressions shown),
then you can ensure that you are within bounds by setting:
x_lo = max(x - size, 0);
x_hi = min(x + size, x_max);
y_lo = max(y - size, 0);
y_hi = min(y + size, y_max);
for (x_pos = x_lo; x_pos <= x_hi; x_pos++)
{
for (y_pos = y_lo; y_pos <= y_hi; y_pos++)
{
// Process the data at array[x_pos][y_pos]
}
}
Basically, the initial assignments determine the bounds of the the array from [x-size][y-size] to [x+size][y+size], but bounded by 0 on the low side and the maximum sizes on the high end. Then scan over the relevant rectangular (usually square) sub-section of the matrix. Note that this determines the valid ranges once, outside the loops, rather than repeatedly within the loops.
If the integer types are signed, you have ensure you never try to create a negative number during subtraction. The expressions could be rewritten as:
x_lo = x - min(x, size);
x_hi = min(x + size, x_max);
y_lo = y - min(y, size);
y_hi = min(y + size, y_max);
which isn't as symmetric but only uses the min function.
Given the coordinates (x,y), you first need to find the surrounding elements. You can do that with a double for loop, like this:
for (int i = x-1; i <= x+1; i++) {
for (int j = y-1; j <= y+1; j++) {
int elem = square[i][j];
}
}
Now you just need to do a bit of work to make sure that 0 <= i,j < n, where n is the length of a side;
I don't know whether the (X,Y) in your code is the center of the square. I assume it is.
If the side of the square is odd. generate the coordinates of the points on the square. I assume the center is (0,0). Then the points on the squares are
(-side/2, [-side/2,side/2 - 1]); ([-side/2 + 1,side/2], -side/2); (side/2,[side/2 - 1,-side/2]);([side/2 - 1, side/2],-side/2);
side is the length of the square
make use of this:
while(int i<=0 && int j<=0)
for (i = x-1; i <= x+1; i++) {
for (j = y-1; j <= y+1; j++) {
int elem = square[i][j];
}
}
}

Progressive loop through pairs of increasing integers

Suppose one wanted to search for pairs of integers x and y a that satisfy some equation, such as (off the top of my head) 7 x^2 + x y - 3 y^2 = 5
(I know there are quite efficient methods for finding integer solutions to quadratics like that; but this is irrelevant for the purpose of the present question.)
The obvious approach is to use a simple double loop "for x = -max to max; for y = -max to max { blah}" But to allow the search to be stopped and resumed, a more convenient approach, picturing the possible integers of x and y as a square lattice of points in the plane, is to work round a "square spiral" outward from the origin, starting and stopping at (say) the top right corner.
So basically, I am asking for a simple and sound "pseudo-code" for the loops to start and stop this process at points (m, m) and (n, n) respectively.
For extra kudos, if the reader is inclined, I suggest also providing the loops if one of x can be assumed non-negative, or if both can be assumed non-negative. This is probably somewhat easier, especially the second.
I could whump this up myself without much difficulty, but am interested in seeing neat ideas of others.
This would make quite a good "constructive" interview challenge for those dreaded interviewers who like to torture candidates with white boards ;-)
def enumerateIntegerPairs(fromRadius, toRadius):
for radius in range(fromRadius, toRadius + 1):
if radius == 0: yield (0, 0)
for x in range(-radius, radius): yield (x, radius)
for y in range(-radius, radius): yield (radius, -y)
for x in range(-radius, radius): yield (-x, -radius)
for y in range(-radius, radius): yield (-radius, y)
Here is a straightforward implementation (also on ideone):
void turn(int *dr, int *dc) {
int tmp = *dc;
*dc = -*dr;
*dr = tmp;
}
int main(void) {
int N = 3;
int r = 0, c = 0;
int sz = 0;
int dr = 1, dc = 0, cnt = 0;
while (r != N+1 && c != N+1) {
printf("%d %d\n", r, c);
if (cnt == sz) {
turn(&dr, &dc);
cnt = 0;
if (dr == 0 && dc == -1) {
r++;
c++;
sz += 2;
}
}
cnt++;
r += dr;
c += dc;
}
return 0;
}
The key in the implementation is the turn function, that performs the right turn given a pair of {delta-Row, delta-Col}. The rest is straightforward arithmetic.

Resources