三维建模软件主要使用紫外测图将纹理映射到三维对象上。U和V的有效值通常位于一个包含[0..1]的范围内。
你买了一个新的三维建模软件,这是超级容易使用。然而,它有一个问题:它从UV值中添加或减去一个随机整数。您的任务是创建一个程序或函数,该程序或函数修改一个输入值,以在包含[0..1]的范围内获得一个浮点值。
生成的浮点数应该与原始浮点数相同,并且尽可能接近原始浮点数。由于0和1都在输出范围内,任何整数0或更少的整数都应该更改为0,而任何整数1或更高的整数都应该更改为1。
JavaScript中的一个示例算法:
function modFloat(input) {
while (input < 0 || input > 1) {
if (input < 0) input += 1;
if (input > 1) input -= 1;
}
return input;
}Input | Output
------------+---------
-4 | 0
-1 | 0
0 | 0
1 | 1
2 | 1
1.0001 | 0.000100
678.123456 | 0.123456
-678.123456 | 0.876544
4.5 | 0.5这是密码-高尔夫,所以以字节为单位的最短代码获胜!
发布于 2017-02-24 17:07:49
发布于 2017-02-24 17:24:54
n=>(n%1+1)%1||n>0|0在JavaScript中,n%x返回一个负数,如果n是负数,这意味着如果我们想得到正余数,那么如果n是负值,就必须添加x。(n%x+x)%x涵盖所有情况:
n n%1 n%1+1 (n%1+1)%1
0 0 1 0
1 0 1 0
2.4 0.4 1.4 0.4
-1 0 1 0
-2.4 -0.4 0.6 0.6另一个20个字节的工作解决方案,它显示了更多的模式:
n=>n%1+(n%1?n<0:n>0)发布于 2017-02-24 17:51:01
1&\0>yg>+输入678.123456示例
1 % Push 1
% STACK: 1
&\ % Implicit input. Divmod with 1
% STACK: 0.123456, 678
0> % Is it positive?
% STACK: 0.123456, 1
y % Duplicate from below
% STACK: 0.123456, 1, 0.123456
g % Convert to logical: nonzero becomes 1
% STACK: 0.123456, 1, 1
> % Greater than? This is true if fractional part of input was zero
% and non-fractional part was positive
% STACK: 0.123456, 0
+ % Add. Implicitly display
% STACK: 0.123456https://codegolf.stackexchange.com/questions/111174
复制相似问题