samedi 30 avril 2016

Random Number Function Broken In Xcode 7.3 & iOS 9.3.1

After upgrading to Xcode 7.3 my Swift application keeps crashing when I execute a specific function.

For the code below I am told that "the 'var' parameters are deprecated and will be removed in Swift 3". The fix is to delete the var i.e. change "(var list: C)" to "(list: C)" but as soon as this is done I get an error five lines down for "swap(&list[i], &list[j])". I still need to shuffle the names (random draw) but unsure how to fix this?

// Shuffle array function
func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C {
    let c = list.count
    if c < 2 { return list }
    for i in 0..<(c - 1) {
        let j = Int(arc4random_uniform(UInt32(c - i))) + i
        swap(&list[i], &list[j])
    }
    return list
}

I am guessing this is the main problem with my application.

Currently the app crashes when the shuffle function is called.

The app is available on the apple store here if you need more context: Shell-Out




Select a random positive element in a list in Python

I need to select a random positive element from a list.

I can select a random number, but how can I limit selection to the positive numbers?




How do i pick a random minute from a period of time? [on hold]

I am looking for a way to turn my bool from false, into true, by giving aevery minute a 1/60 chance to set the bool true. so it will send the bad guys at least once an hour.




Ho do i call the next proxy from a textbox instead of using random next?

Hello I have a question about calling a proxy from a textbox in c# webclient. Right now I am able to get a random next proxy from a textbox but i would like to call the second proxy every time I made a request instead of random.

The code I'm using now is :

readonly List<string> proxies = new List<string>();

WebProxy RandomProxy
    {
        get
        {
            return proxies.Count == 0 ?
                null :
                new WebProxy(proxies[rnd.Next(proxies.Count)]);

        }
    }

proxies.Clear();
proxies.AddRange(txtProxy.Lines.Where(p => !String.IsNullOrWhiteSpace(p)));

var proxy = RandomProxy;
var wc = new WebClient { Proxy = proxy };

After analyzing the request I've noticed that the proxies are changing but not how I would like to have the proxies called. So every request using the next proxy from the textbox.

Any one here who could explain to me how to change that? Thanks in advance. Regards, Dennis




Can C++11 PRNG be used to produce repeatable results?

I'm working on a test suite for my package, and as part of the tests I would like to run my algorithm on a block of data. However, it occured to me that instead of hardcoding a particular block of data, I could use an algorithm to generate it. I'm wondering if the C++11 <random> facilities would be appropriate for this purpose.

From what I understand, the C++11 random number engines are required to implement specific algorithms. Therefore, given the same seed they should produce the same sequence of random integers in the range defined by the algorithm parameters.

However, as far as distributions are concerned, the standard specifies that:

The algorithms for producing each of the specified distributions are implementation-defined.

(26.5.8.1 Random number distribution class templates / In general)

Which — unless I'm mistaken — means that the output of a distribution is pretty much undefined. And from what I've tested, the distributions in GNU libstdc++ and LLVM project's libc++ produce different results given the same random engines.

The question would therefore be: what would be the most correct way of producing pseudo-random data that would be completely repeatable across different platforms?




randomly select serie of records that never been together in another serie

I have two tables in mysql :

table 1 (id_item, item) = [(1,A) (2,B) (3,C) (4,D) (5,E) (6,F)]

table 2 (id_serie, item) = [(1,A) (1,C) (1,D) (2,A) (2,E) (2,F) ...]

how do i select randomly 3 items from table 1 that have never been together in a serie from table 2, example: A,B,C or C,D,E ... wrong result example: A,C,D (have been together in serie number 1 )

this is my try wich is not working :

Select * from table1 where table1.item not in (select item from table2) order by rand limit 3




About randomness and minmax algorithm with alpha beta pruning

Will choosing the child of a node randomly in the alpha beta algorithm have a better chance to get a cut off than choosing them in order?

Here's the pseudocode with my addition marked with ***.

function alphabeta(node, depth, α, β, maximizingPlayer)
     if depth = 0 or node is a terminal node
         return the heuristic value of node
     arrange childs of node randomly ***
     if maximizingPlayer
         v := -∞
         for each child of node
             v := max(v, alphabeta(child, depth - 1, α, β, FALSE))
             α := max(α, v)
             if β ≤ α
                 break (* β cut-off*)
         return v
     else
         v := ∞
         for each child of node
             v := min(v, alphabeta(child, depth - 1, α, β, TRUE))
             β := min(β, v)
             if β ≤ α
                 break (* α cut-off*)
         return v

I ran a small sample with this on a connect four game and it does seem to run a little faster, but when I actually count the cutoffs with and without randomness, there are more cutoffs without randomness. That's a little odd.

Is it possible to prove that it's faster (or slower)?




C Programming; Producing a 2-Dimensional Matrix with Random Numbers without Repetition

I'd like to produce a 6x6 matrix by inserting random numbers to the elements in the row and column without repeating. This is my code so far. Thank you for your help!

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int array[6][6];
int rows, columns;
int random;

srand((unsigned)time(NULL));

for(rows=0;rows<6;rows++)
    {
        for(columns=0;columns<6;columns++)
            {
                random=rand()%36+1;

                array[rows][columns] = random;
                printf("%i",array[rows][columns]);
            }

        printf("\n");
    }

return 0;
}




vendredi 29 avril 2016

Using AES as a portable RNG with a truly random seed?

I am writing a service where a deterministic RNG is needed across multiple platforms that don't share a codebase (except for maybe C). The random numbers need to be exactly 128 bits long. Given a pre-negotiated truly random number, is it OK if I use AES to generate a sequence of random numbers? How it would work is I would encrypt the seed to get the first random number, encrypt the first random number to get the second, etc.

Basically:

rand[0] = truly_random_number;
rand[1] = AES(truly_random_number);
rand[2] = AES(AES(truly_random_number));
rand[n] = AES(AES(AES...AES(truly_random_number...))) //n times

The clients will share their sequence number as they communicate, so it should be possible for any of them to deterministically reconstruct the needed result.

Is this a proper use of AES? Can I use something faster for this, like SHA-256 and truncate the result? Should I just find a C implementation of some RNG and use that instead? I am leaning toward AES because the platforms I am targeting have AES accelerators, so the speed should not be much of an issue.




Distribution of php's random_int() function

What is the distribution of php's random_int function?

I guess it comes down to the distribution of getrandom(2) and /dev/urandom? How are they distributed?

Can random_int be used for a uniform distributed random number generator?




Most efficient way to randomly sample directory in Python

I have a directory with millions of items in it on a fairly slow disk. I want to sample 100 of those items randomly, and I want to do it using a glob as well.

One way to do it is to get a glob of every file in the directory, then sample that:

files = sorted(glob.glob('*.xml'))
file_count = len(files)
random_files = random.sample(
    range(0, file_count),
    100
)

But this is really slow because I have to build up the big list of millions of files, which has to do a lot of disk crawling.

Is there a faster way to do this that doesn't hit the disk as much? It doesn't have to be a perfectly distributed sample or even do exactly 100 items, provided it's fast.

I'm thinking that:

  • Maybe we can use the inodes to be faster?
  • Maybe we can select items without knowing the entirety of what's on disk?
  • Maybe there's some shortcut that can make this faster.



Java Multiple Choice

Creating my final project I'm having two difficulties

So the program is suppose to generate two random numbers and give the user an option to chose A.(random answer) and B.(random answer) Then to the user must enter A or B and sees if the answer they enter is correct.

My question is how do I test if the user entered the correct answer if they entering a letter and the second one how do I output the answers randomly. I have already calculated answer=num1+num2(which were randomly generated) and then answer2=answer+7; what do I do, I'm stuck..and frustrated




How do I specify HTML to display an image randomly?

I have like 138 products in my database. I wish to use only 10 images and randomly select any of these 10 images to be displayed besides their name in HTML .

My HTML code is :

<div class="row">
<div class= "col-md-4"  ng-repeat="coffeedata in coffecataloge">
   <!-- <script type="text/javascript" > alert(counter); if(counter%3 == 0) ++row_number; </script> -->
   <div id="product-box" style="width:600px;height:250px" >
      <div style="width:350px;height:250px;border:1px solid #000;">
         <div></div>
        <!-- IMAGE TO BE INSERTED HERE --> <div> <img src="/coffee/pick_any_of_the_10_images_randomly.jpg" /> </div>
         <div>In Stock : </div>
         <div>Price: </div>
         <br><br><br>
         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <a href="#add-to-cart" class="btn btn-red btn-effect">Add to Cart</a>
      </div>
   </div>
   <br>
</div>

How can I achieve this using Javascript and HTML? Thank you so much.




Generating Random Constrained Graph

I need to generate a randomized graph with a fixed number of vertices. I'm having some difficulty getting a solution every time. Any help would be appreciated.

Graph Rules

1) Each Vertex will have a random number of connections that is at most N-1 where N is the total number of vertices.

2) The Vertices cannot contain direct connections to themselves

3) The vertices cannot contain duplicate connections to other vertices.

4) If a vertex A is connected to Vertex B then Vertex B must connect to Vertex A.

I'm getting a correct solution about 70% of the time, but other times I get fairly far into the graph then no valid vertices are left. What constraints on the vertex connections do I need to guarantee a solution?

What I'm doing so far

1) Check that the total number of connections is even. If A points to B and B points to A then the total number of connections in the graph should be even or else there is no solution. If it is odd modify a vertex so the total number is even.

2) Fill in each vertex that is fully constrained. So a vertex that has N-1 connections must point to ALL other vertices. Fill in a connection from that vertex to all others and give all other vertices a connection to the fully constrained ones.

3) Process each vertex by how tightly it is constrained. So process all vertices with N-2 connections then, N-3 connection, then N-4, etc by generated random vertex indexes.

4) If The new random index is valid connect them then continue, if it is not valid rerandom the index until you get a valid value. (The graphs are only going to be 7-15 nodes or so maximum so this doesn't take extremely long).

Generally I get to the last 1 or 2 vertices but then have no valid values left with this method. Anyone have a better algorithm or an additional constraint on the number of connections values that would help me out?




Randint in class

So I have created this class to randomly assign potential answers to buttons in a quiz I am making. It puts the text of the answer as one of three buttons named answer1, answer2 and answer3. It also saves which one the correct answer is. The problem Im having is everty time I press a button, it resets which answer is the correct one. Does anyone know what Im doing wrong?

question1 = ["The RES building was originally an egg farm... but in what        year was it built?", "1930", "1890", "1945"]
question2 = ["How many chickens did the egg farm hold?", "50,000", "2,500", "25,000"]
question3 = ["How many visitors has RES had since 2004?", "Over 20,000", "3,000", "15,000"]
question4 = ["What does borehole cooling use to cool the RES building?", "Water", "Air", "Oil"]
question5 = ["What are the solar panels at RES used for?", "Electricity and Heating", "Electricity", "To get more sunlight in"]
question6 = ["How many meters squared are the solar panels at RES?", "170", "45", "250"]
question7 = ["How long does it take to earn back the cost of the solar panels?", "8 years", "2 years", "15 years"]
question8 = ["What is the best direction for solar panels to face?", "South", "East", "West"]
question9 = ["What is the scientific name for a solar panel?", "Photovoltaic Cell", "Solar Transformer", "Solar Farm"]
question10 = ["How tall is RES's wind turbine from the floor to the tip?", "50m", "30m", "120m"]
question11 = ["How many houses could the RES turbine power per year?", "30-40", "5-10", "60-70"]
question12 = ["Which is the fastest growing energy market?", "Wind", "Coal", "Solar"]
question13 = ["How tall is a typical turbine RES installs?", "125m", "35m", "70m"]
question14 = ["What proportion of the time does a wind turbine generate electricity?", "70 - 90%", "50%", "10 - 25%"]
question15 = ["How many cubic meters of water can the RES heat store hold?", "1400", "120", "2600"]
question16 = ["What is the name for organic material used as fuel?", "Biomass", "Wood", "Oil"]
question17 = ["What is the other name for 'miscanthus', the crop RES grows?", "Elephant Grass", "Hippo Weed", "Bamboo"]
question18 = ["How efficient at burning fuel is the biomass heater at RES?", "90%", "12%", "47%"]

n = 1
quiz = []
while n < 18:
    quiz.append(eval("question" + str(n)))
    n += 1

class Quiz:

    def __init__(self, question):
        self.question = question
        actual = random.randint(1, 3)
        possible = [1, 2, 3]
        possible.pop(actual-1)
        self.actual = actual
        self.possible = possible

    def show(self):
        question = quiz[self.question].pop(0)
        questionDisplay.config(text=question)
        correct = quiz[self.question].pop(0)
        incorrectA = quiz[self.question].pop(0)
        incorrectB = quiz[self.question].pop(0)

        #actual is correct answer, possible is incorrect answers


        correctButton = "answer"+str(self.actual)
        print(correctButton)
        eval(correctButton).config(text=correct)
        incorrect1 = "answer" + str(self.possible.pop())
        eval(incorrect1).config(text=incorrectA)
        incorrect2 = "answer" + str(self.possible.pop())
        eval(incorrect2).config(text=incorrectB)

    def check(self, button):
        global SCORE
        correct = "answer" + str(self.actual)
        print(correct)
        if button == correct:
            SCORE += 1
            print(SCORE)
            questionDisplay.config(text="CORRECT!")
        else:
            questionDisplay.config(text="INCORRECT!")
        time.sleep(1)




random list object and instantiate gameObject

I will use Pokemon as an example: I have a list of 10 elements, each element contains: string name, GameObject, int hp and mana int, int rarity.

I need after every click or tap, is made a random, even so good, but imagine that these 10 Pokemons, 2 of them are very rare.

after the random, will check out common or rare pokemon. if common, it will be made another radom and will choose only 1. if rare pokemon, choose one of two available. I believe it is very confusing.

the problem and I'm not managing to make the random list not instantiate the object. currently my code this as follows ..

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;

public class Pokemons : MonoBehaviour {

[Serializable]
public class ListPokemons
{
    public string name;
    public GameObject componentObjc;
    public int hp;
    public int mana;
    public int rarity;

}

public ListPokemons[] pokeAtributs;

// Use this for initialization
void Start () {
    List<ListPokemons> list = pokeAtributs.ToList ();

    //ListPokemons pokemon = list.FirstOrDefault (r => r.componentObjc != null);

    }

}

I'm using Unity 5. I am Portuguese and all the text has been translated using google translate. you can add me to skype: morenito-green-eyes@hotmail.com.

thank you. I'll be here to answer all ....




Seeding many PRNGs, then having to seed them again, what is a good quality approach?

I have many particles that follow an stochastic process in parallel. For each particle, there is a PRNG associated to it. The simulation must go through many repetitions to get average results. For each repetition, an exclusive PRNG seed should be chosen for each particle before the simulation begins.

For the first time I just get the seed = time(NULL) as seed for particle1. For the rest I just do particle2 = seed + 1, particle3 = seed + 2, etc.. , so all particles end up having a different seed.

At each repetition, the plan is to add an offset to that initial seed obtained from time(NULL), such as seed = seed + all_particles_offset; and then assign a different seed to each particle using the approach described earlier. My question is if this approach will lead to acceptable randomness quality? I am not concerned with security, just the quality of the random numbers running in parallel and the fact that the process is re-seeding from time to time.

By the way, the PRNG used is the PCG.




Error but it's working: Notice: Undefined variable: random_row [duplicate]

This question already has an answer here:

this is my code:

<?php
$dir = "songs/";
$songs = scandir($dir);
$i = rand(2, sizeof($songs)-1);
?>
<audio src="songs/<?php echo $songs[$i]; ?>" id="audio_player_id" autoplay controls="controls"></audio>

This code get random file from a folder and it's working, but there is an error. The error: Notice: Undefined variable: random_row

How to fix whatever it is and whats the problem?




How scrambles the data array with Congruential Linear Generator / Pseudo Random Number Generator

I have data in an array and want to randomize the data in the aray using linear congruiential methods algorithm, without using a php function rand () / shuffle () and functions Functions that already exist.

How should I define variables and using the linear congruential algorithm that? or maybe other pseudo random generator Like Multivicative Random Generator?

my code:

        <?php
        include("koneksi.php");
        $arr = array();
        $q = mysql_query("select * from tbl_soal");
                while ($row = mysql_fetch_assoc($q)) {
                    $temp = array(
                        "soal_id" => $row['id'],
                        "soal"=>$row['soal'],
                        "a"=>$row['a'],
                        "b"=>$row['b'],
                        "c" => $row['c'],
                        "jawaban" => $row['jwaban'],
                        "gambar" => "http://ift.tt/1SPmwqg".$row['gambar'].""
                    );
                    array_push($arr, $temp);
                }   

            //with a random function from php   
            //shuffle($arr);
            //$dd = array_slice($arr, 0, 5);

            $data = json_encode($dd);
            $data = str_replace("\\", "", $data);
            echo "{\"daftar_soal\":" . $data . "}";
        ?>




Get a random number more frequently

If I have a list like this: L = [1, 1, 1, 1, 1, 1, -1] Does it make sure that when I generate a random number from the list, the chance to get a '1' will be higher than the chance to get a '-1'?




weird behaviour when passing function as an argument in C++

I encountered this strange thing with with C++ when i tried to pass a function as an argument to another one. the problem here is that it works but not giving me the expected result. here's my code (msvc2013):

#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <iostream>

typedef unsigned int uint32_t;
typedef unsigned char uint8_t;
using namespace std;

#include "stdafx.h"

uint32_t random_color()
{
    uint8_t r = rand() % 255;
    uint8_t g = rand() % 255;
    uint8_t b = rand() % 255;
    uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);

    return rgb;
}

void print_rgb(uint32_t(*color_generator)() = &random_color)
{
    std::cout << color_generator << std::endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    for (int i = 0; i < 5; i++)
    {
        srand(time(NULL));
        print_rgb();
    }
    system("PAUSE");
    return 0;
}

the purpose of this code is more complicated, but this is a minimal example.

Question : although as you see, there was an srand(time(NULL)); in order for rand() to change values, it dosen't !

so , at the 5 times, I got the same value ! output

Is there any reason for this ? Am I missing something ?




Coin toss using random numbers does not appear exactly random

I wanted a random number generator to simulate a coin toss and here's what i did

public class CoinToss
{
    public static void main(String args[])
    {
        int num=(int)(1000*Math.random());
        if(num<500)
            System.out.println("H");
        else
            System.out.println("T");
    }
}

The results were discouraging as i got 16 Heads and 4 tails in 20 runs. That does not appear to be random. Its possible but i want a general opinion if the program is correct ? Am i missing something mathematically ?




mt_rand and rand not working (PHP)

I am having a problem where by when I try and generate numbers randomly with either mt_rand or rand (on a larger scale) I get no result at all. This used to work fine on my server but there seems to be issues now and I am unsure why.

<?php
echo 'Your number is: '.rand(0, 99999999999999999999);
?>

Where as it I update it to something like (using a 9 digit number):

<?php
echo 'Your number is: '.rand(0, 999999999);
?>

the lower example will work fine. I have recently changed my server version PHP 7.0. Is there a way to increase the maximum number or a better way to be doing this? Thanks.




Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException without link to my own code

What could be the reason for this exception? I dont know what causes this. It appears at different situations. It seams pretty random. The program is still running without any limitations.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.text.PlainView.paint(Unknown Source)
at javax.swing.text.FieldView.paint(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI$RootView.paint(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.paintSafely(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.paint(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1200(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Only this class uses AWT.

public class GraphicalUserInterface {
private int             currentLineNumber           = 0;
private Font            font;
private JFrame          frame                       = new JFrame("Database");
private Image           icon;
private JTextField      input                       = new JTextField();
private JTextPane       output                      = new JTextPane();
private JPanel          panel                       = new JPanel();
private int             pressedKey                  = 0;
private JScrollPane     scrollPane                  = new JScrollPane(panel);
private StyledDocument  styledDocument              = output.getStyledDocument();
private Object          synchronizerInputConfirm    = new Object();
private Object          synchronizerKeyInput        = new Object();
private Object          synchronizerKeyPressed      = new Object();
private JTextField      time                        = new JTextField();
private Timer           timer                       = new Timer();

public GraphicalUserInterface() throws FontFormatException, IOException, InterruptedException {
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    ClassLoader classLoader = this.getClass().getClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream("DejaVuSansMono.ttf");
    font = Font.createFont(Font.TRUETYPE_FONT, inputStream);
    font = font.deriveFont(Font.PLAIN, 15);
    inputStream.close();
    icon = new ImageIcon(classLoader.getResource("icon.png")).getImage();
    ActionListener inputListener = new ActionListener() {
        @Override public void actionPerformed(ActionEvent e) {
            synchronized (synchronizerInputConfirm) {
                synchronizerInputConfirm.notify();
            }
        }
    };
    KeyListener keyListener = new KeyListener() {
        @Override public void keyPressed(KeyEvent e) {
            pressedKey = e.getExtendedKeyCode();
            if (pressedKey == 8) {
                input.replaceSelection("");
            }
            else if (pressedKey == 10) {
                synchronized (synchronizerKeyInput) {
                    synchronizerKeyInput.notify();
                }
            }
            synchronized (synchronizerKeyPressed) {
                synchronizerKeyPressed.notify();
            }
        }

        @Override public void keyReleased(KeyEvent e) {}

        @Override public void keyTyped(KeyEvent e) {}
    };
    DocumentListener documentListener = new DocumentListener() {
        @Override public void changedUpdate(DocumentEvent e) {}

        @Override public void insertUpdate(DocumentEvent e) {
            synchronized (synchronizerKeyInput) {
                synchronizerKeyInput.notify();
            }
        }

        @Override public void removeUpdate(DocumentEvent e) {}
    };
    input.getDocument().addDocumentListener(documentListener);
    panel.setLayout(new BorderLayout(0, 0));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setIconImage(icon);
    frame.setResizable(false);
    time.setEditable(false);
    time.setEnabled(false);
    time.setFont(font);
    time.setBorder(null);
    time.setBackground(Color.BLACK);
    time.setDisabledTextColor(Color.WHITE);
    panel.add(time, BorderLayout.NORTH);
    output.setEditable(false);
    output.setEnabled(false);
    output.setFont(font);
    output.setBorder(null);
    output.setBackground(Color.BLACK);
    output.setDisabledTextColor(Color.WHITE);
    panel.add(output, BorderLayout.CENTER);
    input.setBorder(null);
    input.setFont(font.deriveFont(Font.ITALIC));
    input.setCaretColor(Color.WHITE);
    input.setBackground(Color.BLACK);
    input.setForeground(Color.WHITE);
    input.addActionListener(inputListener);
    input.addKeyListener(keyListener);
    input.setSelectedTextColor(Color.BLACK);
    input.setSelectionColor(Color.WHITE);
    output.add(input, BorderLayout.AFTER_LAST_LINE);
    timer.scheduleAtFixedRate(new UpdateTime(time), 0, 500);
    scrollPane.setViewportBorder(null);
    scrollPane.setBorder(null);
    JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar();
    verticalScrollBar.setPreferredSize(new Dimension(0, 0));
    verticalScrollBar.setUnitIncrement(10);
    JScrollBar horizontalScrollBar = scrollPane.getHorizontalScrollBar();
    horizontalScrollBar.setPreferredSize(new Dimension(0, 0));
    horizontalScrollBar.setUnitIncrement(10);
    frame.setContentPane(scrollPane);
    panel.add(output);
    for (StringFormat format : StringFormat.values()) {
        format.initialise(styledDocument);
    }
    frame.setSize(800, 530);
    input.setSize(770, input.getFontMetrics(font).getHeight());
    frame.setLocation(dim.width / 2 - frame.getSize().width / 2, dim.height / 2 - frame.getSize().height / 2);
}




Randomising a list with values

Create a program that will generate a random card and then ask the user to go Higher, Lower or Quit. If the player chooses Higher the next card must be of a higher value or the player is out. Likewise for Lower. So far I have something that just produces a random card

import random
Suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
Cards =     ["Ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",     "Jack", "Queen", "King"]
print(random.choice(Suits))
print(random.choice(Cards))




jeudi 28 avril 2016

Generate different random numbers

I want to generate different random numbers . I used srand and rand , but in my output some numbers are identical .

This is my output : enter image description here

How to do with srand to generate different numbers ?

#include<iostream>
#include<time.h>
#include <windows.h>

int main(){
    time_t t;
std::vector<int> myVector;
srand((unsigned)time(NULL));

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

    int b = rand() % 100;
    myVector.push_back(b);
    std::cout << myVector[i] << std::endl;
}
Sleep(50000);

}




How do I customize random UUIDs?

In general I'm using Type 5 random UUIDs as primary to store my data in a database. No I have got the situation, where I would like to store additional information (i. e. mobile vs. landline) within the UUID. Now I could easily set (i. e.) the last bit depending on this information. Strictly speaking it's not a Type 5 anymore and in my case I'm thinking about manipulating 8 bits. So now I'm asking myself, why shouldn't I create a random 128 bit number, which ignores variant and version? All variants except RFC 4122 are reserved or for backward compatibility reasons. Why do I need any information like variant or version, if my application knows, what kind it handles? It's just waste of 6 bits. Do I risk to get side effects ignoring those bits? Java seems to accept all random numbers and Cassandra also... I know, the probability of reduction is rather insignificantly, but actually I'm interested, why I should retain those bits.




Looping for a random number of times java

my problem is that i need to produce a random number, which is fine i've done that part, but then i need to use that random number to loop.

So for example if the random number was 13, then loop a piece of code 13 times.

i've had a mess around and haven't managed to get anything working and haven't been able to find anything online to help me.

Basically what i'm trying to find out is if this is even possible?

thanks guys.




Random integers in a binary search tree

For my homework I'm creating a code that generates one thousand random integers from a set of 10,000 numbers, moves them into a container, and then into a binary search tree. I'm given the following code first:

Random ran = new Random();
Integer x;{  
for(int i = 1; i <= 100; i++){
x = ran.nextInt(10,000) + 1;
}

I have a BSTNode & an Intclass. Given the following code in the BST class, I can use this to search

public boolean search(Integer value) {
    boolean retval = false;
    numofcomps ++;
    if (root == null) {
        retval = false;
    } else {
        retval = searchtree(root, value);
    }
    return retval;
}

public boolean searchtree(BSTNode<IntClass> myroot, int value) {
    numofcomps ++;
    boolean retval = false;
    if (myroot == null) {
        retval = false;
    } else {
        if (value == myroot.element.myInt) {
            retval = true;
        } else {
            if (value < myroot.element.myInt) {
                retval = searchtree(myroot.leftTree, value);
            } else {
                retval = searchtree(myroot.rightTree, value);
            }
        }
    }

I need to figure out how to move the random numbers into the binary tree. Any suggestions?




C: create random numbers from a range that are all different

For exemple i've this 3 variables:

N = 5;
int r1 = rand() % N;
int r2 = rand() % N;
int r3 = rand() % N;

How can i do have 3 different numbers in that range and not the same? I tryed with this code:

do{
  int r1 = rand() % N;
  int r2 = rand() % N;
  int r3 = rand() % N;
}while((r1 == r2) && (r1==r3) && (r2==r3));

but it doesn't works. Sometimes one or two number are the same (ex: 1, 1, 4). But i need all different. How can i do? Thank you




Why am I getting the same number for each iteration when using rand?

This is my code, it's a function which receives a matrix and the dimension of the matrix:

int** define(int **m, int n) {
    int i, j;

    srand(time(NULL));

    m = calloc(n, sizeof(int *));

    for (i = 0; i < n; i++)
        m[i] = calloc(n, sizeof(int));

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++)
            m[i][j] = rand() % 10;
    }

    return m;
}

I want that every element of the array is a random number (independently), but when I run my program and see the matrix, it's either full of 0's, full of 1's ... or full of 9's, so all the elements of my matrix end up with the same random number... Ex:

First time I run my program:

7 7 7 7 7 
7 7 7 7 7 
7 7 7 7 7 
7 7 7 7 7 
7 7 7 7 7 

Second time I run my program:

0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0

It's strange because when I didn't use a function and had that piece of code inside main, it worked perfectly (each element had random numbers independently), but when I tried to do it with another function, it started to work wrong (all the element's have the same random number)




Opengl-Generating random points in a specific range

I want to generate random points in a specific range for an opengl program, say points between the coordinates Xmin=200, Xmax = 400 and Ymin= 200 , Ymax = 400.




ActionPerformed + a Normal function?

so im very very new to java I just started a few days ago so heres my question:

I want to click on that button

 JButton buttonRandom = new JButton("Roll The Dice");

    buttonRandom.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent arg0)
        {



        }

and then it should change this lable

       JLabel lableNum1 = new JLabel(String.valueOf(zufallsZahlOne));
        lableNum1.setFont(new Font("Tahoma", Font.BOLD, 16));
        lableNum1.setHorizontalAlignment(SwingConstants.CENTER);
       lableNum1.setBounds(10, 11, 66, 51);
       frame.getContentPane().add(lableNum1);

into this random number maybe im just too stupid ^^

public int randomZahlenEins()
{

    Random r = new Random();
    int min = 1;
    int max = 6;
    int zufallsZahlEins = r.nextInt((max - min) + 1) + min;
    return zufallsZahlEins;

}




virtualbox crash after random time

i am using a windows 7 virtual machine on ubuntu 14.04 and my virtualbox version is 15.04. When I open virtual machine, after some time it gets aborted. And then it always aborts during the opening animation. I can only open it again if I restart ubuntu. Here are the last logs of the virtual machine :

00:00:00.640818 VMEmt: Halt method global1 (5)
00:00:00.640915 VMEmt: HaltedGlobal1 config: cNsSpinBlockThresholdCfg=2000
00:00:00.641132 Changing the VM state from 'CREATING' to 'CREATED'
00:00:00.645234 Changing the VM state from 'CREATED' to 'POWERING_ON'
00:00:00.645412 AIOMgr: Endpoints without assigned bandwidth groups:
00:00:00.645423 AIOMgr: /home/saim/VirtualBox VMs/windows7-64/virtualstorage.vdi
00:00:00.645427 AIOMgr: /usr/share/virtualbox/VBoxGuestAdditions.iso
00:00:00.645430 AIOMgr: /home/saim/VirtualBox VMs/64BitWindows/64BitWindows.vdi
00:00:00.645511 Changing the VM state from 'POWERING_ON' to 'RUNNING'
00:00:00.645519 Console: Machine state changed to 'Running'
00:00:00.651192 VMMDev: Guest Log: BIOS: VirtualBox 5.0.14
00:00:00.652413 PIT: mode=2 count=0x10000 (65536) - 18.20 Hz (ch=0)
00:00:00.666092 Display::handleDisplayResize: uScreenId=0 pvVRAM=0000000000000000 w=720 h=400 bpp=0 cbLine=0x0 flags=0x1
00:00:00.678808 AHCI#0: Reset the HBA
00:00:00.678854 AHCI#0: Port 0 reset
00:00:00.679208 VMMDev: Guest Log: BIOS: AHCI 0-P#0: PCHS=16383/16/63 LCHS=1024/255/63 0x00000000061a8000 sectors
00:00:00.679249 AHCI#0: Port 1 reset
00:00:00.679641 AHCI#0: Port 2 reset
00:00:00.680035 VMMDev: Guest Log: BIOS: AHCI 2-P#2: PCHS=16383/16/63 LCHS=1024/255/63 0x000000000a000000 sectors
00:00:00.680558 PIT: mode=2 count=0x48d3 (18643) - 64.00 Hz (ch=0)
00:00:00.686129 Display::handleDisplayResize: uScreenId=0 pvVRAM=00007fe442500000 w=640 h=480 bpp=32 cbLine=0xA00 flags=0x1
00:00:03.165998 PIT: mode=2 count=0x10000 (65536) - 18.20 Hz (ch=0)
00:00:03.166144 VMMDev: Guest Log: BIOS: Boot : bseqnr=1, bootseq=0231
00:00:03.166253 VMMDev: Guest Log: BIOS: Boot from Floppy 0 failed
00:00:03.166374 VMMDev: Guest Log: BIOS: Boot : bseqnr=2, bootseq=0023
00:00:03.169154 Display::handleDisplayResize: uScreenId=0 pvVRAM=0000000000000000 w=720 h=400 bpp=0 cbLine=0x0 flags=0x1
00:00:03.174995 VMMDev: Guest Log: BIOS: CDROM boot failure code : 0004
00:00:03.175091 VMMDev: Guest Log: BIOS: Boot from CD-ROM failed
00:00:03.175208 VMMDev: Guest Log: BIOS: Boot : bseqnr=3, bootseq=0002
00:00:03.202356 VMMDev: Guest Log: BIOS: Booting from Hard Disk...
00:00:03.410047 Display::handleDisplayResize: uScreenId=0 pvVRAM=00007fe442500000 w=1024 h=768 bpp=24 cbLine=0xC00 flags=0x1
00:00:05.761057 Display::handleDisplayResize: uScreenId=0 pvVRAM=00007fe442500000 w=1024 h=768 bpp=24 cbLine=0xC00 flags=0x1
00:00:05.803725 VMMDev: SetVideoModeHint: Got a video mode hint (1920x992x24)@(0x0),(1;0) at 0
00:00:09.724482 RTC: period=0x200 (512) 64 Hz
00:00:09.926190 GIM: HyperV: Guest OS reported ID 0x1040601011db1
00:00:09.926211 GIM: HyperV: Open-source=false Vendor=0x1 OS=0x4 (Windows NT or derivative) Major=6 Minor=1 ServicePack=1 Build=7601
00:00:09.926267 GIM: HyperV: Enabled TSC page at 0x000000003fffe000 - u64TscScale=0xc12ff400000000 u64TscKHz=0x33c363 (3 392 355) Seq=1
00:00:09.926315 TM: Switching TSC mode from 'VirtTscEmulated' to 'RealTscOffset'
00:00:11.484414 AHCI#0: Reset the HBA
00:00:11.543132 VMMDev: Guest Log: VBoxGuest: Windows version 6.1, build 7601
00:00:11.565450 VMMDev: Guest Additions information report: Version 5.0.14 r105127 '5.0.14'
00:00:11.565534 VMMDev: Guest Additions information report: Interface = 0x00010004 osType = 0x00037100 (Windows 7, 64-bit)
00:00:11.576510 VMMDev: Guest Additions capability report: (0x0 -> 0x0) seamless: no, hostWindowMapping: no, graphics: no
00:00:11.578607 VMMDev: Guest reported fixed hypervisor window at 00008400000 LB 0x3400000 (rc=VINF_SUCCESS)
00:00:11.578640 VMMDev: vmmDevReqHandler_HeartbeatConfigure: No change (fHeartbeatActive=false).
00:00:11.578670 VMMDev: Heartbeat flatline timer set to trigger after 4 000 000 000 ns
00:00:15.543493 AIOMgr: Flush failed with VERR_INVALID_PARAMETER, disabling async flushes
00:00:15.966636 VMMDev: Guest Log: VBoxMP::DriverEntry: VBox XPDM Driver for Windows version 5.0.14r105127, 64 bit; Built Jan 19 2016 16:43:24
00:00:17.735541 VMMDev: Guest Log: VBoxMP::VBoxDrvFindAdapter: using HGSMI
00:00:17.888554 HDA: Reset
00:00:17.912842 HDA: Reset
00:00:17.953932 OHCI: Software reset
00:00:17.954068 OHCI: USB Reset
00:00:18.021678 OHCI: USB Operational
00:00:19.267465 OHCI#0: Lagging too far behind, not trying to catch up anymore. Expect glitches with USB devices
00:00:20.599253 Display::handleDisplayResize: uScreenId=0 pvVRAM=00007fe442500000 w=1920 h=992 bpp=24 cbLine=0x1680 flags=0x1
00:00:20.831085 VMMDev: Guest Log: VBoxDisp[0]: VBVA enabled
00:00:20.831120 VBVA: InfoScreen: [0] @0,0 1920x992, line 0x1680, BPP 24, flags 0x1
00:00:20.831127 Display::handleDisplayResize: uScreenId=0 pvVRAM=00007fe442500000 w=1920 h=992 bpp=24 cbLine=0x1680 flags=0x1
00:00:29.475454 RTC: period=0x20 (32) 1024 Hz
00:00:29.497559 RTC: period=0x100 (256) 128 Hz
00:00:34.583877 RTC: period=0x200 (512) 64 Hz
00:00:34.600434 RTC: period=0x20 (32) 1024 Hz
00:00:34.615166 RTC: period=0x200 (512) 64 Hz
00:00:48.028415 Starting host clipboard service
00:00:48.028455 ClipConstructX11: X11 DISPLAY variable not set -- disabling shared clipboard
00:00:49.131437 RTC: period=0x20 (32) 1024 Hz
00:00:49.154033 RTC: period=0x100 (256) 128 Hz
00:00:49.598707 VMMDev: Guest Additions capability report: (0x0 -> 0x1) seamless: yes, hostWindowMapping: no, graphics: no
00:00:49.600084 VMMDev: Guest Additions capability report: (0x1 -> 0x5) seamless: yes, hostWindowMapping: no, graphics: yes
00:00:49.989853 RTC: period=0x200 (512) 64 Hz
00:00:58.734365 AIOMgr: Flush failed with VERR_INVALID_PARAMETER, disabling async flushes
00:01:00.115790 RTC: period=0x20 (32) 1024 Hz
00:01:00.146143 RTC: period=0x100 (256) 128 Hz
00:01:16.139185 RTC: period=0x20 (32) 1024 Hz
00:01:19.021395 RTC: period=0x100 (256) 128 Hz
00:01:19.116246 RTC: period=0x20 (32) 1024 Hz
00:01:19.146027 RTC: period=0x100 (256) 128 Hz
00:01:19.147019 RTC: period=0x20 (32) 1024 Hz
00:01:19.162007 RTC: period=0x100 (256) 128 Hz
00:01:19.178779 RTC: period=0x20 (32) 1024 Hz
00:01:30.677813 RTC: period=0x100 (256) 128 Hz
00:01:50.874018 RTC: period=0x20 (32) 1024 Hz
00:01:50.904339 RTC: period=0x100 (256) 128 Hz
00:01:55.139348 RTC: period=0x20 (32) 1024 Hz
00:01:55.169999 RTC: period=0x100 (256) 128 Hz
00:02:16.608283 RTC: period=0x20 (32) 1024 Hz
00:02:16.732244 RTC: period=0x100 (256) 128 Hz
00:02:16.780490 RTC: period=0x20 (32) 1024 Hz
00:02:16.927832 RTC: period=0x100 (256) 128 Hz
00:02:17.100864 RTC: period=0x20 (32) 1024 Hz
00:02:17.130883 RTC: period=0x100 (256) 128 Hz
00:02:17.944080 RTC: period=0x20 (32) 1024 Hz
00:02:17.974424 RTC: period=0x100 (256) 128 Hz
00:02:18.413352 RTC: period=0x20 (32) 1024 Hz
00:02:18.443517 RTC: period=0x100 (256) 128 Hz
00:02:22.117120 RTC: period=0x20 (32) 1024 Hz
00:02:22.146359 RTC: period=0x100 (256) 128 Hz
00:02:25.288096 RTC: period=0x20 (32) 1024 Hz
00:02:25.482420 RTC: period=0x100 (256) 128 Hz
00:02:25.845334 RTC: period=0x20 (32) 1024 Hz
00:02:25.880384 RTC: period=0x100 (256) 128 Hz
00:02:26.451828 RTC: period=0x20 (32) 1024 Hz
00:02:26.484247 RTC: period=0x100 (256) 128 Hz
00:02:26.670882 RTC: period=0x20 (32) 1024 Hz
00:02:26.746077 RTC: period=0x100 (256) 128 Hz
00:02:27.162727 RTC: period=0x20 (32) 1024 Hz
00:02:27.193518 RTC: period=0x100 (256) 128 Hz
00:02:27.278847 RTC: period=0x20 (32) 1024 Hz
00:02:27.326369 RTC: period=0x100 (256) 128 Hz
00:02:27.358192 RTC: period=0x20 (32) 1024 Hz
00:02:27.388601 RTC: period=0x100 (256) 128 Hz
00:02:29.623553 RTC: period=0x20 (32) 1024 Hz
00:02:29.693079 RTC: period=0x100 (256) 128 Hz
00:02:29.868003 RTC: period=0x20 (32) 1024 Hz
00:02:29.912245 RTC: period=0x100 (256) 128 Hz
00:02:37.709843 RTC: period=0x20 (32) 1024 Hz
00:02:37.740212 RTC: period=0x100 (256) 128 Hz
00:02:38.853847 RTC: period=0x20 (32) 1024 Hz
00:02:38.880924 RTC: period=0x100 (256) 128 Hz
00:02:39.858202 RTC: period=0x20 (32) 1024 Hz
00:02:39.960996 RTC: period=0x100 (256) 128 Hz
00:02:39.967450 RTC: period=0x20 (32) 1024 Hz
00:02:39.998079 RTC: period=0x100 (256) 128 Hz
00:02:42.334643 RTC: period=0x20 (32) 1024 Hz
00:02:42.381122 RTC: period=0x100 (256) 128 Hz
00:02:50.592825 RTC: period=0x20 (32) 1024 Hz

Thanks for help




SAS Change the Proportion of a Random Sample

Is there a way to change and manipulate the proportion of a variable in SAS in random sampling?

Lets say that I have table consisting 1000 people. (500 male and 500 female)

If I want to have a random sample of 100 with gender strata - I will have 50 males and 50 females in my output.

I want to learn if there is a way to have the desired proportion of gender values?

Can ı have a random sample of 100 with 70 males and 30 females ?




mercredi 27 avril 2016

Take random word from file to print sentence from BNF grammar

I am confused on what BNF grammar actually is. As of right now, I have a text file called lol.txt and my code prints out a random line in the file. However, I need to pick a adj, prep, noun, etc to make a random sentence. Is my logical approach wrong?

FileInputStream wordsFile = new FileInputStream("lol.txt");

BufferedReader br = new BufferedReader(new InputStreamReader(wordsFile));

    String[] strWordArray;
    strWordArray = new String[10];

    for (int i = 0; i < strWordArray.length; i++) 
    {
        strWordArray[i] = br.readLine();
    }
    wordsFile.close();
    Random rand = new Random();
    String Word = strWordArray[rand.nextInt(strWordArray.length)];
    System.out.println(Word);

}




C++ and rand/srand behavior not performing as expected

I am using rand and srand from cstdlib and g++ as a compiler. I was playing around trying to generate some pseudo random numbers and I was getting some unexpected biased results. I was curious so I wrote a simple function. The expected behavior would be that a random number between 1 and 10 would be generated and printed out to screen a 100x's. The expected value of the average should be 5. However, when I run this function it will a generate a single random number between 1 and 10 and print it 100x's with the average being equal to the random number that was generated.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

float bs(){
        float random;
        srand(time(0));
        random = rand() % 10 + 1;

        return random;
}


int main(){

        float average;
        float random;

        for (int i = 1; i < 101; ++i)
        {
                random  += bs();
                cout << random << endl;
        }

        average = random/100;
        cout << average << endl;

        return 0;
}

If the initial return from bs = 7 it will stay 7 for the duration of the loop and each time bs() is called. The output will be 7 added to itself 100x's and the average will be equal to gasp 7. What is going on here?




Faster random uniform hash function

I need a little help in deciding the faster hash function for my program (in C++). Here is the scenario for which I need the better hash function. I have 4 million data and I would like to hash them [0, n] where n<<< 4M. The random hash function should be uniform e.g. if I hash 4000 data to [0,9], 400 elements should be hashed to 0, 400 to 2 and so on.




Mousover intiates random rollover from array of elements

Forgive me I'm a total noob but I'm making an effort - the errors I get seem to be syntactical. I've been working on this for over 10 days and have got it functioning virtually they way that I want it to. However, what I want (ideally) is to have it so that when an element is mousedOver the function then initiates the image rollover on a different element. eg. points 1,2,3. mouseOver point1 initiates a rollover at a random selection from points 1,2 or 3. So for instance the mouse might be at 'demo1' but initiates a rollover at 'demo3'. Hopefully this makes sense. Edit: found this page wich has similar effect except changes the background instead of the other element (eg. mouseOver square results in color/image change on circle) http://ift.tt/1VTkfyt

The first example returns getElementById(..) null, which I think means that the variable pointed has not been defined yet (because it can't be defined until all the elements are loaded). But if it works will it also provide the effect I am hoping for?

<head>
<script>
//preload
window.onload = function(){
var pixel= ("black.png")
inames= ["black1.jpg", "black2.jpeg", "black3.jpg", "black4.jpg",    "black5.jpg", "black6.jpg", "black7.jpg", "black8.jpg", "black9.jpg", "black10.jpg", "black11.jpg", "black12.jpg", ,"black.png", "black13.jpg", "black14.jpg", "black15.jpg", "black16.jpg", "black17.jpg", "black18.jpg", "black19.jpg", "black20.jpg", "black21.jpg", "black22.jpg", "black23.jpg", "black.png", "black24.jpg", "black25.jpg", "black26.jpg", "black27.jpg", "black28.jpg", "black29.jpg", "black30.jpg", "black31.jpg", "black32.jpg", "black33.jpg", "black34.jpg", "black35.jpg", "black36.jpg", "black37.jpg", "black38.jpg", "black39.jpg", "black40.jpg", "black41.jpg", "black.png", "black42.jpeg", "black43.jpg", "black44.jpg", "black45.jpg", "black46.jpg", "black47.jpg", "black48.jpg", "black49.jpg", "black50.jpg", "black51.jpg", "black52.jpg", "black53.jpg", "black54.jpg", "black55.jpg", "black56.jpg", "black57.jpg", "black58.jpg"]
var selected
var myImage
var selImage
points= ["demo", "demo1", "demo2", "demo3"]
var pointed

//do not delete
document.getElementById(pointed).onmouseover = function() {mouseOver()};
document.getElementById(pointed).onmouseout = function() {mouseOut()};
document.getElementById(pointed).onmouseover = function() {mouseOver1()};
document.getElementById(pointed).onmouseout = function() {mouseOut1()};
document.getElementById(pointed).onmouseover = function() {mouseOver2()};
document.getElementById(pointed).onmouseout = function() {mouseOut2()};
document.getElementById(pointed).onmouseover = function() {mouseOver3()};
document.getElementById(pointed).onmouseout = function() {mouseOut3()};
//Random Image
function randomPick(arr) {
  var selected = arr[Math.floor(Math.random()*inames.length - 1)]
  return selected;
}
//Random Element
function randomPoint(arr) {
    var pointed = arr[Math.floor(Math.random()*points.length + 1)]
  return pointed;
}
//DEMO -> working
function mouseOver() {
    var myImage = document.getElementById(pointed);
    var selImage = randomPick(inames);
    myImage.src = "media/" + selImage;
}
//DEMO -> working
function mouseOut() {
    var myImage = document.getElementById(pointed);
    myImage.src = "media/black.png";
}
//DEMO1 -> working
function mouseOver1() {
    var myImage = document.getElementById(pointed);
    var selImage = randomPick(inames);
    myImage.src = "media/" + selImage;
}
//DEMO1 -> working
function mouseOut1() {
    var myImage = document.getElementById(pointed);
    myImage.src = "media/black.png";
}
//DEMO2 -> working
function mouseOver2() {
    var myImage = document.getElementById(pointed);
    var selImage = randomPick(inames);
    myImage.src = "media/" + selImage;
}
//DEMO2 -> working
function mouseOut2() {
    var myImage = document.getElementById(pointed);
    myImage.src = "media/black.png";
}
//DEMO3 -> working
function mouseOver3() {
    var myImage = document.getElementById(pointed);
    var selImage = randomPick(inames);
    myImage.src = "media/" + selImage;
}
//DEMO3 -> working
function mouseOut3() {
    var myImage = document.getElementById(pointed);
    myImage.src = "media/black.png";
}
}
</script>
  </head>
  <body>

<image id="demo1" src="media/black.png" style="position:absolute; top:250px; left:500px; height:auto; width:auto;" onMouseOver=mouseOver1() onmouseOut=mouseOut1() alt="image2">

<image id="demo2" src="media/black.png" style="position:absolute; top:95px; left:50px; height:auto; width:auto;" onMouseOver=mouseOver2() onmouseOut=mouseOut2() alt="image3">

<image id="demo3" src="media/black.png" style="position:absolute; top:500px; left:10px; height:auto; width:auto;" onMouseOver=mouseOver3() onmouseOut=mouseOut3() alt="image4">
</body>

The second example is a rather large snippet of what I have that works, that I have been trying to modify to add the randomisation to. Again, this is my first real effort at coding anything but I've been working my ass off - I wouldn't ask if I could find out how to do it myself. Any help will be much appreciated. I was searching for a more elegant and solution to create the effect that I want but due to time constraints have just decided to do it however works..

<head>
<script type="text/javascript">
//preload
window.onload = function(){
var pixel= ("black.png")
inames= ["black1.jpg", "black2.jpeg", "black3.jpg", "black4.jpg", "black5.jpg", "black6.jpg", "black7.jpg", "black8.jpg", "black9.jpg", "black10.jpg", "black11.jpg", "black12.jpg", ,"black.png", "black13.jpg", "black14.jpg", "black15.jpg", "black16.jpg", "black17.jpg", "black18.jpg", "black19.jpg", "black20.jpg", "black21.jpg", "black22.jpg", "black23.jpg", "black.png", "black24.jpg", "black25.jpg", "black26.jpg", "black27.jpg", "black28.jpg", "black29.jpg", "black30.jpg", "black31.jpg", "black32.jpg", "black33.jpg", "black34.jpg", "black35.jpg", "black36.jpg", "black37.jpg", "black38.jpg", "black39.jpg", "black40.jpg", "black41.jpg", "black.png", "black42.jpeg", "black43.jpg", "black44.jpg", "black45.jpg", "black46.jpg", "black47.jpg", "black48.jpg", "black49.jpg", "black50.jpg", "black51.jpg", "black52.jpg", "black53.jpg", "black54.jpg", "black55.jpg", "black56.jpg", "black57.jpg", "black58.jpg"]
var selected
var myImage
var selImage

//do not delete
document.getElementById("demo").onmouseover = function() {mouseOver()};
document.getElementById("demo").onmouseout = function() {mouseOut()};
document.getElementById("demo1").onmouseover = function() {mouseOver1()};
document.getElementById("demo1").onmouseout = function() {mouseOut1()};
document.getElementById("demo2").onmouseover = function() {mouseOver2()};
document.getElementById("demo2").onmouseout = function() {mouseOut2()};
document.getElementById("demo3").onmouseover = function() {mouseOver3()};
document.getElementById("demo3").onmouseout = function() {mouseOut3()};

//Random Image
    function randomPick(arr) {
      var selected = arr[Math.floor(Math.random()*inames.length + 1)]
      return selected;
    }
//DEMO -> working
    function mouseOver() {
        var myImage = document.getElementById(pointed);
        var selImage = randomPick(inames);
        myImage.src = "media/" + selImage;
}
//DEMO -> working
    function mouseOut() {
        var myImage = document.getElementById(pointed);
        myImage.src = "media/black.png";
    }
//DEMO1 -> working
    function mouseOver1() {
        var myImage = document.getElementById("demo1");
        var selImage = randomPick(inames);
        myImage.src = "media/" + selImage;
}
//DEMO1 -> working
    function mouseOut1() {
        var myImage = document.getElementById("demo1");
    myImage.src = "media/black.png";
}
//DEMO2 -> working
    function mouseOver2() {
        var myImage = document.getElementById("demo2");
        var selImage = randomPick(inames);
        myImage.src = "media/" + selImage;
    }
//DEMO2 -> working
    function mouseOut2() {
    var myImage = document.getElementById("demo2");
    myImage.src = "media/black.png";
}
//DEMO3 -> working
    function mouseOver3() {
    var myImage = document.getElementById("demo3");
        var selImage = randomPick(inames);
        myImage.src = "media/" + selImage;
}
//DEMO3 -> working
    function mouseOut3() {
        var myImage = document.getElementById("demo3");
    myImage.src = "media/black.png";
}
</script>
</head>
<body>
<image id="demo" src="media/black.png" style="position:absolute; top:35px; left:200px; height:auto; width:auto;" onMouseOver=mouseOver()  onmouseOut=mouseOut() alt="image1">

<image id="demo1" src="media/black.png" style="position:absolute; top:250px; left:500px; height:auto; width:auto;" onMouseOver=mouseOver1() onmouseOut=mouseOut1() alt="image2">

<image id="demo2" src="media/black.png" style="position:absolute; top:95px; left:50px; height:auto; width:auto;" onMouseOver=mouseOver2() onmouseOut=mouseOut2() alt="image3">

<image id="demo3" src="media/black.png" style="position:absolute; top:500px; left:10px; height:auto; width:auto;" onMouseOver=mouseOver3() onmouseOut=mouseOut3() alt="image4">
</body>




playing with a matrix

Im trying to write a class that creates a matrix of zeros, then uses a random number generator to pick spots on the matrix. it changes the zero in that spot to a one, until the matrix is all ones. Can someone critique/correct my code? (I also want the generator to check its proximity on the matrix, and try 3 times to find a spot that is 2 spots away from any ones.)

import random
import numpy as np
#agents is amount of agents available to fill grid
class Gridmodel():
    def __init__(self, gridsize, agents):
        self.gridsize = gridsize
        self.agents = agents 
        self.gridmodel = np.zeros([self.gridsize, self.gridsize],dtype=int)


    def foundspot(self):
        foundspot = False         
        tries = 0
        while foundspot == False and tries <= 3:
            x = random.randint(0, self.gridsize)
            y = random.randint(0, self.gridsize)
            if self.gridmodel[x][y] < 0:
                foundspot = True
        else: 
            tries += 1

    def goodspot(self, x, y):
        goodspot = self.seats[x][y]
        for i in range(-1,2):
            for j in range(-1,2):

                print i, j, self.seats[i][j]             




Java Modulo Function Gives Zero

I am attempting to make my own random class. I do realize that many good ones already exist, however I want to make my own.

Here is the gist of the class:

public class Random {
    private int seed;
    private float count;
    public Random() {
    }
    public Random(int seed) {
        this.seed = seed;
    }
    public double getNextDouble() {
        count += 1;
        return (System.nanoTime() * Math.pow(count + seed, 2)) % 1;
    }
}

I would have thought that the function would return a pseudo random number greater than and equal to zero and less than one. However, the getNextDouble() function unexpectedly returns 0. I've tracked the problem down to the % 1 part of the function.

Why is this causing the number returned to equal zero, and how would I fix this?

Thanks in advance.




C#: Why two different randomizers return same values? [duplicate]

This question already has an answer here:

I am trying to extend my programming skills in .NET as for the moment I just can code in PowerShell. Now I like to transfer a simple function to create a (low-security at all) password to C# but facing confusing situation.

I have two different solutions (I am not sure which one is better at all) in mind to do that see below: Version1

        public static char[] GetPassword(int length)
    {
        char[] password = new char[length];
        string passwordchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        Random randomtoken = new Random();
        for (int i = 0; i < length; i++)
        {
            password[i] = passwordchars[randomtoken.Next(passwordchars.Length)];
        }


        return password;
}

Version2

        public static string GetPassword2 (int length)
    {
        string password2 = "";
        string passwordchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        Random randomtoken2 = new Random();
        for (int i = 0; i < length; i++)
        {
            password2 += passwordchars[randomtoken2.Next(passwordchars.Length)];
        }

        return password2;

    }

Now I am calling the two versions from another class (importing the class with the password methods by "Using static" directive.

      static void Main()
    {
        char[] password = GetPassword(9);
        string password2 = GetPassword2(9);
        Console.WriteLine("1. Passwort:");
        Console.WriteLine(password);
        Console.WriteLine("2. Passwort:");
        Console.WriteLine(password2);
        return;
 }

Expected behaviour: As I am using two different methods with its own randomizer instance it should generate two completely different passwords (actually in my opinion even if I use the same randomizer)

Actual behaviour: Indeed the console output is twice exactly the same password. I have no explanation for this.

How is that? Can someone please explain me this? :) Thank you.




Take always a different random element in range

I need to select two different integers that belong to a certain range [min, max].

Example: rds = 3, min = 0, max = 9. If the first random element is r1 = 6, then r2 must be different from 6 and r3 must be different from r1 and r2.

I thought of building an array containing all the numbers belonging to [min, max]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].

I select a random number between 0 and 9 with return ThreadLocalRandom.current().nextInt(0, 10) and then I swap r1 and the last element of the array. To find r2 I apply the random function from 0 to the penultimate position in the array, and so on.

This is the code:

public void takeRandomXposition(int rds, int[] positions) { 
    int k = positions.length;
    int min = 0;
    int max = k - 1;
    for(int i = 0; i < rds; i++) {
        int r = random(positions[min], positions[max - i]);
        swapPositions(positions, r, max - i);
    }
}

public int random(int min, int max) {
    return ThreadLocalRandom.current().nextInt(min, max + 1);
}

public void swapPositions(int[] positions, int index, int last) {
    int indexA = positions[index];
    int lastA = positions[last];
    positions[index] = lastA;
    positions[last] = indexA;
}

This method works for the first steps, but not anymore. The problem is that the elements in the array are moved and mixed, but I try the random number in a range. I don't know how to explain, I give an example in which the method doesn't work.

positions: [ 0 1 2 3 4 5 6 7 8 9 ]
rds = 3
k = 10
min = 0
max = 9

    i = 0
    search r in range [0, 9]
    r = 5
    positions: [ 0 1 2 3 4 9 6 7 8 5 ]

    i = 1
    search r in range [0, 8]
    r = 3
    positions: [ 0 1 2 8 4 9 6 7 3 5 ]

    i = 2
    search r in range [0, 7]
    r = 5
    positions: [ 0 1 2 8 4 7 6 9 3 5 ]

In addition there is also a problem when r = 0:

positions: [ 0 1 2 3 4 5 6 7 8 9 ]
rds = 3
k = 10
min = 0
max = 9

    i = 0
    search r in range [0, 9]
    r = 0
    positions: [ 9 1 2 3 4 5 6 7 8 0 ]

    i = 1
    search r in range [9, 8]
    Exception in thread "main" java.lang.IllegalArgumentException: bound must be greater than origin

So, I don't want to find a random number in a range [min, max] but a random number in the contents of an array.

Thanks.




How to generate an array containing the number of random strings where each string will have between 3 and 8 lower-case letters, inclusive

I want to create a method where I will give parameter of size and create an array of random strings with each having at least 3 and at most 8 lower case letters, inclusive.

Edit: This is what I tried :

public static String[] makeRandomStringList(int size) {
String[] str = new String[size];
for (int i =0; i <size ; i++) {
   str[i]= randomFill();
}
    return str;
}

public static String randomFill() {
Random rd = new Random();
String randomNum = rd.nextLine();//nextLine() is undefined for random type so I don't know what else to do.
return randomNum;
}




Random questions with Linear Congruent Generator JSON Format

Previously I was using mysql order by rand () limit 15 to generate random questions with 15 questions selected and the results are successful. But what if I want to randomize the questions with Linear Congruent Generator method (LCG).

The heart of an LCG is the following formula:

X(i+1) = (a * X(i) + c) mod M

where 

M is the modulus. M > 0.
a is the multiplier, 0 <= a < M.
c is the increment, 0 <= c < M.
X(0) is the seed value, 0 <= X(0) < M.
i is the iterator. i < M 

How do I apply? so as to generate data in json format with random results using LCG methods and not using the order by rand (). Thanks.

<?php
include("conn.php");
$arr = array();
$x   = mysql_query("select * from question_tbl");
        while ($row = mysql_fetch_assoc($x)) {
            $temp = array(
                "id_question" => $row['id_question'],
                "question"=>$row['question'],
                "a"=>$row['a'],
                "b"=>$row['b'],
                "c" => $row['c'],
                "answer" => $row['answer'],
                "image" => "http://ift.tt/21foofx".$row['image'].""
            );
            array_push($arr, $temp);
        }   
    $data = json_encode($arr);
    $data = str_replace("\\", "", $data);
    echo "{\"question_list\":" . $data . "}";
?>




How to get a normal distribution within a range in numpy?

In machine learning task. We should get a group of random w.r.t normal distribution with bound. We can get a normal distribution number with np.random.normal() but it does't offer any bound parameter. I want to know how to do that?




Ada thread to pass auto random generated data to a procedure

How would i go about creating a procedure that is a thread which continuously passes automatic random generated data within a specified range.

I currently would have to manually enter in each bit of data in the console using this procedure below. I want to creatre a procedure that when running is able to pass data to this procedure as if it was being typed into the console itself.

procedure Analyse_Data is
  Data : Integer;
begin
  DT_Put_Line("Data input by user");
  loop
     DT_Get(Data,"Data must be taken as a whole number");
     exit when (Data >=0) and (Data <= Maximum_Data_Possible);
     DT_Put("Please input a value between 0 and ");
     DT_Put(Maximum_Data_Possible);
     DT_Put_Line("");
  end loop;
  Status_System.Data_Measured := Data_Range(Data);
end Analyse_Data;

I havent included the specification files (.ads) I am new to Ada and any help would be appreciated.




Matlab ask for integer loop

I'm creating a program to simulate a random walk and it requires the user to input an integer number of steps to take for the walk.

The prompt for this uses code very similar to this:

    **% Ask user for a number.
    defaultValue = 45;
    titleBar = 'Enter a value';
    userPrompt = 'Enter the integer';
    caUserInput = inputdlg(userPrompt, titleBar, 1,{num2str(defaultValue)});
    if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
    % Round to nearest integer in case they entered a floating point number.
    integerValue = round(str2double(cell2mat(caUserInput)));
    % Check for a valid integer.
    if isnan(integerValue)
    % They didn't enter a number.  
    % They clicked Cancel, or entered a character, symbols, or something else not allowed.
    integerValue = defaultValue;
    message = sprintf('I said it had to be an integer.\nI will use %d and continue.', integerValue);
    uiwait(warndlg(message));
    end**

However, I want it to simply display the "Enter a value" prompt again if the user does not enter an integer the first time i.e. 4.4.

Any ideas?

Thanks!




NodeJS cryptographically secure number

i´m developing a Jackpot Script in NodeJS and i need a cryptographically secure random number, between 2 numbers.

How can i generate a secure number? is there a good npm for random numbers?




How Random email generation and capturing work

I would like to understand how can I capture emails sent to different random email ids generated by server in one inbox to run analysis on those emails something like this website does : http://ift.tt/10GLh1C

Here , with each page referesh, you would notice a new random email id is generated. If an email is sent to this random email id, the mail-tester server captures that email, assesses it using spamassassin and generates a report. I want to understand how can we capture emails sent to so many different random email ids in a single inbox so that they can be assessed by spamassassin or any other utility.




I need help width the Random code [duplicate]

This question already has an answer here:

I need help width the Random r = new Random(); code.

I will give you my code and tell you what I want to do.

Random r = new Random();
int i = r.nextInt(3);
System.out.println(i);

//now how do i make it not to take 0 as a random number
//One of them is 0, how do i make it take a random int that is
//bigger than 0 but lower than 3. I need help there.




mardi 26 avril 2016

What shape should we get by plotting the log-log graph of Inverse Performance Ratio of eigenvectors vs Eigenvalues for a random matrix?

The Inverse Participation Ratio (I.P.R.) of a vector u = (u1, .... um) for i = 1, ..., m is defined as follows:

enter image description here

When plotting the log-log of IPR of the eigenvectors vs the eigenvalues, L, we should get something interesting, perhaps a straight line like:

enter image description here

But I am getting a haphazard thing:

enter image description here

This is my code.

m=98; n=753;
H=randn(m,n);
W=1/n*(H*(H'));
[U, lambda] = eig(W);

for i=1:size(U,2)
    IPR(i,1)=0;
    for j=1:98
        IPR(i,1)=IPR(i,1)+U(j,i)^4;
    end
    L(i,1)=lambda(i,i);
end

loglog(L,IPR);

Could anyone please point out what I am doing wrong?




Formula for generating Trigen-distributed random variates

Is there any formula for finding random Trigen distributed random variate from a random variate drawn from the uniform distribution in the interval (0, 1) like the formula for Triangular distribution?

I have inputs minimum, likely, maximum, lower % and upper %. How to find the distribution from this? Do we need to find the extended minimum and maximum values first and then generate the triangular distribution with extended minimum, likely and extended maximum values to find the Trigen distribution?

I working in java.

Thanks in advance




Get random ENGLISH alphabet letter MySQL

How to get random ENGLISH letter in MySQL?




Non repeating RNG in a range?

I need a RNG that produces every number once (no storing results). I found a few LFSR (Linear feedback shift register) online but they work as 32bits or 16. I need them somewhere in between (22bits) or in a range. How do I implement this? (my LFSR is weak)




Use a Linear feedback shift register in a range?

I need a RNG that produces every number once. I found a few LFSR (Linear feedback shift register) online but I get them producing 16 or 32 values. I need one that uses an unknown amount of bits (right now I want 22bits). I tried taking a 32bit LFSR and masking out the high bits but I get numbers that repeat as often as 9 times (I found 20 numbers repeated 8 times each).

How do I use a LFSR within a range or use it with a specified amount of bits?




Select random cell from a row 4 seperate times

I would like to select a random cell in a row which contains numbers from, say, 1-20. Each number will occur in the row several times. Then repeat the process 4 times with no duplicate numbers, so I have a set of 4 unique numbers, such as 4 - 6 - 12 - 9. Kind of like a lottery, but each number in the hopper may occur several times, but can't be drawn twice. Thank you! Mike




How to print array index when using random()

I'm having issues with my code. It's suppose to populate an array list with 5 words. A random number is then generated and used to pick a word from the array list based on it's index. The problem I'm having is when I try to print the random number it doesn't match the index of the word displayed.

/*This program will prompt the user to enter 5 words.
These messages will be stored in a ArrayLsit.
The program will then number the messages and display them in a list.
The program will then generate a random number.
The program will then use the random number to display a word from the arraylist.*/

package wordup;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;

public class WordUp {

/* @param args the command line arguments */

public static void main(String[] args) {
    // TODO code application logic here 

    ArrayList<String> words = new ArrayList<>();
    for (int i = 0; i < 5;i++)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a word.");
        words.add(i, input.nextLine());
    }
    for (int i = 0; i < words.size(); i++) {

        System.out.println((i)+". "+words.get(i)); //Should print the messages
    }

    Random word = new Random();
    int index = word.nextInt(words.size());
    System.out.println("Your randomly generated word is: " +words.get(word.nextInt(words.size()))+".");
    System.out.println("It was found at index " +index+".");
}   

}




Distribution of php's random_int() function

What is the distribution of php's random_int function?

I guess it comes down to the distribution of getrandom(2) and /dev/urandom? How are they distributed?

Can random_int be used for a uniform distributed random number generator?




Setting random position of a FrameLayout - Android / Java

I'm trying to set a framelayouts position to a random value onclick for a game I'm creating. I'm very new to java and although I've got the random numbers, I can't find how to set the framelayouts position to those random numbers' value. Here's my uncompleted code. Let me know if you want me to clarify something!

public class MainActivity extends AppCompatActivity {
private int rWidth = (int) Math.round(Math.random() * WIDTH);
private int rHeight = (int) Math.round(Math.random() * HEIGHT);
@Override
    public void onStart(){
        super.onStart();

private int WIDTH = this.getResources().getDisplayMetrics().widthPixels;
private int HEIGHT = this.getResources().getDisplayMetrics().heightPixels;
final FrameLayout mainObject = (FrameLayout) findViewById(R.id.mainObject);


        mainObject.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Here's where I want to change the position!
            }
        });
   }
}

Thanks!




What is a good algorithm to generate a random path?

I need to generate a random path with 25 segments that never crosses itself between two locations in a 1000x1000 area. What is a good algorithm to do this?

My initial idea, which generates ok results, was to generate a random polygon using the space partitioning method and then remove one side.

The results look like this: output

The downside of this method is that the start is always fairly close to the end (since they were originally connected by a line).

The other downside is since they were a polygon, the overall shape is generate some form or distorted circle. There are lots of types of paths that would never be generated, like a spiral.

Does anybody know an algorithm that could help me generate these paths?




N-Queens Display 1 Random Solution

So far I have this code that displays the 92 solutions for an 8x8 board for the N-Queens problem. Instead of displaying ALL 92 solutions, I am wanting to try and get it to just display 1 random solution each time it is ran. How can I do this?

import sys

from ortools.constraint_solver import pywrapcp

# by default, solve the 8x8 problem
n = 8 if len(sys.argv) < 2 else int(sys.argv[1])

# creates the solver
solver = pywrapcp.Solver("n-queens")

# creates the variables
# the array index is the row, and the value is the column
queens = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)]
# creates the constraints

# all columns must be different
solver.Add(solver.AllDifferent(queens))

# no two queens can be on the same diagonal
solver.Add(solver.AllDifferent([queens[i] + i for i in range(n)]))
solver.Add(solver.AllDifferent([queens[i] - i for i in range(n)]))

# tells solver what to solve
db = solver.Phase(queens, solver.CHOOSE_MIN_SIZE_LOWEST_MAX, solver.ASSIGN_CENTER_VALUE)

solver.NewSearch(db)

# iterates through the solutions
num_solutions = 0
while solver.NextSolution():
  queen_columns = [int(queens[i].Value()) for i in range(n)]

  # displays the solutions
  for i in range(n):
    for j in range(n):
      if queen_columns[i] == j:
        print "Q",
      else:
        print "_",
    print
  print
  num_solutions += 1

solver.EndSearch()

print
print "Solutions found:", num_solutions




C# Generate Random number

I am wanting to generate a random number between 1 and 10. Yet I am getting a couple of errors.

 public Form1()
        {
            InitializeComponent();
        }
        int randomNumber = (0, 11);
        int attempts = 0;

    public int RandomNumber
    {
        get
        {
            return randomNumber;
        }

        set
        {
            randomNumber = value;
        }
    }

it is all on the 0, 11 under the comma is says --> struct System.Int32 represents a 32-bit signed integer <--. Under the 11 it says --> Identifier expected Syntax error, ',' expected <--. Now if I just have like int randomNumber = 0; then it will work fine, still have multiple guesses and the guess count adds up like it should, and have the too high too low labels. just the number will always be 0.

Also how can I make it to where I don't have to click the guess button, I can just hit enter on the keyboard?

private void button1_Click_1(object sender, EventArgs e)
    {
        try
        {
            if (int.Parse(textBox1.Text) > RandomNumber) label1.Text = "Too high.";

            else if (int.Parse(textBox1.Text) < RandomNumber) label1.Text = "Too low.";
            else
            {
                label1.Text = "You won.";
                textBox1.Enabled = false;
                label2.Text = "Attempts: 0";
                textBox1.Text = String.Empty;
                MessageBox.Show("You won in " + attempts + " attempts, press generate to play again.", "Winner!");
                attempts = 0;
                label2.Text = "Attempts: " + attempts.ToString();
                return;
            }
            attempts++;
            label2.Text = "Attempts: " + attempts.ToString();
        }
        catch { MessageBox.Show("Please enter a number."); }
    }




Random words C# [on hold]

how can I put words from a text box (sepparated by points or comma) into an another text box? But only one word. It's for random words.

I attached an image.

enter image description here




How do I generate a random alphanumeric array that has 3 letter and 6 digits in c#?

I am trying to generate a random alphanumeric array that consist of 3 letters and 6 digits. The entire array must be random. The only way I could think of is generating 2 individual random arrays and then merging them and randomizing the merged array. Any help would be appreciated. I specifically need help on ensuring that the correct number of variable types are stored. Here is my semi-working code:

 static void Main(string[] args)
    {
        var alphabetic = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        var numeric = "0123456789";
        var stringChars = new char[9];
        var random = new Random();


        for (int i = 0; i < 3; i++)
        {
            stringChars[i] = alphabetic[random.Next(alphabetic.Length)];
        }
        for(int i = 3; i< stringChars.Length; i++)
        {
            stringChars[i] = numeric[random.Next(numeric.Length)];
        }


        var ranChars = new char[9];
        var semisorted = new String(stringChars);

        for (int i=0; i< ranChars.Length; i++)
        {
            ranChars[i] = semisorted[random.Next(semisorted.Length)];
        }


        var final = new string(ranChars);

        Console.WriteLine("{0}", final);
        Console.ReadLine();


    }




Using Python Networkx and Numpy.Choice & Getting ValueError

Language: Python 2.x Packages: Networkx, Numpy

My code picks a random node from my graph then does the following:

1- if it's an isolate, go back to the beginning of the while loop and pick another random node

2- if it is not an isolate, get it's neighbors

3 - if it has only 1 neighbor then the random neighbor you pick is that only neighbor

4-if it has more than one neighbor, then pick a random neighbor out of the choices available

5- that random choice, check to see if it has neighbors. Just like above.. if it has one than set the neighbor of neighbor to be that one neighbor

6-if it had more than one then pick a random neighbor of neighbor

7- connect the neighbor of my neighbor to me (the original random node)

This code HAD been working until I introduced some minor changes in another part of my program. I know all the syntax works, but I simply cannot get passed the error. Below is my code and the error.

while i <= self.iterations:
            node_list = nx.nodes(self.origin_network)


            random_node = numpy.random.choice(node_list)
            #print (" This random node has no neighbors:", self.origin_network.neighbors(random_node))
            if nx.is_isolate(self.origin_network, random_node) == True:
                i += 1
                print (" This random node has no neighbors:", self.origin_network.neighbors(random_node), "on turn", i)
                continue
            else:
                Neighbs = self.origin_network.neighbors(random_node)

                if len(Neighbs) == 1:
                    print ("The neighbor has no additional neighbors", "on turn", i)
                    random_neighb = Neighbs
                else:
                    random_neighb = numpy.random.choice(Neighbs) ***#This is line 108 which the error references***

                neighbs_of_neighb = self.origin_network.neighbors(random_neighb)
                if len(neighbs_of_neighb) == 1:
                    print ("This neighbor has only the original neighbor on turn", i)
                    random_NofN = neighbs_of_neighb
                    self.origin_network.add_edge(random_node, random_NofN)
                else:
                    random_NofN = numpy.random.choice(neighbs_of_neighb)
                    self.origin_network.add_edge(random_node, random_NofN)
                    print "success"
            i += 1

The error I receive is:

self.triadic_method(self.origin_network , iteration, sim_number)

File "D:\network.py", line 108, in triadic_method random_neighb = numpy.random.choice(Neighbs) File "mtrand.pyx", line 1121, in mtrand.RandomState.choice (numpy\random\mtrand\mtrand.c:12473) File "mtrand.pyx", line 945, in mtrand.RandomState.randint (numpy\random\mtrand\mtrand.c:10732) ValueError: low >= high

line 108 which the error references is this one:

random_neighb = numpy.random.choice(Neighbs) #This is line 108 which the error references




Inserting data to DB using system-uuid

I have run into a problem related to System generated uniquer identifier.

Below is the definition of a datamember from my bean class:

@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(name = "id")
private String id;

Whenever the client action is invoked, data will be persisted to DB based with the value for id attribute generated dynamically using above system-uuid. Now I have a requirement wherein i have to perform mass insert to this table. As there is no import functionality, is there any way that i can perform the bulk insert from backend using oracle insert queries? If so, how do i mention the value for the column 'id' so that it works like the same as the insert happened from client.




Excel Randbetween number show up for limited times

I want to randomly setup a group of numbers of 1 and 0, and 1 generate no more than 10 times. i have used =countif(range,"<9")*randbetween(0,1) but its not working




Python 3 - creating list with randint [duplicate]

This question already has an answer here:

I have the following code:

import random

num_custs = int(input('custs '))
num_floors = int(input('floors '))

start = (random.randint(0, num_floors) for x in range(num_custs))
start = list(start)
print(start)
end = (random.randint(0, num_floors) for x in range(num_custs))
end = list(end)
print(end)

It outputs:

custs 10
floors 5
[5, 0, 0, 5, 1, 2, 2, 0, 3, 1]
[4, 1, 5, 1, 1, 1, 1, 3, 2, 0]

What I want is one list with the values from the first list mapped to the values from the second list like this:

[(5, 4), (0, 1), (0, 5), (5, 1)] etc.

I have been searching for this online for ages and can't seem to find what I am looking for.

Am I approaching this correctly or is there a better way?




Scikit-learn SVC always giving accuracy 0 on random data cross validation

In the following code I create a random sample set of size 50, with 20 features each. I then generate a random target vector composed of half True and half False values.

All of the values are stored in Pandas objects, since this simulates a real scenario in which the data will be given in that way.

I then perform a manual leave-one-out inside a loop, each time selecting an index, dropping its respective data, fitting the rest of the data using a default SVC, and finally running a prediction on the left-out data.

import random
import numpy as np
import pandas as pd
from sklearn.svm import SVC

n_samp = 50
m_features = 20

X_val = np.random.rand(n_samp, m_features)
X = pd.DataFrame(X_val, index=range(n_samp))
# print X_val

y_val = [True] * (n_samp/2) + [False] * (n_samp/2)
random.shuffle(y_val)
y = pd.Series(y_val, index=range(n_samp))
# print y_val

seccess_count = 0
for idx in y.index:
    clf = SVC()  # Can be inside or outside loop. Result is the same.

    # Leave-one-out for the fitting phase
    loo_X = X.drop(idx)
    loo_y = y.drop(idx)
    clf.fit(loo_X.values, loo_y.values)

    # Make a prediction on the sample that was left out
    pred_X = X.loc[idx:idx]
    pred_result = clf.predict(pred_X.values)
    print y.loc[idx], pred_result[0]  # Actual value vs. predicted value - always opposite!
    is_success = y.loc[idx] == pred_result[0]
    seccess_count += 1 if is_success else 0

print '\nSeccess Count:', seccess_count  # Almost always 0!

Now here's the strange part - I expect to get an accuracy of about 50%, since this is random data, but instead I almost always get exactly 0! I say almost always, since every about 10 runs of this exact code I get a few correct hits.

What's really crazy to me is that if I choose the answers opposite to those predicted, I will get 100% accuracy. On random data!

What am I missing here?




How can I insert a random element into a dictionary and have it randomised whenever I call it?

I'm writing a Facebook bot which will eventually produce a couple of randomly-generated statuses a day. Right now, I'm at the stage where I've got the logic of selecting bits of phrases from dictionary entries and I've written it so it will just work in the Python shell for the time being - the Facebook authentication stuff will come later.

Right now though, I thought it'd be cool to randomise certain nouns within the phrases contained in the dictionaries, and I was doing this with random.choice() and running a function that should return a new random element every time I generate a status. But the problem is that whenever I call the phrase, I can see that it's generated one random noun, but that noun gets 'fixed' for some reason such that the same random noun is reproduced every time. When I run the function as part of building a status, it seems to be working fine, but for some reason I can't figure, any new random nouns are not passed to the dictionary. Naturally, it works when I restart the programme, but if I'm aiming to do this as a bot, I'd ideally like to not have to restart the programme every time I want a new status.

I've done some investigating and I think the problem is not to do with my actual random.choice() stuff or the functions that they're in, but that the dictionary gets 'fixed' before my random noun function can touch it (e.g. the random choice function produces a random selection from the fruit list, but the dictionary will only ever have the same fruit selected when I run the StatusBuilder function). I have tried out some potential solutions with global variables and so on, but nothing has worked. The excerpt demonstrated in the code below is, I think, the closest I've come.

from random import randint
from random import choice
from textwrap import fill

def RandomFruit():
    return choice(["mango", "pomelo", "guava", "grapefruit", "watermelon"])

class DoTable():
    def __init__(self, text):
        self.text = text

DoDict = {
    "do0": DoTable("sitting on the roof, completely naked, throwing Herb Alpert records at a dog like they were frisbees"),
    "do1": DoTable("eating a " + RandomFruit() + " like it's a handfruit"),
    "do2": DoTable("lurching around a supermarket"),
    }

class BeTable():
    def __init__(self, start_text, end_text):
        self.start_text = start_text
        self.end_text = end_text

BeDict = {
    "be0": BeTable("I guess ", " is what my life has come to."),
    "be1": BeTable("", ", just waiting for the police to arrive."),
    "be2": BeTable("If ", " is wrong, then I don't ever want to be right!"),
    }

def StatusBuilder():
#DoDict and BeDict will always have one entry selected from each, though
#BeDict will always have two attributes selected as part of the one entry.
    DoRNG = randint(0,len(DoDict)-1)
    BeRNG = randint(0,len(BeDict)-1)
#Logic to display concatenated strings
    status = BeDict["be" + str(BeRNG)].start_text + DoDict["do" + str(DoRNG)].text + BeDict["be" + str(BeRNG)].end_text
#print the status with textwrapping and with the first letter always capitalised.
    print fill((status[0].capitalize() + status[1:]), 80)
    print
    Controls()

def Controls():
    command = raw_input("([RETURN] FOR ANOTHER ROUND OF BULLSHIT, [Q] TO QUIT): ")
    if command.lower() == "q":
        quit()
    elif command.lower() == "":
        print
        RandomElements()
        StatusBuilder()
    else: 
        print
        print fill("Some kind of wise guy are you? Try again, this time with a PROPER command please.", 80)
        print
        Controls()

#Start the program
print "PHILBOT V1.0"
print "A social media status generator."
print
command = raw_input("(PRESS [RETURN] TO GET STARTED): ")
print
RandomElements()
StatusBuilder()




lundi 25 avril 2016

random number with p(x)= x^(-a) distribution

How can I generate random number within [1,inf] with below distribution in MATLAB:

p(x)= x^(-a)




Why do I get Chinese characters when generating random numbers in Java?

This program generates 50 random numbers between 1 to 100 and the output are written in the fileresult.txt .

    FileWriter outputChar = new FileWriter(new File ("fileresult.txt"));
    Random random = new Random();
    for(int i = 1 ; i <= 50 ; i++){
        int min = 1;
        int max = 100;
        int number = random.nextInt(max - min + 1) + min;
        outputChar.write(number);
    }
    outputChar.close();

The problem is the output are not integer values, but many Chinese characters instead. Why does this happen?




Snake Game random colors

I created a snake game but i want every new block added onto it to genarate a random new color. This is what I have right now but all it does is send a "null" back and causes it to be white.

// Draw a square for each segment of the snake's body
Snake.prototype.draw = function () {
for (var i = 0; i < this.segments.length; i++) {
this.segments[i].drawSquare(randomColor());
}
};








function randomColor() {
    return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6);
}



What does this thread_local RNG seed accomplish?

As part of an assignment, one of my professors gave me code that looks kind of like this:

namespace
{
  thread_local unsigned seed; // for use with rand_r

  void run_custom_tests() {
      // set this thread's seed
      seed = 0;

      // insert some random numbers into a map
      std::map<int, int> m;
      for (int i = 0; i < key_max; ++i)
          m.insert(i, rand_r(&seed));

      auto random_operations = [&]()
      {
          // do more stuff with rand_r(&seed)
      };

      std::thread t1(random_operations);
      std::thread t2(random_operations);
      t1.join();
      t2.join();
  }

} // end anonymous namespace

void test_driver()
{
    run_custom_tests();
}

My question is what is the purpose of that thread_local seed? I understand that you can't allow two threads to access the same global variable. But why not just make it local? Since seed is only used to fill that map and inside the lambda, and each thread has its own stack, wouldn't a local variable accomplish the same goal?

I did fine on the assignment, since the point wasn't to understand this usage of thread_local. But I'm still confused by this aspect of the program.




(JavaScript) Pick a random equation with random numbers

Ok, so I want these equations to be randomly picked: Equation 1: 4 x 3 + {4 x [(5 x 6) - 4] + 5} = x

Equation 2:
654 x 345 = y

Equation 3:
34s x 45 = z
s = 9

Equation 4:
4 + {45 x [34 + (5 x 7) + 7] + 67} = x

Equation 5:
x = 3e + 1l x 2 + 4a
e = 4,
l = 5,
a = 6

Equation 6:
e = [7 x 6z] + {3 - 4} + (3 + 4)
z = 4

Equation 7:
e = p x 73 / 21 - 34 + 15

With every number being a random number. So far I have some code but it won't work. Any help? P.S. I just want solid code answers. I need this TONIGHT. Please share to anyone who you think can help.




Random Number Generation : same C++ code, two different behaviors

My colleague and I are working on a Monte Carlo project together, in C++. She uses Visual Studio, I use Xcode, we shared the code through git. We are computing American option prices thanks to a given method requiring random number generation. We realized we were getting wrong results for a certain parameter K (the higher the parameter, the more wrong the answer), and my colleague found that changing the random source for Mersenne Twister to rand() (though poor generator) made the results good for the whole range of K.

But when I changed the source on my version of the code, it did nothing.

More puzzling for me, I created a new Xcode project, copied inside it her whole source and it still gives me wrong results (while she gets good ones). So it can't stem from the code itself. I cleaned the project, relaunched Xcode, even restarted my computer (...), but nothing changes : our projects behaves consistently but differently, with the same code behind.

Do you have any idea of what the cause of this dual behavior could be ?




Easiest way to get an array of random values from another array in PHP

I'm wondering what is the easiest/cleanest way to get an array of random values from an array in PHP. It's easy to get an array of random keys but it seems there's not function to get array of values straight away

The easiest way I found out is:

$tokens = ['foo', 'bar', '...'];
$randomValues = array_map(function($k) use ($tokens) {
    return $tokens[$k];
}, array_rand($tokens, rand(7, 20)))

This returns 7-20 random values from $tokens variable. However this looks ugly and is very unclear at first sight what it does.




random 6-sided dice roll looped 30 times

Hi i'm trying to loop this code 30 times using a random 6 sided dice roll and make a scatter cloud in the tirangle. I got it to give me 2 points but i cant figure out how to loop it after that

import numpy as np
import pylab as plt




a=1.0
h=np.sqrt(3)/2.0*a
edgepoint[0,]=[-1/2.*a, 0]
edgepoint[1,]=[1/2.*a, 0]
edgepoint[2,]=[0, h]
x=edgepoint[[0,1,2,0],0]
y=edgepoint[[0,1,2,0],1]
plt.plot(x,y)

# seed with a first random point, first the x-axis
x0=np.random.uniform(low=-1/2.0*a,high=1/2.0*a,size=1)
# now the y-coordinate, for this we need to define an upper
# limit for the random number
# per default np.random.uniform() returns numbers between 0 and 1
if (x0>=0):
    ymax=h-x0*2*h/a
else:
    ymax=(a/2+x0)*2*h/a

y0=np.random.uniform(low=0.,high=ymax,size=1)
p0=np.array([x0,y0])
plot_point(p0)

test=np.random.random_integers(0,2,1)
newx=x[test]
newy=y[test]
pnew=np.array([newx,newy])

p2=step(p0,pnew)
plot_point(p2,ic=1)