如何解决检查两个向量是否是子集
我正在尝试检查{1,...,M}中是否存在整数i,以使a_i = 1和b_i = 0,而在{1,...,M}中是否存在整数j,以使b_j = 1且a_j =0。如果成立,则输出1(无与伦比);否则,输出0(它们是可比较的)。
我尝试过:
a<-c(1,1,0)
b<-c(1,1)
M<-length(a)
incomparable<-function(M,a,b)
{
for(i in 1:M){
for(j in 1:M){
if(a[i]!=b[i] && b[j]!=a[j]) {
print (1)
}
else {
print(0)
}
}
}
}
incomparable(M,b)
> incomparable(M,b)
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 1
[1] 1
[1] 0
[1] 0
[1] 1
[1] 1
我需要的只是0或1作为输出。如何修复我的代码?
解决方法
我相信这适用于您描述的条件。
incomparable <- function(a,b){
cond1 <- sum(a>b) > 0 # Returns true is if there is at least one case such that a_i is 1 and b_i is 0
cond2 <- sum(b>a) > 0 # True if at least one case such that one case with b_i is 1 and a_i is 0
cond1*cond2
}
##### Check a case where they are incomparable vectors
a<-c(1,1,0)
b<-c(1,0)
incomparable(a,b)
[1] 1
##### Check case where a = b
a<-c(1,1)
b<-c(1,1)
incomparable(a,b)
[1] 0
#### Case where a \subset b
a<-c(1,1)
incomparable(a,b)
[1] 0
### Case where b \subset a
a<-c(1,b)
[1] 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。