我需要一个在给定7时可以返回5的函数,并且在给定5时可以返回7.但是不允许使用条件语句。 我需要通过10种不同的技术(所有这些都没有条件语句)。
但是,我已经用5种不同的方式实施了。如果你帮我写其他5,那将是一种乐趣:)
int returner( int input ) {
return 12 - input;
}
int returner( int input ) {
if(input != 0) {
return 35 / input;
}
return 0;
}
int returner( int input ) {
return input ^= 2;
}
int returner( int intput ) {
return ( 7 % input ) + 5;
}
最后,在红宝石中
def returner(input)
return ([5,7]-[input]).pop
end
答案 0 :(得分:2)
这是另外5个:
p RUBY_VERSION
require 'set'
def fun1(x)
[5,7].to_set.delete(x).to_a[0]
end
p fun1(7)
def fun2(x)
a = [5,7].to_set
b = [x].to_set
p a.difference(b).to_a[0]
end
fun2(5)
def fun3(x)
a = [5,7]
a.slice!(a.index(x),1)
p a[0]
end
fun3(5)
def fun4(x)
a = [5,7]
a.delete(x)
p a[0]
end
fun4(5)
def fun5(x)
a = '57'
a = a.rpartition(7.to_s)
p a[a.index(7.to_s)].to_i
end
fun5(7)
输出:
"2.0.0"
5
7
7
7
5
答案 1 :(得分:2)
我不认为这是一个很好的问题,但我认为这里有机会学习一些不同的想法。 i
代表输入。尝试以下i=7
,然后“其他任何”作为输入。请注意,这些方法都不会对输入值使用数学。
注意:这些将需要调整以返回逆 - 这是一个练习。
散列。默认情况下,失败的查找返回nil
。可以使用Hash.new
指定默认值。
h = {7: 5}
h[i] // 5 or nil
h = Hash.new(0)
h[7] = 5
h[i] // 5 or 0
Array枚举方法 - 学习它们。这里我们只计算特定值(7)的元素数量。
a = [7,7,7,7,7]
a.grep {|x| x == i }.count // 0 or 5
// or more idiomatic
a.count(i)
布尔运算符链接 - &&
和||
的结果是成功表达式或“最少失败”表达式。
i == 7 && 5 // false or 5
(i == 7 && 5) || 0 // 0 or 5
throw/catch和内联异常填充的反常使用。
catch (:"7") do
throw i.to_s.to_sym rescue nil;
// only here if i is not 7 or convertible to "7" AND
// there is no matching catch further up
return 0
end
return 5
在类似的说明中,如何在没有if
的情况下重写除法示例。当然,如果函数域只是 {5,7},那么即使这不是必需的,因为0永远不会是[有效]输入 - 并且无效输入超出了方法契约。
return (35 / i rescue 0)
答案 2 :(得分:1)
我可以使用逻辑运算符及其排序电路行为提供另外两种方法:
首先,它的myown:
int r(char x){
(x == 7 && (x=5)) || ( (x == 5) && (x=7));
return x;
}
int main(){
printf("\n If r(5) then return = %d", r(5));
printf("\n If r(7) then return = %d", r(7));
printf("\n");
return 1;
}
运行:
$ ./a.out
If r(5) then return = 7
If r(7) then return = 5
第二,有些日子我看到了这个伎俩:
int r(char x){
int l[8] = {0,0,0,0,0,7,0,5};
return l[x];
}
第三次:我在第一次
中使用的技巧int r(char x){
(x > 5 && (x=5)) || (x < 7 && (x=7));
return x;
}
<强>四强>:
int r(char x){
((x & 2) && (x&=~2)) || ( (!(x & 2)) && (x|=2));
return x;
}
五十:您自己的XOR
int r(int x){
x = (x & ~2) | (~x & 2) ;
return x;
}