dimanche 31 juillet 2016

Seeded Binary Random Generator Matrix

I need to known what is the mininum number of bits that it is necessary by the seed of a random binary generator matrix.




Are C++ distributions keep or update parameters on op(URNG, params)?

Question to C++ language lawyers, applicable to pretty much any distribution (normal, uniform, poisson, ...), but I'll use Poisson as an example.

Simple code

#include <random>

std::default_random_engine rng;

double lambda = 5.0;
std::poisson_distribution<int> Poisson(lambda);

auto A = Poisson(rng);      // call with lambda equal to 5
auto B = Poisson(rng, 3.0); // call with lambda equal to 3
auto C = Poisson(rng);      // call with lambda equal to what?

What lambda would be used in case of C?

All distribution have the same overloaded operators:

template<class URNG> result_type operator()(URNG& g);
template<class URNG> result_type operator()(URNG& g, const param_type& parm);

If we construct distribution with one set of parameteres, then call second op(), will distribution state altered? Or it will use parameters from the constructor?




coin flip experiment in C++ using std::rand() giving incorrect result

I'm trying to count the number of occurrences of the string HHHHHHTTTTTT in 1 million flips. For the coin flip, I'm using a simple std::rand() % 2. The code below. Mathematically, the expected answer is

(10^6 - 12 + 1) / 2^12 = 244

I got this result from a probability textbook. But my code is consistently getting only about half of that, i.e. around 122. Is this an issue with using std::rand() as a coin flip algorithm, or is there a bug in my code?

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

using std::vector;

bool coin_flip(){
  return std::rand() % 2;
}

int count_string(int n, const vector<bool>& s){
  int k=0, res=0;
  for(int i=0; i<n; i++){
    if(coin_flip()==s[k]){
      k++; 
      if(k==s.size()){
        res++;
        k=0;
      }
    }else{
      k=0;
    } 
  }
  return res;
}

int main(){
  std::srand(std::time(0));

  vector<bool> v(12);
  const int a[12] = {1,1,1,1,1,1,0,0,0,0,0,0};
  for(int i=0; i<12; i++){
    v[i] = a[i];
  }

  std::cout << count_string(1000000, v) << '\n'; 
  return 0;
}




java - Random inside while loop causes infinite loop with all same numbers

On the Programming By Doing website I'm stuck on the DoubleDice exercise. It's supposed to run a while loop until you come up with the same value for each dice (doubles - 3 and 3, 4 and 4, etc.)

I've input what I think to be the correct code, but I get this infinite loop that prints out the exact same "randoms" every time through the while loop.

I've pondered this for about a day and decided to give it to SO.

Thanks.

import java.util.Random;

public class diceDoubles {

    public static void main(String[] args){

        Random dice = new Random();

        int roll1 = 1 + dice.nextInt(6);
        int roll2 = 1 + dice.nextInt(6);

        System.out.println("HERE COMES THE DICE!\n");

        while(roll1 != roll2) {

            System.out.println("Die 1: " + roll1);
            System.out.println("Die 2: " + roll2);
            System.out.println("The total is " + (roll1 + roll2) + "\n");
        }
    }
}




Generating Random Numbers in For Loop from External Class

First of all, I apologize if this has been asked before and I couldn't find it. I scoured the depths of the internet looking for some guidance but did not come up successful.

In my programming II class we are working on creating a program for the lottery. We have created external classes (did that in the classroom) and have used the objects created in those classes in our driver. For this assignment, we are creating a program which outputs lottery numbers. The program asks the user if they are playing Pick 3, 4, or 5 and then is supposed to output a random number for each "ball". In one of the separate classes we have already imported and instantiated the randomizer. However, when I program the array and for loop, while it generates the proper number of printouts (3 printouts for 3, 4 printouts for 4, and 5 printouts for 5), a new number is not being generated for each loop. Instead, it is holding onto the first value and printing that out for each loop after. I've included my code below. Please help!

import java.util.Scanner;

public class LotteryGame2 {

  public static void main(String[] args){

    //Declare and instantiate objects
    PickGame2 pick = new PickGame2();
    Scanner keyboard=new Scanner(System.in);
    pick.activate();

    //Ask for and obtain user input
    System.out.print("Are you playing Pick 3, Pick 4, or Pick 5? Enter number here: ");
    int numberOfGame=keyboard.nextInt();
    PickGame2[] gamenumber=new PickGame2 [numberOfGame];

    for (int i=0; i<gamenumber.length; ++i){
        int ball=pick.pullBall();
        System.out.println("Ball " + (i+1) + " is " + ball);
    }//Ending bracket of for loop

    //Close Scanner object
    keyboard.close();

  }//Ending bracket of main method
}//Ending bracket of class LotteryGame2




I would Like to Random Match up in vb.net [duplicate]

This question is an exact duplicate of:

I'm Currently creating a program that will Match Up the cocks(Chicken). For Example I have 10 category(Category 1 (range 1001 to 1005 )Category 2 (range 1006 to 1010 )Category 3 (range 1011 to 1015 ) and so on....)

for now i already know how to categorized, the categorization will based on the weight of the cock(chicken) for example: there are 10 cocks that is under the category 1 because there weight is between 1001 to 1005. after categorize it will random match up example cock1 match cock2, cock4 match cock6 and so on. therefore there are 5 match.fights for the category1.... So my problem is how to add the match cocks to another table and assign a MAtchID Example COck1 and cock2 will save to other table and will be given a MAtchID... Hope you understand and could help me with this... Thank you in advance

   DataGridView1.Sort(DataGridView1.Columns(3), ListSortDirection.Ascending)
    For Each row As DataGridViewRow In DataGridView1.Rows
        If Not row.IsNewRow Then

            If row.Cells(3).Value <= 1005 Then
                If row.Cells(1).Value = row.Cells(1).Value Then 'to Check if there is duplicate in NAme
                    ' in here to put the MAtch up Syntax to save the random match up to another table


                Else 'to Check if there is duplicate in NAme
                    MsgBox("Duplicate Name")
                End If
            ElseIf row.Cells(3).Value <= 1010 Then
                If row.Cells(1).Value = row.Cells(1).Value Then 'to Check if there is duplicate in NAme
                    MsgBox("No Duplicate Name")


                Else 'to Check if there is duplicate in NAme
                    MsgBox("Duplicate Name")
                End If
            ElseIf row.Cells(3).Value <= 1010 Then
                If row.Cells(1).Value = row.Cells(1).Value Then 'to Check if there is duplicate in NAme
                    MsgBox("No Duplicate NAme")


                Else 'to Check if there is duplicate in NAme
                    MsgBox("Duplicate Name")
                End If
            End If

        End If
    Next




samedi 30 juillet 2016

Swift - Seeding arc4random_uniform? Or alternative?

Let me start by stating what I'm trying to accomplish:

  1. I need to randomly generate a set of numbers within a range
  2. I would like those numbers to be somewhat uniformly distributed
  3. I need to be able to seed the random number generation such that, given a seed, the resulting random numbers will always be the same.

After experimenting quite a bit with drand48(), rand() and arc4random(), I have currently settled on using rand() for obtaining a random number, and srand() for seeding. Here is a small example simplified from what I am doing:

let seed: UInt32 = 10
srand(seed)
let start = 0
let end = 100
let randomNumber = Double(rand()) % (end + 1 - start) + start

This works. Given the same seed, the same random number comes out. Performing multiple randomNumber calculations results in multiple, different random numbers coming out. Re-seeding via srand starts the "randomness" over again.

The only downside is rand() is not uniformly distributed. Indeed I pretty much always end up with a set of numbers that are linearly increasing for the most part.

It sounds like arc4random_uniform will generate more of a uniform random output, however from my research it isn't possible to seed arc4random, as it seeds itself the first time it is invoked and isn't necessarily "designed" to be seeded externally.

So my question; is there a better alternative to srand() / rand() that will still give me the same outputs for a given seed, but those outputs are more uniformly distributed?

Thanks, - Adam




I need to make groups of 4-4-3 out of this shuffledClassroom list

static void Main(string[] args) { List classroom = new List { "Armen", "Babken", "Hayk", "Edgar", "Tatev", "Anna", "Aram", "Karo", "Baghdig", "Harut", "Ruzanna" }; foreach (string student in classroom) { Console.WriteLine(student); }

        List<string> shuffledClassroom = ShuffleList(classroom);
        foreach (string student in shuffledClassroom)
        {
            Console.WriteLine(student);
        }


        Console.ReadLine();
    }

    static List<T> ShuffleList<T>(List<T> inputList)
    {
        List<T> randomList = new List<T>();

        Random rnd = new Random();
        int randomIndex = 0;
        while (inputList.Count > 0)
        {
            randomIndex = rnd.Next(0, inputList.Count); 
            randomList.Add(inputList[randomIndex]);
            inputList.RemoveAt(randomIndex);
        }
        return randomList;
    }




Java Random nextInt(int) method [duplicate]

This question already has an answer here:

While reading the documentation of nextInt(int) method in Random class, i didn't understand what is the meaning of the following paragraph :

The algorithm is slightly tricky. It rejects values that would result in an uneven distribution (due to the fact that 2^31 is not divisible by n). The probability of a value being rejected depends on n. The worst case is n=2^30+1, for which the probability of a reject is 1/2, and the expected number of iterations before the loop terminates is 2.

can anyone give me an example of a number that will be rejected by nextInt(int) method ?

Source Random class documentation.




Random Number following a certain distribution in python

I'm stuck with a problem. I have to implement an algorithm in python which needs a random number X such as Pr[X >= k] = 1/k. I don't know if already exists a distribution which can give me this exact value or if there is a way to implement this random generator using the simple random python library. Is there a way to do this? Thank you in advance for your help!




cycle never reaching final value

This is my random unique numbers generator I try to create for my cards software. It generates numbers and write into array OK. I have problem with the loop here. when integer i reaches 29, it stops growing and code cycles infinitely and never reaches 30, which would stop the loop.

Without the if statement it works, but it won't fill the range needed.

public partial class Form1 : Form
{
    int[] rndCards = new int[30];
    public Form1()
    {
        InitializeComponent();
        richTextBox1.Text = "random numbers";


    }


    private void button1_Click(object sender, EventArgs e)
    {
        int i = 0;
        rndCards = new int[30];
        richTextBox1.Clear();
        Random rnd = new Random();
        while (i < 30)
        {
            int cardTest = rnd.Next(0, 30);
            while (rndCards.Contains(cardTest)) 
            {
                    cardTest++;
                    if (cardTest == 30)
                    {
                        cardTest = 0;
                    }
            }

            rndCards[i] = cardTest;
            richTextBox1.Text += rndCards[i] + ", ";
            i++;
        }
    }




vendredi 29 juillet 2016

C random number generator generate sometimes the same numbers

i have strange behavior in which i try to generate random numbers and they sometimes totally the same , or there is problem if they created on the same time? using VC 2012

for (int i = array_size; i < (array_size); i++)
{

        srand((unsigned int)time(NULL));
        int rw = rand() % 960 + (20); //returns a pseudo-random integer between x resolution size 0 -> width
        int rh = rand() % 640 + (20);    //returns a pseudo-random integer between x resolution size 0 -> height
        lwsl_notice("c:%d width %d height %d\n",c, rw, rh);
        c++;
}

The output is :

[2016/06/30 09:39:09:7274] NOTICE: c:0 width 606 height 567
[2016/06/30 09:39:09:7274] NOTICE: c:1 width 606 height 567
[2016/06/30 09:39:09:7274] NOTICE: c:2 width 606 height 567
[2016/06/30 09:39:09:7274] NOTICE: c:3 width 606 height 567




how to generate random int value using System.Security.Cryptography

i want to generate random int values using System.Security.Cryptography from 0 to 26 how can i do that ? i know can use system.random to do this but i want to use System.Security.Cryptography




How to write a random number generator with a weight in C# (or plain math)?

I am trying to write a random number generator function in C# that would take a minimum, maximum, and weight parameters.

With weight == 0, the result would equal minimum, and with weight == 1, the result would equal maximum. With weight == 0.5, all the numbers within the range would have equal chance of being selected.

What I want to achieve is as the weight is approaching the minimum, the minimum has more chances of being selected and the maximum less, and vice versa.




How to get 7 random numbers from lists

I have the following code:

public static void main(String[] args) {
    ArrayList<Integer>  list1 = new ArrayList<Integer>();
    list1.add(10);
    list1.add(8);
    list1.add(5);
    list1.add(3);
    list1.add(9);
    list1.add(2);

    Random e = new Random();

    ArrayList<Integer>  list2 = new ArrayList<Integer>();
    list2.add(50);
    list2.add(18);
    list2.add(44);
    list2.add(4);
    list2.add(23);
    list2.add(37);
    list2.add(38);
    list2.add(26);
    list2.add(25);
    list2.add(10);
    list2.add(30);
    list2.add(49);
    list2.add(14);
    list2.add(29);
    list2.add(42);
    list2.add(5);
    list2.add(11);
    list2.add(21);
    list2.add(79);
    list2.add(15);
    list2.add(17);
    list2.add(24);
    list2.add(1);
    list2.add(13);
    list2.add(45);
    list2.add(6);
    list2.add(27);

    Random n = new Random();

    System.out.println(list1.get(n.nextInt(list1.size() - 1)));
    System.out.println(list2.get(n.nextInt(list.size() - 1)));

}

How do I get 2 random numbers (no duplicate) from list1 and 5 random numbers (no duplicate) from list2 at the same time without having to run the code 7 times to get the 7 numbers I need




Creating random numbers with time out javascript

Have a function thats emulated server request

function request(val, callback) {
  setTimeout(function() {
  callback(val * val);}, Math.randInt(1000));}

val – integer value; callback – function that will be executed after some random delay. It has one integer parameter.

I need folowing: generate number and emulate server timeout by this function

try to this

    <script>

       var a = function randomInteger(max) {
        var rand = 0 + Math.random() * (max + 1 - 0 -1);
        rand = Math.floor(rand);
        return rand;
        };

        var q = a(50);
        var g = request(q);
        function request(val, callback) {
      setTimeout(function() {
      callback(val * val);}, 3000);}
console.log(g);
        </script>

but have answer: Uncaught TypeError: callback is not a function - after 3 seconds. Need to generate number and after some timeout show it, using function at the top

and I dont understand what means Math**.randInt**(1000));




random math function generator

I am looking for a library that generates random math functions. For example, the library might include the following functions...

rand_poly would take in arguments like terms=3 and would output a random polynomial such as x^2 + 3x + 1.

rand_trig would output one of cos(x), sin(x), tan(x), etc, randomly.

For my specific needs, I much prefer Python. Also, I would like the output to be a string formatted in TeX. But these are not absolute requirements, as I could convert myself if necessary.

I was not able to find a suitable library in PyPI.




C++ Random Number Generator

I'm very new to programming and have just started learning C++ over the last day or two.

Im trying to make a small program in which the computer guesses a number the user has thought of.

I've got a loop that generates a random number between 0-100. What I'm trying to achieve is if the user inputs 'too high', the program will loop and generate a new number lower than its previously generated number. Same if the user inputs 'too low', the program will loop and generate a new number higher than its previously generated number.

I just cannot figure out what to write to get it to generate a new number higher or lower than the previously generated number.

For example, if the computer generates the number 60 and the user inputs 'high', the next random number should be between 0 and 59.

Any help would be greatly appreciated!

    srand(time(NULL));
    int rndNumber = rand() % 100 + 1;
    string userHighLow;

    cout << "Think of a random number between 0-100 and the computer will try and guess!" << endl;
    cout << "Use the keywords 'High' and 'Low' to help the computer guess." << endl;


 do {   
    cout << "My guess is: " << rndNumber << endl;

    cin >> userHighLow;

    if (userHighLow == "High" || userHighLow == "high")
    {
        //Unsure how to write new rand number lower than previous

    } else if (userHighLow == "Low" || userHighLow == "low")
    {
        //Unsure how to write new rand number higher than previous
    }
 }
    while (userHighLow != "Correct" || userHighLow == "correct");
    return 0;
}




Using unique random numbers for a switch statement

I need a function or an array that gives me random numbers from 1 - 47, so I can use it for my code below.

public function output($question_id, $solution) {
    $yes = ($GLOBALS['TSFE']->sys_language_uid == 0) ? 'Ja' : 'Oui';
    $no = ($GLOBALS['TSFE']->sys_language_uid == 0) ? 'Nein' : 'No';
    switch ($question_id) {
        case 1:
            $arg = array(
                'main_content' => $this->build_html(1, '01_0429_04_14_Psori_Arthro.jpg', $yes, $no, $solution)
            );
        break;
        case 2:
            $arg = array(
                'main_content' => $this->build_html(2, '02_0342_05_14_Psori_Arthropathie.jpg', $yes, $no, $solution),
            );
        break;
        case 3:
            $arg = array(
                'main_content' => $this->build_html(3, '03_0255_05_14_Psori_Arthropathie.jpg', $yes, $no, $solution),
            );
        break;
    }
}

Example

This

case 1:
    $arg = array(
        'main_content' => $this->build_html(1, '01_0429_04_14_Psori_Arthro.jpg', $yes, $no, $solution)
    );

should look somehow like this:

case $random_id:
    $arg = array(
        'main_content' => $this->build_html($random_id, '01_0429_04_14_Psori_Arthro.jpg', $yes, $no, $solution)
    );

So that means, each case and each first parameter of the function build_html should get a unique random id.

Of course I could use rand() but then it is quite possible that I get duplicated values.

Any help would be appreciated!




jeudi 28 juillet 2016

How to generate random graph of n vertices with random connections in matlab

Hi I am interested in creating random undirected graph with n vertices and with random connections. This generated graph has to display its adjacency connections in a nxn matrix.I have tried this code but it is not working for my requirement.

   n=input('No. of vertices')
   c=input('Random connections')
   MM=0;   %arbitrary starting value
    all_nums=1:n;

    while MM ~=n*c

        M = sparse([],[],[],n,n,n*c);
        ctin = zeros(1,n);

        for ii=1:n
            noconnect=ctin>=c;
            noconnect(ii)=true;

            rem_nums = all_nums(~noconnect); % remaining numbers
            rp=randperm(n-sum(noconnect));
            rp = rem_nums(rp); % remaining numbers, hussled

            if numel(rp)<c
                break
            else
                r=rp(1:c);
            end
            M(ii,r)=1;
            ctin(r)=ctin(r)+1;
        end
        MM=sum(ctin);
    end
end
   A= adjacency(M)




Randomised image from array is displaying the wrong image in image tag

functionality:

I have set 2 image tags in my html body to be displaying 2 randomised images from an array. Secondly, I have ensured that the 2 displayed randomised images will not repeat itself via the code line BrandNameArray.splice(random_BrandIndex,1);.

Issue:

I have done a console log for the 2 image items that will be displayed within the image tag of my html body. However, when the 2 images are displayed, the 2nd image will sometimes display the wrong image.

Meaning:

I have an array_Image = [A, B, C, D, E] and within my console log, it is stated that the randomised image returns 2 images of [0,3], hence rightfully, it should be showing image [A , D] in my image tag of my html body. However, the images that are displayed are [A, C].

Could i please get some help on this. Thanks

I have attached the following code for your perusal.

var Brand_list = [];
var BrandNameArray = ["lib/img/Offer/Anson.png", "lib/img/Offer/CF.png", "lib/img/Offer/Chick.png", "lib/img/Offer/Fish.png", "lib/img/Offer/Food.png"];


//Auto populate into brand container once randomised
$('#BrandWinlist > img').each(function(i, img) {
  random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
  console.log("random_BrandIndex:" + random_BrandIndex);

  //Assign Variable to generate random Brands
  var Brand = BrandNameArray[random_BrandIndex];

  //To prevent the images from displaying twice
  BrandNameArray.splice(random_BrandIndex, 1);

  Brand_list.push(random_BrandIndex);
  $(img).attr('src', Brand).show();
});
<div id="MainBackground" align="center" style="position:absolute; width:1080px; height:1920px; background-repeat: no-repeat; z-index=8; top:0px; left:0px; margin:auto;">


  <!--Div to show my 2 randomised images-->
  <div class="GameWinBrand_Container">
    <div id="BrandWinlist" class="GameWinBrand_innerScroll">
      <img id="GameBrand_1" style="width:230px; height:230px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
      <img id="GameBrand_2" style="width:230px; height:230px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
    </div>
  </div>


</div>



How to Prevent Triplicates in Pandas DataFrame

I have the following code:

stim_df = pd.concat([block1,block2,bloc3,block4], axis=0, ignore_index=True).sample(frac=1).reset_index(drop=True)
stim_df.columns = ["Prime","Target","Condition"] 

#Check for triplicates: 
for j in xrange(len(stim_df)):
    if j == 0 or j == 1:
        pass
    else:
        if stim_df["Condition"][j] == stim_df["Condition"][j-1] == stim_df["Condition"][j-2]:
            stim_df[j-2:j+3] = stim_df[j-2:j+3].reindex([j-2,j-1,j+2,j,j+1])

What I'm trying to prevent from happening is three adjacent rows with the same "Conditions" value appearing together. So if my conditions are "1","2",and "3", I want to prevent an order like 1,1,2,2,2,1,3,1 from occurring, where the condition value 2 appears three times in a row.

My code doesn't solve the issue. Would it be better to create a pseudo-randomization function, rather than trying to deal with this after I've already randomly mixed the dataframe? Any assistance or suggestions would really help.




How to randomly pick a vertices from graph?

I am looking for solution to pick a number randomly from graph using c++.
For example I have a graph that add edge (one or more) between two vertices, how can I pick a number randomly?
some of code :

#include <iostream>
#include <list>
#include <queue>

using namespace std;
// Graph class represents a undirected graph using adjacency list representation
class Graph
{
private:
    int V; // # of vertices
    list<int> *adj;  // Pointer to an array containing adjacency lists
public:
    Graph(int V)  // Constructor
    {
        this->V = V;
        adj = new list<int>[V];
    }
    void addEdge(int v, int w); // function to add an edge to graph
    void print(int v, int w); //function to display 
    };

void Graph::addEdge(int v, int w)
{
    adj[v].push_front(w); // Add w to v’s list.
    adj[w].push_front(v); // Add v to w’s list.
    print(v, w);

}

void Graph::print(int v, int w) {
cout << v << " - " << w << endl;}


In the main:

Graph g(4);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);


Sample output:

0 - 1
0 - 2
1 - 3




radomize ul tag not working

this is probably an easy question for you guys but I'm very new to coding and can't figure out this. I have a code that I want to randomize the given choices in the questions, and I've found a script online that does that but it's not working. I don't know what the "// shuffle only elements that don't have "group" class $ul.find("li[class!='single_question', 'question', 'title', 'text']").each(function() { " means so I tried to put all id that I don't need to randomize in it but it's still not working. Can someone help me this please? Also is there anyway I can add choice "A", choice "B", choice "C", and choice "D" in front of each given options so even after the options(answers) are randomized, the A,B,C,D options will still be in order? Thank you. Here's the code:

HTML:

<div id="quiz_container">

        <ul class="quiz_container">

            <li class="single_question" data-question-id="1" data-correct-answer="1">
                <div class="question">
                    <h1 class="title">
                         P.1 Grammar Review
                    </h1>
                    <p class="text">
                        1. "What is your name__"
                    </p>
                </div>
                <ul class="options">
                    <li value="1">?</li>
                    <li value="2">.</li>
                    <li value="3">,</li>
                </ul>
                <div class="result"></div>
            </li>


<li class="single_question" data-question-id="2" data-correct-answer="b">
 <div class="question">
  <p class="text">
   2. "Do you like the banana__"
  </p>
 </div>
 <ul class="options">
  <li value="a">.</li>
  <li value="b">?</li>
  <li value="c">,</li>
 </ul>
 <div class="result"></div>
</li>
    </div>
    </body>
</html>

JS:

 $(document).ready(function(){

/*
 * shuffles the array
 * @param {Array} myArray array to shuffle
 */
function shuffleArray(myArray) {
    for (var i = myArray.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = myArray[i];
        myArray[i] = myArray[j];
        myArray[j] = temp;
    }
    return myArray;
}

var $ul, $li, li_content, li_list;
// find all lists to shuffle
$("#quiz_container > ul").each(function() {
    $ul = $(this);
    li_list = [];
    // shuffle only elements that don't have "group" class
    $ul.find("li[class!='single_question', 'question', 'title', 'text']").each(function() {
       // add content to the array and remove item from the DOM
       li_list.push($(this).html());
       $(this).remove();
    });

    // shuffle the list
    li_list = shuffleArray(li_list);
    while(li_content = li_list.pop()) {
        // create <li> element and put it back to the DOM
        $li = $("<li />").html(li_content);
        $ul.append($li);
    }        
});

$("#contact_div").show();
  });


 $(document).on('click', '.single_question .options li', function(){

      // Save the question of the clicked option 
      question = $(this).parents('.single_question');

      // Remove If Anyother option is already selected
      question.find('.selected').removeClass('selected');

      // Add selected class to the clicked li
      $(this).addClass('selected');

      // selected option value
selected_answer_value = $(this).attr("value");

// Value of correct answer from '.single-question' attribute
      correct_answer_value = question.attr("data-correct-answer");
      correct_answer_text = question.find('.options').find("li[value='"+correct_answer_value+"']").text();

      if(correct_answer_value == selected_answer_value)
       result = "<div class='correct'> Correct ! </div>";
      else
       result = "<div class='wrong'> Correct answer is -> "+correct_answer_text+"</div>";

      // Write the result of the question
      $(this).parents('.single_question').find('.result').html(result);

      // Calculate the score
      score_calculator();

     });


     /**
      * It loops through every question and increments the value when "data-correct-answer" value and "option's value" are same
      */
     function score_calculator() {
      score = 0;
      $('.single_question').each(function(){
       question = $(this);
       if(question.attr('data-correct-answer') == question.find('.selected').attr("value")) {
        score++;
       }
      });
      $('.correct_answers').html(score);
     }




Unable to get random number to be generated every time object is created

I am creating an object with the same parameters multiple times over and over again. The object has a random method (using Math.random()) in it which I know should return a different number every time, but each time within the program I create a new object of that class and call the method on it, it returns the same value. How should I fix this?

place where I call the method contract:

for (int i = 0; i < 212000; i++){
            Contractions c = new Contractions(a, b);
            temp = c.contract();
            if (temp < min){
                min = temp;
            }
            if (i%1000 == 0){
                System.out.println(min);
            }
        }

method:

while (vertices.size() > 2){
        Edge randEdge = edges.get((int) (Math.random()*edges.size())); .....


return edges.size();




How do I generate random numbers from an array without repetition?

I know similar question have been asked before but bear with me.

I have an array:

int [] arr = {1,2,3,4,5,6,7,8,9};

I want numbers to be generated randomly 10 times. Something like this: 4,6,8,2,4,9,3,8,7 (Although some numbers are repeated, no number is generated more than once in a row).

But not like this: 7,3,1,8,8,2,4,9,5,6 (As you can see, the number 8 was repeated immediately after it was generated. This is not the desired effect).

So basically, I'm ok with a number being repeated as long as it doesn't appear more than once in a row.




How to generate random numbers using C# that hasn't been listed in a database?

I'm working on an application that allows me to generate random ID numbers (6 integers) for employees but I would like to know how to generate these random numbers using C# and not duplicate the numbers that has been already used by another employee in the SQL database. Below is the code done in SQL:

declare @unique_UID varchar(6)

select @unique_UID = Right(ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)), 6)

while exists (select 1 from dbo.tblUserID 

   where @unique_UID = UserID_UID 
         and len(@unique_uid) = 6
         and @unique_UID <> @parm_User_Pin)(
         select @unique_UID = Right(ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)), 6)

`




mercredi 27 juillet 2016

Pick a random element from list/array of strings in netLogo

I am new programmer in netlogo. I waned to know how can I pick a random string from a list/array of strings in netLogo? If anyone can please guide me, I will be very much thankful. Thanks

PS : I have done efforts on my part, I only know how to pick a random number from a number range like this

random-float (PRICE * 0.20) ;For float value (price is an integer defined by me)
random round (DifferenceAmt * 0.10) ; For random rounded amount




java - lotto read from text file

My console is supposed to read sets of numbers from a text file. The numbers in the file must be compared to 7 'lucky numbers'. The program must find out how many people had 3 matches, 4 matches, 5 matches, 6 matches and 7 matches with the 'lucky numbers', and the results must be printed at the end.

I dont know how to do the comparing between the numbers in the file and generating the 'lucky numbers'.

import java.io.*;
import java.util.*;
import java.util.Scanner.*;

public class Lotto {
    public static void main (String[] args) throws FileNotFoundException {

        Scanner lottoFile = new Scanner(new File("c:\\Exercises\\New Folder\\Lotto.txt"));
        ArrayList<Double> lotto = new ArrayList<Double>();

        while(lottoFile.hasNextLine()){
            String line = lottoFile.nextLine();

            Scanner scanner = new Scanner(line);
            scanner.useDelimiter(",");
            while(scanner.hasNextDouble()){
                lotto.add(scanner.nextDouble());
            }
            scanner.close();
        }

        lottoFile.close();

        System.out.println(lotto);
    }
}




Pick a random letter from string in JavaScript

I'm trying to pick a random letter from a string in JavaScript using Math.floor(Math.random()* string.length) and a while loop. It needs to continually add new random letters to this string until a specified length.

My code is:

var emptyString = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var getRandomLetter = alphabet[Math.floor(Math.random() * alphabet.length)];
var randomLetter = getRandomLetter;

while (emptyString.length < 6) {
emptyString += randomLetter;
emptyString ++;
} 
console.log(emptyString);

Problems: The output is the same letter 6 times: ex. pppppp

The random letter is generated from the string only once and then repeated until the specified length. I need it to generate random output for each letter: ex. pwezjm

I also noticed that if I do a second different while loop over the string it will generate the same output as the first loop: ex. pppppp

I thought it would at least generate a different random letter then the first loop but it does not. Why is that?

Thanks!




Processing one char at a time within a string in a foreach loop

I have a string that storages a sequence of numbers. Then I split in chars using foreach, send the info to highlightButton()and using a dictionary he does some actions. The problem is that it is processing all the chars at once but I'd like it to process it one char at a time: He's changing all backgrounds at once; i'd like it to be one at a time, in order. Perhaps using a timer? Code below

  Random rng = new Random();
  sequence = sequence + rng.Next(1, 5);

  foreach (char c in sequence)
        {
            highlightButton(charToButton[c]);
        }

private void highlightButton(Button button)
    {
        Dictionary<Button, PictureBox> buttonToPB = new Dictionary<Button, PictureBox>();
        //4 buttons
        buttonToPB.Add(bRED, pbRED);
        buttonToPB.Add(bYELLOW, pbYELLOW);
        buttonToPB.Add(bGREEN, pbGREEN);
        buttonToPB.Add(bBLUE, pbBLUE);

        buttonToPB[button].BackColor = Color.Black;
    }




BankAccount customer python [duplicate]

This question already has an answer here:

So today I have an assignment that requires me to construct a bank account class. I have everything in order for my output to match the expected output.

My Output:

Alin,Smith (SSN:111-11-1111) account number: 5040470401, balance: $20000
Alin,Smith (SSN:111-11-1111) account number: 5040470401, balance: $15000
Alin,Smith (SSN:111-11-1111) account number: 5040470401, balance: $15100.0
Mary,Lee (SSN:222-22-2222) account number: 5040470401, balance: $10000
Mary,Lee (SSN:222-22-2222) Insufficient Funds to withdraw: $15000
Mary,Lee (SSN:222-22-2222) account number: 5040470401, balance: $10000
Mary,Lee (SSN:222-22-2222) account number: 5040470401, balance: $10500.0

However as you can see, even though Mary and Alin are different customers, they generate the same account number.

My question today is how can I give a different random 10-digit account number for each customer object created in my Bank Account class.

right now I have my Customer class

class Customer:
def __init__(self,firstName, lastName, social):
    self.firstName = firstName 
    self.lastName = lastName 
    self.social = social 

def setfirstName(self,firstName):
    self.firstName = firstName

def setlastName(self,lastName):
    self.lastName = lastName

def __str__(self):
    self.name = "{},{} (SSN:{})".format(self.firstName, self.lastName,self.social)
    return self.name 

and then my BankAccount class (only including random number parts):

class BankAccount(Customer):
from random import randint
n = 10
range_start = 10**(n-1)
range_end = (10**n)-1
accountNumber = randint(range_start, range_end)

def __init__(self,customer,balance = 0):
    self.customer = customer
    self.balance = balance 

def setCustomer(self,customer,accountNumber):
    self.customer = customer
    self.accountNumber = accountNumber 

def getCustomer(self,customer,accountNumber):
    return self.customer, self.accountNumber

 def __str__(self):
    customer = "{} account number: {}, balance: ${}".format(self.customer,self.accountNumber,self.balance)
    return customer 

I figured that for every account object I made, a new random number would be generated but that does not seem to be the case.

Any ideas?




Random numbers, iterations until none repeats

Doing things with the random generator I've found that with seed (0), and using Random.Next(0,3) every 8 times the function is called all the numbers { 0, 1, 2, 3 } will appear. Is this coincidence? Or is it a thing that's supposed to happen?




Assign a value to Integer between two constant values?

Lets say I have 3 Integers:

int a, b, c;
b = 25;
c = 10;

Now I want a to be either 25 or 10 but by random not something like:

a = b;

I want something like in if statement:

a = b || c;

How can I achieve it?




mardi 26 juillet 2016

ECC Random Points Generation FPGA

I want to give a large number of ECC points to my FPGA for testing purpose. I want to save the file containing ECC points as well. Is there any way , I can generate ECC random points for specific Elliptic curve? May be directly in FPGA or I can generate it using any other tool and then use them there. Any recommendations??




Compare a New Array Entry to all its Ancestors

I'm attempting to create an array composed of unique random integers. The method I've constructed, shown below, will almost work. The problem is in the while loop, that compares the new random entry to its immediate ancestor. This condition ensures that there will not be a pair of matching values, side-by-side, in the array. Unfortunately this condition does not compare the new random value to every random value generated thus far. How can I accomplish this?

private static Random rand = new Random();

//'dynamicLength' is dependent on another object. With the way I've set up the 
//method, the size shouldn't matter.
private static int[] randArr = new int[dynamicLength];

public static int[] randGenArr(int upBound, int lowBound)
{
    int newRand;

    for (int i1 = 0; i1 < randArr.length; i1++)
    {
       //new random value
       newRand = rand.nextInt(upBound - lowBound + 1) + lowBound;

       //walk through the randArr up to the point we initialized
       //last iteration
       for (int i2 = 0; i2 <= i1; i2++)
       {
           //compare the new value to its IMMEDIATE ancestor
           while (newRand == randArr[i2])
           {
               newRand = rand.nextInt(upBound - lowBound + 1) + lowBound;
           }
       } 
       //after validation, initialize randArr          
       randArr[i1] = newRand;
   }

   return randArr;
}

I'm only focused on the body of this code. I've included the method header and the field declarations for clarity.




Replacing magic ID numbers with random IDs generated at compile-time

My app contains numerous IDs. I want to eventually make the code viewable by others, but not make it easy for runtime reverse engineers to look for easily known IDs. Also, during development it is helpful to have constant IDs in the log files for easier debugging. But at runtime I would like to make these IDs random by generating them during the Release compile. Suggested code using the <random> lib can be seen in GetRandomId1() below. constexpr makes their use in the code possible like in switch statements. However, I am having trouble using constexpr in my proposed function because <random> is not constexpr compatible. Is there another way to generate random numbers at compile time? Or is generating random numbers at compile time to be used as constants at runtime considered against the concept of constexpr?

#include <iostream>
#include <random>

// this is the code I would like to use to generate a random number at compile time
/*constexpr */int GetRandomId1()
{
  std::random_device rd; // non-deterministic seed
  std::mt19937 gen( rd() ); // with constexpr uncommented: 
    // error C3250: 'rd': declaration is not allowed in 'constexpr' function body
    // error C3249: illegal statement or sub-expression for 'constexpr' function
    // error C3250: 'gen': declaration is not allowed in 'constexpr' function body

  std::uniform_int_distribution<> distri( 1000, 9999 ); // with constexpr uncommented: 
    // error C3250: 'distri': declaration is not allowed in 'constexpr' function bod
    // error C3249: illegal statement or sub-expression for 'constexpr' function
    // error C2134: 'std::uniform_int<_Ty>::operator ()': call does not result in a constant expression

  return distri( gen );
}

// this code is what works so far
constexpr int GetRandomId2()
{
  return 22; // how to make somewhat random?
}

constexpr int AAA = 10;
//constexpr int AAA = GetRandonId1(); // error: is not constexpr function
constexpr int BBB = GetRandomId2(); // ok

void Func1( long ab )
{
  switch( ab )
  {
    case AAA:
      std::cout << AAA << std::endl;
      break;

    case BBB:
      std::cout << BBB << std::endl;
      break;
  }
}

int main()
{
  Func1( 22 ); // ok: prints 22

  return 0;
}

I am looking for a straight forward, maintainable solution like the one I proposed and unlike the heavy use of templates as proposed in How can I generate dense unique type IDs at compile time?. Also in this posting @jmihalicza points to the Random number generator for C++ template metaprograms research paper. This paper describes compile-time random number generation using template metaprogramming which is a complicated attempt that accomplishes a task for which IMO constexpr was (dare I say, or should have been?) designed.

Because of app architectural reasons I don’t have to worry about ID collisions so that is not a concern. The app code would make sure there would be no duplicates returned.




F# using System.Random() to get random number lists give the same lists

I have been searching other questions, where users would instantiate many System.Random()'s within a loop or method and therefore create many of the same randoms from the same clock. But here I have one instantiated System.Random() but when i try to use it to create multiple random number lists, they are all the same.

module Scripts =
let rnd = System.Random() 

let getRandom36 =
    let rec generate (l : list<int>) =
        match l.Length with
        |8 -> l
        |_ -> let number = rnd.Next 38
              if(List.exists(fun elem -> elem=number) l) then generate l else generate (number::l)
    List.sort(generate List.empty)

let myseq = Seq.init 4 (fun _ -> getRandom36)

The important part is not really how the code inside getRandom36 works, I have been tampering with it to work in different ways, but I keep getting lists that look the same when calling myseq;;.

myseq;;
val it : seq<int list> =
  seq
    [[2; 8; 10; 11; 18; 21; 22; 35]; [2; 8; 10; 11; 18; 21; 22; 35];
     [2; 8; 10; 11; 18; 21; 22; 35]; [2; 8; 10; 11; 18; 21; 22; 35]; ...]

Any ideas why? I mean shouldnt the rnd.Next be different each time since no new instance of rnd is made for each iteration.




Get random data from sql but no repeated values

I need to get 10 random rows from table at each time, but rows never repeat when repeat the query

But if i get all rows it will repeat again from one, like table have 20 rows, at first time i get 10 random rows and 2nd time i will need to get remaining 10 rows at my 3rd query i need to get 10 rows randomly.

Currently my query for getting 10 rows randomly

select top 10 * FROM tablename
ORDER BY NEWID()   




How to pick two random numbers with no carry when adding

I'm trying to make this algorithm which inputs a lower and upper limit for two numbers (the two numbers may have different lower and upper limits) and outputs two random numbers within that range

The catch is however that when the two numbers are added, no "carry" should be there. This means the sum of the digits in each place should be no more than 9.

How can I make sure that the numbers are truly random and that no carrying occurs when adding the two numbers

Thanks a lot!




C# - How to select distinct random records from datatable

I am trying to fetch records from DataTable randomly with some limit. I am able to fetch the data randomly as follows -

 var r = new Random();
 var _randomSelection = dt.Rows.OfType<DataRow>().OrderBy(rand => r.Next()).Take(limit);

But the values seems to be redundant. I want to get the unique values. So far I have tried Distinct() as -

var _randomSelection = dt.Rows.OfType<DataRow>().OrderBy(rand => r.Next()).Take(limit).Distinct();

But that doesn't seems to be worked out. Can anybody please guide where am going wrong with this. Thanks.




Unable to append second image from array B to html img tag

I have 2 arrays of elements:

Array A = ["lib/img/band/A.png", "lib/img/band/B.png", "lib/img/band/C.png"]; 

and

ArrayB = ["lib/img/secondary/A1.png", "lib/img/secondary/B1.png", "lib/img/secondary/C1.png"];

I have managed to randomised Array A and append all randomised image to 2 img tag. Hence, on document.getready(), the img container will be showing 2 randomised elements.

When user clicks on one of the generated randomised image shown from Array A, in the image tag. The corresponding image from Array B will be displayed in a pop-u, meaning when image A= lib/img/band/A.png is clicked/selected, the second image from image B= lib/img/secondary/A1.png will be shown.

Issue: However, at this point in the html body, there are 2 randomly generated images and when i clicked on the second image from array A, it does show the correct secondary image from array B, meaning: the page is showing 2 randomly generated image: 1.)"lib/img/band/B.png" 2.) "lib/img/band/A.png". There when I clicked on 2.) "lib/img/band/A.png", it is showing b.) "lib/img/secondary/A1.png". However, when I clicked on 1.)"lib/img/band/B.png", it is still showing a.) "lib/img/secondary/A1.png" when it should be showing a.) "lib/img/secondary/B1.png"

I have console log and it is showing the secondary image from arrayB when I clicked on the second image but the console.log is showing the wrong secdonary image from array B when i click on the first image. vice versa.

Therefore, I would need to ask what is missing. I really have no idea how to continue. please help. thanks.

var BrandNameArray = ["lib/img/Brands/A.png", "lib/img/Brands/B.png", "lib/img/Brands/C.png", "lib/img/Brands/D.png"];

var OfferArray = ["lib/img/Offer/A1.png", "lib/img/Offer/B1.png", "lib/img/Offer/C1.png", "lib/img/Offer/D1.png"];

var random_BrandIndex, selectedOffer;

function ShowInitialBrand() {
  $('#BrandWinlist > img').each(function(i, img) {
    random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
    //Assign Variable to generate random Brands
    var Brand = BrandNameArray.splice(random_BrandIndex, 1)[0];
    $(img).attr('src', Brand).show();
  });
}

function selectBrand(flag) {
  selectedOffer = OfferArray[random_BrandIndex];

  console.log("selectedOffer: " + selectedOffer);

  $("#P_Description").attr('src', selectedOffer).show();
}
.GameWinBrand_Container {
  position: absolute;
  top: 950px;
  left: 286px;
  height: 250px;
  width: 500px;
  overflow: hidden;
}
.GameWinBrand_innerScroll {
  position: relative;
  width: 480px;
  font-size: 30px;
  text-align: justify;
  color: #ffffff !important;
  overflow: hidden;
}
.GameWinBrand_Container::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 12px;
  background-color: #ffffff;
}
.GameWinBrand_Container::-webkit-scrollbar {
  width: 12px;
  background-color: #5e5767;
}
.GameWinBrand_Container::-webkit-scrollbar-thumb {
  border-radius: 20px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #5e5767;
}
.BrandMenu {
  background-color: #FFFFFF;
  filter: alpha(opacity=80);
  opacity: 0.8;
}
<!--Randomly generated images where it allows user to click for the second image to pop-up as P_Description-->
<div class="GameWinBrand_Container">
  <div id="BrandWinlist" class="GameWinBrand_innerScroll">
    <img id="GameBrand_1" style="width:230px; height:230px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
    <img id="GameBrand_2" style="width:230px; height:230px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
  </div>
</div>


<!--Second image will pop-up that corresponds with the random image clicked above-->
<div id="P_BrandDescription" class="BrandMenu" align="center" style="position:absolute; width:1080px; height:1920px; background-repeat: no-repeat; display: none; z-index=9; top:0px; margin:auto;">

  <img id="P_Description" class="BrandDescription" style="position:absolute; width: 1080px; height:762px; top:500px; left:0px; z-index=99;">
</div>



lundi 25 juillet 2016

jQuery animate background color. Remove Math.random

I want to animate between an array of background colors.

I found the following code, but it uses Math.random to display the background colors in random order.

$(document).ready(function() {  
    setInterval(function() {
        var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
        var theColour = theColours[Math.floor(Math.random()*theColours.length)];
        $('#branding').animate({backgroundColor: theColour}, 500);
    }, 1000);
}); 

JSFiddle

I want to remove the Math.random and display the next color in the array.

However, if I replace Math.random, with the following, the animation doesn't proceed beyond the first color in the array.

$(document).ready(function() {  
    setInterval(function() {
        var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
        var currentColour = 0;
        var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
        $('#branding').animate({backgroundColor: theColour}, 500);
    }, 1000);
}); 




Not able to append element

I have set 2 image container that shows 2 randomly generated image from an array of elements. When user clicks on either of the 2 randomly generated images, an image pop-up will appear. This generated image pop-up; from a second array of image, is in relation to what random generated image that has been displayed.

Therefore, this is the right behaviour: - random generated image A and image B is shown in the page 1, when user click on image A, image pop-up A1 will be shown else image B1 will be shown when image B is clicked.

Issue:

I have managed to achieve the following:

1.) randomly generate 2 images from array A and append it to the initial 2 image container

2.) link array B to items generated in array A

I have set out a console log and was able to see that the element from the 2nd array element is correctly called when i select the randomly generated image from array A

However, at this point in time, I am unable to append the item from array B to the image pop-up in my html body..

Please help

Here is the code:

var BrandNameArray = ["lib/img/Brands/A.png", "lib/img/Brands/B.png", "lib/img/Brands/C.png", "lib/img/Brands/D.png"];

var OfferArray = ["lib/img/Offer/A.png", "lib/img/Offer/B.png", "lib/img/Offer/C.png", "lib/img/Offer/D.png"];

function ShowInitialBrand() {
  $('#BrandWinlist > img').each(function(i, img) {
    random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
    //Assign Variable to generate random Brands
    var Brand = BrandNameArray.splice(random_BrandIndex, 1)[0];
    $(img).attr('src', Brand).show();
  });
}

function selectBrand(flag) {
  selectedOffer = OfferArray[random_BrandIndex];

  console.log("selectedOffer: " + selectedOffer);

  $("#P_Description").html(selectedOffer);
}
.GameWinBrand_Container {
  position: absolute;
  top: 950px;
  left: 286px;
  height: 250px;
  width: 500px;
  overflow: hidden;
}
.GameWinBrand_innerScroll {
  position: relative;
  width: 480px;
  font-size: 30px;
  text-align: justify;
  color: #ffffff !important;
  overflow: hidden;
}
.GameWinBrand_Container::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 12px;
  background-color: #ffffff;
}
.GameWinBrand_Container::-webkit-scrollbar {
  width: 12px;
  background-color: #5e5767;
}
.GameWinBrand_Container::-webkit-scrollbar-thumb {
  border-radius: 20px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #5e5767;
}
.BrandMenu {
  background-color: #FFFFFF;
  filter: alpha(opacity=80);
  opacity: 0.8;
}
<!-- The first page where 2 randomly generated images are shown-->
<div class="GameWinBrand_Container">
  <div id="BrandWinlist" class="GameWinBrand_innerScroll">
    <img id="GameBrand_1" style="width:230px; height:230px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
    <img id="GameBrand_2" style="width:230px; height:230px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
  </div>
</div>

<!-- The second page that will show the image in relation to the image that has been clicked-->

<div id="BrandDescription" class="BrandMenu" align="center" style="position:absolute; width:1080px; height:1920px; background-repeat: no-repeat; display: none; z-index=9; top:0px; margin:auto;">
  <img id="P_Description" style="position:absolute; width: 1080px; height:762px; top:500px; left:0px; z-index=99;">

</div>



Randomly colored circle

I am working on a little project which assigns a random color to this circle from all the possible colors.

I am trying to achieve this by assigning a random number to each RGB value. However, It doesn't seem to work this way. I also tried to setAttribute() way to assign it that way but also no luck. Please have a look:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Beginning JavaScript</title>
        <style>




        #circle{
            margin:auto;
            border:1px solid black;
            border-radius: 50%;
            background-color:rgb(0,0,0);
            height:200px;
            width:200px;
        }


        </style>
    </head>
    <body>
<div id="circle"></div>
<script>

var circle = document.getElementById('circle');
var value1 = Math.floor(Math.random() * 256);
var value2 = Math.floor(Math.random() * 256);
var value3 = Math.floor(Math.random() * 256);
circle.style.backgroundColor = "rgb(value1,value2,value3)"




Random list of numbers

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main()
{
   int i;
   int diceRoll;

   for(i=0; i < 20; i++)
   {
       printf("%d \n", rand());
   }

    return 0;
}

This is the code I wrote in c++ (codeblocks) to get random numbers, the problem is I always get the same sequence: 41,18467,6334,26500 etc...

I'm still learning so please try to explain like you're talking with a 8 year old D:




Order of pseudo-random numbers to form samples from multivariate distribution

I am interested in creating n samples from a d-dimensional distribution (independent uniform is fine) using a pseudo-random number generator. There are two possible strategies:

Dimension-by-dimension: Use the first n random numbers as the n samples from the first dimension, the second n random numbers as the n samples from the second dimension, etc.

Sample-by-sample: Use the first d random numbers as the first multi-dimensional sample, the next d random numbers as the second multi-dimensional sample, etc.

I understand that in principle these are identical, but seeing as pseudo-random number generators are not perfect, is one preferable to the other in very high-dimensional spaces?

For concreteness, I'm using the most common form of the Mersenne Twister. The fact that the MT is 623-distributed to 32-bit accuracy suggests to me that the sample-by-sample method may be preferable, but that is largely a guess.




Randomised Array is not appended to id tag

I have set a method to randomised an array of images. These randomised images will then be appended to the id tag within the html body. I have set 2 image id and have tried to append the randomised image array to the image id.

However, no images are being displayed.

Hence, what has been done wrong? please help.

Code:

var BrandNameArray = ["lib/img/Brands/A.png", "lib/img/Brands/C.png", "lib/img/Brands/B.png"];

function Game_Congrats() {



  //Randomised Brand Offer
  //Auto populate into brand container once randomised
  for (i = 0; i < $('#list').find('img').length; i++) {

    random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);

    //Assign Variable to generate random Brands
    var Brand = BrandNameArray[random_BrandIndex];
    BrandNameArray.splice(random_BrandIndex, 1);
    $('#Brand_' + (i + 1)).attr('src', Brand);
    $('#Brand_' + (i + 1)).show();
  }
}

}
.GameWinBrand_Container {
  position: absolute;
  top: 950px;
  left: 286px;
  height: 250px;
  width: 580px;
  overflow: hidden;
}
.GameWinBrand_innerScroll {
  position: relative;
  width: 550px;
  font-size: 30px;
  text-align: justify;
  color: #ffffff !important;
  overflow: hidden;
}
.GameWinBrand_Container::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 12px;
  background-color: #ffffff;
}
.GameWinBrand_Container::-webkit-scrollbar {
  width: 12px;
  background-color: #5e5767;
}
.GameWinBrand_Container::-webkit-scrollbar-thumb {
  border-radius: 20px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #5e5767;
}
<div class="GameWinBrand_Container">
  <div id="BrandWinlist" class="GameWinBrand_innerScroll">
    <img id="GameBrand_1" style="width:250px; height:230px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
    <img id="GameBrand_2" style="width:250px; height:230px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
  </div>
</div>



Anyone who knows how to create a memory game using code.org?

Please help me I am currently making a memory game using code.org for a school project but i can't seem to find out how to creare a code on how to match the tiles thank you!




Show only one word out of a random list of lines? [on hold]

def random(self): # Generator-knapptryck
    import tkinter
    with open('dishes.txt') as f:
        resultat = random.sample([i.strip() for i in f], 7)
    tkinter.messagebox.showinfo("Meny", "Veckomeny:\n %s" % resultat)
    f.close()

This is my code for a random seven meals. I have created lines of meals in a txt with groceries that is needed. Ex: "Lasagne, Minced meat, Tomatosaus,... etc"

I would like the result to only include the first word in each line. (First word is the name of the meal). I tried the split function but got some errors, Im quite new to this..




Generating single-cycle sinusoidal distributed numbers

I am not good at Math so, I want to generate single-cycle sinusoidal distributed numbers:

You can see an example of the plot I want to get after generating the values: Lag Plot for single-Cycle sinusoidal

The dataset for this plot is included here: http://ift.tt/2a87tcG

The programming language I prefer is Python, but any other language would do for generating such distributed values.

Objective: creating a function to generate such distributions for analytical purposes and predictions.




Simulating a logarithmic spiral galaxy in python

I am simulating a logarithmic spiral galaxy using python. Using the parametric equations,

x= a*exp(b*theta)*cos(theta) and y= a*exp(b*theta)*sin(theta)

I used numpy.random for getting the random distribution of stars. The sample code is given below.

import random
from math import *
from pylab import *
import numpy as np

n=100000
a= 1
b=0.6
th =np.random.randn(n)
x= a*exp(b*th)*cos(th)
y=a*exp(b*th)*sin(th)
x1 = a*exp(b*(th))*cos(th+ pi)
y1=a*exp(b*(th))*sin(th + pi)
plot(x,y,"*")
plot(x1, y1,"*")
show()

The resulting image is shown below spiral galaxy with two arms

What I need: 1) stars should be radially distributed in the spiral galaxy. I got the distribution only along the arms. 2) Both arms should be blue. Here I have one arm with blue color and other with green.

After simulating this, I need to rotate the galaxy. Any help regarding this would be appreciable.




mingw32-make.exe: *** No rule to make target '/usr/share/perl5/core_perl/ExtUtil s/typemap', needed by 'Random.c'. in Perl for windows 7

I used strawberry perl in windows 7. I need to install Math::Random.

using command:

1. perl Makefile.PL phrtsd_orig
2. "C:/MinGW/bin/mingw32-make.exe"
3. "C:/MinGW/bin/mingw32-make.exe" test
4. "C:/MinGW/bin/mingw32-make.exe" install

But the 2nd command give error:

Skip blib/lib/Math/test1.pl (unchanged) Skip blib/lib/Math/example.pl (unchanged) Skip blib/lib/Math/test2.pl (unchanged) Skip blib/lib/Math/Random.pm (unchanged) Running Mkbootstrap for Math::Random ()

chmod 644 "Random.bs" mingw32-make.exe: *** No rule to make target '/usr/share/perl5/core_perl/ExtUtil s/typemap', needed by 'Random.c'. Stop.

how to solve this problem?




Code feedback for python guessing game

I am new to Python (and coding in general) and after about a week of reading "Thinking Like a Computer Scientist: Learning with Python" I decided to try and build a version the classic "guessing game". I added some extra features such as counting the number of guesses the user takes, and playing against a simulated "computer" player to make the program slightly more interesting. Also, the number of guesses the computer takes is based on the mean number of guesses needed to guess a number in a given range (which is logarithmic of base 2 for range n) and varies according to standard deviation. Any feedback on the structure of my code or the way I generate the number of guesses the computer takes would be much appreciated!!!

Anywayyysss.... here is my code

import random


def get_number(level):                  #selects a random number in range depending on difficulty selected
    if level == "e":
        number = random.randint(1,20)
    if level == "m":
        number = random.randint(1,100)
    if level == "h":
        number = random.randint(1,1000)
    elif level != "e" and level != "m" and level != "h":
        print ("Invalid input!")
        get_number()
    return number


def select_level():                   #prompts the user to select a difficulty to play on
    level = str(input("Would you like to play on easy, medium, or hard? \n"
                      "Type 'e' for easy, 'm' for medium, or 'h' for hard!\n"))
    return level


def guess_number(level):        #function that prompts the user to guess within range depending on chosen difficulty
    if level == "e":
        guess = int(input("Guess a number between 1 and 20:\n"))
    if level == "m":
        guess = int(input("Guess a number between 1 and 100:\n"))
    if level == "h":
        guess = int(input("Guess a number between 1 and 1000:\n"))
    return guess


def check_guess(guess,number):         #processes the users guess and evaluates if it is too high, too low, or bang on
    if guess > number:
        print ("your guess is too high! Try again! \n")
    if guess < number:
        print ("your guess is too low! Try again! \n")
    if guess == number:
        print("\n{0} was the number!".format(number))


def com_num_guesses(level):          #function to get the number of guesses taken by the computer
    if level == "e":
        com_guesses = round(random.normalvariate(3.7,1.1))
    if level == "m":
        com_guesses = round(random.normalvariate(5.8,1.319))
    if level == "h":
        com_guesses = round(random.normalvariate(8.99,1.37474))
    print("The computer guessed the number in {0} guesses! Can you beat that?".format(com_guesses))
    return com_guesses


def mainloop():
    level = select_level()
    number = get_number(level)
    com_guesses = com_num_guesses(level)
    guess = guess_number(level)
    check_guess(guess,number)
    num_guesses = 1
    if guess == number:           #tells program what to do if first guess is correct
        print("You got it in {0} guesses.".format(num_guesses))
        if num_guesses == com_guesses:
            print("It took the computer {0} guesses too!\nIt's a tie!\n".format(com_guesses))
        if num_guesses > com_guesses:
            print("It took the computer {0} guesses.\nThe computer wins!\n".format((com_guesses)))
        if num_guesses < com_guesses:
            print("It took the computer {0} guesses.\nYou win!\n".format(com_guesses))
        play_again = str(input("To play again type 'yes'. To exit type 'no'. \n"))
        if play_again == "yes":
            mainloop()
        if play_again == "no":
            raise SystemExit(0)
    while True:                 #tells program how to handle guesses after the first guess
        guess2 = guess_number(level)
        check_guess(guess2,number)
        num_guesses += 1
        if guess2== number:
            print( "You got it in {0} guesses.".format(num_guesses))
            if num_guesses == com_guesses:
                print("It took the computer {0} guesses too!\nIt's a tie!\n".format(com_guesses))
            if num_guesses > com_guesses:
                print("It took the computer {0} guesses.\nThe computer wins!\n".format((com_guesses)))
            if num_guesses < com_guesses:
                print("It took the computer {0} guesses.\nYou win!\n".format(com_guesses))
            play_again = str(input("To play again type 'yes'. To exit type 'no'. \n"))
            if play_again == "yes":
                mainloop()
            if play_again == "no":
                raise SystemExit(0)
            break





mainloop()




dimanche 24 juillet 2016

struggling to understand Random class constructor with one parameter of long type [duplicate]

This question already has an answer here:

I'm relatively new to java and is studying the random class in java se8. I'm struggling to understand the random class constructor with one parameter of type long. I have attached a screen shot of the explanation in java documentation, bt I'm really struggling to understand what it actually means. Could someone please kindly explain it to me in a way that's easier to understand? Thanks in advance for any help!

enter image description here




Create smooth, normally distributed variable

Just to start off, I'm aware of numpy's np.random.normal() and np.random.randn() functions. However, I have a code that requires a very accurate normal distribution - small variations from this will cause instabilities due to it's non-linear nature. This is exactly the problem - the numpy functions above are not smoothly distributed, and so ever for N = 30,000 samples, a histogram of the distribution will reveal some nasty patches.

A google search reveals very little, but I was wondering if there was a Python function or module that could be used to create a smooth, normally distributed variable with given mean and variance. Else, is there a simple code that will do this? My knowledge of statistics is not particularly advanced.

EDIT: Using the np.random.normal() function to create four normal distributions yields the plots shown in the image.Here.

Although they may look fairly normally distributed (they are), you can observe that they are not smooth functions. Manual examination of the numbers show that there are differences of ~5-10% from expected values between each bin. This difference is enough to cause instabilities in a non-linear code I am writing.




How can I exclude multiple values from an operation? Would I use an or operator along with an if else statement?

I know it would be easier if I just use consecutive numbers, but I want to make it easier for the user to select a number that corresponds to the die type they pick. If I use an or operator am I limited to comparing just two things? This is what I tried to do but it didn't work. Is my syntax wrong or can I not string multiple terms in one statement?:

if (typeOfDice != 4 || typeOfDice != 6 || 
        typeOfDice != 8 || typeOfDice != //10 || typeOfDice != 12 || 
        typeOfDice != 20 || typeOfDice != 100)

Here is the short program I'm trying to make it work in. I just want to make sure the user can't break the program:

    static void Main(string[] args)
    {
        Start:
        Random roll = new Random();

        // Request dice type from user
        Console.WriteLine("Please input the type of dice you want to roll. ");

        // Display dice types to user
        Console.WriteLine("4) Four-sided");
        Console.WriteLine("6) Six-sided");
        Console.WriteLine("8) Eight-sided");
        Console.WriteLine("10) Ten-sided");
        Console.WriteLine("12) Twelve-sided");
        Console.WriteLine("20) Twenty-sided");
        Console.WriteLine("100) Percentage");
        Console.WriteLine(" ");

        // Take dice type from user
        Console.Write("Type of Dice: ");
        int typeOfDice = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(" ");

        // Prevents user from breaking the program by printing a corrective message
        // and restarting the program in the event an inappropriate choice is made by the user.
        if (typeOfDice != 4 || typeOfDice != 6 ||
        typeOfDice != 8 || typeOfDice != //10 || typeOfDice != 12 || 
        typeOfDice != 20 || typeOfDice != 100)
            Console.WriteLine("That is not an acceptable die type. Please try again.");
        goto Start;
        else
        {

            // Initiates random variable and total variable
            Random rnd = new Random();
            int total = 0;

            // Request number of dice from user
            Console.WriteLine("Please input the number of dice you want to roll ");
            Console.WriteLine(" ");

            // Accept number of dice from user 
            Console.Write("Number of Dice: ");
            int numberOfDice = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(" ");

            /// Assigns random generator parameters to user's choice of dice type and 
            // generates random number, looping until the die is rolled the requested 
            // number of times and the result of each new roll is added to the total
            switch (typeOfDice)
            {

                case 4:
                    for (int count = 0; count < numberOfDice; count++)
                    {

                        int currentRoll = rnd.Next(typeOfDice);
                        total += currentRoll + 1;
                        Console.Write("{0} ", currentRoll + 1);
                        //Console.WriteLine(" ");

                    }
                    break;

                case 6:
                    for (int count = 0; count < numberOfDice; count++)
                    {

                        int currentRoll = rnd.Next(typeOfDice);
                        total += currentRoll + 1;
                        Console.Write("{0} ", currentRoll + 1);
                        //Console.WriteLine(" ");

                    }
                    break;

                case 8:
                    for (int count = 0; count < numberOfDice; count++)
                    {

                        int currentRoll = rnd.Next(typeOfDice);
                        total += currentRoll + 1;
                        Console.Write("{0} ", currentRoll + 1);
                        //Console.WriteLine(" ");

                    }
                    break;

                case 10:
                    for (int count = 0; count < numberOfDice; count++)
                    {

                        int currentRoll = rnd.Next(typeOfDice);
                        total += currentRoll + 1;
                        Console.Write("{0} ", currentRoll + 1);
                        //Console.WriteLine(" ");

                    }
                    break;

                case 12:
                    for (int count = 0; count < numberOfDice; count++)
                    {

                        int currentRoll = rnd.Next(typeOfDice);
                        total += currentRoll + 1;
                        Console.Write("{0} ", currentRoll + 1);
                        //Console.WriteLine(" ");

                    }
                    break;

                case 20:
                    for (int count = 0; count < numberOfDice; count++)
                    {

                        int currentRoll = rnd.Next(typeOfDice);
                        total += currentRoll + 1;
                        Console.Write("{0} ", currentRoll + 1);
                        // Console.WriteLine(" ");

                    }
                    break;

                case 100:
                    for (int count = 0; count < numberOfDice; count++)
                    {

                        int currentRoll = rnd.Next(typeOfDice);
                        total += currentRoll + 1;
                        Console.Write("{0} ", currentRoll + 1);
                        //Console.WriteLine(" ");

                    }
                    break;

            }

            // Prints total of dice rolls.
            Console.WriteLine(" ");
            Console.WriteLine("Total: {0}", total);
            Console.WriteLine(" ");

            goto Start;
        }

    }




How can I generate a random AES key and encrpyt/decrpyt a string using OpenSSL?

I wan to create an application which generates random AES keys and encrypts or decrpyt a file or a string, but my method doesn't seem to work. My code so far:

#include <openssl\aes.h>
#include <openssl\rand.h>
#include <stdio.h>
#include <string>
#include <conio.h>

using namespace std;

int main(int argc, char* argv[])
{
    unsigned char buffer[512];
    unsigned char encrypted[512];
    unsigned char decrypted[512];

    unsigned char ckey[32];
    unsigned char iv[32];

    RAND_bytes(ckey, sizeof(ckey));
    RAND_bytes(iv, sizeof(iv));

    AES_KEY key;
    FILE *out;
    out = fopen("out.txt", "w");

    const char test[] = "This is a test string";
    memcpy((char*)buffer, test, sizeof(buffer));

    AES_set_encrypt_key(ckey, 256, &key);
    AES_encrypt(buffer, encrypted, &key);

    fprintf(out, "%s\n\n", encrypted);

    AES_set_decrypt_key(ckey, 256, &key);
    AES_decrypt(encrypted, decrypted, &key);

    fprintf(out, "%s\n\n", decrypted);

    _getch();
    return 0;
}

But it generates a very strange output

LuÂ6(ö$Áü
žčLdqĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚThis is a test string

This is a test sĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚLuÂ6(ö$Áü
žčLdqĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚĚThis is a test string

I guess the test string shouldn't be there in the encrypted string.

Could anyone help me?




Random topological sorting with uniform distribution in near linear time

I want an algorithm for topological sorting that doesn't provide the same sorting each time, but a random one, each sorting being equally likely to all others.

Generating all possible topological sortings and picking one at random is correct, but far too slow. Generating all permutations and filtering the invalid topological sorts is also very slow; the first one degrades into the second one if the tree/forest is wide enough.

Inserting new nodes into a random position in the queue of nodes to be checked seems like it would produce a biased result, and putting it at the end and doing a fisher-yates shuffle also seems biased, since both fail to account for the number of nodes "hidden" under each node, i.e. how many nodes depend on a or b being scheduled. a could have no children, while b holds the rest of the tree.

How can I generate a random topological sorting with each valid sorting being equally likely, in near-linear time?




Pseudo Random network coding with WBAN

Please can any one help me to decide if Pseudo Random network coding can work better with wireless body are network (WBAN)?




samedi 23 juillet 2016

Formula to make higher numbers harder to get in a random

I'm looking for a formula or a method to allow getting higher numbers in a random harder to obtain. For instance if I was attempting to get a number out of 1000, getting 1000 would be much harder than getting a lower number such as 1 - 250.




C++ - Boost : Getting same random number . Seeding does not seem to work

I created a class MyRandomto roll a die on a uniform distribution, given the range as input:

MyRandom.cpp

#include "MyRandom.h"

MyRandom::MyRandom(){
    gen.seed(static_cast<unsigned int>(std::time(0)));
}


int MyRandom::die(int min, int max){

    boost::uniform_int<> dist(min, max);
    boost::variate_generator<boost::mt19937&, boost::uniform_int<> > role(gen, dist);
    int result = role();
    role.engine().seed();
    role.distribution().reset();
    return result;
}

main.cpp

std::cout <<  myRandom.die(0, 8) << std::endl; 
std::cout <<  myRandom.die(0, 8) << std::endl;
std::cout <<  myRandom.die(0, 8) << std::endl;
std::cout <<  myRandom.die(0, 8) << std::endl;
std::cout <<  myRandom.die(0, 8) << std::endl;
std::cout <<  myRandom.die(0, 8) << std::endl;
std::cout <<  myRandom.die(0, 8) << std::endl;

I keep getting the same number (except the first one, so my reset somewhat works). Obviously, I am not seeding this correctly. I tried to add the reset() as suggested here without success. What am I missing?




How can I make a running total that keeps its value outside of the switch case?

I am writing my first program without the use of a tutorial. It is a polyhedral die rolling program in C#. The user can input the type of dice to be rolled and the number of dice. It is working well except that I'm not sure how to add up the total and then print it out. It is successfully printing each individual roll, though, so I know it is working as far as generating the random numbers in the proper range determined by the user. I wanted to print the total at the end of the program, but it is not working. Does the value of the variable disappear after the program leaves the switch case? Is there something I can do to fix that? Thanks.

    static void Main(string[] args)
    {
        Random roll = new Random();

        // Request dice type from user
        Console.WriteLine("Please input the type of dice you want to roll. ");

        // Display dice types to user
        Console.WriteLine("4) Four-sided");
        Console.WriteLine("6) Six-sided");
        Console.WriteLine("8) Eight-sided");
        Console.WriteLine("10) Ten-sided");
        Console.WriteLine("12) Twelve-sided");
        Console.WriteLine("20) Twenty-sided");
        Console.WriteLine("100) Percentage");
        Console.WriteLine(" ");

        // Take dice type from user
        int typeOfDice = Convert.ToInt32(Console.ReadLine());

        Random rnd = new Random();

        // Request number of dice from user
        Console.WriteLine("Please input the number of dice you want to roll ");
        Console.WriteLine(" ");

        // Accept number of dice from user 
        int numberOfDice = Convert.ToInt32(Console.ReadLine());


        // Assigns random generator parameters to user's choice of dice type
        switch (typeOfDice)
        {

            case 4:
                for(int count = 0; count < numberOfDice; count++)
                {

                    int currentRoll = rnd.Next(typeOfDice);
                    int total = currentRoll + 1;
                    Console.WriteLine(currentRoll + 1);
                    Console.WriteLine(" ");

                }
                break;

            case 6:
                for (int count = 0; count < numberOfDice; count++)
                {

                    int currentRoll = rnd.Next(typeOfDice);
                    int total = currentRoll + 1;
                    Console.WriteLine(currentRoll + 1);
                    Console.WriteLine(" ");

                }
                break;

            case 8:
                for (int count = 0; count < numberOfDice; count++)
                {

                    int currentRoll = rnd.Next(typeOfDice);
                    int total = currentRoll + 1;
                    Console.WriteLine(currentRoll + 1);
                    Console.WriteLine(" ");

                }
                break;

            case 10:
                for (int count = 0; count < numberOfDice; count++)
                {

                    int currentRoll = rnd.Next(typeOfDice);
                    int total = currentRoll + 1;
                    Console.WriteLine(currentRoll + 1);
                    Console.WriteLine(" ");

                }
                break;

            case 12:
                for (int count = 0; count < numberOfDice; count++)
                {

                    int currentRoll = rnd.Next(typeOfDice);
                    int total = currentRoll + 1;
                    Console.WriteLine(currentRoll + 1);
                    Console.WriteLine(" ");

                }
                break;

            case 20:
                for (int count = 0; count < numberOfDice; count++)
                {

                    int currentRoll = rnd.Next(typeOfDice);
                    int total = currentRoll + 1;
                    Console.WriteLine(currentRoll + 1);
                    Console.WriteLine(" ");

                }
                break;

            case 100:
                for (int count = 0; count < numberOfDice; count++)
                {

                    int currentRoll = rnd.Next(typeOfDice);
                    int total = currentRoll + 1;
                    Console.WriteLine(currentRoll + 1);
                    Console.WriteLine(" ");

                }
                break;

        }

       // Console.WriteLine(total);

        // int[] xfiles = new int[amountofdice];

    }




How does the time it takes Math.random() to run compare to that of simple arithmetic operation?

In Java, how long relative to a simple arithmetic operation does it take Math.random() to generate a number? I am trying to randomly distribute objects in an ArrayList such that a somewhat even, but not completely even distribution is created, and I am not sure if choosing a random index for every insertion point by using Math.random() is the best approach to take.




To which extent is C# System.Guid.NewGuid() safe for the following situation?

I'm building an app. Assume it is a messaging app and becomes as popular as whatsapp.

A GUID will be given for every message sent in the world.

There will be a problem if any 2 GUIDs of in the world are equal.

As of today 30billion!(official) whatsapp messages are sent in the world in a day.

I'm using C# (Xamarin)'s System.Guid.NewGuid method to generate GUIDs.

What is the chance for a 'problem' occur because the random numbers are not truly random?




1 on 1 Random Matchmaking

I am developing a random chat application that matches a client with another "random" client. Pseudo-Random because the client would query a list of "open" clients and pick from the top of the list.

I have searched for an answer but seemingly no resources exist for a matchmaking solution based off of a relational database in mySQL. The problem I ran into is that if all clients were set to "search", then each(user) would try to connect to one(a) while the one(a) would be trying to connect to another(b). {*user is chasing a while a is chasing b simultaneously.}

What would be the simplest structure and process to connect two random clients to exchange information when both are in a pool of unmatched-clients?




Random Video not working into Chrome

Hy

Sorry my English Google Translate is helping me ;-) I use this Code to display a random Movie on my Page. It works perfect into Firefox.

But into Google Chrom its not workig.

var randomVid; randomVid = function() { var mp4, randomMp4SrcList, randomWebMSrcList, srcMp4, srcWebM, webM; randomMp4SrcList = [ "files/random_movies/video1.mp4", "files/random_movies/video2.mp4", "files/random_movies/video3.mp4", "files/random_movies/video4.mp4", "files/random_movies/video5.mp4", "files/random_movies/video6.mp4", ]; randomWebMSrcList = [ "http://ift.tt/2ajRsTq", "http://ift.tt/2alvvQK"]; mp4 = randomMp4SrcList[Math.floor(Math.random() * randomMp4SrcList.length)]; webM = randomWebMSrcList[Math.floor(Math.random() * randomWebMSrcList.length)]; srcMp4 = document.querySelectorAll("#bgvideo > source")[0]; srcWebM = document.querySelectorAll("#bgvideo > source")[1]; srcMp4.src=mp4; srcWebM.src=webM; return; };
        <div class="background-video-holder">
            <video id="bgvideo" class="background-video hidden-xs" preload="auto" autoplay="autoplay" loop="loop">
                <source src=" " type="video/mp4">
                    <source src=" " type="video/webm">
                        <script>
                            randomVid();
                        </script>
            </video>

Any Ideas? What i have to Change to see a Random Video into any Browsers?

Thanks Guys!




C: variable with random value debugger error

In a function I have a local variable which is initialized at the beginning. Further in the code this variable is "filled" with a random value, generated with rand() It doesn't work and the debugger tells me:

  random_color_value  Failed getting location list for symbol die# 0x4b9  Error

This is a snippet of the code:

struct cRGB colorFade(void){    
    uint8_t random_color_value; 
   .
   .
   .        
   srand(2);
   random_color_value = rand() % 12 +1; // generate random value between 1 and 12 (including 12) 
   .
   .
   . 
}

The compiler inside my AVR-Studio is set to optimize for size. What could cause that problem?




Stack overflow in uniform_int_distribution

My program has a function for generating random numbers, and started crashing. Valgrind produces this error:

==6952== Stack overflow in thread #1: can't grow stack to 0xffe801000
==6952== 
==6952== Process terminating with default action of signal 11 (SIGSEGV)
==6952==  Access not within mapped region at address 0xFFE801FF8
==6952== Stack overflow in thread #1: can't grow stack to 0xffe801000
==6952==    at 0x403B19: int std::uniform_int_distribution<int>::operator()<std::mersenne_twister_engine<unsigned long, 32ul, 624ul, 397ul, 31ul, 2567483615ul, 11ul, 4294967295ul, 7ul, 2636928640ul, 15ul, 4022730752ul, 18ul, 1812433253ul> >(std::mersenne_twister_engine<unsigned long, 32ul, 624ul, 397ul, 31ul, 2567483615ul, 11ul, 4294967295ul, 7ul, 2636928640ul, 15ul, 4022730752ul, 18ul, 1812433253ul>&, std::uniform_int_distribution<int>::param_type const&) (random.tcc:881)
==6952==  If you believe this happened as a result of a stack
==6952==  overflow in your program's main thread (unlikely but
==6952==  possible), you can try to increase the size of the
==6952==  main thread stack using the --main-stacksize= flag.
==6952==  The main thread stack size used in this run was 8388608.

My code:

std::random_device rd; 
std::mt19937 rng(rd());  
int rnd(int min, int max, std::mt19937& rng) {
    std::uniform_int_distribution<int> uni(min,max);
    return uni(rng);
}
rnd(0, 1000, rng);

I tried to look at the file it's referring to, but I don't understand a line of it. What is causing the segfault?




Using rand function in C [duplicate]

This question already has an answer here:

Hey guys I'm doing my assingment but I stuck with this rand() function I'm rolling dice with this function for 2 players in order to determine who will start first. but it always give the same number for both of them I dont know why I tried adding another rand function but result was the same, can some one help me with it ?

int bunco_starts()
{
    int p1roll=0, p2roll=0;
    printf("Dice are rolled by each player in order to select who will start first:\n");
    p1roll=roll_a_dice();
    printf("%d\n", p1roll);
    p2roll=roll_a_dice2();
    printf("%d\n", p2roll);
    printf("Dice 1 (rolled by player 1): %d  Dice 2 (rolled by player 2): %d\n", p1roll, p2roll);




}
int roll_a_dice()
{

    return 1+rand()%6;

}




Random number generator in C++

I need a method which returns a single random variable of the interval (0,1) at a time but that number should almost be unique. The method could possibly return the same number multiple times but with a very low probability.

If tried several approaches using standard C++ features and boost but I usually end up getting similar or even identical results.

Here's some pseudo code of the function:

double getRandomNumber(){
  //generate random number r 
  return r;
}

Could someone give me an advise how to implement this properly, please?




vendredi 22 juillet 2016

Overlapping random divs

I'm making a simple game (whack a mole), the game works like this: Every time you press the start button, it will place 10 divs into the DOM. The divs will be placed randomly into the DOM.

My problem is that they overlap each other and sometimes they're place outside of their container.

I'd like to know how can i place them randomly inside the container without overlapping each other, i prefer not to use a grid to place them, i want them to be randomly distributed across the container.

here's the main function:

function randomPos(size){
var result = new Array();
var height = (document.getElementById('field').clientHeight);
var width = document.getElementById('field').clientWidth;
for (var i = 0; i < size; i++) {
    var obj = {};
    var posY = Math.floor(Math.random() * height);
    var posX = Math.floor(Math.random() * width);
    if (result.length == 0){
        obj.x = posX;
        obj.y = posY;
        result.push(obj);
    }
    else{
        var flag = true;
        for (var j = 0; j < i && flag; j++){
            if (result[j].y == posY && result[j].x == posX){
                flag = false;
            }
        }
        if(flag){
            obj.x = posX;
            obj.y = posY ;
            result.push(obj);
        }
        else{
            i--;
        }
    }
}
return result;
}

here's a jsfiddle




Wordpress random image header with Wordfence caching

Q: How can I serve an image that is randomized every time a user visits/refreshes a page, via a method that caching doesn't break?

I've coded the following in my Wordpress site's page.php:

<?php if (has_post_thumbnail( $posts_page_id ) ):  // part 1  ?>

    <div class="featured-img" style="background-image:url(<?php echo $thumb_url_splash ?>);"></div>

<?php else:  // part 2

    $gallery = get_field('header_images', 530);
    $rand = array_rand($gallery, 1);
    <div class="featured-img" style="background-image: url('<?php echo $gallery[$rand]['url']; ?>');"></div>

<?php endif; ?>

  1. Check if the page has a featured image. If it does, display it.
  2. If not, display a random image every time the page is loaded (from an ACF Pro-generated gallery on another page with ID of 530).

This works fine until I turn on Wordfence's caching -- then the randomization is cached along with the rest of page, and the page displays the same image until the next time the cache is cleared.

(Wordfence has a doNotCache function but calling it prevents the entire page from being cached; since I'm using this header image code in 90% of pages, using doNotCache would basically turn caching off on 90% of pages, defeating the point of enabling caching!)

I'm good at HTML/CSS but less experienced at PHP/JS. I've heard that JS won't be cached by Wordfence, and that one solution might be passing the PHP array to JS via json_encode, but I have no idea how to make that work or if it's the best solution to this problem.

Apologies for my ignorance, hopefully my explanation is clear. Thanks!




Generate new random value if value is in array

I have a situation where I'm using protractor to click a random link on the page. (There are a lot). I have an array of links that I don't want to click, so I want to know when my random link is in that array and generate a new random link.

Here's my working code to click a random link on the page

var noClickArray = ['link2', 'link3']; // array much bigger than this
var parent = this;

function() {
  var links = element.all(by.css('.links'));
  return links.count().then(function(count) {
    var randomLink = links.get(Math.floor(Math.random() * count));
    randomLink.getText().then(function(text) {
      parent.selectedLink = text; // used in a different function
      var containsLink = _.includes(noClickArray, text);
    });
    return randomLink.click();
  });
}

I'm using lodash to find if the randomLink text is in noClickArray but I don't know how to keep generating random values until the value does not exist in the array. How can I do this?