filenlRandom.cpp
  0
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
//  nlRandom.cpp
//
//  Created by Daisuke Nogami on 9/30/05.
//  Copyright 2005 Daisuke Nogami [null-null.net]. Some rights reserved.
*/
 
#include "stdafx.h"
 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
// http
#include <windows.h>
#include <wininet.h>
 
// selfmade class
#include "nlRandom.h"
 
// random.org param
#define GEN_RAND_INTS 10000
#define SMALLEST_VALUE -1000000000
#define LARGEST_VALUE 1000000000
#define COLUMNS 1
 
nlRandom::nlRandom(){
  int i;
 
  // initialize random source
 
  std::srand( time( NULL ) );
 
  randsrc = new int[GEN_RAND_INTS];
  for( i = 0; i < GEN_RAND_INTS; i++ ){
    randsrc[i] = -1000000001;  /* SMALLEST_VALUE -1 */
  }
  counter = 0;
}
 
nlRandom::~nlRandom(){
  delete []this->randsrc;
  this->randsrc = 0;
}
 
// [0-1]
double nlRandom::rand(){
  int res = randsrc[counter];
  int randmax;
 
  if( res == -1000000001 /* SMALLEST_VALUE -1 */ ){
    res = std::rand();
    randmax = RAND_MAX;
  }
  else{
    res = randsrc[counter]-(SMALLEST_VALUE);
    randmax = LARGEST_VALUE-SMALLEST_VALUE;
  }
 
  counter++;
  if( counter >= GEN_RAND_INTS ){
    counter = 0;
  }
 
  return (double)res/(double)randmax;
}
 
void nlRandom::load(){
  HINTERNET hInet;
  HINTERNET hFile;
  DWORD dwSize;
  char* lpszBuf = (LPTSTR)GlobalAlloc( GPTR, 1024 );
  std::string buff;
  int i, idx;
 
  char url[256];
  sprintf(
    url,
    "%s%d%s%d%s%d%s%d",
    "http://www.random.org/cgi-bin/randnum?num=",
    GEN_RAND_INTS,
    "&min=",
    SMALLEST_VALUE,
    "&max=",
    LARGEST_VALUE,
    "&col=",
    COLUMNS
  );
 
  // open url
  hInet = InternetOpen(
    "random.org",
    INTERNET_OPEN_TYPE_DIRECT,
    NULL,
    NULL,
    0
  );
 
  hFile = InternetOpenUrl(
    hInet,
    url,
    NULL,
    0,
    INTERNET_FLAG_RELOAD,
    0
  );
  
  // get from random.org
  while( true ){
    dwSize = 0;
    memset( lpszBuf, 0x00, sizeof( lpszBuf ) );
    if( !InternetReadFile( hFile, lpszBuf, sizeof(lpszBuf)-1, &dwSize ) ){
      break;
    }
 
    buff += std::string(lpszBuf);
 
    if( dwSize == 0){
      break;
    }
  }
  
  // convert to int from string
  i = idx = 0;
  while( (idx = buff.find('\n')) != std::string::npos && i < GEN_RAND_INTS ){
    randsrc[i] = atoi( buff.substr( 0, idx ).c_str() );
    buff = buff.substr( idx+1, buff.length() );
    i++;
  }
 
  // close url
  InternetCloseHandle(hFile);
  InternetCloseHandle(hInet);
}
[トップ] [一覧] [最終更新] [検索] [バックアップ]