Recent Entries 10
- pattern minor 112d agoPerlin Noise terrain in Unity3DI've recently had time to devise another program so this time I decided to write the Perlin Noise algorithm in code. I have succeeded and the code works but I can't help but feel that my practices while writing are still not as good as they should be (especially since I'm still pretty new to the topic of programming). Please note that as I am working in Unity I have not separated the class files that I wrote into different source files. The code is comprised of a total of 3 class files: the main MonoBehaviour class named perlin_terrain and the two I have declared - named "Grid" and "Point". ``` using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class perlin_terrain : MonoBehaviour { public Terrain terrain; public int gridResolution = 512; // Will be adjusted to be divisible by the subdivision value. public int gridSubdivision = 4; // Value must be a power of 2. [Range(0, 1)] public float steepness = 0.12f; Grid grid; private static float[,] heights; // Use this for initialization void Start() { if (gridResolution unitPoints = new List(); unitPoints = getUnitPoints(x, y); int n = 0; foreach (Point point in unitPoints) { switch (n) { case 0: value1 = Vector2.Dot(point.GradientVector, distanceVectors[0]); break; case 1: value2 = Vector2.Dot(point.GradientVector, distanceVectors[1]); break; case 2: value3 = Vector2.Dot(point.GradientVector, distanceVectors[2]); break; case 3: value4 = Vector2.Dot(point.GradientVector, distanceVectors[3]); break; } n++; } weighed1 = Mathf.Lerp(value1, value2, fadeValue(pointX)); weighed2 = Mathf.Lerp(val
- snippet minor 112d agoGenerate random letter by frequencyWhich method below should I use to generate a "random letter by frequency" using Javascript? From https://gist.github.com/furf/2413792 ``` var randomAtoZ = (function (lookup) { return function () { var random = Math.random() * 100000, letter; for (letter in lookup) { if (random < lookup[letter]) { return letter; } } } })({ // Ranges calculated from data found at // http://en.wikipedia.org/wiki/Letter_frequency a: 8167, b: 9659, c: 12441, d: 16694, e: 29396, f: 31624, g: 33639, h: 39733, i: 46699, j: 46852, k: 47624, l: 51649, m: 54055, n: 60804, o: 68311, p: 70240, q: 70335, r: 76322, s: 82649, t: 91705, u: 94463, v: 95441, w: 97801, x: 97951, y: 99925, z: 100000 }); ``` My re-write ``` function randomAtoZ() { // Ranges calculated from data found at // http://en.wikipedia.org/wiki/Letter_frequency var lookup = { a: 8167, b: 9659, c: 12441, d: 16694, e: 29396, f: 31624, g: 33639, h: 39733, i: 46699, j: 46852, k: 47624, l: 51649, m: 54055, n: 60804, o: 68311, p: 70240, q: 70335, r: 76322, s: 82649, t: 91705, u: 94463, v: 95441, w: 97801, x: 97951, y: 99925, z: 100000 }; var random = Math.random() * 100000; for (letter in lookup) { if (lookup[letter] > random) { return letter; } } } ```
- pattern minor 112d agoPseudo Random Number GeneratorI recently watched this video about the random number generation in Super Mario World. The technique that is used, as seen in the image below, multiplies one of the seeds by 5 and adds 1, the other seed is multiplied by 2, and then depending on whether the 4th and 7th bits are the same, 1 is added. So as stated in the video, the sequence of numbers will repeat after 27776 successive calls. In my implementation of a pseudo random number generator, I have used 16 bit values for the two seeds to allow for a greater range of numbers, and my `get_rand()` function returns the two 16 bit strings joined together, resulting in a 32 bit number. This means that the sequence of numbers repeats after 526838144 successive calls, which is far greater than that achieved with the pseudo random number generator used in Super Mario World. I have also created a `rand_int()` and a `random()` function that allow for better use of the numbers generated, these simply divide the number returned by `2 ** 32` over the difference between the integer range. The `PRNG Test.py` is there only so that I can make sure that all the functions work as expected, and it seems to provide evenly split pseudo random numbers. So I am just after a review of the `PRNG.py` file, as it is that which I would like to optimize and improve. PRNG.py ``` #Make sure Seeds.txt exists try: file = open('Seeds.txt') except FileNotFoundError: file = open('Seeds.txt', 'a+') file.write('0\n0') #Gets the values of the seeds from the file values = file.readlines() file.close() S = int(values[0].rstrip('\n')) T = int(values[1]) def seed(seed_value): '''Resets the seed for the PRNG to make values predictable''' global S, T with open('Seeds.txt', 'w') as file: file.write(str(seed) + '\n' + str(seed)) file.close() S = seed T = seed def update_seeds(S, T): '''Generates the next two seeds''' S = 5 * S + 1 try: bit_11 = '{0:b}'.format(T)[-11] except IndexError
- pattern minor 112d agoIterator producing unique random numbers in a specified rangeI needed an iterator that produced random numbers, never repeating them, in a specified range of 0..max-1 (index for a collection). When the numbers are exhausted it should not have a next anymore. The simplest way might be to shuffle an ArrayList and make an iterator. But in typical usage, I will want only 4-5 unique random numbers, from a total in the region of 100. So shuffle seemed too CPU-heavy. And here is the class I came up with. It is written in Java 8 (the requirement of version 8 is acceptable in my case). ``` import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; public class NonRepeatingRandom implements Iterator { private List unused; private Random random; public NonRepeatingRandom(int max) { unused = IntStream.range(0, max).boxed().collect(Collectors.toList()); random = new Random(); } @Override public boolean hasNext() { return ( unused.size() > 0 ); } @Override public Integer next() { int size = unused.size(); if ( size==0 ) { throw new java.util.NoSuchElementException(); } int idx = random.nextInt(size); int result = unused.get(idx); unused.remove(idx); return result; } } ``` I would appreciate comments on this code.
- pattern minor 112d agoMonty Hall simulation with any number of doorsAfter answering Monty hall python simulation I wondered what the outcome were to be if there were more than three doors, say four or seven. And so I decided to modify the problem slightly to adjust for this. There are \$x\$ amount of doors. Behind one door is a car, the others are goats. You pick a door, and the host reveals a goat in a different door. You're then given the choice to change from the selected door to any door except the open door, or the already selected door. And so I decided to find out how many times a person is likely to win if they always pick a random door when asked if they want to switch door. And so programmed the following: ``` import random def monty_hall(amount, doors=3): if doors < 3: raise ValueError(f'doors must be greater than three, not {doors}') wins = 0 for _ in range(amount): player_choice = random.randrange(doors) car_placement = random.randrange(doors) other_doors = set(range(doors)) - {player_choice, car_placement} shown_door = random.choice(list(other_doors)) swap_doors = set(range(doors)) - {player_choice, shown_door} final_choice = random.choice(list(swap_doors)) wins += final_choice == car_placement return wins print(monty_hall(1000000, 3)) print(monty_hall(1000000, 4)) print(monty_hall(1000000, 5)) ``` I then decided to optimize the above code, and came up with the following ways to do this: - Change `player_choice` to `doors - 1`. The first player choice doesn't have to be random. - Change `other_doors` and `swap_doors` to account for (1). Rather than removing an item that will always be in the set, remove it from the range and the second set. And so `other_doors` becomes: `set(range(doors - 1)) - {car_placement}`. - Remove `player_choice` as it's no longer used. - Change `shown_door` to always be the first door. However if the car is the first door, show the second. `shown_door = car_placement == 0`. - Remove `other_doors` as it
- pattern major 112d agoC++ Coin flip simulator and data collectorAsks the user for the chance of a coin landing on heads, the number of trials per experiment, and the number of experiments. For example, given 5 trials per experiment and 20 experiments, the program will flip a coin 5 times and record the results 20 times. Then, it displays the results, as well as the theoretical and observed probabilities of each event happening. I turned this in already but I really enjoyed doing the assignment and I'd like to know how to make it better, faster, etc. I'm pretty new to computer science so I'd like to learn the correct practices and everything. Right off the bat I know that I should pass things by reference instead of by value and that I shouldn't have used global variables. ``` //Name Lastname //Class //Coin Flip Simulation //LIBRARIES #include #include #include #include #include using namespace std; //FUNCTION PROTOTYPES bool generate(); //Performs a coin flip with the given chance void runExperiment(); //Performs and prints the results of the trials void getInfo(); //Gets the information to perform the experiment int choose(int, int); //Performs a combination (nCk) double probability(int); //Calculates the probability of a coin hitting heads n times (binomial thrm) //GLOBAL VARIABLES double chance = 0.5; //Chance of landing on heads int numTrials = 5; //Number of trials per experiment int numExperiments = 1000; //Number of experiments bool printT = false; //Whether to print the results of each trial int main() { srand(time(NULL)); getInfo(); runExperiment(); getchar(); getchar(); return 0; } void getInfo() { cout > chance; cout > numTrials; cout > numExperiments; cout > printT; } void runExperiment() { int m = 0, n = 0, a[22]; for (int b = 0; b n) return 0; int r = 1; for (int d = 1; d <= k; ++d) { r *=
- snippet minor 112d agoGenerate cryptographically secure random numbers in a specific rangeA project I'm working on requires generating a random number of \$N\$ length to a very high degree of fair distribution between digits \$[0, 9]\$. That said, I used the `RNGCryptoServiceProvider` in the .NET framework, and built my own window restriction / clamping. First, we have the clamping. This clamps the values to the range from \$[lower, upper)\$, allowing the user to specify what range of values they want. For me, it's \$[0, 9]\$. Mathematically speaking, using a cryptographically secure random number generator should yield a truly random set. The problem is clamping: if we simply take `val % 10` to reduce it to our desired \$[0, 9]\$ range, we'll find that we have a slight favoritism / bias towards numbers at the lower end of the set. In fact, we should have the most bias towards the set \$[0, 5]\$. To reduce, or even eliminate, this bias I took a previously working algorithm and modified it slightly to create a bounded number of loops. The idea is simple: to generate a random value in the domain \$[0, 9]\$ take the random value from the set \$[0, 255]\$ and test that it is within the range \$[0, 249]\$. If it is within that range, take \$value \mod 10\$ as the result. If it is in the range \$[250, 255]\$ then we draw a new number. This can be expanded to define the following general-purpose formula: $$upperLimit = 256 - (256 \mod modulo)$$ We can then define the number to take the modulo by as: $$modulo = upper - lower$$ We set the loop up to bound to a specific value, in this case I'm creating the loop So far, my results have yielded almost perfect distribution of the values \$[0, 9]\$, when generating \$1,000,000\$ values. I have run this several times, and each time I get a slightly different distribution, by a very small margin. That is perfect, as it demonstrates that the RNG is not predictable by any manner. ``` Value 0: 100090 occurrences (10.009%) Value 1: 100298 occurrences (10.0298%) Value 2: 100034 occurrences (10.0034%) Value 3: 999
- pattern minor 112d agoInfinite monkey theorem demonstration in PythonThis was the assignment: Here’s a self check that really covers everything so far. You may have heard of the infinite monkey theorem? The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. Well, suppose we replace a monkey with a Python function. How long do you think it would take for a Python function to generate just one sentence of Shakespeare? The sentence we’ll shoot for is: “methinks it is like a weasel” You’re not going to want to run this one in the browser, so fire up your favorite Python IDE. The way we’ll simulate this is to write a function that generates a string that is 27 characters long by choosing random letters from the 26 letters in the alphabet plus the space. We’ll write another function that will score each generated string by comparing the randomly generated string to the goal. A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done. If the letters are not correct then we will generate a whole new string.To make it easier to follow your program’s progress this third function should print out the best string generated so far and its score every 1000 tries Soo i have created a python program which generates the string provided, i am in learning phase, can someone please suggest any improvement or any tips or corrections. Note: I know i have not did the exact method said in that question, but i have created the expected result. makeRandSent: This will give me random character. compare: This will give me final result by comparing each user character with randomly generated character and it will only change those chracter which are not match. ``` def makeRandSent(userSent): counter = 0 randSent = [""] * (len(userSent) - 1) randSent.clear() while counter 0: counter = 0
- pattern moderate 112d agoMonty hall python simulationI have the following code that simulates the monty hall problem (see google for more details). I used sets to do it but is there a more intuitive or efficient way to do it? ``` import random as r from sets import Set def montysim(N): K = 0 for i in range(N): s = Set([1,2,3]) doorstoswitch = Set([1,2,3]) cardoor = r.randint(1,3) chosendoor = r.randint(1,3) doorstoswitch.remove(chosendoor) if chosendoor != cardoor: s.remove(chosendoor) s.remove(cardoor) montydoor = r.sample(s, 1)[0] doorstoswitch.remove(montydoor) newdoor = r.sample(doorstoswitch, 1)[0] if newdoor == cardoor: K+=1 return float(K) / float(N) print montysim(10000) ```
- pattern minor 112d agoHelper method to shuffle cards list for online gamingI have written this code to shuffle a deck of cards. I would like to hear your inputs. ``` public static class Helper { public static Int32 GetRandomNo(this RNGCryptoServiceProvider rng, byte[] data) { rng.GetBytes(data); var randomNo = BitConverter.ToInt32(data, 0); return randomNo; } public static void Shuffle(this List source) { using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) { // Buffer storage. byte[] data = new byte[4]; source = source.Select(element => new {element, randomValue = rng.GetRandomNo(data)}) .OrderBy(entry => entry.randomValue) .Select(entry => entry.element) .ToList(); } } } ```