我正试图在lua中生成一个随机乘数,因此每新的一周都会选择一个新的乘数。
例如第一周可能是:1000*1.2下周可能是:1000*0.8
应该来自数学。随机(0.8,1.2(但我想把这个随机数保留一周。
我已经能够在php中找到一种方法来做到这一点,但当试图在lua中格式化日期时,我找不到解决它的方法。
我需要ISO-8601周编号年份和周编号。
这个php代码正是这样做的:
<?php
mt_srand((int)date('oW')); //this week date('oW') returns 202114
$number = mt_rand(0.8, 1.2); //from the mt_srand above it will always return 1 on this specific week, even if the script is re-executed
$value = 1000 * $number;
echo $value; //current week returns 1000
?>
有没有聪明的人能破解这个?我觉得这个概念很有趣。注意:我不想把它存储在数据库中,这就是这样做的原因。
例如,您可以实现公式
1000000000 % YYYYWW * YYYYWW % 401 + 800
以获得800到1200范围内的伪随机数。
这就是如何在Lua 5.3+上计算ISO-8601周数:
function iso_year_week(time)
-- returns two numbers: iso_year, iso_week (1-53)
local t = os.date("*t", time or os.time())
t.day = t.day + (1 - t.wday) % 7 - 3 -- nearest Thursday
os.time(t) -- normalize all the fields
return t.year, math.ceil(t.yday / 7)
end
function get_YYYYWW_number(time)
return tonumber(string.format("%04d%02d", iso_year_week(time)))
end
mt_rand将一个整数作为参数。如果需要介于800和1200之间的值,则可以直接使用这些值。
时间戳用于为未来几周测试算法。
$weekInFuture = 0; //0 this week, 1 next week for test
mt_srand((int)date('Wo',strtotime("$weekInFuture weeks")));
$value = mt_rand(800, 1200);
echo $value;
本周我得到了1140的值。在接下来的几周里,11041916。。
如果你不喜欢这些值,如果你使用"魔兽世界"作为日期,你可以生成其他值。