Random.cc

Go to the documentation of this file.
00001 /*
00002  *    Copyright 2005-2006 Intel Corporation
00003  * 
00004  *    Licensed under the Apache License, Version 2.0 (the "License");
00005  *    you may not use this file except in compliance with the License.
00006  *    You may obtain a copy of the License at
00007  * 
00008  *        http://www.apache.org/licenses/LICENSE-2.0
00009  * 
00010  *    Unless required by applicable law or agreed to in writing, software
00011  *    distributed under the License is distributed on an "AS IS" BASIS,
00012  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  *    See the License for the specific language governing permissions and
00014  *    limitations under the License.
00015  */
00016 
00017 #include <cstdlib>
00018 
00019 #include "../debug/DebugUtils.h"
00020 #include "Random.h"
00021 
00022 namespace oasys {
00023 
00024 ByteGenerator::ByteGenerator(unsigned int seed)
00025     : cur_(seed) 
00026 { 
00027     next(); 
00028 }
00029 
00030 void 
00031 ByteGenerator::fill_bytes(void* buf, size_t size)
00032 {
00033     char* p = static_cast<char*>(buf);
00034     
00035     for(size_t i=0; i<size; ++i) {
00036         *p = cur_ % 256;
00037         ++p;
00038         next();
00039     }
00040 }
00041 
00042 void ByteGenerator::next() 
00043 {
00044     cur_ = (A * cur_ + C) % M;
00045 }
00046 
00047 PermutationArray::PermutationArray(size_t size)
00048     : size_(size)
00049 {
00050     array_.reserve(size_);
00051     for(unsigned int i=0; i<size_; ++i) {
00052         array_[i] = i;
00053     }
00054 
00055     for(unsigned int i=0; i<size_ - 1; ++i) {
00056         size_t temp;
00057         unsigned int pos = Random::rand(size_-i-1)+i+1;
00058         
00059         temp = array_[i];
00060         array_[i]   = array_[pos];
00061         array_[pos] = temp;
00062     }
00063 }
00064 
00065 unsigned int
00066 PermutationArray::map(unsigned int i) {
00067     ASSERT(i<size_); 
00068     return array_[i];
00069 }
00070 
00071 }; // namespace oasys
00072 
00073 #if 0
00074 #include <iostream>
00075 
00076 using namespace std;
00077 using namespace oasys;
00078 
00079 int
00080 main()
00081 {
00082     const size_t SIZE = 20;
00083     PermutationArray ar(SIZE);
00084 
00085     for(int i=0;i<SIZE;++i) {
00086         cout << i << "->" << ar.map(i) << endl;
00087     }
00088 }
00089 #endif

Generated on Thu Jun 7 12:54:29 2007 for DTN Reference Implementation by  doxygen 1.5.1