Recent Entries 10
- principle minor 112d agoDoodlebug vs. ant population simulationI am looking for a review on one of my homework assignments for this semester. This homework has already been submitted and graded and my final has already been submitted so there is no cheating or conflict of interest in my review request! I would love some advice on how to better manage my class interactions and how to better encapsulate data. The specific area I struggle with is when using parent classes and giving access to only protected assets from child classes. My professor has mentioned on several occasions that it would be much better to keep data private and give access through functions, but how would I initialize those member variables when instantiating an instance of a child class that has private members in the parent class? I understand the idea of encapsulation is to protect data that shouldn't be manipulated by outside programmers or irrelevant classes. I was the sole developer on this project so I understand in this specific example encapsulation may not be paramount, but on a larger project with multiple engineers it would certainly be relevant. Includes ``` #include "stdafx.h" #include #include #include using namespace std; ``` ** Note the coordinates struct just contains an integer xCoordinate and an integer yCoordinate main ``` int main() { //Create environment object containing environment antDoodlebugSimulation; antDoodlebugSimulation.InitializeSimulation(); return 0; } ``` Environment ``` class environment { //friends of environment friend class organism; friend class doodlebug; friend class ant; private: organism * environmentBoard[20][20]; void CreateStartPopulation(); int GenerateRandomStartingLocations(int min, int max); void OutputCurrentEnvironment(); void DoodlebugsAct(); void AntsAct(); void ResetCritterTimeStep(); public: //constructor environment(); //deconstructor ~environment(); //public member functions void Initializ
- pattern minor 112d agoRandom Dice SimulationI extended the example in 04-random.elm to support N dice and to draw the results using SVG. ``` import Html exposing (..) import Html.Events exposing (..) import Random import List exposing (length, repeat, range) import Svg exposing (Svg, svg, circle) import Svg.Attributes exposing (..) main = Html.program { init = init, view = view, update = update, subscriptions = subscriptions } -- MODEL type alias Model = { dieFaces : List Int } init : (Model, Cmd Msg) init = let numDice = 5 in (Model (repeat numDice 1), Cmd.none) -- UPDATE type Msg = Roll | NewFaces (List Int) update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of Roll -> ( model, Random.generate NewFaces ( Random.list (length model.dieFaces) (Random.int 1 6) ) ) NewFaces newFaces -> (Model newFaces, Cmd.none) -- SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.none -- VIEW view : Model -> Html Msg view model = div [] ( List.map drawFace model.dieFaces ++ [ button [ onClick Roll ] [ text "Roll" ] ] ) drawFace : Int -> Html Msg drawFace numDots = div [ style "width: 66px; height: 66px; padding: 10px" ] [ svg [ version "1.1", width "66", height "66" ] (drawDice :: (List.map (\i -> drawDot i numDots) (range 0 (numDots - 1)))) ] drawDice: Svg Msg drawDice = circle [ fill "gold", stroke "orange", strokeWidth "3", cx "33", cy "33", r "30" ] [] drawDot: Int -> Int -> Svg Msg drawDot i n = circle [ fill "black", cx (toString (posX i n)), cy (toString (posY i n)), r "5" ] [] posX: Int -> Int -> Int posX i n = round (33 + (15 * cos (6.28 * (toFloat(i) / toFloat(n))))) posY: Int -> Int -> Int posY i n = round (33 + (15 * sin (6.28 * (toFloat(i) / toFloat(n))))) ```
- pattern minor 112d agoMonty Hall Simulator - PythonI'm pretty new to Python (I've been doing it for about 4 months, but not every day) and I've been struggling to get to grips with how to use functions and deploy them efficiently to solve problems. To test my abilities, I created the below program to simulate the Monty Hall problem. The program does the following things: - It chooses a winning door at the start from list `door = [1,2,3].` - It then asks the user to choose a door. - Then it checks to see if the user's guess matches the winning door. - If the user guesses the winning door, it randomly selects one of the two remaining doors to 'open'. If, however, the user doesn't guess the winning door, it 'opens' the one remaining unpicked door. - It then asks the user if they want to switch doors. If the user picked the correct door first time out, then sticking with that choice wins the game and switching loses. The reverse is true if the user didn't pick the correct door first time. - Finally, it updates a running tally of wins and losses, then asks the user if he wants to play again. The program works and the probabilities are correct (I ran it 100 times just to make sure and got 74 wins and 26 losses, which is around about what I'd expect). I'm just not sure the program is as efficient as it could be. In fact, given my relative lack of experience I'm pretty sure it isn't. Would anyone be able to tell me how good they think the code is, how I could go about improving it? ``` import random win = 0 lose = 0 while True: door = [1,2,3] x = 0 def pick_answer(): """Computer chooses the winning door""" answer = random.choice(door) return answer a = pick_answer() def pick_guess(): """User guesses winning door""" guess = int(input("Please choose a door (1-3): ").strip()) return guess b = pick_guess() if a == b: def montys_door_if_a_is_b(): """If answer = guess, pick one of the remaining doors to open"""
- 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 *=
- 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 agoPowerball Lottery Simulator in CI made a Powerball lottery simulator in C. I chose C because it is fast. Here's how it plays: - The user plays one ticket every day. - The user can choose to play the same ticket every day or a different ticket every day. - The numbers on each ticket are a "quick pick" -- that is, randomly generated. - The program also generates a random winning drawing every day. - The program stops when a user-decided number of balls on that day's ticket match with the same number of balls in the drawing. - The user decides whether the powerballs (the 6th balls) must match before the program stops. - The program ends with telling the user how many tickets they bought, how many years and days they played, and how much they won. My main problem is that when I run this to not stop until all 6 balls match, I am waiting for days (real life days) without a match. I comment out the `printf()` lines in `main()` that show the numbers for better efficiency, but I still have yet to get a match on all six numbers. What else can I do to improve efficiency? Here's the project on GitHub if anyone wants to try it out. main.c: ``` /* *** This program simulates a person playing the powerball *** everyday and stops once a certain number of balls *** match. Ther user decides how many balls should match *** before stopping. */ /* DEFINTIONS: redball and powerball refer to the same thing */ #include #include /* for rand(), srand() */ #include #include /* for time(), to seed srand() */ /* functions to get user input for program options */ #include "options.h" /* functions to do the calculation */ #include "calc.h" /* functions for output */ #include "output.h" int main(void) { /* customer ticket, powerball drawing */ int ticket[6] = {0}; int draw[6] = {0}; /* how many in-program days have we been playing? */ int days = 0; int years = 0; /* how much did the player win? */ int winnings = 0; /* Intializes random number generator */
- pattern minor 112d agoMonte Carlo estimation of πMy C program uses the Monte Carlo method to approximate the mathematical constant π, the ratio of a circle's circumference to its diameter (and, importantly for this code, 4 times the ratio of a circle's area to that of its bounding square). This estimation executes more slowly when parallelised using OpenMP than it does when executed in a single thread. I think that my random generator function is not thread safe, and that may be the cause of the slowdown. ``` #include #include #include #include #define DART 1000000 // Number of darts each player throws // Number of random dots in the square[-1,+1] #define MAXPLAYER 8 // Maximume number of participant players // Number of threads /** Generates a random number between two params given @param: random number scope @return: desired random number */ long double fRand(long double fMin, long double fMax) { long double f = (double)rand() / RAND_MAX; return fMin + f * (fMax - fMin); } /** Generates random dots on the board @param: playerDarts, total number of darts to throw @return: score, number of darts thrown in the circle */ int player(int playersDarts) { srand(time(NULL)); long double pi, x, y; int score = 0; for (int i = 0; i < playersDarts; i++) { x = fRand(-1.0, 1.0); y = fRand(-1.0, 1.0); if (x*x + y*y < 1.0) score++; } return score; } void main() { long double pi; long const double REAL_PI = 3.141592653589; int score = 0, playersDarts; //////////////////////////////////////////////////// // Parallel // //////////////////////////////////////////////////// // devide the total number of DARTS between players playersDarts = DART / MAXPLAYER; double beginParallel = omp_get_wtime(); #pragma omp parallel for for (int i = 1; i <= MAXPLAYER; i++) score += player(playersDarts); double endParallel = omp_get_wtime(); pi = 4.0 * ((lo
- pattern minor 112d ago4-Bar Mechanism GenerationFor a school project, I will design and prototype a bicycle brake that uses a four-bar linkage to accomplish its goal. My Python 3 code does this mechanism generation, and implements methods to remove mechanisms I don't think will work well to hopefully give me a good final mechanism to construct. Overall I wrote this up quite quickly, hence its messiness. I'm hoping to dramatically clean up the code and improve efficiency. Any suggestions on where to begin? Background (This section isn't critical to review the code, but I thought would be nice to include) To create the mechanism, I need to define a set of three "precision positions" on the coupler curve, which are points the coupler point of the four-bar will pass through. Since the points I define are just approximate guesses what I think the path should be (approximate linear motion), I loop over a small range for each coordinate I define. I then also choose the driver rotation between PP1 and PP2 (\$ \beta_2 \$) and PP1 and PP3 (\$ \beta_3 \$). The \$ \alpha \$'s are solved from the given precision positions (the couplers rotation), as well as the \$ \delta \$'s (the translational movement of the coupler point). The following picture illustrates this: The following system of equations is solved to obtain a 2 dyads (shown above, cut the mechanism in half between the coupler point, the two links on each side is a dyad). The two dyads together form the 4-bar. $$\vec{W_A}(e^{i\beta_{2A}} - 1) + \vec{Z_A}(e^{i\alpha_{2A}} - 1) = \delta_2$$ $$\vec{W_A}(e^{i\beta_{3A}} - 1) + \vec{Z_A}(e^{i\alpha_{3A}} - 1) = \delta_3$$ $$\vec{W_B}(e^{i\beta_{2B}} - 1) + \vec{Z_B}(e^{i\beta_{2A}} - 1) = \delta_2$$ $$\vec{W_B}(e^{i\beta_{3B}} - 1) + \vec{Z_B}(e^{i\beta_{3A}} - 1) = \delta_3$$ gen.py: ``` import numpy as np import matplotlib.pyplot as plt import math from filter import links_to_joints, filter_length, filter_orientation, filter_configuration, filter_mechanical_advantage from plot import plot_four_bar_
- pattern minor 112d agoLissajous pattern simulatorI had seen a YouTube video making actual Lissajous patterns with sand falling from a pendulum with 2 different periods and looking in the Wikipedia page the looked very easy to simulate. I made a Processing sketch simulating such a pattern. Here is an example output with `a = 3`, `b = 4` (the same as the third Wikipedia example). ``` // Lissajous patterns simulator // https://en.wikipedia.org/wiki/Lissajous_curve void setup() { size(600, 600); background(255); } int A = 300; // X stretching factor int B = 300; // Y stretching factor float a = 3; // x "relative importance" float b = 4; // y "relative importance" float time = 0; int offset = 0; final float TIMESTEP = 0.001; void draw() { int x = (int) ( A * sin(a*time + offset) ); int y = (int) ( B * sin(b*time) ); point(x + A, y + B); time += TIMESTEP; } ``` I have two main questions: - I kept the names short to match closely the Wikipedia specification, and added a short comment near them. Is this best practice? - I have quite a few related variables. Should I encapsulate them into a class (maybe `LissajousSimulator`, with a single function `updateState`)? Or would that just be over-engineering?