Algorithm for detection of overlaping between vectors [duplicate] - vector

This question already has answers here:
How do you detect where two line segments intersect? [closed]
(27 answers)
Closed 8 years ago.
I am currently developing a math-physics program and I need to calculate if two vectors overlap one another, the one is vertical and the other is horizontral. Is there any fast algorithm to do this because what I came up so far, has a lot of repeats. Eg lets say we have vector V1((0,1),(2,1)) and a V2((1,0),(1,2)) where the first parenthesis is the coordinates starting and the second coordinates that the vector reaches. I want as a result to take that they overlap at (1,1)
So far the only idea I came up is to ''expand'' each vector to a list of points and then compare the lists
e.g for V1 its list would be (0,1) (1,1) (2,1)

Something like this? (V1 is always the horizontal vector and the coordinates are ordered, i.e. V1.x0 < V1.x1 and V2.y0 < V2.y1):
func intersection( V1, V2 )
if v1.x0 <= v2.x0 and v1.x1 >= v2.x0 and
v2.y0 <= v1.y0 and v2.y1 >= v1.y0 then
return ( V2.x0, V1.y0 );
else
return NO_INTERSECTION;
end if
end func

Related

How to substract list elements of the same list in R? [duplicate]

This question already has answers here:
Difference between neighbouring elements of a vector
(2 answers)
What does the diff() function in R do? [closed]
(2 answers)
Closed 2 years ago.
I have a list like this:
anteilSelbststaendige <- ((100/input$bevoelkerung) * input$selbststaendige)
anteilSelbststaendige
[1] 5.460547 5.551961 5.561330 5.474761 5.460763 5.455431 5.467829 5.409999 5.356277 5.159937 4.990305 4.915012 4.882196
[14] 4.860807 4.855824 4.826342 4.768927 4.719400 4.660732 4.615460 4.527033 4.486686 4.455891 4.908780 4.964310 4.973149
[27] 5.011707 5.050273 5.016059 5.000409 4.976963 5.014764 5.064687 5.122957 5.163057 5.284785 5.368078 5.566300 5.816041
[40] 6.028620 6.257261 6.434038 6.676781 7.157343
and I want to know the difference between the value and the following value. (For all values of the list) Like this:
anteilSelbststaendigeV <- anteilSelbststaendige[2] - anteilSelbststaendige[1]
The result should be a list of the differences of the next following values.
I tried "for" loops, but it doesn't work and I don't know why.
I'm new to R and don't really know what functions there are and what to do.
We can use diff to get the difference between the current and next value
anteilSelbststaendigeV <- c(NA, diff(anteilSelbststaendig))
NOTE: Based on the data structure showed, it is a vector and not a list

R: select region on matrix

Assume X is a 5x5 matrix (which represents pixel luminosity from a picture):
I would like to select the element that fit within a given simple geometrical shape (e.g. square, circle, ovale) superposed to this matrix. In this example I would like to select the elements from the matrix that fall (even slightly) within the ovale.
Ultimately those elements position would be return into a vector logical vector elementInOvale on which I could perform a simple operation such as X[elementInOvale] <- 0
I have the feeling that this is a common problem which has already been solved, I just don't know how to formulate or where to find information about it, and to do with R.

Q-Learning in R: Updating a matrix based on the adjacency of two cells in another matrix using nested loops

my first question on Stack Overflow.
I'm trying to update a 25x25 matrix representing states in a 5x5 grid. The rows represent current states, columns represent the next state. I'm using a formula given below to assess the adjacency of a given state to another given state by their coordinates. The aim is to then use those coordinates to update the 25x25 state matrix with 1's where moving from one numbered state in the 5x5 grid to it's adjacent state is possible.
|x1−x2|≤1 and |y1−y2|≤1
No errors, and only the T[25,25] element is updating. Any ideas why this isn't working properly?
T = matrix(c(1:25),nrow=5,ncol=5, byrow=T)
S = matrix(0,nrow=25,ncol=25)
for (i in nrow(T)){
for (j in ncol(T)){
for (f in nrow(T)){
for (g in ncol(T)){
if ((abs(i-f) <= 1) & (abs(j-g) <= 1)){
S[T[i,j], T[f,g]] = 1
}}}}}

R code for simulation of a of setup for picking tiles from a bag

The problem is there is box with 5 tiles numbered 1,2,3,4,5. I pick 2 tiles note the numbers and drop the tiles in the bag. And then I pick 2 tiles again and note the numbers. What is probability that there is no overlap between the numbers? Say got 1,4 the first time and then the second time I get 3,5. No overlap. The theoretical result is 3/10. But this simulation is keeps giving me an answer close to 0.5. Any insights about what I am doing wrong? Could it be sample function in R ?
I make a matrix with all possible pairs you could get with 5 tiles 1,2 1,3 etc and then generate two random numbers which give the row numbers. I assume these are the two draws of numbers and see if they are equal.
set.seed(1234)
n=10000
count=0
t<-cbind(c(1,1,1,1,2,2,2,3,3,4),c(2,3,4,5,3,4,5,4,5,5))
idx<-sample(1:10,2*n,replace=T)
i<-idx[1:n]
j<-idx[(n+1):(2*n)]
for( ii in 1:n) {
if( (t[i[ii],1] != t[j[ii],1]) && (t[i[ii],2] != t[j[ii],2]))
count=count+1
}
count/n
[1] 0.5004
Any insights will be helpful. I am sure the theoretical answer is 3/10
It's been awhile since I've used R so apologies if I'm a little rusty. Seems to me you're almost there. The problem is in your if statement within the for loop. You're testing whether the first number in the first pair is different from the first number in the second pair AND the second number in the first pair is different from the second number in the second pair. But you're forgetting about whether the first number in the first pair is different from the second number in the second pair AND the second number in the first pair is different from the first number in the second pair. Here's the full line:
if(
(t[i[ii],1] != t[j[ii],1]) &&
(t[i[ii],2] != t[j[ii],2]) &&
(t[i[ii],1] != t[j[ii],2]) &&
(t[i[ii],2] != t[j[ii],1])
) count=count+1
There might be other ways to accomplish this, but this seems to do the trick. I get about 0.3 for the result. And thanks for the opportunity to think about R again.
I would not use a loop. 10000 observations is not big enough to prevent you from building a data.frame with your samples. In the following code, I take samples twice and put it in a 10000 rows by 4 column object. I then identify which rows have duplicated picks. I then divide by your total number. The 1- is there because the code counts duplicateds. My result is in line with the theoretical number.
n <-10000
res <-cbind(t(replicate(n,sample(1:5,2,replace=FALSE))),t(replicate(n,sample(1:5,2,replace=FALSE))))
1-sum(apply(apply(res, 1, duplicated),2,any))/n
#[1] 0.2979

Completing a list of possible binary sequences give a binary sequence with gaps

So, I am working on a program in Scilab which solves a binary puzzle. I have come across a problem however. Can anyone explain to me the logic behind solving a binary sequence with gaps (like [1 0 -1 0 -1 1 -1] where -1 means an empty cell. I want all possible solutions of a given sequence. So far I have:
function P = mogelijkeCombos(V)
for i=1:size(V,1)
if(V(i) == -1)
aantalleeg = aantalleeg +1
end
end
for i=1:2^aantalleeg
//creating combos here
end
endfunction
sorry that some words are in dutch
aantalleeg means amountempty by which I mean the amount of empty cells
I hope I gave you guys enough info. I don't need any code written, I'd just like ideas of how I can make every possible rendition as I am completely stuck atm.
BTW this is a school assignment, but the assignment is way bigger than this and it's just a tiny part I need some ideas on
ty in advance
Short answer
You could create the combos by extending your code and create all possible binary words of the length "amountempty" and replacing them bit-for-bit in the empty cells of V.
Step-by-step description
Find all the empty cell positions
Count the number of positions you've found (which equals the number of empty cells)
Create all possible binary numbers with the length of your count
For each binary number you generate, place the bits in the empty cells
print out / store the possible sequence with the filled in bits
Example
Find all the empty cell positions
You could for example check from left-to-right starting at 1 and if a cell is empty add the position to your position list.
V = [1 0 -1 0 -1 1 -1]
^ ^ ^
| | |
1 2 3 4 5 6 7
// result
positions = [3 5 7]
Count the number of positions you've found
//result
amountempty = 3;
Create all possible binary numbers with the length amountempty
You could create all possible numbers or words with the dec2bin function in SciLab. The number of possible words is easy to determine because you know how much separate values can be represented by a word of amountempty bits long.
// Create the binary word of amountEmpty bits long
binaryWord = dec2bin( i, amountEmpty );
The binaryWord generated will be a string, you will have to split it into separate bits and convert it to numbers.
For each binaryWord you generate
Now create a possible solution by starting with the original V and fill in every empty cell at the position from your position list with a bit from binaryWordPerBit
possibleSequence = V;
for j=1:amountEmpty
possibleSequence( positions(j) ) = binaryWordPerBit(j);
end
I wish you "veel succes met je opdracht"

Resources