samedi 31 octobre 2015

Text adventure game--randomly connecting rooms together - C

I'm trying to create a text adventure game that 7 rooms, with the information saved in files. This question IS similar to Connect Rooms Randomly in Adventure Game however the answer didn't exactly help me. I've gone about my program in a different way than that OP so I'm not sure how to use that answer to help me.

The idea is you have 7 rooms, named say A, B, C, D, E, F, and G. After the rooms are created, I need to randomly connect them to each other. Each room needs between 3 and 6 random connections. If room A is connected to B, C, and D, each of those rooms should be connected to A. This information is then saved to a file which is read later.

The code I have for this section so far is:

    char connections[7][7];
    int j = 0;
    int randomRoom;
    for (j = 0; j <= randConnections; j++) {
             randomRoom = rand() % 10;
             if (randomRoom == randName) {
                     randomRoom = rand() % 10;
             } else {
                    connections[j] = names[randomRoom];
    }

randConnections is a random int between 3 and 6, defined earlier in the code. names is a string array that holds the names of the rooms, also defined earlier in my program.

Now first of all, this code doesn't compile. There is an issue with the line

   connections[j] = names[randomRoom];

I can't seem to figure out why this assignment statement doesn't work either. I am pretty new to C (I'm mostly experienced with Java) so I can't figure it out. The error I get is: incompatible types when assigning to type char[7] from type char *

I should mention, this is all in one function defined as:

    void createRooms(FILE *fp)

I know there are probably more efficient ways to do this, but at this point I'm just trying to get the code working and deal with efficiency later.

I've done a ton of googling and am honestly beating my head against the wall right now. Any help would be greatly appreciated. If there's any more code I should post or any other information let me know.




Runs test function of RNG quality

I wrote the function that uses the runs test to access the quality of RNG. Is there a way to write it without "if" and "for"?

u=runif(10,0,1)
runs.test=function(u){
x=(u<0.5)
x=as.numeric(x)
count=1;
for (i in 1:(length(x)-1)){
  if (x[i]==x[i+1]){
    count=count;
  }else{
    count=count+1;
  }
  }
  return(count);
}




Inserting numbers from a list in a repeating sentence

I have a list of all 5 digit combinations possible and I also have a sentence in which I would like to add each number. Here's an example:

  • List items:

11111, 22222, 33333.. etc

  • Sentence:

Hello userXXXXX, how are you?

  • Desired result:

    1. Hello user11111, how are you?
    2. Hello user22222, how are you?
    3. Hello user33333, how are you?

The list of numbers is huge and the sentence keeps changing. I need a way to do this automatically.

Is such a thing possible?




Customize chances of picking element randomly

I have two defined objects: x and y
If I do following, chances of getting either x or y are equal – 1 of 2:

var primary = [x, y];
var secondary = primary[Math.floor(Math.random() * primary.length)];

This would take a 1 of 3 (smaller) chances of getting y:

var primary = [x, x, y];
// secondary unchanged

etc.

But I believe, this is bad practice because if I'd wanted to set infinitesimal chances (e.g. 1 of 1e9) of getting y, I would have to do something extremely wasteful like this:

var primary = new Array();
for (i = 1e9 - 1; i--; i) primary.push(x);
primary.push(y);
var secondary = primary[Math.floor(Math.random() * primary.length)];

Is there a better way to do this in JavaScript?




Paging random with linq to entities

I need to search on the database a random result. Every new request the result should come different. This result should use paging (Skip, Take).

Any idea?




Add random integer to hash set only if in another list

I have the following code:

Random rand = new Random();
HashSet<int> hsP = new HashSet<int>();
int tempRandVal = rand.Next(0,10000); //random number between 0 and 1000
var rng = Enumerable.Range(0,10000).Where(i => listP.Contains(i));  //create range with previously populated list

        while (hsP.Count < 200)
        {

            if(rng.Contains(tempRandVal))
            {
                hsP.Add(tempRandVal);
            } 
            else
            {
                tempRndValue = rnd.Next(10000);
            }
        }

The above is causing an infinite loop. An extra eye would be great.




Distribution of dice rolls

from random import randrange

def roll2dice() -> int:
    roll2 = []
    for i in range(50):
        sum = randrange(1,7) + randrange(1,7)
        roll2.append(sum)
    return roll2

The above function is for generating the random rolling sum of two die.

def distribution (n: int):
    result = []
    for x in range(2,13):
        result.append(roll2dice())
    for x in range(2,13):
        dice = result.count(x)
        num_of_appearances = result.count(x)
        percentage = (result.count(x) / int(n)) * 100
        bar = result.count(x)*'*'
    print("{0:2}:{1:8}({2:4.1f}%)  {3.5}".format(dice, num_of_appearances, percentage, bar))

I then used roll2dice to create a distribution function in which

distribution(200)

should yield:

 2:     7 ( 3.5%)  *******
 3:    14 ( 7.0%)  **************
 4:    15 ( 7.5%)  ***************
 5:    19 ( 9.5%)  *******************
 6:    24 (12.0%)  ************************
 7:    35 (17.5%)  ***********************************
 8:    24 (12.0%)  ************************
 9:    28 (14.0%)  ****************************
10:    18 ( 9.0%)  ******************
11:     9 ( 4.5%)  *********
12:     7 ( 3.5%)  *******

However, the error said: "ValueError: cannot switch from automatic field numbering to manual field specification" Any way I can get the code to have that output without the error?




How to select randomly multiple items, with replacement, from an array in javascript

I have an array with all letters of the alphabet plus full stop and space. What I want to do is select randomly a large number of these letters (it does not matter if the same letter gets selected more than once) and print them on the screen. What I've got this far is this:

var letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", ".", " "];

for (var i = 0; i <= 10; i++) {
    var random_letter = Math.floor(Math.random() * 28);
    var result = [];
    result[i] = [letters[random_letter]];
    document.write(result);
}   

However, when I run the script in Firefox I get this output:

X,C,,N,,,A,,,,T,,,,,.,,,,,,N,,,,,,,T,,,,,,,,G,,,,,,,,,O,,,,,,,,,,G 

Which correctly contains 10 letters and a space. But it also contains all these commas! Which are not part of my array. Why is this thing happening? Am I doing something wrong? Any help would be much appreciated. Alex




Python 2.7 Attribute Error

I was wondering if it was possible for someone to assist me with an error I receive when using the 'random' function:

AttributeError: 'builtin_function_or_method' object has no attribute 'choice'

I have already imported the entire 'random' library and ensured there are no other files called 'random.py' in the same directory as where the file is saved.

Code:

from random import *

# Generates the random card

rank = ["Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
suit = ["Hearts", "Clubs", "Diamonds", "Spades"]

card_1 = ("The card is the %s of %s") % (random.choice(rank), random.choice(suit))




vendredi 30 octobre 2015

Random not working inside LINQ [duplicate]

This question already has an answer here:

Consider the following code:

string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
IEnumerable<string> randoms = Enumerable.Range(1, 10)
                              .Select(i => 
                              new string(alphabet
                                         .OrderBy(c => new Random().Next())
                                         .ToArray()));

As you can see I am ordering by new Random().Next() which should be a different number in each evaluation, right?

However this is the result I am getting:

ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ

As you can see none of the characters got shuffled.

What is happening here?




pywinauto: how to set focus at one random window when there can show up one window from three different

I am trying to automate some application using pywinauto but there is some step that I don't know how to solve.

When I am at the main window I click "proces" buton and after this there is a possibility to open 1 window from 3 different but only 1 at a time. Please help me to solve this.

example: main window --> buton click --> 1st window (process file) or 2nd window (Your password expired, set new password) or 3rd window (this user is already logged in please kill his session and continue or break) --> process 1 of 3 windows but which will show up I don't know --> ...




Trying to use UNION on two random SELECT provides same result

I am trying to get 5 random listings related to a category in a directory website in Wordpress.

However the sticky ones have to be shown first always. I have this query that if I remove the UNION and make the queries separately works giving me the randomized sticky listings and then the other query the randomized non sticky listings.

But when I join them the same order is applied always, so they are not randomized anymore.

(SELECT p.ID,p.post_title, pm.meta_value as level 
FROM wp_posts p 
LEFT JOIN wp_term_relationships tr ON p.ID=tr.object_id 
LEFT JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id=tt.term_taxonomy_id 
LEFT JOIN wp_terms t ON t.term_id=tt.term_taxonomy_id 
LEFT JOIN wp_postmeta pm ON p.ID=pm.post_id 
WHERE tt.taxonomy LIKE ('wpbdp_category') AND t.name LIKE('Acupuncture') AND pm.meta_key LIKE ('_wpbdp[sticky]') AND pm.meta_value LIKE ('sticky') 
ORDER BY  RAND() ) 
UNION
(
SELECT pp.ID,pp.post_title, '' as level 
FROM wp_posts pp 
LEFT JOIN wp_term_relationships ptr ON pp.ID=ptr.object_id 
LEFT JOIN wp_term_taxonomy ptt ON ptr.term_taxonomy_id=ptt.term_taxonomy_id 
LEFT JOIN wp_terms pt ON pt.term_id=ptt.term_taxonomy_id 
WHERE ptt.taxonomy LIKE ('wpbdp_category') AND pt.name LIKE('Acupuncture')  
ORDER BY  RAND()
)
LIMIT 5

Any ideas on what I might be doing wrong?




Random Number Generators in C# [duplicate]

This question already has an answer here:

Hey everyone I'm using C# to predict the results of a simulation of a whole school virus spread my school is doing (Just for the heck of it). I'm having problems with random number generation as the runtime speed is pretty darn fast and it's probably using the same seed everytime it iterates through the number cruncher loop. Is there a way to fix this? (Without adding a delay)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Human
    {
        public enum State
            {
                Healthy,
            Infected,
            Immune,
            Dead
            };
        public int infectionsLeft; //Constrainted inital value of 1-3
        public State state;

        public Human() //Constructor
        {
            state = State.Healthy; //Human is healthy
            Random randomizer = new Random();
            infectionsLeft = randomizer.Next(1, 4); //rand num from 1-3
        }
    }
    class Program
    {      
        static void Main(string[] args)
        {
            List<Human> humans = new List<Human>();
            double numberOfDays = 3; //Number of days simulation will be run
            double wastedCards = 0;
            for(int i = 0; i != 1000; i++)
            {
                Human human = new Human();
                if (i == 0)
                {
                    human.state = Human.State.Infected; //First human will start infected
                }
                humans.Add(human);
            }
            for (int a = 0; a != numberOfDays; a++)
            {
                foreach (Human human in humans)
                {
                    if (human.state == Human.State.Infected) //Infect if infected
                    {
                        Random r = new Random();
                        while (human.infectionsLeft > 0)
                        {                          
                            int theNextInfectedHuman = r.Next(humans.Count);
                            Human toBeInfectedHuman = new Human();
                            toBeInfectedHuman = humans[theNextInfectedHuman];
                            if (toBeInfectedHuman.state != Human.State.Healthy)
                            {
                                wastedCards++;
                            }
                            else
                            {
                                toBeInfectedHuman.state = Human.State.Infected;
                            }

                            human.infectionsLeft--;
                        }
                        int deathRoll = r.Next(1, 1001); //deathRoll! 33.33 percent chance of DEATH!
                        Console.WriteLine("DEATHROLL! " + deathRoll);
                        if(deathRoll < 234)
                        {
                            //SAFE!
                            human.state = Human.State.Immune;
                        }
                        else
                        {
                            //DEAD!
                            //Since this is a prediction of the simulation at school, I won't del the object,
                            //just set state to dead so cards can be wasted on a dead person too
                            human.state = Human.State.Dead;
                        }
                    }                  
                }
                //COUNT THE PPLS STATES!
                int healthy = 0;
                int infected = 0;
                int immune = 0;
                int dead = 0;
                foreach(Human human in humans)
                {
                    if(human.state == Human.State.Healthy)
                    {
                        healthy++;
                    }
                    else if (human.state == Human.State.Infected)
                    {
                        infected++;
                    }
                    else if (human.state == Human.State.Immune)
                    {
                        immune++;
                    }
                    else if (human.state == Human.State.Dead)
                    {
                        dead++;
                    }
                }
                using (System.IO.StreamWriter file =
                       new System.IO.StreamWriter(@"data.txt", true))
                {
                    file.WriteLine("-----DAY " + (a + 1) + "-----");
                    file.WriteLine("Healthy people: " + healthy);
                    file.WriteLine("Infected people: " + infected);
                    file.WriteLine("Immune people: " + immune);
                    file.WriteLine("Dead people: " + dead);
                    file.WriteLine("Wasted cards: " + wastedCards);
                }

            }
        }
    }
}




Using .html() to clear previous random string not working

I am writing a short function that appends a random string that is equal in length to a given word. For example, if you input the word 'hello' it would return a random string that is 5 letters long.

This part works as expected. However, I am using $('output').html(""); to overwrite the last random string. I have used this for other functions before and it has worked as expected but it does not here. I have tried moving it around the function to see if it has something to do with the order of the function but it's not deleting the previous random string.

What am I doing wrong?

Fiddle here

HTML:

<input type="text" id="input">
<button id="button">Click Me</button>
<div id="output"></div>

JavaScript:

var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
$(document).ready(function () {
    $('#button').on('click', function () {

        var value = ($('#input').val());
        for (i = 0; i < value.length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        };
        $('#input').val("");
        $('#output').html("");
        $('#output').html(text);
    });
});




NetworkX: how to build an Erdos-Renyi graph from a set of predetermined positions?

I am new to NetworkX. I need to build something like an Erdos-Renyi model (random graph):

enter image description here

I need to create it from a dictionary of node positions that is generated by a deterministic function. This means that I cannot allow Python to randomly decide where each node goes to, as I want to decide it. The function is:

pos = dict( (n, n) for n in G.nodes() ).

I was thinking of creating an adjacency matrix first, in order to randomly generate something similar to pairs of (start, endpoint) of each edge, like this:

G=np.random.randint(0, 1, 25).reshape(5, 5)

Then I was thinking of somehow turning the matrix into my list of edges, like this:

G1=nx.grid_2d_graph(G)

but of course it does not work since this function takes 2 args and I am only giving it 1.

My questions:

  1. How to create this kind of graph in NetworkX?
  2. How to make sure that all nodes are connected?
  3. How to make sure that, upon assigning the 1 in the matrix, each pair of nodes has the same probability of landing a 1?

Example for point 3. Imagine we created the regular grid of points which positions are determined according to pos. When we start connecting the network and we select the first node, we want to make sure that the endpoint of this first edge is one of the N-1 nodes left in the network (except the starting node itself). Anyhow, we want to make sure that all N-1 nodes have the same probability of being connected to the node we first analyze.

Thanks a lot!




Generating a random number in Java [duplicate]

This question already has an answer here:

I'm new to java and I need to create a program that generates random numbers as dice rolls. I'm trying to use this:

    static Random randGen = new Random();

But I keep getting an error message that says "error: illegal start of expression" pointing to "static". Any suggestions?




Php shuffle 2 unique numbers

I got a database with users and numbers.

I built a shuffle and tried to randomly give a user a number, that worked.

Now I have the issue that I want to give the user 2 random numbers with shuffle which shall be unique.

Main Code looks like this:

    $numbers = range(0, $counts); // $counts are the number of users in my databse
    $numbers2 = range(0, $counts);
    shuffle($numbers);
    shuffle($numbers2);

    foreach($users as $user) {
        # Starts from 1 if higher than 52
        $uniqueRand  = (array_pop($numbers)+$currentWeek) % 52 + 1;
        $uniqueRand2 = (array_pop($numbers2)+$currentWeek) % 52 + 1;

        # tried something like this but did         
        while($uniqueRand == $uniqueRand2) {
            $numbers2 = range(0, $counts);
            shuffle($numbers2);
            $uniqueRand2 = (array_pop($numbers2)+$currentWeek) % 52+1;
        }

         ...# Storing in database
    }

Here a little sketch of the application

Users      |       numbers
__________________________
Frank      |  14, 24
Tim        |  21, 43
Tom        |  52, 6
Hanz       |  8,  3
Benjamin   |  5,  1
West       |  7,  6
Thompson   |  4,  9
.....

The first line of numbers 14,21,52... stand for $numbers and the second line for $numbers2, I want to create unique random values which do not repeat themselves, but how do I check if the $number do not repeat in the same line and are still vertical unique.

So for instance would something like this be wrong:

Users      |       numbers
_________________________
Frank      |       14, 14

Something like this would be wrong too:

Users      |       numbers
_________________________
Frank      |     14, 24
Tim        |     21, 14
Tom        |     14,  6
Hanz       |      8,  3
Benjamin   |      5,  14
West       |      14,  6
Thompson   |      4,  9




Generate float Random number between [0,1] and restricting decimal

I want to generate Random Float numbers between Interval [0,1]. The generated Random values will be compared with an input from a file. The content of the File is a probability (float values) and hence they are in range[0,1] and it looks like:

0.55

0.14

0.005

0.870

0.98

0

1

I am reading this File and storing probability values into a DoubleList. Now I want to generate a float Random Number between [0,1]. As you see the file have probability values upto 1 digit, 2 digits decimal and 3 digits decimal as well. I am using following Code:

public static double randomNumberGenerator()
{
    double rangeMin = 0.0f;
    double rangeMax = 1.0f;
    Random r = new Random();
    double createdRanNum = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
    return(createdRanNum);
}

The random float value generated should be also be like Probabilities values (like generated upto the maximal decimal digits as in the file). How can I restrict the generated decimal digits?

I checked the following Link: Java random number between 0 and 0.06 . People suggested Int number generation and then did the double division by 100. Is this the good way? Can't we restrict the decimal generated directly?

PS: If I compare the random generated number from the above code with the double values from File, would there be some memory fall issues in the DoubleList?




C++ fread reads random characters at the beginning of the file

I have an input file like;

A;Ali;Aksu;N;2;deposit;withdraw

and I read it like this;

char a[5];
fread(a, sizeof(char), 5, input);

But when I try to print

cout << a;

it writes random characters at first like

+^%'A;




Random choice function

I am making a game using pygame based on the game war. I am getting an error when running the code for splitting my deck in the main loop (it is in its own file). The error says:

"/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 275, in choice
return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
IndexError: list index out of range

The deck splitting file looks like this:

import Deck
from random import *
deck = Deck.deck
playerDeck = []
AIDeck = []

def splitDeck():
player_deck_count = 26

while player_deck_count > 0:

    transfer_card = (choice(deck))

    playerDeck.append(transfer_card)
    deck.remove(transfer_card)

    player_deck_count -= 1

AIDeck = deck
shuffle(playerDeck)
shuffle(AIDeck)


print "Player deck length:" + str(len(playerDeck))
print "AI deck length:" + str(len(AIDeck))
print "Deck length:" + str(len(deck))

The Deck file looks like this:

deck = [
    '2_c',
    '2_d',
    '2_h',
    '2_s',

I get that is has to do with the sequence (list is empty) but there is obviously still 26 cards in the original deck. I have tried changing when the while player_deck_count loop stops but with no luck. Thanks for the help in advance

P.S. just comment if you want the main loop.




jeudi 29 octobre 2015

Making a plot from randomly generated number in R

I wonder how I can make plots from randomly generated number.

For example, if I generated random number from rt(1000) or rchisq(1000),

I get y value for a plot.

How may I get x value from them or let me know, if there is other way to

make plots with functions.

(I won't use density function, please make plots from randomly generated number.)




FIlling a 2D array with random integers java

I am trying to create an nxn array full of random integers between 1 and 10. When I try to print it out, I am getting an odd number of integers not filling an array, and never up to the correct number of integers (for instance, a supposed 5x5 array is returning 17 integers). Code snippet follows, assume all variable are declared correctly unless contained in here and java.util.Random is imported.

if (choice==1){
     Random rand = new Random();
     System.out.println("Please input a power n for (nxn array) between 1-6");
     int power = kb.nextInt();
     int[][] randMatrix = new int[power-1][power-1];
     if (power < 1 || power > 6){
        System.out.println("Invalid power");
     }else{
        for (i=0; i<randMatrix.length; i++){
           for (j=0; j<randMatrix.length; j++){
              randMatrix[i][j] = rand.nextInt(9);
           }
        }for (i=0; i<randMatrix.length; i++){
           for (j=0; j<randMatrix.length; j++){
              System.out.println(randMatrix[i][j]);
           }
        }
     }
  }




Pick a matrix cell according to its probability

I have a 2D matrix of positive real values, stored as follow:

vector<vector<double>> matrix;

Each cell can have a value equal or greater to 0, and this value represents the possibility of the cell to be chosen. In particular, for example, a cell with a value equals to 3 has three times the probability to be chosen compared to a cell with value 1.

I need to select N cells of the matrix (0 <= N <= total number of cells) randomly, but according to their probability to be selected.

How can I do that?

The algorithm should be as fast as possible.




How to set the color of a Random JButton?

I'm trying to make a simple game in java. Basicially, upon clicking a "start" JButton, 3 other buttons (labeled A, B, and C) will pop up in a separate JFrame. I want one of the buttons (a random one) to be red as soon as this second JFrame opens. Each time I click the start button, a random button must be red. In addition to that, after I click the red button, I want another random button to be red, and the cycle continues. Here is my code so far:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Driver {
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Game());
    JFrame window;
    window = new JFrame("Clicking Game");
    window.setSize(300, 300);
    JButton b = new JButton("START");
    window.setLayout(new GridLayout(5,5));
    window.add(new JLabel("INSTRUCTIONS: \n Click the 'START' button to start the game."
            + " Click as many of the red buttons as you can before time runs out!"));
    window.add(b);
    window.pack();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
    b.addActionListener(new StartButtonHandler());
    b.addActionListener(new ActualButtonHandlers());



}

}

package code;


import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

class StartButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JFrame win = new JFrame("CLICK FAST!");
            win.setVisible(true);
            win.setSize(500, 500);
            JButton a = new JButton("A");
            JButton b = new JButton("B");
            JButton c = new JButton("C");
            win.add(a);
            win.add(b);
            win.add(c);
            win.pack();
            win.setLayout(new GridLayout(1,3));




url rotator with divs in php+html5 (no js+no iframe)

I made an url rotator with only php and html5 so not used iframe and trying to do without using js. Urls from db will be shown with next button and open web page in div object.How should i define variable to put inside object data ?

    <!DOCTYPE html>
<html>
<head>
</head>
<?php
$servername = "xxxxxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxx";
$dbname = "db";

    $conn = mysql_connect($servername, $username, $password);
    $vt_sec=mysql_select_db("db",$conn);


    if ($_GET['orderby']=='timer') {
    $get= mysql_query ("select * from urllist order by timer asc");
    }
        else {
         $get= mysql_query ("select * from urllist order by id desc");
     }
    $list= mysql_fetch_array($get);
    $url = $list['url'];
    ?>
<body style="background-color: lightgray;margin: 0px">
        <div class="menu" style="height: 50px">
            <div class="menuin" style="float:left"><a href="index.php">Home</a></div>                           
            <div class="menuin" style="float:right"><a href="<?php $url['url']?>">NEXT</a></div>


        </div>
        <div style="background-color: green;margin:0px ">
    <object name="main" data= '<?php $url ?>' type="text/html"style="position:fixed;width:100%;height:100%;margin:0px"></object>
        </div>
</body>
</html>




Checking for random string in Python [duplicate]

This question already has an answer here:

Is there a library that allows me to check for the randomness of an input string? Something like:

 >>> is_random_str("dfgjfgnsdfj9p5230948hfirif") -> returns True
 >>> is_random_str("Hello theree") -> returns False




How to concatenate Faker's random first name and its last name to a full name in Laravel 5

I am trying to use Faker in Laravel 5. Now I need to create some users in my User table, I choose Faker.

I know how to create random firstname, lastname or userName, but I want to concatenate each FN and LN to be username, how can I do that? Here is my codes in seeder file.

public function run()
{
    $faker = Faker::create();

    foreach(range(1, 10) as $index) {
        User::create([
            'first_name'     => $faker->firstName($gender = null|'male'|'female'),
            'last_name'     => $faker->lastName,
            'username'     => $faker->userName(),
            'email'     => $faker->email,
            'password'     => bcrypt($faker->password(6))
        ]);
    }
}

image of seeder content




C++ Bowling Simulator Program

I recently received an assignment to create a bowling program in C++ that simulates two people bowling and outputs the correct score for each frame. My program works by first generating all the throws for each frame and then accumulating the score afterwards in a separate method. I was able to get the program to work when the player bowls a non-perfect game and a perfect game, but I am having problems with when a player bowls all spares. I rigged the code to make it so I have 9 for a first throw and 1 for the second throw (this is in frame.cpp). The total should be 190, but I am getting 191 and I can't seem to find the error. Each bowling class contains an array of 11 frames. I know there are only 10 frames but this is to account for if the player gets a strike on the tenth frame. Any help would be appreciated, thanks.

Here is the frame. h file

#ifndef FRAME_H
#define FRAME_H
#include<iostream>
using namespace std;

class Frame
{
private: int throw1;
         int throw2;
         int score;
         bool spare;
         bool strike;

public: Frame();
        int genThrow(int size);
        int getFirstThrow();
        int getSecondThrow();
        int getScore();
        void setScore(int);
        void setFirstThrow(int value1);
        void setSecondThrow(int value2);
        void setStrike(bool value);
        void setSpare(bool value);
        bool getStrike();
        bool getSpare();
};
#endif

Here is the frame.cpp file

#include "Frame.h"
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

Frame::Frame()
{
    spare = false;
    strike = false;
    throw1 = 0;
    throw2 = 0;
    score = 0;
}

//generates a random throw
int Frame::genThrow(int size)
{
    int randomNumber = 0;

    if (size < 10 || throw1 != 10)
    {
        randomNumber = 0 + rand() % (11 - throw1); //generate a number between 0 and 10
    }
    else
    {
        randomNumber = 0 + rand() % (11);
    }

    //cout << randomNumber << endl;

    return randomNumber;
}

//get first throw
int Frame::getFirstThrow()
{
    return throw1;
}

//get second throw
int Frame::getSecondThrow()
{
    return throw2;
}

//get the score of both throws
int Frame::getScore()
{
    return score;
}

//set the score
void Frame::setScore(int value)
{
    score = value;
}

//set the first throw
void Frame::setFirstThrow(int value1)
{
    //throw1 = genThrow(value1); //normal generator
    //throw1 = 10; //strike game rigged
    throw1 = 9; //spare game rigged
}

//set the second throw
void Frame::setSecondThrow(int value2)
{

    //throw2 = genThrow(value2); //normal generator

    throw2 = 1; //spare game rigged
    //throw2 = 10; //strike game rigged
}

//set the strike
void Frame::setStrike(bool value)
{
    strike = value;
}

//set the spare
void Frame::setSpare(bool value)
{
    spare = value;
}

//get the strike
bool Frame::getStrike()
{
    return strike;
}


//get the spare
bool Frame::getSpare()
{
    return spare;
}

Here is the bowling.h file

#ifndef BOWLING_H
#define BOWLING_H
#include "Frame.h"
#include<iostream>
using namespace std;

class Bowling 
{
private: Frame a[11];

public: void accumulateScore();
        void bowl();
        void printData();
};
#endif

Here is the bowling.cpp file

#include "Bowling.h"
#include<iostream>
using namespace std;

//takes all of the throw values after bowling and accumulates the correct score
void Bowling::accumulateScore()
{
    int totalSum = 0;
    for (int x = 0; x < 10; x++)
    {
        if (a[x].getFirstThrow() + a[x].getSecondThrow() < 10) //not a strike or spare
        {
            totalSum += a[x].getFirstThrow() + a[x].getSecondThrow();
            a[x].setScore(totalSum);
        }
        else if (a[x].getFirstThrow() == 10) //throws a strike
        {
            if (x < 9)
            {
                totalSum += 10 + a[x + 1].getFirstThrow() + a[x + 1].getSecondThrow();
                if (a[x + 2].getStrike() == true)
                {
                    totalSum += 10;
                }
                a[x].setScore(totalSum);
            }
        }
        else if (a[x].getFirstThrow() + a[x].getSecondThrow() == 10) //throws a spare
        {
            if(x < 10)
            {
                totalSum += 10 + a[x + 1].getFirstThrow();
                a[x].setScore(totalSum);
            }
        }
    }

    //player got the 11th frame
    if (a[9].getStrike() == true)
    {
        totalSum += 10 + a[10].getFirstThrow() + a[10].getSecondThrow();
        a[9].setScore(totalSum);
    }
    else if (a[9].getSpare() == true)
    {
        totalSum += 10;
        a[9].setScore(totalSum);
    }
}

void Bowling::bowl()
{
    //generate all throws and store them in the frames
    for (int x = 0; x < 10; x++)
    {
        a[x].setFirstThrow(x);
        if (a[x].getFirstThrow() == 10)
        {
            a[x].setStrike(true);
        }
        if (a[x].getStrike() == false)
        {
            a[x].setSecondThrow(x);
            if (a[x].getFirstThrow() + a[x].getSecondThrow() == 10)
            {
                a[x].setSpare(true);
            }   
        }
        a[x].setScore(a[x].getFirstThrow() + a[x].getSecondThrow());
    }

    //play the 11th frame if they got a strike on the tenth frame

    if(a[9].getStrike() == true)
    {
        a[10].setFirstThrow(10);
        if (a[10].getFirstThrow() == 10)
        {
            a[10].setStrike(true);
        }
        a[10].setSecondThrow(10);
        cout << "The second throw is this value: " << a[10].getSecondThrow() << endl;
        if (a[10].getSecondThrow() == 10)
        {
            a[10].setStrike(true);
        }
        else if (a[10].getFirstThrow() + a[10].getSecondThrow() == 10)
        {
            a[10].setSpare(true);
        }
        a[9].setScore(a[10].getFirstThrow() + a[10].getSecondThrow());

    }
}

void Bowling::printData()
{
    for (int x = 0; x < 10; x++)
    {
        cout << "*****************************" << endl;
        cout << "Frame " << x + 1 << endl;
        cout << "First throw: ";
        if (a[x].getStrike() == true)
        {
            cout << "Strike!" << endl;
        }
        else
        {
            cout << a[x].getFirstThrow() << endl;
        }


        cout << "Second throw: ";
        if (a[x].getStrike() == false)
        {
            if (a[x].getSpare() == true)
            {
                cout << "Spare!" << endl;
            }
            else if(a[x].getSpare() == false)
            {
                cout << a[x].getSecondThrow() << endl;
            }
            else
            {
                cout << endl;
            }
        }
        cout << "Score: " << a[x].getScore();
        cout << endl;
    }

    if (a[9].getStrike() == true)
    {
        cout << "*****************" << endl;
        cout << "Frame 11" << endl;
        cout << "First throw: ";
        if (a[10].getStrike() == true)
        {
            cout << "Strike!" << endl;
        }
        else
        {
            cout << a[10].getFirstThrow() << endl;
        }
        cout << "Second throw: ";

        if (a[10].getStrike() == false)
        {
            if (a[10].getSpare() == true)
            {
                cout << "Spare!" << endl;
            }
            else
            {
                cout << a[10].getSecondThrow() << endl;
            }
        }
        else
        {
            cout << "Strike!" << endl;
        }
        //cout << "Score: " << a[10].getScore();
        cout << endl;
    }
}

Here is where I test it in main

#include "Bowling.h"
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(time(0));
    int dummy = 0;

    //create two players that can bowl
    Bowling player1;
    Bowling player2;
    int player1Score = 0;
    int player2Score = 0;

    //have the players bowl their throws before accumulating score
    player1.bowl();
    player2.bowl();

    //accumulate the score after all of the throws have been done
    player1.accumulateScore();
    player2.accumulateScore();

    //print player 1 data
    cout << "Here are the throws and score for the first player: " << endl;
    player1.printData();

    //spacing
    cout << endl << endl;

    //print player 2 data
    cout << "Here are the throws and score for the second player: " << endl;
    player2.printData();

    cout << "Enter a dummy number:" << endl;
    cin >> dummy;
    return 0;
}




Meteor-Random - How to know if strong or weak generator

The meteor documentation at http://ift.tt/1C8PFGi says:

... It uses a cryptographically strong pseudorandom number generator when possible, but falls back to a weaker random number generator when cryptographically strong randomness is not available (on older browsers or on servers that don't have enough entropy to seed the cryptographically strong generator).

Q: May I get somewhere in my scripts the information if generating a strong random generator is available or not.

I would like to show a box like: "Sorry you can not generate strong randoms within your environment" instead of creating weaker ones.

Thanks for some feedback Tom




random number generators from c++

I'm learning about the library, which improves on the old rand and srand in many ways. But with the rand it's clear that there is one and only one random number generator that gets called and updated whenever rand is used, wherever that is in your program. With the new way I'm not sure how to imitate this behaviour efficiently and with good style. For instance what if I want a dice roll and, aping online examples written in the main procedure, I write an object with a method like this:

class foo{
    public:
    float getDiceRoll(){
        std::random_device rd;
        std::default_random_engine e1(rd());
        std::uniform_int_distribution<int> uniform_dist(1, 6);
        return uniform_dist(e1);
   }
}

This looks terrible because the engine is re-created every time you want a dice roll. This is a bit of a contrived case, but in a large program you are going to have to put the declaration of the random number generator somewhere. As a first attempt to use I just want there to be one generator for all random numbers, like in the old days. What is the nicest way to achieve this? Easily available examples online are all written straight into the main procedure and so they do not answer this basic question. I cannot think of anything that doesn't seem like taking a sledgehammer to crack a nut. Any help would be great.




Random path in MATLAB

I have a simple random path code:

    while t <= T 
    p=rand(1,N); 
    for i=1:N 
    if p(i) < p_l
        pos(i)=pos(i)-delta_x; 
    elseif p(i) < (1-p_r)
        pos(i)=pos(i); 
    else
        pos(i)=pos(i)+delta_x; 
    end
    end
    t=t+tau; 
    end

But I need a help with a more complicated random path project, it's about a need for two functions that need for the generation of random trajectories. The first one calculates the cumulative density functions for both change of segment length and change in direction and stores it for later use (and analysis). The second one then takes the number of segments from the measured path and generates a random trajectory by using the cdfs generated by the first function. This step should be fast as that is used repeatedly many times to generate a high number of random paths; ranging from -1 to 1. A typical path consists of 4 - 50 segments. First xy values representing the first node, the next pair the next node and so forth. The direct connection between a node to the next represents a segment. Each segment has a specific length and a specific directional aberration relative to the preceding segment.
For a measured path, both change of segment lengths and change of direction show a specific distribution that can be expressed as a cumulative density function. I think this could be done with a built in cd function.

Any suggestions?

Thanks! Stepphan




What it is best way to generate random FUZZY numbers?

I am wondering about the best way to generate random fuzzy numbers. In the case of triangular fuzzy numbers. Is it fine to consider the generation of three random REAL numbers (a1, a2, a3) as a correct approach in terms of distribution ?




std::rand() function gives back unproper results

I have simply functions to random numbers but there is something wrong with the first one because the results are not correct.

 int wylosuj(int a, int b)
{
    int wynik=(( std::rand() % b-a+1 ) + a);
    return wynik;
}

Second Function (this one gives me the proper result)

int wylosuj(int a, int b)
{
int endNumber=b-a+1;
int startNumber=a;
return std::rand()%endNumber+startNumber;
}

In my main function I have got this line to run the function with arguments:

wylosuj(3,3);

So desired results should be only 3.

Where did I make mistake with first function?




Generate random number using given number. C++

I'm stuck with a problem. I'm making the Rock-Paper-Scissors game for my homework, but I don't know how to generate the number using just 3 specific given number and convert to character using char and ASCII Those given numbers are : 66, 71 and 75




How to add objects in Android Studio to move randomly

I see a tutorial for moving droid here : http://ift.tt/1o5BUyr

How can I another object in the main Java code? I already add the other object in the MainGamePanel.Java but still, there is just 1 object shown.




Creating specific images and placing them in random positions within a div

Using the code submitted here, how could I do a similar thing but with a specific number of specific images, with the only random variable being their positions?

$(document).ready(function(){
var ticket="<div class='ticket'><img src='http://ift.tt/1GysLg0'></div>";
var numTickets=10;
for(var x=1;x<=numTickets;x++){
    $(ticket).appendTo("body");
}
// get window dimentions
var ww = $(window).width();
var wh = $(window).height();
$(".ticket").each(function(i){
    var posx = Math.round(Math.random() * ww)-20;
    var posy = Math.round(Math.random() * wh)-20;
    $(this).css("top", posy + "px").css("left", posx + "px")
});
});

I edited 2pha's code to get rid of rotation, since that's what I'm after, but I don't know I'd edit it to generate a specific set of images.

Here's an edited Fiddle to show what I'm talking about

Thanks a lot :)




Why is this shuffle not uniformly random?

Why is this shuffle not uniformly random? (psuedocode)

    for (int i = 0; i < N; i++)
    {
        int r = random number between 0 and (N-1);
        swap array[i] and array[r];
    }




Q: use rejection sampling for true random number generation in a range (entropy from radioactive decay)

Hi everyone I have been doing some reading and have come across true random number generation using the entropy from radioactive decay. I have written a helper tool that returns the next random byte. It uses a server that provides bits from such a setup, I believe its data is from cesium decaying. I have done quite a bit of searching and have not really been able to figure out how to go about using this to generate numbers in a range from 0..n-1.

A user on the unofficial SO irc told me this

if you have a random byte, 0..255 evenly distributed and you want a random number in the range 0..5 there are 6 values in the output range and 256 in the input range the greatest multiple of 6 that is <= 256 is 252 so you would sample your random byte until you get a number in the range 0..251 then you could take the number MOD 6 to get your output number.

Im not really sure how to sample the byte. Do I use a single byte or do I have to continually request more bytes? Im really just having a hard time rapping my head around this, so any thorough explanation not using obscure math notations would be extremely appreciated.

Thanks.




mercredi 28 octobre 2015

Function returning too many poker cards and duplicates

I'm trying to get the second function to call the first function, check for duplicates, then return 2 cards (made up of 2 items from RANK and 2 from SUIT). It's returning more than 2 cards though and I don't know why.

It's returning two lists in the output. 2 of which are duplicates, but I don't know if it's how I appended them in the first function that's at fault or something else.

#!/usr/bin/python3
from random import choice
from random import randint

class Cards(object):
    RANK = [1,2,3,4,5,6,7,8,9,10,'J','Q','K','A']
    SUIT = ['Club','Diamond','Heart','Spade']
 #Creates One random card/suit combo   
    def picker(self):
        pick=[]
        pick.append(choice(self.RANK))
        pick.append(choice(self.SUIT))
        return pick

#'Should' create 2 cards, check that they aren't dupes, and return them.
    def hole(self):
        hold=[]
        nodup=[]
        while len(hold)<5:
            nodup.append(self.picker())
            if nodup not in hold:
                hold.append(nodup)
            else:
                hold.append(self.picker())
                continue
        return hold

When I call the function, I get this-

>>> from cards import Cards
>>> test=Cards().hole()
>>> test
    [[[2, 'Heart'], ['Q', 'Spade'], [2, 'Diamond'], [9, 'Club'], [1, 'Diamond']], [5, 'Heart'], [5, 'Heart'], [5, 'Club'], ['K', 'Heart']]

I want-
>>> [2, 'Heart'], ['Q', 'Spade']




Encog NEAT Network evolving to a maximum size? (for approximating a complex function)

I am trying to create a neural network to approximate the output of a deterministic pseudo-random number generator function. I am starting of by using Encog's NEAT network.

Generating a pseudo random number involves a lot of arithmetic (yes I know NN's is not ideal for this) and I thus expect quite a lot of hidden layers and neurons to finally approximate this function.

Is there any limit in growth size increase(amount of neurons) of the NN offspring while evolving which might thus hinder populations to properly evolve into the fittest state possible?

Hoping that Jeff (http://ift.tt/1SayGJc) picks up on this question.




Connect Random Room from Directory (C)

I have almost similar questions like this thread (Connect Rooms Randomly in Adventure Game), but not similar since I'm using file from directory (not just pure loose file.txt)

Summary: I have to create 7 rooms that must have a random (3 to 6) connections between files, and also provide a connection back. (If "a" connect to "b", then "b" must have connection back to "a").

What I'm doing is that I'm solving this problem by creating like a "matrix" to provide the connection between the files.

My code: (I'm still following the answer given from the thread above, but going to modify it soon)

#define MAX_ROOM 7

int conn[MAX_ROOM][MAX_ROOM] = {{0}};

int uniform(int n) {
    return n * (rand() / (double) RAND_MAX);
}

// function for connection between file

void connect(int visited[], int final, int initial) {
    conn[initial][final] = 1;
    conn[final][initial] = 1;

    if (visited[initial] ==0) {
        int room[MAX_ROOM - 1];
        int next[MAX_ROOM - 1];
        int i, j;
        visited[initial] = 1;

        for (i = 0; i < MAX_ROOM; i++) {
            room[i] = i;
        }
        room[initial] = MAX_ROOM - 1;

        i = MAX_ROOM - 1;
        while (i) {
            int swap;
            j = uniform(i--);
            swap = room[i];
            room[i] = room[j];
            room[j] = swap;
        }

        j=0;
        for (i=0; i < MAX_ROOM; i++) {
            if (visited[room[i]] == 0) {
                next[j++] = room[i];
            }
        }

        for (i=0; i < MAX_ROOM; i++) {
            if (visited[room[i]] !=0) {
                next[j++] = room[i];
            }
        }

        for (i = 0; i < 3; i++) {
            connect(visited, initial, next[i]);
        }
    }
}

int main () {
    char *room_name[7];
    room_name[0]="L";
    room_name[1]="R;
    room_name[2]="K";
    room_name[3]="W";
    room_name[4]="D";
    room_name[5]="M";
    room_name[6]="B";

    int visited[MAX_ROOM] = {0};
    int i,j;

    connect(visited,0,1);

    i = 10;
    while (i) {
        char *pointer;
        j = uniform(i--);
        pointer = room_name[i];
        room_name[i] = room_name[j];
        room_name[j] = pointer;
    }
    int counter;
    for (counter=0; counter < 7; counter++){

    snprintf(currentFile, bufSize ,"%s/file-%d.txt",DIRECTORY_NAME,counter);
    FILE *f = fopen(currentFile,"a");
    if (f==NULL) {
        perror("Error in opening the file. \n");
    } else {

    for (i=0; i < MAX_ROOM; i++) {
        printf("%s\n", room_name[i]);
        for (j=0; j < MAX_ROOM; j++) { 
            if (conn[i][j]) {
                printf("CONNECTION 'j' -> %s\n", room_name[j]);
            }
        }
        printf("\n");
     }
 fclose(f);
}

What I'm expecting is:

(inside "file-1.txt" in directory & assume I got 4 connections)

CONNECTION 1: L
CONNECTION 2: D
CONNECTION 3: B
CONNECTION 4: R

But instead, I got:

(inside EVERY FILE in my directory)

CONNECTION 1: L
CONNECTION 2: D
CONNECTION 3: B
CONNECTION 4: R
CONNECTION 5: M
CONNECTION 6: S

So no matter how many connection created, it just simply print all connections in every room to every room.

Is it something wrong in my nested for loop between counter and i? Or is it something else?




How to generate random Email Address by Name, Date of Birth and other data?

Lets say I have data like this : enter image description here

I need to generate email address from that 4 fields with PHP. For example : marc93-marquez@email.com, vale-rossi@email.com, lorenzo99@email.com (it's totally random for all email but stick to the value of each field. How do I create that logic with PHP?

Thanks for your help.




How to use ISAAC in C

I downloaded isaac64 from here and I have some problem with usage. I had to comment a part of code in isaac64.c becouse it contained main function. But I can't use it... I can't properly initialize it and get random number, can you help me? I couldn'y found any example.




trouble turning file into array and then outputting object value

The goal of my application is simple:

  • Accept a random number parameter
  • Read the dictionary.txt file
  • turn that file into an array by taking each word in the file (each word is on a new line in the file)
  • push each array item created into an object and then have itself as a word property

At the point I have the object created, my aim is to get a random word from that object, for example:

outputObj[randNum].word

Which should return the word at the index I set in the randNum parameter and the value stored in its word property.

I am getting confused and have tried everything I can think of to achieve the end result.

Here is my current JS:

var fs = require('fs),
    getWordFromRandomNumber = function(randNum) {
        var output = fs.readFileSync('../dictionary/dictionary.txt', 'utf8')
            .trim()
            .split('/n')
            .map(line => line.split('/n'))
            .reduce(function(outputObj, line){
            outputObj[line] =  outputObj[line] || [];
            outputObj[line].push({
                word: line,
            });
            return outputObj[randNum].word;
        }, {});


        console.log(JSON.stringify(output, null, 2));
    }

getWordFromRandomNumber(25);

I expect this to return to me the value of outputObj[25].word but all I get is a cascade of the whole file, see here (note I am using my cmd to run the file using babel and node with the command "babel wordGenerator.js | node":

enter image description here

Any help would be much appreciated as I am all out of ideas at the moment.

Thanks, SD




Java sorting: random gen numbers same as sorted numbers(in terms of order)

I have a program that sorts randomly generated numbers from least to greatest or greatest to least depending on the users choice. 2 problems are occurring.

When the user does Insertion Sorting with Descending, the randomly generated numbers and sorting numbers output like this for example:

Randomly Generated Numbers: 89 90 2 830 399


After sorting using the Insertion Sort, Using Descending Order, the array is: 89 90 2 830 399

It's weird because my other methods are EXACTLY the same, and they work fine, but for some reason this doesn't work.

Here is my code:

import javax.swing.*;
import java.lang.reflect.Array;
import java.util.Random;


public class RoutineSorter {

private static int[] generateRandomArray(int size, int randomMax) {
    int[] array = new int[size];
    Random randomGenerator = new Random();
    for (int i = 0; i < size; i++) {
        array[i] = randomGenerator.nextInt(randomMax);
    }
    return array;
}

public static void main(String[] args) {
    int MethodChoice = Integer.parseInt(JOptionPane.showInputDialog("What method would you like to use to sort the random numbers" + "\n" + "1 - Selection Sort" + "\n" + "2 - Bubble Sort" + "\n" + "3 - Insertion Sort" + "\n" + "4 - Quick Sort"));
    int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog("What is the total number of integers?"));
    int SortOrder = Integer.parseInt(JOptionPane.showInputDialog("1 - Ascending, " + "2 - Descending"));

    int[] array = generateRandomArray(iTotalCount, 1001);

    System.out.println("Randomly Generated number list: ");
    for (int i: array) {
        System.out.print(i + " ");
    }
    System.out.println("\n---------------------------------");


    if (MethodChoice == 1) {
        if (SortOrder == 2) {
            selectionSortReverse(array);
            System.out.println("After sorting using the Selection Sort, " + "Using Descending Order" + " " + "the array is: ");
        } else if (SortOrder == 1) {
            selectionSort(array);


            System.out.println("After sorting using the Selection Sort," + " the array is:");
        }
    } else if (MethodChoice == 2) {
        if (SortOrder == 2) {
            bubbleSortReverse(array);
            System.out.println("After sorting using the Bubble Sort, " + "Using Descending Order" + " " + "the array is: ");
        } else if (SortOrder == 1) {
            bubbleSort(array);


            System.out.println("After sorting using the Bubble Sort," + " the array is:");
        }
    } else if (MethodChoice == 3) {
        if (SortOrder == 2) {
            insertionSortReverse(array);
            System.out.println("After sorting using the Insertion Sort, " + "Using Descending Order" + " " + "the array is: ");
        } else if (SortOrder == 1) {
            insertionSort(array);


            System.out.println("After sorting using the Insertion Sort," + " the array is:");

        } else if (MethodChoice == 4) {
            if (SortOrder == 2) {

            }

        }

        for (int i: array) {
            System.out.print(i + " ");
        }

    }

}


public static void quickSort(int data[], int low, int high) {
    int partitionLoc;
    if (low < high) {
        partitionLoc = partition(data, low, high);
        quickSort(data, low, partitionLoc - 1);
        quickSort(data, partitionLoc + 1, high);
    }
}

public static void quickSortReverse(int data[], int low, int high) {
    int partitionLoc;
    if (low > high) {
        partitionLoc = partition(data, low, high);
        quickSort(data, low, partitionLoc - 1);
        quickSort(data, partitionLoc + 1, high);
    }
}

public static int partition(int data2[], int left, int right) {
    boolean moveLeft = true;
    int separator = data2[left];

    while (left < right) {
        if (moveLeft == true) {
            while ((data2[right] >= separator) && (left < right)) {
                right--;
            }
            data2[left] = data2[right];
            moveLeft = false;
        } else {
            while ((data2[left] <= separator) && (left < right)) {
                left++;
            }
            data2[right] = data2[left];
            moveLeft = true;
        }
    }
    data2[left] = separator;
    return left;
}



public static void bubbleSort(int data[]) {
    //Loop to control number of passes
    for (int pass = 1; pass < data.length; pass++) {
        //Loop to control # of comparisons for length of array-1
        for (int element = 0; element < data.length - 1; element++) {
            //compare side-by-side elements and swap them if
            //first element is greater than second element
            if (data[element] > data[element + 1]) {
                swap(data, element, element + 1); //call swap method
            }
        }
    }
}

public static void bubbleSortReverse(int data[]) {
    //Loop to control number of passes
    for (int pass = 1; pass < data.length; pass++) {
        //Loop to control # of comparisons for length of array-1
        for (int element = 0; element < data.length - 1; element++) {
            //compare side-by-side elements and swap them if
            //first element is greater than second element
            if (data[element] < data[element + 1]) {
                swap(data, element, element + 1); //call swap method
            }
        }
    }
}


public static void swapBubble(int array2[], int first, int second) {
    int hold = array2[first];
    array2[first] = array2[second];
    array2[second] = hold;

}


public static void insertionSort(int data[]) {
    int insert;

    for (int next = 1; next < data.length; next++) {
        insert = data[next];
        int moveItem = next;

        while (moveItem > 0 && data[moveItem - 1] > insert) {
            data[moveItem] = data[moveItem - 1];
            moveItem--;
        }
        data[moveItem] = insert;
    }
}

public static void insertionSortReverse(int data[]) {
    int insert;

    for (int next = 1; next < data.length; next++) {
        insert = data[next];
        int moveItem = next;

        while (moveItem < 0 && data[moveItem - 1] < insert) {
            data[moveItem] = data[moveItem - 1];
            moveItem--;
        }
        data[moveItem] = insert;
    }
}



public static void selectionSort(int data[]) {
    int smallest;
    for (int i = 0; i < data.length - 1; i++) {
        smallest = i;
        //see if there is a smaller number further in the array
        for (int index = i + 1; index < data.length; index++) {
            if (data[index] < data[smallest]) {
                swap(data, smallest, index);
            }
        }
    }
}

public static void selectionSortReverse(int data[]) {
    int smallest;
    for (int i = 0; i < data.length - 1; i++) {
        smallest = i;
        //see if there is a smaller number further in the array
        for (int index = i + 1; index < data.length; index++) {
            if (data[index] > data[smallest]) {
                swap(data, smallest, index);
            }
        }
    }
}




public static void swap(int array2[], int first, int second) {
    int hold = array2[first];
    array2[first] = array2[second];
    array2[second] = hold;



}

}




Generating a list of random permutations of another list

So, I'm trying to tackle the TSP with a Genetic Algorithm. To do that I need to create a population pool. What I wan't to accomplish is to create a list of random permutations that will represent a population pool. I'm trying to do this using random.shuffle. Here's my code that should handle that part. Cities is a list of cities and routes is where I want to keep the population pool (a list of N random permutations):

for x in range(n):
    random.shuffle(cities)
    routes.append(cities)

What happens is that it just appends the same permutation n times. Anybody have any idea about what I might be missing?




Problems when shuffling an array of strings

I am attempting to shuffle an array of strings, below is the segment of code i have already. However, a problem with this code is that alot of the times it shuffles the content but excludes one value. e.g shuffling A, B, C, D it will do this: A, D , , C.

Any help would be greatly appreciated.

Private rnd = New Random()

Public Sub Shuffle(ByRef List() As String)
    Dim Limit As Integer = List.Length - 1

    For i = Limit To 0 Step -1
        Dim j As Integer = rnd.Next(0, i + 1)
        Dim temp As String = List(i)
        List(i) = List(j)
        List(j) = temp
    Next
End Sub




Random syntax errors in script

I have a very puzzling problem in Python 2.7 I use Notepadd++ After developing a script of no more than 25 lines, when running it on Python it gives me "Syntax Errors" on different lines of the script on re-running it even if the that line runs OK on the interpreter. For instance, on simple statements like assigning a value to a variable, the second or third assignment to that variable gives me the syntax error. I went to the length of typing line by line on the interpreter and each executed with success, arriving at the proper result in the last line. I tried to re-write and run the same script (copying line by line) on IDLE (which gives me also random line syntax errors) and lastly resorting to Microsoft Notepad. No better. Please your help will make me understand such a complex language as Python. Thank you. I use WIndows 10 and the script is a test of Hashing and AES encrypting from Crypto.Hash / Crypto.cipher. I am ready to furnish a copy of the script.




Randomly place n elements in an array of m elements

I need a boolean or binary numpy array size (m,m) with n True values scattered randomly. I'm trying to make a random grid pattern. I will have a 5x5 array with 3 True values over it and will sample at those points only.
Using random.choice I sometimes get more or less than the 3 desired True values.

for x in range(0,25):
    x = np.random.choice([True,False], p=[0.15,0.85])




start position and movement randomly for some divs

I'm now looking for some days on the internet for a right code but i wont find it. I want to make the following action, but than that the divs start at a random position instead of the top left:

*http://ift.tt/1P55Da1

Unfortunately my javascript skills are not so good enough to find the solution by myself.




Need something better than a massive if else if a specific random number is returned

Hopefully you can see what I am going for here. Obviously this code doesn't work but I'm basically trying to say if the random number is one of these values, run this code. If the random number is another value run that code. I need something that is equivalent to a big or statement without using a large if-else. Thanks

    static int cardNumber = rnd.nextInt(13) + 1;

    if (cardNumber == 1||11||12||13)
    {
        System.out.println(faceCard + " of " + suit);
    } 
    else 
    {
        System.out.println(cardNumber + " of " + suit);
    }




How to code for rabbit and tortoise race in matlab?

The racing track consists of a rectangle of perimeter P and area A. While the turtle runs slowly at the regular pace of one step per unit of time, the rabbit, who feels confident in his racing abilities, randomly decides to run for a random distance. When the rabbit runs, the distance it covers is an integer between 2 and 10 selected following the uniform distribution. Notes: A unit of time is represented by a loop iteration. The race starts in (0,0) at the bottom left corner of the rectangle, and is run in the clockwise direction.

Write a MATLAB function taking as input: P and A, as well as the probability for the rabbit to rest (that is, not to run). The function should plot the progress of the race at each unit of time using a red cross for the turtle and a blue line for the rabbit. Notes: The turtle and the rabbit both run on the same line. It is not necessary to plot the racing track. You are only required to plot the trajectory of the two runners.

Anyone can help me with this question!!?/




Random number generator between -1 and 1 in C++ [duplicate]

This question already has an answer here:

The title pretty much says it all. I've looked online but I couldn't find anything for this language. I've seen the following: ((double) rand() / (RAND_MAX)) with no luck. I'd also like to avoid using external library's.

The value should be a float as I'm working out X,Y coordinates.




How to randomly choose five pixels from a particular row

I have a part of an image of size 128-by-128 pixels and I want to randomly choose 5 pixels from a given row, say the 1st row. How do I do that?




mardi 27 octobre 2015

random number generation from a copula using set.seed

I'm running two sessions of RStudio on my laptop.

When I ran

set.seed(1)
runif(1)

twice in each session, four of them gave the same number 0.2655087.

But if I generate random numbers from a copula using rCopula function of copula package, it does not work. It produces the same numbers if I run it twice within the same session, but different numbers in a different session.

On session 1,

set.seed(5)  
dat = rCopula(50, gumbelCopula(2.07, dim = 2))
dat[1,]
# [1] 0.7058623 0.3512414
set.seed(5)  
dat = rCopula(50, gumbelCopula(2.07, dim = 2))
dat[1,]
# [1] 0.7058623 0.3512414

On session 2,

set.seed(5)
dat = rCopula(50, gumbelCopula(2.07, dim = 2))
dat[1,]
# [1] 0.2489993 0.6595176
set.seed(5)
dat = rCopula(50, gumbelCopula(2.07, dim = 2))
dat[1,]
# [1] 0.2489993 0.6595176

Why does it happen and how can I get the same numbers?




creating a random function that only gives integers in Processing

I'm trying to use the random() function in Processing in terms of an array, so random index #s are selected each time. I need all my random numbers to be integers for the array to work, is there any way I can specify the random function so it only returns whole numbers?




Create & Append Files into Directory

I kinda have similar questions like this guy (coava) posted.

(Append Random Text without Repetition for File (C))

I've tried the solution given but it doesn't work for me, maybe because in my case I'm storing those file in the directory as well.

So my code pretty much looks like this:

char *room[4];
room[0] = "okay";
room[1] = "sure";
room[2] = "fine";
room[3] = "noo";

int pid = getpid();
char dirname[30]
sprintf(dirname,"rooms.%d",(int)getpid());
mkdir(dirname,0777);

int bufSize=128;
char *current = malloc(bufSize);
int nroom = sizeof(room) - 1;
int count;

for (count=0;count<3;count++) {
 int ipick = rand()%nroom;
 int *pick = room[ipick];
 room[nroom] = room [--nroom];
 snprintf(currentFile,bufSize,"file-%d.txt",count);
 FILE *f = fopen(currentFile,"w")
 fprintf(f, "YOUR ROOM: %s\n",pick);
 fclose(f);
}

Then I get a seg.fault, I tried to modify

snprintf(currentFile,bufSize,"file-%d.txt",count);

into

snprintf(currentFile,bufSize,"file-%d.txt",dirname,count);

It didn't give seg.fault, but it just print outside the directory with the addition of inside of each file sometimes I got random value like

"connection host: @blablabla" or some junk symbol.

Is there something wrong in my for loop? Or is it somewhere else?




what does "an object reference is required for the non-static field, method, or property 'Random.Next(int, int)' mean?

The problem I'm having is that Visual studio is throwing an error under the code "Random.Next(1,10);" that says:

"an object reference is required for the non-static field, method, or property 'Random.Next(int, int)' "

So, I looked at answers to other questions with similar phrases. In these examples on Stack Overflow most suggestions said that someone needed to simply make the method or class static. I tried all combinations of this in this code and it did not fix the error in Visual Studio.

Any help is appreciated, Thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Data_Collector_Course_Assignment
{
    public class Device
    {
        // Returns a randoom integer between 1 and 10 as a measurement of an 
           imaginary object

        public int GetMeasurement()
        {
            int randomInt = Random.Next(1,10);
            return randomInt;
        }
    }
}




openssl RAND_add() documentation refers to RFC1750. RFC1750 is silent on the matter

The documentation for the openssl library's RAND_add function has this to say about the entropy argument:

The entropy argument is (the lower bound of) an estimate of how much randomness is contained in buf, measured in bytes. Details about sources of randomness and how to estimate their entropy can be found in the literature, e.g. RFC 1750.

source: http://ift.tt/1PPBH3j

RFC 1750 can be found here: http://ift.tt/1MS1HVr

... but of course it is completely silent on the subject of "entropy" (a text search reveals zero occurrences of this word in the document).

So here are my questions:

  1. What specifically is the entropy argument supposed to be a measurement of?
  2. What is the valid range of values (the argument is of type double)?

Many thanks.




Only add random number to list in loop when doesn't already exist

New to using lists. For automated testing purposes I am generating a list of distinct values. The following is a code block of concern:

Random rnd = new Random();
List<int> lVars = new List<int>();

        while (VarsCount < randVarsCount)
        {
            if(VarsCount > 0)
            {
                while(lVars.Distinct().Count() != lVars.Count()) 
                {
                    lRowVars.Insert(VarsCount, rnd.Next(1, 11)); //problem code 
                }
            }
            lVars.Add(rnd.Next(1, 11));
            MessageBox.Show(lRowVars[aRowVarsCounter].ToString());
            aRowVarsCounter++;
        }

Basically, how do I check to see if the int being added matches all of the list (as my code doesn't work)....I've tried some other code but ends up being ALOT of extra code and loops; usually when I feel I'm doing something superfluous I find there is an easier way.




Change variable value each time its called

I've used a variable that is set by choosing a word from an array (using time as the "random" index) throughout a site. Everything works great.

However - on some pages that variable is displayed multiple times, and each time it displays the same word.

Because I've hardcoded the variable (and randomly generated it on page load), it will be a massive headache to go through and change the variable to a function that instead returns the word. (This was not done in the first place for a reason - that didn't take the duplication into account.)

Here's the question: Is there a way to make a variable change its value each time its called?

I was thinking something along the lines of

<?php
$var = function returnNewWord(){
      /* generate random word here */
      return $ranWord;
}
?>

That does not work - but it may give you an idea of what I mean.

Anyone know how this may be possible? Thank you for your help.




Can't access a public variable [duplicate]

This question already has an answer here:

I'm trying to use a variable through a getter, but I cant't seem to access the variable. Here is the code, its a random number generator which is supposed to decide a random color. Any help is greatly appreciated.

import java.util.Random;

public class RNG {

  public void startRNG(){

    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }
  }

  public void showRandomInteger(int aStart, int aEnd, Random aRandom) {
    long range = (long)aEnd - (long)aStart + 1;
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart); // The variable I'm trying to access

  }

  public int getRandomNumber() {
      return randomNumber; // Can't access randomNumber
  }

  public void colorChooser() {
      switch (getRandomNumber()) {
      case 1:
          break;
      case 2:
          break;
      case 3:
          break;
      case 4:
          break;
      case 5:
          break;
      case 6:
          break;
      case 7:
          break;
      case 8:
          break;
      case 9:
          break;
      case 10:
          break;
      }
  }

} 




rand() somtimes outputs blank lines, and other times it works just fine

When this program runs it's supposed to display 3 different fruits/vegetables at random (repeats are OK) but sometimes one or more of the outputs are blank and I'm not sure how to correct this. It also counts and displays how many times you chose to run the program.

Sometimes the output looks like this: Broccoli Kiwi Kiwi

And other times the output looks like this: (blank line) Tomato (blank line)

How do I fix this? I'm sure the problem is somewhere within the for-loop with boxInt

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

const int BOX_SIZE = 3;

class BoxOfProduce
{
public:
    BoxOfProduce();
    void displayWord(int boxInt);
    void input();
    void output();
    string Box[BOX_SIZE];

private:
    string full_list[5];
    static int count;
};


int BoxOfProduce::count = 0;


BoxOfProduce::BoxOfProduce()
{
    full_list[0] = { "Broccoli" };
    full_list[1] = { "Tomato" };
    full_list[2] = { "Kiwi" };
    full_list[3] = { "Kale" };
    full_list[4] = { "Tomatillo" };
}


void BoxOfProduce::input(){}


void BoxOfProduce::output()
{
    srand(time(0));

    int i;
    cout << "your bundle: " << endl;
    for (i = 0; i < 3; i++) // loop to execute code 3 times
    {
        int boxInt = rand() % 5; //make random number
        Box[i] = full_list[boxInt]; //add it to the Box
        displayWord(boxInt); //display it
    }
}
void BoxOfProduce::displayWord(int boxInt)
{
    cout << Box[boxInt] << endl;
}

int main()
{
    char userInput;
    static int counter = 0; // static variable for keeping track of how many boxes the user has opened

    do
    {
        cout << "Open new box of random produce? (y/n): ";
        cin >> userInput;

        if (userInput == 'y')
        {
            counter++;
            BoxOfProduce box1;
            box1.input();
            box1.output();

            cout << "\nCurrent number of produces boxes: " << counter << endl << endl;
        }
        else
        {
            return 0;
        }
    } while (userInput = 'y');

    system("pause");
}




Run Rand() Excel function until desired outcome occurs

I am trying to simulate values for a portfolio, and part of that includes generating pairs of 1200 randomly generated numbers. Skipping a few steps, a portfolio consisting of multiple paths is set up. In order to calculate the continuously compounded return, the terminal values of each path need to be positive, which in turn depend on the randomly generated numbers.

Now my question would be, is it possible to keep the Rand() function running, until all of the terminal values exhibit positive signs? Or do I need to manually click "calculate" until I get the result I want?

Thank you in a dance for you answers.




Monty Hall Simulator

This code compiles and runs, but I don't get the correct percentage for the Monty Hall problem. The answer should be closer to 66% for switching. I cannot find where the problem is. The percentage for staying with the same door is right, but the switching, which includes the switchChoice and the revealedDoor function is giving consistent but incorrect results.

#include <iostream>
#include <vector>
#include <iomanip>
#include <time.h> 

using namespace std;
int winner();
int userChoice();
int switchChoice(int, int);
bool decision( int, int);
vector <int> simulation();
void analytics();
int revealedDoor();

int main(int argc, char *argv[]) {
    time_t seconds;
    time(&seconds);
    srand((unsigned int)seconds);
analytics();    
}
int winner(){
    return  (rand() / ( RAND_MAX / 3 ) + 1);
}
int userChoice(){
    return (rand() / ( RAND_MAX / 3 ) + 1);
}
int revealedDoor(int winnerX){  
    if (winnerX == 1){
            return  (2 + rand() % 2);
        }
        else if (winnerX == 2){
            if( ( 3 + rand() % 2) == 4){
                return  1;
            }else{
                return  3;
            }
        }
        else if (winnerX == 3){
            return  (1 + rand() % 2);
        }
    else return winnerX;
}
int switchChoice(int uChoice, int revealedD){
    int newChoice;
    do{
        newChoice =  1 + rand() % 3;
    }while ( uChoice == newChoice || newChoice == revealedD);

    return newChoice;
}
bool decision(int uChoice, int winnerX){
        if(uChoice == winnerX){
            return true;
        }else{
            return false;
        }

}
vector<int> simulation (){
    long n, winnerX, uChoice = 0;
    vector<int> choiceCtr;
    choiceCtr.push_back(0);
    choiceCtr.push_back(0);

    cout << "How many times would you like to run the simulation? ";
    cin >> n;
    choiceCtr.push_back(n);

    for(int i = 0; i < n; i++){
        winnerX = winner();
            if(decision(switchChoice(userChoice(), revealedDoor(winnerX)), winnerX)){
                choiceCtr[0]++;             
            }
    }
    for(int i = 0; i < n; i++){
    if(decision(userChoice(), winner())){
        choiceCtr[1]++;             
    }
    }
    return choiceCtr;
}

void analytics(){
    vector<int> choices;

    choices = simulation();

    double percent = choices[0] / static_cast<double>(choices[2]);
    double percent2 = choices[1] / static_cast<double>(choices[2]);

    cout << choices[0] << endl;
    cout << choices[1] << endl;

    cout << fixed << setprecision(2)<< "Switching: " << endl << "-----------------" << endl << "You won " << choices[0] << " out of " << choices[2] << " Which is " << percent * 100  << " percent." << endl << endl;
    cout << fixed << setprecision(2)<< "Staying: " << endl << "-----------------" << endl << "You won " << choices[1] << " out of " << choices[2] << " Which is " << percent2 * 100  << " percent." << endl << endl;
}




How to write true color random (java)

Soo this is cod:

  import java.awt.*;
  import java.util.Random; 
  import javax.swing.*;
  public class GraphsPaneTest {
public static void main(String[] args) {
    myFrame window = new myFrame();
}
  }
  class myFrame extends JFrame
  {
public myFrame()
{
    myPanel panel = new myPanel();
    Container cont = getContentPane();
    cont.add(panel);
    setBounds(100,100,500,500);
    setVisible(true);
}
  }

  class myPanel extends JPanel
  {
public void paintComponent(Graphics gr)
{
    super.paintComponent(gr); 
    Random ab = new Random(); 
    colors={Color.BLUE, Color.RED, Color.ORANGE, Color.PINK}; //Here an error
    int colorsThis = ab.nextInt(colors[colorThis]); //Here an error
    gr.setColor(Color.RED); //I try it, but it does't work //And here an error
    int a=1;
    while (a<10)
    {
        Random b = new Random(); 
        gr.fillRect(b.nextInt(900+1),b.nextInt(900+1), b.nextInt(50+1), b.nextInt(50+1)); 
        a++; 
    }
}

  }

I tried to create a cod which has square which has a random color and random corrdinat and random bounds. Soo i have an error. Please help. I know my English is very bad.




Trying to write c++ code to generate random genetic code

I wrote this simple program to generate random genetic code comprising of ATGC. I’m pretty sure the code is correct; however, it won’t compile on my system. If someone out there could debug this it would be greatly appreciated.

This is what I have come up with.

simplest code to generate random genetic code

#include "StdAfx.h"
#include <iostream>
#include <cstdlib>
using namespace std;
(int main(
int x = rand();
if {(x % 2 == 0)
(int main(
int y = rand());
if {(y % 2 == 0)
{
cout<<"A\n";}}
else
{
cout<<"T\n";}
}))}
else 
(int main(
int z = rand());
if {(z % 2 == 0)
{
cout<<"G\n";}}
else 
{
cout<<"C\n";}
}))}




Simulating dice rolls with RNGCryptoServiceProvider

Lets say I generated a random number using RNGCryptoServiceProvider, the minimum generation is between 0,255. now if I want to simulate a dice roll(of lets say 6 sides), I would discard any result that is over 6(and discard 0), if I do that, does the resulting number still random?(meaning will it be the same as if RNGCryptoServiceProvider was able to generate a number between 1 and 6)?

also, in general, is RNGCryptoServiceProvider good enough for dice rolls simulation? or am I better off using a service like random.org(which I have no idea how to use..)

Edit: not a duplicate, I know how to do it(I did it the same as the answer in the other question), I'm asking if doing that will still provide a random number with the same level of randomness of RNGCryptoServiceProvider.




How would I append a students score to their names?

Here I am trying to change my code so that the students last three scores are saved to their names, but at the moment it will just save their scores and when the teacher prints their scores it will just print all the times the student did the quiz regardless of how many times they did it. here is my code:

import random
import sys

def get_input_or_quit(prompt, quit="Q"):
    prompt += " (Press '{}' to exit) : ".format(quit)
    val = input(prompt).strip()
    if val.upper() == quit:
        sys.exit("Goodbye")
    return val

def prompt_bool(prompt):
    while True:
        val = get_input_or_quit(prompt).lower()
        if val == 'yes':
          return True
        elif val == 'no':
          return False
        else:
         print ("Invalid input '{}', please try again".format(val))


def prompt_int_small(prompt='', choices=(1,2)):
    while True:
        val = get_input_or_quit(prompt)
        try:
            val = int(val)
            if choices and val not in choices:
                raise ValueError("{} is not in {}".format(val, choices))
            return val
        except (TypeError, ValueError) as e:
                print(
                    "Not a valid number ({}), please try again".format(e)
                    )

def prompt_int_big(prompt='', choices=(1,2,3)):
    while True:
        val = get_input_or_quit(prompt)
        try:
            val = int(val)
            if choices and val not in choices:
                raise ValueError("{} is not in {}".format(val, choices))
            return val
        except (TypeError, ValueError) as e:
                print(
                    "Not a valid number ({}), please try again".format(e)
                    )

role = prompt_int_small("Are you a teacher or student? Press 1 if you are a student or 2 if you are a teacher")
if role == 1:
    score=0
    name=input("What is your name?")
    print ("Alright",name,"welcome to your maths quiz."
            " Remember to round all answers to 5 decimal places.")
    level_of_difficulty = prompt_int_big("What level of difficulty are you working at?\n"
                                 "Press 1 for low, 2 for intermediate "
                                    "or 3 for high\n")


    if level_of_difficulty == 3:
        ops = ['+', '-', '*', '/']
    else:
        ops = ['+', '-', '*']

    for question_num in range(1, 11):
        if level_of_difficulty == 1:
            max_number = 10
        else:
            max_number = 20

        number_1 = random.randrange(1, max_number)
        number_2 = random.randrange(1, max_number)

        operation = random.choice(ops)
        maths = round(eval(str(number_1) + operation + str(number_2)),5)
        print('\nQuestion number: {}'.format(question_num))
        print ("The question is",number_1,operation,number_2)
        answer = float(input("What is your answer: "))
        if answer == maths:
            print("Correct")
            score = score + 1
        else:
            print ("Incorrect. The actual answer is",maths)

    if score >5:
        print("Well done you scored",score,"out of 10")
    else:
        print("Unfortunately you only scored",score,"out of 10. Better luck next time")

    class_number = prompt_int_big("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")

    filename = (str(class_number) + "txt")
    with open(filename, 'a') as f:
        f.write("\n" + str(name) + " scored " + str(score) +  " on difficulty level " + str(level_of_difficulty) + "\n")
    with open(filename) as f:
        lines = [line for line in f if line.strip()]
        lines.sort()

    if prompt_bool("Do you wish to view previous results for your class"):
        for line in lines:
            print (line)
    else:
        sys.exit("Thanks for taking part in the quiz, your teacher should discuss your score with you later")
if role == 2:
    class_number = prompt_int_big("Which class' scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3")
    filename = (str(class_number) + "txt")

    f = open(filename, "r")
    lines = [line for line in f if line.strip()]
    lines.sort()
    for line in lines:
        print (line)  




Turning code into an image

I am looking for a website to turn my code into images like the following:

http://ift.tt/1P2p9DW

If any could tell me the website, it would be much appreciated




Pick randomly user from list to another list

i'm trying to pick randomly users from this list:

    private static List<User> users = new ArrayList<>();

into this one:

    private static List<Lunchpairs> pairs = new ArrayList<>();

and that's my code:

public static List<Lunchpairs> getPairs() throws NoUserException{

    if(users.isEmpty()){
        throw new NoUserException("No participants.");
    }

    for(int i=0; i< 2; i++){

        Random pickPairs = new Random();
        Lunchpairs randomPairs = users.get(pickPairs.nextInt(users.size()));
        pairs.add(randomPairs);

    }
    return pairs;

}

But it doesn't work like this. I think the problem is that i can't get the names from List<User> and get it into List<Lunchpairs>.(If i'm not right, please let me know)

How can i solve this problem?




Append Random Text without Repetition for File (C)

I have 5 list of name

char *name[] = {"a","b","c","d","e"};

and I have 3 files

char path1[PATH_MAX+1]
snprintf(path1, PATH_MAX+1, "%sfile1.txt",dirname);
FILES *filename1 = fopen(path1, "w")
.
.
.
char path3[PATH_MAX+1]
snprintf(path3, PATH_MAX+1, "%sfile3.txt",dirname);
FILES *filename3 = fopen(path3, "w")

What I want is to randomly append a,b,c,d,e (one of them per file) into three of those files without repetition.

What I have right now is (example from one of them)

srand(time(NULL));
int one = rand()%5;
char path1[PATH_MAX+1];
snprintf(path1, PATH_MAX+1, "%sfile1.txt",dirname);
FILES *filename1 = fopen(path1, "w");
fputs(name[one],filename1);
fclose(filename1);

However, sometimes it is still possible where my file1.txt and file3.txt both contain b (same alphabet from name)

Questions

Did I miss something to make sure that all the random result always unique?

Is it also efficient tho to have 6 lines of code to create one file and append a random name inside it? I'm just wondering if I have to create like 20 files, I will write 120 lines that basically almost the same, just different in number (filename1 to filename3)

Thank you.




lundi 26 octobre 2015

Random number between 0 and 1 in python

I want a random number between 0 and 1 . like 0.3452 I used random.randrange(0,1) but it is always 0! for me. what should i do?




What is a good algo for glsl lowp random number generation (for use in graphics)?

I need a random number generator to create some graphical static. I'm not looking for noise algorithms- I just want white noise. All I need for this is a random number generator in glsl. Specifically, I'll be using it to create a random lightness offset per-fragment, over time.

Requirements:

  • generates number between 0.0 and 1.0 (don't care if inclusive/exclusive)
  • This needn't be that random. This won't be used for any security purposes, it just needs to be "random" to the naked eye.
  • It needs to be computable with lowp floats only! (for use on mobile)
  • Only has fragment_x, fragment_y, and time_mod_ten_pi as inputs (time_mod_ten_pi is exactly what it sounds like; the time (in seconds) since the game began, mod (10*3.1415) passed in as a float to allow for easy, continuous oscillations without worrying about precision issues. and 30 seconds is waaay more than enough time that a human won't notice repeating noise)
  • when displayed on a fragment_x * fragment_y grid, I don't want any visible patterns (statically, or in motion)
  • the simpler/faster, the better!

want to reiterate here- needs to function with only lowp floats. that one-liner going around the internet (fract(sin(dot(...)))) does not fulfill this condition! (at least, I assume the issue is with the lowp floats... could be really feeble sin implementation as well... so if you can avoid sin of high numbers too? bonus?)




Append Random Text to File (C)

I'm trying to create a file inside a directory, then append some random text inside of the file.

My Code

char dirname[30]; 
sprintf(dirname, "myroom.%d", (int)getpid()); 
mkdir(dirname,0777); 

char path[path_max+1];
snprintf(path1, PATH_MAX+1, "%s/file1.txt,dirname); 
FILE *filedir1 = fopen(path1, "a+"); 
fclose(filedir1); 

char *random_name = { "burger", "toast", "burrito", "noodles" };
int number = rand();
fputs(random_name[number], filedir1];

What I want

(Inside directory "dirname")

When I open file1.txt, I expect there will be either the word burrito, burger, toast, or noodles in the first line.

What I get

file1.txt still empty.

Questions

Anybody know what happen with my code? I saw from youtube video, to append some text into a file, all I need is the fputs command but it doesn't seem to work in my code. Is it because I'm using "a+" in fopen?

Any help will be highly appreciated. Thanks




NoLoop() Stops MousePressed

I am trying to create a random number of grape objects on a plate. My for loop creates the grapes, however; I realized that if I don't add the code line noLoop(); to stop the random function, then the last grape created will only show.

My issue is that now noLoop() stops my mousePressed actions to happen. I know that noLoop() stops the draw() function which ultimately allows mousePressed to work whenever the user clicks the mouse.

So my question is, is there another way to stop my random from resetting so that all grapes will be created without the noLoop() statement?

int grapeCount = 10;
int grapePosX = 100;
int grapePosY = 300;
//int numberOfGrapes = 5;
boolean newState = false;
PFont font;
boolean stopCreate = true;

void setup(){
 size(800,500);
 font = createFont("Frutiger",20, true);
 textFont(font);
}
void draw(){

 background(255);
 drawTable();
 drawPlate();
 drawGrapes();


 if (mousePressed){   
    background(255);
    //newPlate();
    //newTable();
    //runawayGrape();
    fill(255,0,0);
    text("YOU CANT GET ME!!", 150,100);

  }
}

void drawGrapes(){

//determine how many grapes will be created on plate (5 to 10) and create the grape
for(int i=0; i < numberOfGrapes(); i++){    
  updateGrapePosition();   
}
  //stopCreate = false;
  noLoop();
}
//draw plate background
void drawPlate(){
  fill(255);
  strokeWeight(2);
  ellipse(300,300,500,300);
  ellipse(300,300,450,250); 
}
//draw table background
void drawTable(){
  strokeWeight(0);
  fill(87,67,6);
  rect(0,100,width,400);
}
//determine the random number of grapes created
int numberOfGrapes(){

 int grapeC = round(random(5,10)); 

  return grapeC; 
}
//update position of each grape
void updateGrapePosition(){
  if (grapePosX >= 300){
   grapePosX = grapePosX -30;
  }
   grapePosX = grapePosX + 30;
   Grapes(); 
}
//create each Grape
void Grapes(){
  strokeWeight(1);
  fill(66,2,70);
  //grape Body
  ellipse(grapePosX, grapePosY, 30,30); 
  strokeWeight(5);
  //grape eyes
  point(grapePosX-5,grapePosY-5);
  point(grapePosX+4, grapePosY-5); 
}

void mousePressed(){

 newState = true; 

}

enter image description here