LoginSignup
9
8

More than 5 years have passed since last update.

数値のスクランブル

Last updated at Posted at 2015-05-14

一意な番号を割り振りたいが、連番になることを避けたいときに用いる。

C言語で書くとこんな感じ。


unsigned long function scramble(unsigned long seed) {
  // 好きなスクランブル用の値。
  unsigned long hash_keys = [0x12345678, 0x87654321];
  unsigned long value = seed;

  for(int i=0; i<hash_keys; i++) {
    unsigned long hash = (hash_keys[i] & 0x7fffffff | 0x1);
    // 掛け算して有効範囲分に切り捨て
    value = (value * hash) & 0x7fffffff;
  }

  return value;
}

PHPで書くとこんな感じ。


function scramble($seed) {
  $hash_keys = array(
    0x12345678, 0x87654321
  );

  $value = $seed;
  foreach($hash_keys as $hash) {
    $hash = ($hash & 0x7fffffff | 0x1);
    $value = ($value * $hash) & 0x7fffffff;
  }

  return $value;
}

よく忘れかけるのでメモメモ。
任意の数値xに奇数nを掛け算することで数値が巡回する。
奇数n単位で採番してるのと同義って感じですかね。

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8