【发布时间】:2013-03-22 20:38:17
【问题描述】:
我正在尝试使用一种算法来为我的 rails 应用程序中的模型生成唯一的非顺序标记。
例如:
MyModel.create.token #=> '183685'
MyModel.create.token #=> '456873'
MyModel.create.token #=> '813870'
我能想到的唯一方法是创建一个随机的东西,检查冲突,然后重试。这对我来说似乎是一种很臭的代码,在某种程度上是一种力量。
class MyModel < ActiveRecord::Base
before_create :set_token
def set_token
existing_model_count = nil
# Loop while we have a token that already belongs to an existing model.
while existing_model_count.nil? || existing_model_count > 0
random_token = TokenGenerator.random_token
existing_model_count = MyModel.where(token: random_token).count
end
# Loop exited, meaning we found an unused token.
self.token = random_token
end
end
有没有更好的方法来做到这一点,不涉及while 循环,该循环将迭代未知次数?
虽然这里的示例是 ruby,但这是一种适用于任何语言的通用算法问题,因此欢迎使用其他语言的解决方案。
【问题讨论】:
-
您可以生成更长的令牌(例如 UUID)并假设它们很可能是唯一的。 stackoverflow.com/questions/39771/…en.wikipedia.org/wiki/Universally_unique_identifier
-
遗憾的是,我正在寻找的位数远少于此。很容易在电话中写下来或陈述的事情。
-
您可以持续枚举您的令牌范围内的所有有效令牌,然后让
TokenGenerator.random_token随机选择一个并将其删除。 -
您是否提前知道您需要多少令牌(大约,也许)?或者您正在寻找一种完全开放的唯一令牌生成算法?
标签: ruby-on-rails ruby algorithm