简化问题是,我想找到一个分配,DEFG/ABC=9
A,B,C,D,E,F,G
所有的分配都不同。
我该怎么写
a!=b!=c!=d!=e!=f!=g"
在R?
我的尝试:
for(a in 1:9){
for(b in 1:9){
for(c in 1:9){
for(d in 1:9){
for(e in 1:9){
for(f in 1:9){
for(g in 1:9){
if(((a+10*b+100*c)/(d+e*10+f*100+g*1000))==9 && a!=b!=c!=d!=e!=f!=g)
print(c(a,b,c,d,e,f,g))
#error: unexpected '!=' in:
提前谢谢
答案 0 :(得分:4)
!anyDuplicated(c(a, b, c, d, e, f, g))
如果所有值都是唯一的,则返回TRUE
。
答案 1 :(得分:1)
也许:
a <- 1; b <- 2; c <- 3;
vars <- c(a,b,c)
all(combn(vars,2,FUN=function(x) x[1] != x[2] ))
#[1] TRUE
有一个失败的例子:
a <- 1; b <- 1; c <- 3;
vars <- c(a,b,c)
all(combn(vars,2,FUN=function(x) x[1] != x[2] ))
#[1] FALSE
答案 2 :(得分:0)
每对变量都需要形成自己的条件,需要通过&
(对于矢量化)或&&
## Parens added for clarity, but not needed
(a != b) & (b != c) & (a != c)
然而,看起来你期望整数,或者至少是实数,在这种情况下,你可以使用像
这样的东西 vars <- c(a, b, c, d, e, f, g)
any(vars != mean(vars))
# Since any one of the value being different from the group average
# indicates that they are all different
如果你想要所有唯一值(而不是“不是所有相同的值”),你可以使用
保存自己很多次迭代 for(a in 1:9) {
for(b in setdiff(1:9, a)) {
for(c in setdiff(1:9, c(a, b)) {
for(d in setdiff(1:9, c(a, b, c)) {
etc ...
答案 3 :(得分:0)
尝试:
ss = c(a,b,c,d,e,f,g)
for(i in 1:7) for(j in 1:7)if (i!=j) if(ss[i]==ss[j])
{ notgood=TRUE; break}
但三位数除以四位数如何才能等于9? (这里没有使用0)。
以下代码可用于生成此类4位和3位数字:
> ss = sample(0:9, 7)
> while(TRUE){
+ num1 = (ss[4]+10*ss[3]+100*ss[2]+1000*ss[1])
+ num2 = (ss[7]+10*ss[6]+100*ss[5])
+ if((num1/num2) == 9 ) cat('\nFound: ',num1,' and ',num2)
+ ss = sample(0:9, 7)
+ }
Found: 8523 and 947
Found: 8253 and 917
Found: 6489 and 721
Found: 4761 and 529
Found: 5481 and 609
Found: 4608 and 512
Found: 6489 and 721
Found: 3789 and 421
Found: 2781 and 309
Found: 2781 and 309
Found: 5742 and 638
Found: 8613 and 957
Found: 3762 and 418
Found: 5742 and 638
Found: 3762 and 418
Found: 8523 and 947
Found: 8523 and 947
Found: 5823 and 647
Found: 8253 and 917
Found: 1854 and 206
Found: 3762 and 418
Found: 7254 and 806
Found: 7326 and 814
...