Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write own rng #25

Merged
merged 1 commit into from
Feb 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions inkcpp/random.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#pragma once

#include "../shared/public/system.h"

namespace ink::runtime::internal {
/**
* @brief pseudo random number generator based on Linear Congruential Generator.
*/
class prng {
static constexpr uint32_t C = 12345;
static constexpr uint32_t A = 1103515245;
static constexpr uint32_t M = 1<<31;
public:
void srand(int32_t seed) {
_x = seed;
}
uint32_t rand() {
_x = (A*_x+ C) % M;
return _x;
}
int32_t rand(int32_t max) {
uint64_t prod = rand();
prod *= max;
return static_cast<int32_t>(prod / M);
}
private:
uint32_t _x = 1337;
};
}
6 changes: 3 additions & 3 deletions inkcpp/runner_impl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -929,13 +929,13 @@ namespace ink::runtime::internal
int sequenceLength = _eval.pop();
int index = _eval.pop();

_eval.push(rand() % sequenceLength); // TODO: platform independance?
_eval.push(_rng.rand(sequenceLength));
} break;
case Command::SEED:
{
// TODO: Platform independance
int seed = _eval.pop();
srand(seed);
int32_t seed = _eval.pop();
_rng.srand(seed);

// push void (TODO)
_eval.push(0);
Expand Down
3 changes: 3 additions & 0 deletions inkcpp/runner_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "functions.h"
#include "string_table.h"
#include "array.h"
#include "random.h"

#include "runner.h"
#include "choice.h"
Expand Down Expand Up @@ -163,6 +164,8 @@ namespace ink::runtime::internal
bool _is_falling = false;

bool _saved = false;

prng _rng{};
};

template<>
Expand Down
3 changes: 0 additions & 3 deletions inkcpp/value.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@
#include "output.h"
#include "string_table.h"

// TODO
#include <cstdlib>

namespace ink
{
namespace runtime
Expand Down