samedi 30 septembre 2017

Get a random object with random value from a List in Java [duplicate]

This question already has an answer here:

i tried to get a random value from 50 to 100 of an object but i didn't find a solution! any help please?

public class OneArmedBandit implements Item {

Random rand = new Random();

private List<Integer> Item = new ArrayList<Integer>();

public OneArmedBandit(List<Integer> ItemList) {
    this.Item=ItemList;
}

public int AnyItem(List<Integer> ItemList) {

        Random rand = new Random();

        int index = ItemList.get(rand.nextInt(ItemList.size()));
        return ItemList.get(index);

}

public List<Integer> getListItem(){
    return this.Item;
}

}




Creating random binary tree in haskell

I am new to Stackoverflow aswell as quite new to programming with haskell. I need to generate a random binary tree with a given maximum depth. Nodes have either 2 or one child.




Consistent discrete uniform number generation

How would one create a function where the following would give the same result every time, generates every integer value an equal amount of times, repeats, and is seemingly random?

while(true)
{
    number = discrete_uniform_generator(A_VALUE, ANOTHER_VALUE);
    printf("%i ", number);
}




UPDATE a column in every row with a random unique number

I have a small table of about 20k rows. In that table there is a column named random_uid (INT NOT NULL). I would like to update all 20k rows with a random unique number.

Since my table is small I dont think I need to use a string or a UUID so I went with

SELECT FLOOR(RAND() * 100000000) AS random_num
FROM table1 
WHERE "random_num" NOT IN (SELECT random_uid FROM table1)
LIMIT 1;

My problem is that I cant update and select from the same table, so I was having trouble creating the UPDATE query.




Numpy random.seed not working from __init__ to other methods

I have a class with constructor and method as below:

import numpy.random as random
class practiceObject(object):

    def __init__(self):

        random.seed(10)

    def getRandom(self, x):

        rd = random.randint(x)
        return rd

Now I would figure this means that for the same x I pass into "getRandom", the same value should be returned. And yet:

myObject = practiceObject()
print myObject.getRandom(100)
print myObject.getRandom(100)
>>9
>>15

Why is this happening, and what can I do to ensure each call to getRandom with the same x value will return the same value?




Sampling rows in data frame with an empirical probability distribution of a variable

I have got a following problem.

Let's assume that we have a data frame with few variables. Morover one variable (var_A) is a probability score - its values ranges from 0 to 1. I want to sample rows from this data frame in a way that it will be more probable to pick a row with higher value of var_A - so I guess that I have to draw from an empirical distribution of var_A. I know how to implement edf function of var_A as it's suggested here but I have no idea how to use this distribution for sampling rows.

Can you please help me with this?

Thanks




NASM x86 Assembly Optimization [Linear congruential generator]

I have tried writing my first assembly program (NASM x86 assembly). It is an linear congruential generator, or the plan was that is is one. Because of limitations of my assembly skills I had to change the starting parameters of the pseudo random number generator (prng):

name: before: after

seed:214567:21456

a:22695477:16807

c:1:0

m:2^32:2^24

%include "io.inc"
section .data
;cheating with the numbers by putting a 0. infront of them so they look like floats
msg db "0.%d",10,0
msgDone db "done",10,0
msgStart db "start",10,0
;see http://ift.tt/1MDS8uz
seed dd 21456
a dd 16807
c dd 0
m dd 16777216
section .text
global CMAIN
extern printf
CMAIN:
    mov ebp, esp; for correct debugging
    ;create stack frame
    push ebp
    mov ebp, esp
    ; edi is used for the loop count
    mov edi, 0
    push msgStart
    call printf
    generate:
        ;seed = (seed*a+b)%m
        mov eax, [seed]
        mov ecx,[a]
        ;seed*a
        mul ecx
        ;seed*a+b
        add eax,[c]
        mov ecx, [m]
        ;(seed*a+b)%m
        div ecx
        mov eax,edx
        mov [seed], edx
        ;push to print them out
        push eax;disable for testing
        push msg;disable for testing
        call printf ;disable for testing
        add esp,8
        inc edi
        cmp edi, 12 ; set this to 1000000000
    jne generate
    ;destroy stack frame
    push msgDone
    call printf
    xor eax, eax
    mov esp, ebp
    pop ebp
    ret

I have written the same code in java and in NASM x86 assembly and expected an performance increase relative to java with NASM. But in the end it took 3 times longer than java did. Nasm ~ 10sec , Java ~ 3-4 sec. My test was letting each program generate 1.000.000.000 random numbers. Of course without the System.out.prints/ call printf because they needed a lot of time.

I knew from the beginning that my assembly code would be badly optimized, because I have never programmed in it before and now just wanted to try it, but that the performance would be that bad is something I never had excpected.

Can someone tell me why my programm needs so much time and how assembly programs can be optimized?

Thanks

---The code was written with SASM on Win10 64bit




R function attribute for generating random variables until condition is met

I am generating discrete uniform random numbers from 1 to 6. I want to find the index of the array by which point all of the numbers from 1 to 6 have been generated. I am arbitrarily generating 100 numbers at a time (under the pretty safe assumption that all distinct numbers have been generated within 100 numbers).




How to add listener or initialize a class with the clicking of OK in showMessageDialog in Java?

I am trying to output a showMessageDialog stating that a color will be randomly chosen and stating the color chosen. Once the user clicks OK the program should initialize the JFrame utilizing createFrame(). Once initialized the title I set and a label and text box are added with the class createContents(). Color scheme is then chosen based on what random color was chosen and once set visible is set to true. The only issue I am having is initializing my frame on the click of ok. I have tried setting the J.OptionPane.showMessageDialog = int x and use an if loop but receive void cannot be converted to int. I have also attempted to initialize createFrame() with visibility set to false but its not static so cannot initialize it from the main whether it is a class or a method. Thanks for your time and assistance.

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 


public class JMUnit7Ch17 extends JFrame
{
  private JTextField nameBox; //Holds user's name
  private static ArrayList<String> colors = new ArrayList<>();//creates 
       array to hold colors 
  private static int n;//will hold a random value

  public static void main(String[] args)
  {
   //adds colors to ArrayList Colors
   colors.add("Red"); 
   colors.add("White"); 
   colors.add("Yellow"); 
   colors.add("Green"); 
   colors.add("Blue"); 

   //creates a new random number n between 0-4
   Random rand = new Random(); 
   n  =rand.nextInt(4);

   //Outputs the message appropriatly formated
   int x=JOptionPane.showMessageDialog(null, String.format("%s%n %s%n%n %s %s",
   "The following window color will be randomly chosen from"
   ,"Red, White, Yellow, Green, Blue.","Your color will be:",colors.get(n))); 
   //Need to create a function to initialize createFrame() on click of ok from showMessageDialog
   //fuction
}

//Method for inserting the label and  text field with a listener for the users name

private void createContents()
{
 JLabel namePrompt = new JLabel("What is your name?"); 
 nameBox= new JTextField(15);
 add(namePrompt); 
 add(nameBox); 
 nameBox.addActionListener(new Listener()); 
}
//Action listener class is initialized by createContents() method

private class Listener implements ActionListener
{
 public void actionPerformed(ActionEvent e)
 {
     String message; 
     message = "Thanks for playing"+ nameBox.getText();  
    }
}
//creates a JFrame with unique title and colors based on the randomly chosen on
//createContent() is used here then JFrame is setVisible with boolean true

private void createFrame()
{
 JFrame colorFrame = new JFrame(); 
 setTitle("Color Changing Frame"); 
 createContents(); 
 switch(n)
 {
     case 0: getContentPane().setBackground(Color.RED);
             getContentPane().setForeground(Color.WHITE);    
                 break;
     case 1: getContentPane().setBackground(Color.WHITE);
             getContentPane().setForeground(Color.BLACK);
                 break;
     case 2: getContentPane().setBackground(Color.YELLOW);
             getContentPane().setForeground(Color.BLACK);
                 break;            
     case 3: getContentPane().setBackground(Color.GREEN);
             getContentPane().setForeground(Color.BLUE);
                 break;
     case 4: getContentPane().setBackground(Color.BLUE);
             getContentPane().setForeground(Color.WHITE);
                 break;            
    }   
 setVisible(true);  
}
}




C# Randomly Choosing Word Not Working

I'm working on a hangman game, each time via debugging I find that despite guessIndex generating a number it doesn't pick a word from the words array. I've debugged and I know 100% that it creates a number, but currentWord is still null. Can anyone help fix this?

namespace Guess_The_Word
{

    public partial class Form1 : Form
    {
        private int wrongGuesses = 0;
        private int userGuesses;
        private string secretWord = String.Empty;
        private string[] words;
        private string currentWord = string.Empty;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadWords();
            setUpWords();

        }

        private void guessBtn_Click(object sender, EventArgs e)
        {

            wrongGuesses++;
            if (wrongGuesses <= 0)
            {
                MessageBox.Show("You have lost! The currect word was {0}", currentWord);
            }
        }

        private void LoadWords()
        {

            string path = (@"C:\commonwords.txt"); // Save the variable path with the path to the txt file
            string[] readText = File.ReadAllLines(path);
            words = new string[readText.Length];
        }

        private void setUpWords()
        {
            wrongGuesses = 0;
            int guessIndex = (new Random()).Next(words.Length);
            currentWord = words[guessIndex];
            userGuesses = currentWord.Length;

        }
        private void ResetGame()
        {

            //.Show("You have {0} guesses for this word, guess three in a row to win!");
        }

        private void resetGamebtn_Click(object sender, EventArgs e)
        {
            LoadWords();

        }
    }
}

I get System.NullReferenceException: 'Object reference not set to an instance of an object.'

at line 58




How to make a number appear in a range from 0 to 9?

I am currently completing a project and have come across an error in my coding.

I have a button which calls a JS prompt box asking to enter an integer between 0 and 9.

This number is then used as a game where 3 random integers from 0 and 9 appear every second and when you click on the matching number your score increases.

This is my code so far:

<script>

function chooseNum() 
{
var txt;
var person = prompt("Choose an integer between 0 and 9:");
if (person == null || person == "") {
    txt = "User cancelled the prompt.";
} else {
    txt = person;
}
document.getElementById("chosen").innerHTML = txt;
}

</script>

I want to know exactly how to display random integers in a range from 0 and 9.

Is a code like this on the right track?

<script>

var id = window.setInterval(function(){randomNumber();},1000);

function randomNumber()
{
var rand = Math.floor(Math.random()*9);
$('#number1').html(rand);
}

</script>

Can anyone point me in the right direction?

Cheers.




Check after random sample in python

This is my first little project and first question so sorry for the formatting. I have two lists containing recipe names as strings. I want to ask the user how many meals from each list they want and then take a random selection.

I then want to check if a meal was chosen by the selection and display the price of the meal which I would store in a variable.

My idea was to add the random sample to a new list and to check the contents via an if in statement. If the recipe was inside the new list then it would print the variable containing the price.

When I check the new list for the recipe however, it doesn't think it is in the list. Is there something I've missed or a better way to do this? Thank you.

My code so far:

import random
Vegetarian = ["Jungle Curry", "Chickpea Curry", "Dhal", "Buddha Bowl", 
"Chickpea Salad", "Lazy Noodles", "Fry Up"]
Meat = ["Chilli", "Butter Chicken", "Lamb and Hummus"]

v = int(raw_input("How many vegetarian meals this week? > "))
m = int(raw_input("How many meaty meals? > "))

Veg1 = random.sample(Vegetarian, v)
Meat2 = random.sample(Meat, m)

veg_week = []
meat_week = []

veg_week.append(Veg1)
meat_week.append(Meat2)

jungle_curry = 10
chickpea_curry = 10

if "Jungle Curry" and "Chickpea Curry" in veg_week:
    print jungle_curry + chickpea_curry




How to check if PHP rand() has randomly generated all the possible unique numbers by randomly generating numbers

I want to make sure that PHP rand() function has randomly generated all the possible unique numbers between the range given.

for example, this function rand(0,9) can generate unique numbers only 10 times right. ex: (randomly: 1,10,4,3,7,9,0,5,8,2,6)-(no duplication). So how do i determine that this rand() function has generated its all possible unique numbers?




vendredi 29 septembre 2017

How to add class to random element in pure javascript

I have a ul with some li's inside. I want to randomly select an li and add an .active class for 1second, then remove .active class and randomly select a next li.

I am trying to do this without the use of setInterval or Timeout, so I have tried using requestAnimationFrame although I think my logic with javascript is not quite right on randomizing.

Currently I have it working but it selects the same li each time the function is called again.

<ul>
  <li class="light active"></li>
  <li class="light"></li>
  <li class="light"></li>
  <li class="light"></li>
  <li class="light"></li>
</ul>

Javascript

(function() {

var lights = document.getElementsByClassName("light");
var random = Math.floor(Math.random() * (lights.length - 1)) + 0;
var randomLight = lights[random];

function repeatOften() {
  randomLight.classList += randomLight.classList ? ' active' : ' light';
  requestAnimationFrame(repeatOften);
}
requestAnimationFrame(repeatOften);

})();

Here is a pen: http://ift.tt/2xMgdRo

Thanks in advance!




Is it more efficient to generate a large random number and split it than to generate several smaller ones?

So the question is: is it more efficient to generate a large random number and split it than to generate several smaller ones?

Underlying assumptions, you want to generate x values of n size (e.g. 64-bit). That's it. This isn't a question how HOW, more that I'm interested in the general rule of thumb for MODERN computers (anything as recent as x86 is close enough), preferably on 64 bit architectures. If you want to pull in some stats for your answer, please do, it'll probably help, but this is for stackoverflow, not stats.stackexchange, so reasoning based on computers please!

Note, no specific algorithm for this, although we would probably assume that it's at the very least a good PRNG, and that all bits are equally random. However, if you want to factor that into your answer, please do!




Get the value of a dice in a 5dice game from another window

I'm developing a 5 dice game in WPF. I have a usercontrol where I made the design of a dice. Then on my mainWindow I added this usercontrol 5 times (so this are my dices).

I have a class named ScoreCheck. In that class I write the code to get the value of the dice (1, 2, 3, 4, 5 or 6).

The problem is that I can do something like this in my usercontrol dice:

int worp = rand.Next(1, 7);
switch (worp)
            {
                case 1:
                    dso1.Fill = new SolidColorBrush(steenkleur);
                    dso2.Fill = new SolidColorBrush(steenkleur);
                    dso3.Fill = new SolidColorBrush(steenkleur);
                    dso4.Fill = new SolidColorBrush(oogkleur);
                    dso5.Fill = new SolidColorBrush(steenkleur);
                    dso6.Fill = new SolidColorBrush(steenkleur);
                    dso7.Fill = new SolidColorBrush(steenkleur);
                    break;

                case 2:
                    dso1.Fill = new SolidColorBrush(steenkleur);
                    dso2.Fill = new SolidColorBrush(steenkleur);
                    dso3.Fill = new SolidColorBrush(oogkleur);
                    dso4.Fill = new SolidColorBrush(steenkleur);
                    dso5.Fill = new SolidColorBrush(oogkleur);
                    dso6.Fill = new SolidColorBrush(steenkleur);
                    dso7.Fill = new SolidColorBrush(steenkleur);
                    break;

                case 3:
                    dso1.Fill = new SolidColorBrush(steenkleur);
                    dso2.Fill = new SolidColorBrush(steenkleur);
                    dso3.Fill = new SolidColorBrush(oogkleur);
                    dso4.Fill = new SolidColorBrush(oogkleur);
                    dso5.Fill = new SolidColorBrush(oogkleur);
                    dso6.Fill = new SolidColorBrush(steenkleur);
                    dso7.Fill = new SolidColorBrush(steenkleur);
                    break;

                case 4:
                    dso1.Fill = new SolidColorBrush(oogkleur);
                    dso2.Fill = new SolidColorBrush(steenkleur);
                    dso3.Fill = new SolidColorBrush(oogkleur);
                    dso4.Fill = new SolidColorBrush(steenkleur);
                    dso5.Fill = new SolidColorBrush(oogkleur);
                    dso6.Fill = new SolidColorBrush(steenkleur);
                    dso7.Fill = new SolidColorBrush(oogkleur);
                    break;

                case 5:
                    dso1.Fill = new SolidColorBrush(oogkleur);
                    dso2.Fill = new SolidColorBrush(steenkleur);
                    dso3.Fill = new SolidColorBrush(oogkleur);
                    dso4.Fill = new SolidColorBrush(oogkleur);
                    dso5.Fill = new SolidColorBrush(oogkleur);
                    dso6.Fill = new SolidColorBrush(steenkleur);
                    dso7.Fill = new SolidColorBrush(oogkleur);
                    break;

                case 6:
                    dso1.Fill = new SolidColorBrush(oogkleur);
                    dso2.Fill = new SolidColorBrush(oogkleur);
                    dso3.Fill = new SolidColorBrush(oogkleur);
                    dso4.Fill = new SolidColorBrush(steenkleur);
                    dso5.Fill = new SolidColorBrush(oogkleur);
                    dso6.Fill = new SolidColorBrush(oogkleur);
                    dso7.Fill = new SolidColorBrush(oogkleur);
                    break;
            }

Console.WriteLine(worp);

So now I get the value of all dices. Something like this: 2 6 4 1 5 1.

But I don't want this. I want them dice by dice on another window so I can check the score. So on my mainWindow I named my dices: dice1, dice2, dice3, dice4 and dice5. So I want to do something like this in my ScoreCheck.

var mwaanspreken = Application.Current.Windows.OfType<MainWindow>().SingleOrDefault();
Console.WriteLine(mwaanspreken.steen1.worp);

But then my output is always 0.

So does anyone know how to get the value of my dice from another window?




(Nearly) Evenly select items from a list

I have a list of N elements, and I'd like to sample M (<= N) values which are as evenly spaced as possible. To be more specific, lets say the selection should minimize the differences in the spacings between sampled points. For example, lets say I'm constructing a boolean indexing array (i.e. in python) to select elements,

I tried the algorithm (from this similar, but different question: How do you split a list into evenly sized chunks?) :

q, r = divmod(N, M)
indices = [q*jj + min(jj, r) for jj in range(M)]

And sometimes that works well:

N=11 M=6
good_index = [0 1 0 1 0 1 0 1 0 1 0]

N=14 M=6
good_index = [0 1 1 0 1 1 0 1 0 1 0 1 0 1]

Here, the first example is trivial because the array can be evenly divided. The second example cannot be evenly divided, but the spacing between points is as similar as possible (2, 2, 1, 1, 1, 1).

But often it works poorly:

N=16 M=10
bad_index = [0 1 0 1 0 1 0 1 0 1 0 1 0 0 0 0]

N=14 M=10
bad_index = [0 1 0 1 0 1 0 1 0 0 0 0 0 0]

Because you have values piled up at the end.




Generate random number, Poisson Distribution Fortran

I couldn't find on Internet, is there any native function in FORTRAN to generate random number with a Poisson distribution ?




best way to generate a random a key and vector in Linux

I want to generate a random key and vector in order to encrypt an image.

$ openssl enc -des -in [filename of the original file] -out [filename of the encrypted file]
-v -p -K [your key] -iv [initialization vector] -e

Is this the best way to generate a key and vector?

cat /dev/urandom | head -1 > randombytes.bin

xxd randombytes.bin | head -1




Java, random selection from an array with no repetition [duplicate]

This question already has an answer here:

How can I randomly select elements from an array and move them to different smaller arrays with no repetition.

For example my original array has the numbers 1-52 in it (representing each card in a standard deck). I want to randomly place each card in a pile without any repetition (like a game of solitaire).

Is there a a function for random selection like this?




Mean of a Poisson Distribution Using R's rpois function

I entered the following command in R:

my_pois <- replicate(100,rpois(5,10))

I believe this creates 100 sets of 5 numbers in which each set should have a mean of 10. However when I look at the mean of each column(set created), this is what I get:

[1] 10.8  9.4  9.0 11.2 11.6 11.6  7.8 12.4  9.6 11.0  9.6  9.8 10.0  8.6  9.8  8.6  9.4
 [18] 11.4 12.0  8.4 10.2 10.2 10.8 10.2  7.6  9.8  8.4 10.6 11.6  8.6  9.6 11.0 11.0 10.0
 [35]  9.8  9.2  8.2  8.2 10.2  9.0 10.4  9.2 10.4 10.0 11.8 13.8 10.2  9.8 12.4 10.4  9.8
 [52]  9.8  8.6  7.4  9.2  9.0  7.4  9.2  9.4 11.8  9.2  9.8 11.6  9.8 10.8  8.6 12.4 10.4
 [69]  9.4  9.4  9.0 11.2 10.6  9.4  9.6  8.2  9.6 10.6 10.6  8.2  9.2 10.0 11.2  9.0  9.6
 [86] 10.4  8.0 10.2  9.8  7.4  9.6  9.0  7.2  8.4 11.8 10.8  9.4 12.4 11.2 12.0

Shouldn't they all be 10 since we specified a mean of 10?




Random Images in Ruby on rails 4 App

I am using this code to display random images for similar products in the same category the selected product is in.

 <div class="row container product-teaser">
   <h4 class="text-center teaser-text"> similar products to <%= @product.title %> : </h4>

     <% @products_rand.each do |product| %>
       <div class="col-sm-2 col-xs-3 center-block product-thumbs-product-view" >
          <%= link_to product_path (product) do %>
             <% if product.images.first %>
          <%= image_tag @product.images.first.image.url(:medium), :size => "100%x100%", class: "img-responsive center-block" %>
          <% end %>        
      <% end %>
      <h5 class="text-center"><%= link_to product.title, product, class: "text-center" %></h5>
  </div>
    <% end %>
 </div>

The problem is that the products in this loop are all displaying the image for the one selected product but the names and the link for the products are correct.

THis picture shows what I mean, the Customer have selected a product called ATLAS and similar products ( products from the same category) are displaying with the Atlas picture.

enter image description here

here is the product_controller.rb

 class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]


  def show

  offset = rand(100)
  @meta_title = "Concept Store #{@product.title}"
  @meta_description = @product.description
  @products_rand = Product.where(category_id: @product.category_id).order("RANDOM()").limit(6)
 end

private
# Use callbacks to share common setup or constraints between actions.
def set_product
  @product = Product.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def product_params
  params.require(:product).permit(:title, :description, :price, :image, :category_id, :stock_quantity, :label_id, :query, :slug, images_attributes: [:image , :id , :_destroy])
end


end




Random selection in Netezza

I need help with a random selection in Netezza.

I have for example 4 customers and each one has some options for a variable.

Customer 1: 4,5,6

Customer 2: 10,12,16

Customer 3: 1,2,3,4,5,6

Customer 4: 5,8

And I need to select only one option for each Customer using a random selection.

Thanks!




jeudi 28 septembre 2017

Why is my return values keep giving me 0 on a random congruential number generator program?

So I'm creating a simple random congruential number generator. It's the first time I'm using windows forms and for some reason the results keep giving me 0. Can someone tell me what's going on?

What my program is doing is the user adds the seed the a, c, mod value, and how many times it wants to iterate random numbers. But when I click generate it just gives me 0's in each new line depending how much I want it to iterate. At least I know the iteration is correct.

namespace Metodos
{
    public partial class Mixto : Form
    {
        public Mixto()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void bttnGen_Click(object sender, EventArgs e)
        {
            int seed, a, c, mod, it, numrand, residuo;
            float division;

            seed = Convert.ToInt32(txtSeed.Text);
            a = Convert.ToInt32(txtA.Text);
            c = Convert.ToInt32(txtC.Text);
            mod = Convert.ToInt32(txtMod.Text);
            it = Convert.ToInt32(txtIt.Text);




            for (int i = 1; i <= it; i++)
            {
                string newLine = Environment.NewLine;

                numrand = seed * a + c;

                residuo = numrand % mod;

                division = residuo / mod;

                residuo = seed;

                results.Text = results.Text + newLine + division.ToString();

            }







        }

        private void results_Click(object sender, EventArgs e)
        {

        }

        private void bttnClear_Click(object sender, EventArgs e)
        {

            results.Text = "";

        }
    }
}




Random order of specific elements in list of objects c#

In c# have a list of objects. For example a list of "cars" with attribute "color". Now I want to order randomly all cars with attribute "green" for example.

Car c01 = new Car("green","HONDA");
Car c02 = new Car("blue","BMW");
Car c03 = new Car("green","NISSAN");
Car c04 = new Car("blue","VW");
Car c05 = new Car("red","MERCEDES");
Car c06 = new Car("green","BMW");

List<CarAcceleration> Cars = new List<CarAcceleration>();
Cars.Add (c01);
Cars.Add (c02);
Cars.Add (c03);
Cars.Add (c04);
Cars.Add (c05);
Cars.Add (c06);

My idea would be to first write all green cars to a second list, reorder it and then somehow overwrite the elements in the first big list. Is there maybe a better solution? Thanks




Generate random value in json

{
  "description": "Appname",
  "name": "appname",
  "partnerProfile":  {
    "email": "aa@gmail.com",
    "firstName": "John",
    "lastName": "Jobin",
    "partnerName": "app"
  }
}

I am passing the following body in a json file. How do I generate random value(time stamp) for partnerName for different test run. I am using Newman to run the script

Newman run Automation.json -e Dev.json -r html




VBScript - How to scramble characters in a string?

I am writing a script that reads in a txt file. After the header lines, I read in the data lines. As each data line is read in, String values in columns AssetID and Description are to be scrambled. I split each line on tab delimiter. Knowing that AssetID is in array position 1, and Description is in position 2, I can get the strings.

I am new to VBScript, and I would like to know a simple way to scramble the two strings. Here is some code for reference. TIA!

P.S. for now I commented to the loop out so that I could test the "scrambling" on the first header line to make sure it works before I implement it on the entire project.

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFile = objFSO.OpenTextFile("S:\PBS\G & A Non-Host\ELTP 28 Floor Experience\Resources and Links\AssetImport.txt", ForReading)
Set objFile2 = objFSO.CreateTextFile("S:\PBS\G & A Non-Host\ELTP 28 Floor Experience\Resources and Links\new.txt")

REM Do Until objFile.AtEndOfStream

    strLine = objFile.ReadLine

    arrFields = Split(strLine, vbTab)


    if (uBound(arrFields) = 1) then
        REM script to write header lines here
    Dim temp As String = RndStr
    objFile2.WriteLine arrFields(0)
    else
        REM scramble AssetID and Description Columns, then write

    end if

Wscript.echo arrFields(0)

REM Loop

objFile.Close
objFile2.Close




Rename multiple files randomly

I created a Menu to call this script that renames multiple text files randomly, it is only working in a .bat file alone. But it is not working in the context of the menu I created, I believe it's something to do with looping, since it only renames the first file! I would like someone to evaluate the situation, thank you very much already.

:4
cls

setlocal disableDelayedExpansion
set "chars=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
for /f "eol=: delims=" %%F in ('dir /b /a-d *.txt') do call :renameFile "%%F"
exit /b

:renameFile
setlocal enableDelayedExpansion
:retry
set "name="
for /l %%N in (1 1 8) do (
  set /a I=!random!%%36
  for %%I in (!I!) do set "name=!name!!chars:~%%I,1!"
)

echo if exist !name!.txt goto :retry
endlocal & ren %1 %name%.txt

)

pause
goto Menu
)

:5 < - here start the next option of menu
...




Segmentation fault using rand(): no such file or directory

I'm trying to implement a Fibonacci program that uses fork() and message queues while using getopt to set command line options for the nth Fibonacci number and 'm' computing threshold. So far, I get my program to compile but when I try to run it I get either Segmentation fault (11 or core dumped). I tried using gdb to debug it but I'm not having any luck. I'm just starting to learn about segmentation faults and gdb so any guidance will be greatly appreciated. Thanks!

main.c

    #include <stdlib.h>
    #include <stdio.h> 
    #include <unistd.h> 
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h> 
    #include <sys/stat.h> 

    int fib_seq(int x);

    int main(int argc, char **argv)  
    {

      int c, n, m, Fflag, Sflag; int x=0;

      pid_t pid; 

      //interprocess communication
      const int size=4096; 
      char *shared_memory; 

           int segment_id=shmget(IPC_PRIVATE, size, S_IRUSR|S_IWUSR);
           shared_memory= (char *)shmat(segment_id, NULL, 0); 

      //command line option entry
      while ((c=getopt(argc, argv, "F:S:")) != -1) 
           switch(c) 
             {
             case 'F':
               Fflag = 1;
               printf("test\n");
               n= atoi(optarg);
               break;
             case 'S':
               Sflag = 1;
               m= atoi(optarg);
               printf("n=%d\nm=%d\n", n, m);
               break;
             default:
                abort ();
             }

      //begin fibonacci sequence
      for(int i=0; i<=n; i+=1){

           fib_seq(x);
           x+=1;

           if (((x-1)>m)||((x-2)>m)){

           pid=fork();

           fib_seq(x); 
           x+=1; 

           }  
       }
    }

fib_seq.c:

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

    int extern x;

    int fib_seq(int x) { 

         srand(time(NULL));
         int i, rint = (rand() % 30); 
         double dummy; 

         for (i = 0; i < rint*100; i++) { 
           dummy = 2.3458*i*8.7651/1.234;
         }

         if (i == 0) return(0);
         else if (x == 1) return(1); 
         else return(fib_seq(x-1)+fib_seq(x-2));
    }

Makefile:

    # make all: compiles and links all files
    # make test: runs executable for prob1
    # make clean: cleans up .o and *~ files


    CC = gcc
    CFLAGS = -g -Wall -Werror -c
    OBJ = main.o fib_seq.o

    ################################  Make All  ####################################

    # Compiles all files
    all: main fib_seq
        $(CC) $(OBJ) -o myfib

    # Compiles object files
    main: main.c
        $(CC) $(CFLAGS) $@.c

    fib_seq: fib_seq.c
        $(CC) $(CFLAGS) $@.c

    ################################ Test ##########################################

    test: myfib
        ./myfib -F 6 -S 3

    #############################  Clean  ##########################################

    clean:
        $(RM) *.o *~ prob* $(SO)

gdb run:

    Program received signal SIGSEGV, Segmentation fault.
    0x00007ffff7a47b0f in __random () at random.c:293
    293 random.c: No such file or directory.

gdb list/where:

    (gdb) list
    288 in random.c
    (gdb) where
    #0  0x00007ffff7a47b0f in __random () at random.c:293
    #1  0x00007ffff7a47f69 in rand () at rand.c:27
    #2  0x00000000004008e5 in fib_seq (x=-135319) at fib_seq.c:8
    #3  0x000000000040098d in fib_seq (x=-135318) at fib_seq.c:17
    #4  0x000000000040098d in fib_seq (x=-135317) at fib_seq.c:17
    #5  0x000000000040098d in fib_seq (x=-135316) at fib_seq.c:17
    #6  0x000000000040098d in fib_seq (x=-135315) at fib_seq.c:17
    #7  0x000000000040098d in fib_seq (x=-135314) at fib_seq.c:17
    #8  0x000000000040098d in fib_seq (x=-135313) at fib_seq.c:17
    #9  0x000000000040098d in fib_seq (x=-135312) at fib_seq.c:17
    #10 0x000000000040098d in fib_seq (x=-135311) at fib_seq.c:17
    #11 0x000000000040099c in fib_seq (x=-135309) at fib_seq.c:17
    #12 0x000000000040098d in fib_seq (x=-135308) at fib_seq.c:17
    #13 0x000000000040098d in fib_seq (x=-135307) at fib_seq.c:17
    #14 0x000000000040098d in fib_seq (x=-135306) at fib_seq.c:17
    #15 0x000000000040098d in fib_seq (x=-135305) at fib_seq.c:17
    #16 0x000000000040098d in fib_seq (x=-135304) at fib_seq.c:17
    #17 0x000000000040098d in fib_seq (x=-135303) at fib_seq.c:17
    #18 0x000000000040098d in fib_seq (x=-135302) at fib_seq.c:17
    #19 0x000000000040098d in fib_seq (x=-135301) at fib_seq.c:17
    #20 0x000000000040098d in fib_seq (x=-135300) at fib_seq.c:17
    #21 0x000000000040098d in fib_seq (x=-135299) at fib_seq.c:17
    #22 0x000000000040098d in fib_seq (x=-135298) at fib_seq.c:17




Python - choice() takes 2 positional arguments but 13 were given

import string


import random

def generator():

    password = ""

    passwordlength = random.randint(8,12)

    length = 0

    while length < passwordlength:
        password = password + random.choice(string.digits + string.ascii_letters + "!","$","%","^","&","*","(",")","-","_","=","+")

        length = len(password)

    print(password)

generator()

I have this code here but when I run it, it immediately comes up with the error "choice() takes 2 positional arguments but 13 were given". I am clueless as to what's a fault




TSP GA parent and child route have same distance

here is the link to the code The fittest path generated has the same score(fitness) as the initial parent route even after, performing mutation() & crossover() on the parent random generated route. could it be due to the lose functioning of srand()? the code produces a check.txt in which it writes the fitness of parent route and it displays as output, the fitness of the best produced child route through iteration,mutation and crossover. help!enter code here




Is there a way to generate a random list of users using Instagram API or otherwise?

I'm trying to train a data model and would like a random list of Instagram users that I can manually review for desired characteristics.

I wasn't able to find any random list generator in the API or online. Other ways of finding users (have a certain word in their handle, hashtag something specific, follow someone specific) seem like they would create a biased dataset.

Open to any recommendations or hacks to get a pseudorandom list.




Randomly draw rows from dataframe based on unique values and column values

I have a dataframe with many descriptor variables (trt, individual, session). I want to be able to randomly select a fraction of the possible trt x individual combinations but control for the session variable such that no random pull has the same session number. Here is what my dataframe looks like:

trt <- c(rep(c(rep("A", 3), rep("B", 3), rep("C", 3)), 9))
individual <- rep(c("Bob", "Nancy", "Tim"), 27)
session <- rep(1:27, each = 3)
data <- rnorm(81, mean = 4, sd = 1)
df <- data.frame(trt, individual, session, data))
df
   trt individual session             data
1    A        Bob       1 3.72013685581385
2    A      Nancy       1 3.97225419000673
3    A        Tim       1 4.44714175686225
4    B        Bob       2 5.00024599458127
5    B      Nancy       2 3.43615965145765
6    B        Tim       2  6.7920094635501
7    C        Bob       3 4.36315054477571
8    C      Nancy       3 5.07117348146375
9    C        Tim       3 4.38503325758969
10   A        Bob       4 4.30677162933005
11   A      Nancy       4 1.89311687510669
12   A        Tim       4 3.09084920968413
13   B        Bob       5 3.10436190897144
14   B      Nancy       5 3.59454992439722
15   B        Tim       5 3.40778069131207
16   C        Bob       6 4.00171937800892
17   C      Nancy       6 0.14578811080644
18   C        Tim       6 4.20754733296227
19   A        Bob       7 3.69131009783284
20   A      Nancy       7  4.7025756891679
21   A        Tim       7 4.46196017363017
22   B        Bob       8 3.97573281432736
23   B      Nancy       8  4.5373185942686
24   B        Tim       8 2.40937847038141
25   C        Bob       9 4.57519884980087
26   C      Nancy       9 5.19143914630448
27   C        Tim       9 4.83144732833874
28   A        Bob      10 3.01769965527235
29   A      Nancy      10 5.17300616827746
30   A        Tim      10 4.65432284571663
31   B        Bob      11 4.50892032922527
32   B      Nancy      11 3.38082717995663
33   B        Tim      11 4.92022245677209
34   C        Bob      12 4.54149796547394
35   C      Nancy      12 3.21992774137179
36   C        Tim      12 3.74507360931023
37   A        Bob      13 3.39524949548056
38   A      Nancy      13 4.17518916890901
39   A        Tim      13 3.02932375225388
40   B        Bob      14 3.59660910672907
41   B      Nancy      14 2.08784850191654
42   B        Tim      14 3.98446125755258
43   C        Bob      15 4.01837496797085
44   C      Nancy      15 3.40610126858125
45   C        Tim      15 4.57107635588582
46   A        Bob      16 3.15839276840723
47   A      Nancy      16 2.19932140340504
48   A        Tim      16 4.77588798035668
49   B        Bob      17  4.3524768657397
50   B      Nancy      17 4.49071625925856
51   B        Tim      17 4.02576463486266
52   C        Bob      18 3.74783360762117
53   C      Nancy      18 2.84123227236184
54   C        Tim      18  3.2024114782253
55   A        Bob      19 4.93837445490921
56   A      Nancy      19  4.7103051496802
57   A        Tim      19 6.22083635045134
58   B        Bob      20  4.5177747677824
59   B      Nancy      20 1.78839270771153
60   B        Tim      20 5.07140678136995
61   C        Bob      21 3.47818616035335
62   C      Nancy      21 4.28526474048439
63   C        Tim      21 4.22597602946575
64   A        Bob      22 1.91700925257901
65   A      Nancy      22 2.96317997587458
66   A        Tim      22 2.53506974227672
67   B        Bob      23 5.52714403395316
68   B      Nancy      23  3.3618513551059
69   B        Tim      23 4.85869007113978
70   C        Bob      24  3.4367068543959
71   C      Nancy      24 4.47769879000349
72   C        Tim      24 5.77340483757836
73   A        Bob      25 4.78524317734622
74   A      Nancy      25 3.55373702554664
75   A        Tim      25 2.88541465503637
76   B        Bob      26 4.62885302019139
77   B      Nancy      26 3.59430293369092
78   B        Tim      26 2.29610255924296
79   C        Bob      27 4.38433001299722
80   C      Nancy      27 3.77825207859976
81   C        Tim      27 2.12163194694365

How do I pull out 2 of each trt x individual combinations with a unique session number? This is an example what I want the dataframe to look like:

       trt individual session             data
    1    A        Bob       1 3.72013685581385
    5    B      Nancy       2 3.43615965145765
    7    C        Bob       3 4.36315054477571
    12   A        Tim       4 3.09084920968413
    15   B        Tim       5 3.40778069131207
    17   C      Nancy       6 0.14578811080644
    19   A        Bob       7 3.69131009783284
    29   A      Nancy      10 5.17300616827746
    31   B        Bob      11 4.50892032922527
    34   C        Bob      12 4.54149796547394
    39   A        Tim      13 3.02932375225388
    40   B        Bob      14 3.59660910672907
    47   A      Nancy      16 2.19932140340504
    51   B        Tim      17 4.02576463486266
    54   C        Tim      18  3.2024114782253
    59   B      Nancy      20 1.78839270771153
    71   C      Nancy      24 4.47769879000349
    81   C        Tim      27 2.12163194694365

I have tried a couple things with no luck.

I have tried to just randomly select two trt x individual combinations, but I end up with duplicate session values:

setDT((df))
df[ , .SD[sample(.N, 2)] , keyby = .(trt, individual)]
    trt individual session             data
 1:   A        Bob      25  2.7560788894668
 2:   A        Bob      19 4.12040841647523
 3:   A      Nancy       4 5.35362338127901
 4:   A      Nancy      19 5.51636882737692
 5:   A        Tim      19 5.10553640201998
 6:   A        Tim       1 2.77380671625473
 7:   B        Bob      23 3.50585105164409
 8:   B        Bob       8 3.58167259470814
 9:   B      Nancy      23 2.85301307507985
10:   B      Nancy       8 2.85179395539781
11:   B        Tim      26 2.40666507132474
12:   B        Tim      20 3.31276311351286
13:   C        Bob      24 3.19076007024549
14:   C        Bob       3 3.59146613276121
15:   C      Nancy       9 4.46606667880457
16:   C      Nancy      15 2.25405252536256
17:   C        Tim      12 4.43111661206133
18:   C        Tim      27 4.23868848646589

I have tried randomly selecting one of each session number and then pulling 2 trt x individual combinations, but it typically comes back with an error since the random selection doesnt grab an equal number of trt x individual combinations:

ind <- sapply( unique(df$session ) , function(x) sample( which(df$session == x) , 1) )
df.unique <- df[ind, ]
df.sub <- df.unique[, .SD[sample(.N, 2)] , by = .(trt, individual)]
Error in `[.data.frame`(df.unique, , .SD[sample(.N, 2)], by = .(trt, individual)) : 
  unused argument (by = .(trt, individual))

Thanks in advance for your help!




Generating random number for class attribute

I have the following code:

from numpy import random

class Person():

    def __init__(self, name, age=random.randint(18,65)):
        self.name = name
        self.age = age

I want age to be a random number between 18 and 65, unless explicitly specified. However, when I create different instances of this class, like so:

p1 = Person('Bob')
p2 = Person('Sue')
p3 = Person('Jeff')

Each person always have the same age. How can I fix this?




python how to draw a variable again if it is the same as another variable

I have two lists, basically the same number

import random

A = [ 0, 10, 20, 30, 40 ] 
B = [ 0, 10, 20, 30, 40 ]
drawA =(random.choice(A))
drawB =(random.choice(B)) # want to exclude the number drawn in drawA

How can I ask python to draw again if drawB = drawA or simply how I can draw a number from list B excluding the number already drawn in list A.




Please help me with the code - trying to figure out for the whole night

Could anybody help with a code. I need my program to pick a number in between two numbers (min and max) that I had selected, then I have 5 tries to figure out which number he has in mind ... But the problem is that computer doesn't really interprete the limits right - picked number is sometimes outside of the extremes. min=3 max=6 - Why do I get as a result the correct number is 7?

The code is here:

import java.util.*;

public class Game1 {
         public static void main(String[] args) {
         Scanner sc = new Scanner(System.in); 

    int min = sc.nextInt();

    int max = sc.nextInt();

    System.out.println("insert a number");

        int rand = min + (int)(Math.random() * ((max - min) + 1));

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

        int number = sc.nextInt();

            if (number == rand){

                System.out.println("congratulations! :D");
                break;
            }

            else if (i < number){

            System.out.println("The number is too big");

            }

            else if (i > number){

            System.out.println("the number is too small");

            }

            else{

            System.out.println("Try again");

            }               

            }

        }

 }




mercredi 27 septembre 2017

I need Half Gauss Bell in Javascript

I have created a function that returns a Gaussian number between the minimum and the maximum that you put. The random subfunction gives a Gaussian number between 0 and 1, usually 0.5. I want to know if there is any way that the number tends to be 0. As if it were half gauss bell

function gaussianNumber(min, max, strength) {

function random(){
    var rand = 0;
    for (var i = 0; i < strength; i++) {
        rand += Math.random();
    }
    return rand / strength;
}

return Math.floor(random()*(max+1-min)+min);

}




Setting Applescript variable to list from text file

I'm new to Applescript and the world of coding in general. I'm trying small scripts to get my feet wet and have some fun.

I want to make a random prompt generator. I know how to set the variable to a list but what I have in mind is much bigger than a few choices. I was wondering how to get the information from a text file. In said file I have over 200 prompts to choose from. I want to make a script that selects a random one from among these and displays them in a dialog box. I'm having trouble setting the initial variable to the contents of the file as a list. The follow up (random selection) I think I have a pretty good grasp on. I hope this is clear and thank you for looking.




Get random subsample from pyfits data table

I have a very simple question, but Google does not seem to be able to help me here. I want a subsample of a pyfits table... basically just remove 90% of the rows, or something like that. I read the table with:

data_table = pyfits.getdata(base_dir + filename)

I like the pyfits table organization where I access a field with data_table.field(fieldname), so I would like to keep the data structure, but remove rows.




Write a function in php, which allows to randomly draw an element from a list

I would like to write a function in PHP which allows to randomly draw an element from a list according to defined probabilities.

For example:

For an argument with the input (x = 20, y = 15, z = 35, t = 30), the function should have a 20% chance for x, 15% for y, 35% for z and 30% for t

Any ideas?




Fastest way to generate random number from uniform distribtution python

I need to generate large(1 Million) number of random numbers from a uniform distribution. I did some experiments generating 60K random number from uniform distribution over [1-1000] using

scipy.stats.randint(0,1000).rvs(60000)

and it took ~0.6s. Then I tried same thing using boost library

boost::random::uniform_int_distribution

and it took ~0.25s. So my question is this- Are there better ways of doing what I want to do using python(libraries)? Any suggestions are greatly appreciated. Thanks.




Runif is not generating a uniform distribution

n_len <- 400000
jdc<- data.frame(rnd = numeric(n_len))
jdc$rnd <- runif(n_len,0,1)
ggplot(jdc,aes(x = rnd)) + geom_density()

ggplot output

As you will note the distribution of the rnd variable drops off towards both boundaries.

I am trying to sample based on some i less than rnd, but range of i is between 0, .05, thus this distribution is a problem.




C# Random Number

I'm building a random number generator and seeding it with two inputs from the user (numberEntry and integerEntry). I am also requiring the user to press a button for each new random number. I guess my question is this: will this generate a truly random sequence of numbers? Is there a better, more elegant way to do this? I'm new to C# so go easy on me (and my lowly code).

//kinda, sorta, psuedo-random number Method seeded with user inputs

static double NumberMashUp(double numberEntry, int integerEntry)
{
    double pseudoRandom;
    Random rnd = new Random();
    return numberEntry * (pseudoRandom = rnd.Next(1, integerEntry));
}




Fastest way to generate hash function from k wise independent hash family for small k(<=5)

I need a hash function h[n]:[t] from k wise independent hash family when k is small(<=5). Or I need n hash values from [1-t] coming from a hash function which comes from k wise independent hash family. I am trying to implement some randomized algorithms where I needed this. I was generating n random number from range [1-t] using scipy.stats.randint(0,self._t).rvs(self._n)
but this seems to be too slow for my application. Since I don't need full randomness but only 4 wise independence I was wondering if I could speed this up. I know I can use polynomial hash family to get k wise independence but is this the best? If yes are there any fast implementation of this which I can plug in? If no what are the alternative ways(libraries possibly in python)?
I have looked at this thread Obtaining a k-wise independent hash function but I am not sure what the accepted answer mean by this "if you need k different hash, just re-use the same algorithm k times, with k different seeds"
Any suggestions are greatly appreciated. Thanks




how do i get a random quiz of mine to give out a list of answers from people who have finished it?

ok so i need help with some python programming. I have a random quiz made and i don't know how to get a scoreboard which updates when someone finishes the quiz. Is this possible? Plz help

Players = []
Score = []
Name=str(input("What is your name?:  "))
Players.append(Name)
Age=int(input("What is your age?:  "))

import random

correct = 0
for count in range(10):
  num1 = random.randint(1, 10)
  num2 = random.randint(1, 10)
  symbol = random.choice(["+", "-", "*"])
  print("Please solve:\n", num1, symbol, num2)
  user = int(input(""))

  if symbol == "+":
    answer = num1 + num2
  elif symbol == "-":
    answer = num1 - num2
  elif symbol == "*":
    answer = num1 * num2

  if user == answer:
    print("Correct")
    correct = correct + 1
  else:
    print("Wrong")

print(Name, ", You Got", correct, "Out Of 10")
Score.append(correct)
list




cant generate random number in omnetpp

I have define host traffic send interval in this way in my NED file and I expect to receive different number in every execution:

    volatile double sendInterval @unit("s") = default(exponential(1s));

but it gives me same result in every execution, where is the problem?




Purpose random mix of data

I have one table vehicle_info.

m_id, x,            y,          z,        a
426,  2151.3999,    987.5999,   10.6,     0.0
415,  2132.8999,    1009.9,     10.6,     269.5
429,  2132.8999,    1025.8,     10.6,     270.0
411,  2163.3999,    1016.2,     10.6,     90.0
402,  2171.5,       1025.8,     10.6999,  90.25
560,  2141.8999,    1019.4,     10.5,     90.0
451,  2125.8,       987.5,      10.5,     0.0
603,  2185.8,       987.5999,   10.6999,  180.5
477,  2171.5,       1006.5,     10.6,     270.0
507,  2394.3999,    987.0,      10.8,     0.0`

Now I want to mix row m_id with rest of rows. For example, value 426 (first) mix with 507 (last), but without changing x, y, z, a, only m_id. After the change it would look like

m_id,   x,          y,            z,      a
507, 2151.3999,    987.5999,   10.6,     0.0
426, 2394.3999,    987.0,      10.8,     0.0`

Order isn't matter, simply I want to mix data by random. I tried RAND function, but it isn't what I want.

SELECT * FROM vehicle_info ORDER BY m_id, RAND()




mardi 26 septembre 2017

How to insert random number after text using sed

I'd like to insert a random number after specific text using a shell script. I can generate a random number (32 char):

cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 32 | head -n 1

How do I insert this random number (32_char_random_number) after text (e.g. "alphabet" in a file?:

sed '/\balphabet \b/& 32_char_random_number/' file

thanks.




Get Static Random Value with two seed

How do to get the same number every time assuming i have two seed and i want to get a random value between 1-99.

In c# there is a System.Random function but it use next() which mean i can't guess what number that came out assuming i know both seed. Is there another function in c# that able to accomplish my goal?

int gameSeed = 123;

public void GenerateAgeList(){
    GenerateAge(1); //Always return for example 23
    GenerateAge(2); //Always return for example 34
    GenerateAge(1); //Since the popSeed is also one also return 23
    for(int i = 1; i<5 ; i++){
        GenerateAge(i);
    } // Always return for example 23,34,10,...
}

public int GenerateAge(int popSeed){
    return unknownFunction(gameSeed,popSeed,1,99));
}




draw random circles using PIL in python

I'm having some problems to draw in python N numbers of circles of the same size in a XY tiff image. My progress is not to much, but I have the following code:

di = 0.25   # Diameter of circles in micrometers
d = np.round(di/0.065) # conversion to pixels
s = 512  #  Image size x
s1 = 512 #  Image size y



image = Image.new('RGB', (s, s1),'black')
TCZs = [50]

for n in TCZs:

    x = random.randint(0-d,s-d)
    y = random.randint(0-d,s-d)
    x1 = x+d
    y1 = y+d
    draw = ImageDraw.Draw(image)
    draw.ellipse((x,y,),(x1,y1), fill = 'red', outline ='red')


image.save('test.tif','tiff')

This code produce the following error:

TypeError: ellipse() got multiple values for argument 'fill'

I understand that this error is produced by my iteration, however I don't understand how to keep going with the solution. Some ideas? thanks in advance




PHP show random images from directory

I am kinda new to PHP.

I am searching a way to make PHP showing 6 random JPG images from a directory, no matter what the imagename is. The other important thing is that all the displayed images should be different.

Do you have any idea what's the easiest way to do it? I know i should use the glob function, but how to limit the images to 6,random and non repeatable?

I have that as code for the moment:

    <?php
$pictures = glob("images/gallery/*.jpg"); 
$no_pictures = count($pictures)-1;  
$limit = $no_pictures-5;            
for( $i = $no_pictures; $i >= $limit; $i--){ 
echo '<div class="col-md-4 col-sm-6 col-xs-12 wow fadeInUp">
        <a class="thumb" href="'.$pictures[$i].'"><img src="'.$pictures[$i].'" alt="Gallery"/><span class="thumb_overlay"></span></a>
    </div>'; 
}  
?>          

But on image refresh it's not displaying different images, it's just tooking random 6 and keep displaying them all the time.




Assigning random values to variables WITHOUT overlaps

i'm quite new to coding but i'm already in love.

I'm working on an (over)ambitious project but i need some help.

I'm trying to (in Python) assign 9 values (1-9) to 9 variables (the letters a-i), i have no clue how to do this and though research taught me how to assign them random numbers between those values, i don't manage to make them not overlap (other than sheer luck).

example of what i want randomly generated: a = 7 , b = 8 , c = 4 , d = 6 , e = 9 , f = 1 , g = 2 , h = 3, i = 5




Dynamically generate copies of DOM element and animate randomly with Greensock

I am trying to do the following with plain JS but can't get the for loop to work properly:

Objective: To fill the banner div with dynamically generated 'dot' divs that are placed at random positioned, then animate alpha in and out at random times.

http://ift.tt/2fxxI1N

var width = 300;
var height = 250;

function stars_tl() {
var banner = document.getElementById('banner'),
    star = document.getElementsByClassName('dot'),
    tl = new TimelineMax();

    for(var i=0; i<300; i++) {
     //console.log(i);
     banner.appendChild(star);
     var stars = star[i];

      TweenMax.set(stars, {
      autoAlpha:0,
      y:Math.random()*height,
      x:Math.random()*width
      });

      tl.to(stars, 0.5, {autoAlpha:1, yoyo:true, repeat:1}, 
      Math.random());

     }
}




How to write a unit test to ensure output is within certain limits?

If I have a requirement that says the output of a function must always be within certain limits, how can I test this if the function returns unpredictable results?

For example, lets say I have a function that generates random numbers or passwords; how can I test that the number is always between 1000 and 9999 or the password is always between 6-12 characters?

Let's use the number generator example - currently I would write two tests: one that runs the function in a finite loop and tests each result is >= 1000 and a second that ensures the output is <= 9999. Obviously the loop must be run a large number of times (>9K) for each test to have any chance of covering all the possible output values.

Are there any better approaches (i.e. ones that would be considered more reliable) when testing the output of unpredictable functions




Python: Trying to make random values during program run or indexable class

using Python 3.6.2

In this code I am making an Enemy class and calling a function that displays random values for it's variable Name, LVL, and health. This code works, but the random module will only work once when the program initializes. After that first time, every subsequent function call has the same values as the first.

How would I make it random every time while the program runs?

I will be calling this class from another code by importing it. It does not currently change every time I call it from the other code.

-

If I can't make this happen, how can I make my class indexable so I make it pseudo random by making new variables?

I've read that __ getitem __ and __ setitem __ would help me index but i don't know how to implement it as I really don't know much about it or what it does. I've tried reading about it but I don't seem to grasp the concept.

Here is my code:

import random as rnd

class enemy():

    def __init__(self, name, level, health):

        self.name = name
        self.level = level
        self.health = 20+(5*self.level)

Forest = ['Wolf', 'Bear', 'Bandit', 'Hunter']

Plains = ['Bandit', 'Large Bird', 'Lion']

City = ['Thiefs', 'Rats', 'Guards']



EnemyStart = enemy(rnd.choice(Forest), rnd.randint(1,2), [])
EnemyLow = enemy(rnd.choice(Plains), rnd.randint(3,5), [])
EnemyCh1 = enemy(rnd.choice(City), rnd.randint(6,8), [])

Count=0

def ResetCond():
    Count+=1
    EnemyStart = enemy(rnd.choice(Forest), rnd.randint(1,2), [])
    EnemyLow = enemy(rnd.choice(Plains), rnd.randint(3,5), [])
    EnemyCh1 = enemy(rnd.choice(City), rnd.randint(6,8), [])
    return Count

##if using index I would have this instead in the 
##ResetCond----EnemyStart[Count]=----
##----print(EnemyStart[count].name)----
## repeat for all similar variables
##But this gives me error object enemy is not indexable.

def DisSE():
    print (EnemyStart.name)
    print ('LVL:', EnemyStart.level)
    print ('HP:', EnemyStart.health)

def DisLE():
    print (EnemyLow.name)
    print ('LVL:', EnemyLow.level)
    print ('HP:', EnemyLow.health)

def DisC1E():   
    print (EnemyCh1.name)
    print ('LVL:', EnemyCh1.level)
    print ('HP:', EnemyCh1.health)


DisSe()
DisLe()
DisC1E()

print()

DisSe()
DisLe()
DisC1E()

print()

DisSe()
DisLe()
DisC1E()




Picking random numbers from array without duplicate picks

I have a program that will pick random numbers from an array. I need to modify it so it will not pick duplicate numbers (numbers can only appear once in the array). Possibly could I add the already picked values to another array and check if the value exists in both arrays? Any tips are appreciated, thank you.

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

int main() {
int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int size = 10;
int numDigits = 5;
int temp;
int x;
int finalArray[] = {};
srand(time(0));


for (int i = 0; i < 5; i++) {
    array[i] = rand() % 10;
}

for (int i = 0; i < 5; i++) {    // shuffle array
    int temp = array[i];
    int randomIndex = rand() % 10;

    array[i]           = array[randomIndex];
    array[randomIndex] = temp;
    finalArray[i] = array[randomIndex];



}

for (int i = 0; i < 5; i++) {    // print array
    printf("%d,",array[i]);
}

}




How to check if something printed using random module is repeated?

This is my code so far:

import random

words = ['a', 'b', 'c']
def abc():
    print(random.choice(words))
    input('Press Enter to Continue')
    abc()
abc()

How can I make it so every time it prints a word from the list words, it checks if it has been repeated before? I would prefer the answer being either in python without modules or with the random module.




Using System Time For Random Number Generator Seed

I am creating a random number generator that picks out random numbers from an array. I am used to using Java and not having to worry about the srand seed. How can I make my program use the system time as a seed so every time upon running my program has a new seed (time) for the random number generator.




Generating an array of random variables (positive and negative) that sum up to 1

I am trying to create a numpy array with random variables that sum up to 1, but I also want to include negative values.

I am trying:

size =(50,1)
w = np.array(np.random.random(size))

to create the array and populate with numbers (negative and positive), and this works fine.

Now I am trying to make them sum up to 1 with:

w /= np.sum(w)

But this changes my values to be all positive (eliminating the negative values).

What is the proper way to do an array like this?




How to random struct array?

I've been trying with no result to pick a random question from a struct array.. Can someone help me doing this?

I have an ImageView on the left side of the display, and 3 answers on the right. And I'm trying to make a random load from this array.. and load a new image with their answers each time i press Next. If it's possible.. i'd like to load only 15 questions with no repeat..

Here is my struct code..

var currentQuestion: Question?
var currentQuestionPos = 0

struct Question {
    let image: UIImage
    let answers: [String]
    let correctAnswer: Int
    let corect: String
}

var questions: [Question] = [
    Question(
        image: UIImage(named: "palla")!,
        answers: ["cerchio", "palla", "aereo"],
        correctAnswer: 1,
        corect: "palla"),
    Question(
        image: UIImage(named: "guanto")!,
        answers: ["guanto", "maglietta", "calzino"],
        correctAnswer: 0,
        corect: "guanto"),
    Question(
        image: UIImage(named: "casa")!,
        answers: ["albero", "macchina", "casa"],
        correctAnswer: 2,
        corect: "casa"),
    Question(
        image: UIImage(named: "cerchio")!,
        answers: ["cerchio", "sole", "palla"],
        correctAnswer: 0,
        corect: "cerchio"),
    Question(
        image: UIImage(named: "lego")!,
        answers: ["bambola", "lego", "panino"],
        correctAnswer: 1,
        corect: "lego"),
    Question(
        image: UIImage(named: "chiavi")!,
        answers: ["porta", "pizza", "chiavi"],
        correctAnswer: 2,
        corect: "chiavi"),
    Question(
        image: UIImage(named: "tazza")!,
        answers: ["tazza", "forchetta", "piatto"],
        correctAnswer: 0,
        corect: "tazza"),
    Question(
        image: UIImage(named: "aereo")!,
        answers: ["bicicletta", "gelato", "aereo"],
        correctAnswer: 2,
        corect: "aereo"),
    Question(
        image: UIImage(named: "macchina")!,
        answers: ["televisore", "macchina", "pattini"],
        correctAnswer: 1,
        corect: "macchina"),
    Question(
        image: UIImage(named: "libro")!,
        answers: ["scatola", "foglio", "libro"],
        correctAnswer: 2,
        corect: "libro"),
    Question(
        image: UIImage(named: "piano")!,
        answers: ["piano", "chittara", "arpa"],
        correctAnswer: 0,
        corect: "piano"),
    Question(
        image: UIImage(named: "dadi")!,
        answers: ["dadi", "ghiaccio", "cubo"],
        correctAnswer: 0,
        corect: "dadi"),
    Question(
        image: UIImage(named: "pizza")!,
        answers: ["hamburger", "panino", "pizza"],
        correctAnswer: 2,
        corect: "pizza"),
    Question(
        image: UIImage(named: "palla")!,
        answers: ["cerchio", "palla", "aereo"],
        correctAnswer: 1,
        corect: "palla")
]

Thanks, Radu




Which programming language to use for a random generator?

If we want to create a random generator, which programming language should we choose? Regarding interoperability and security.

Thinking about ex.: Devs unknowingly use “malicious” modules snuck into official Python repository: http://ift.tt/2wxfRdC




lundi 25 septembre 2017

Generate random points above and below a line in Python

I would like to generate random points on an x,y scatter plot that are either above or below a given line. For example, if the line is y=x I would like to generate a list of points in the top left of the plot (above the line) and a list of points in the bottom right of the plot (below the line). Here's is an example where the points are above or below y=5:

import random
import matplotlib.pyplot as plt

num_points = 10
x1 = [random.randrange(start=1, stop=9) for i in range(num_points)]
x2 = [random.randrange(start=1, stop=9) for i in range(num_points)]
y1 = [random.randrange(start=1, stop=5) for i in range(num_points)]
y2 = [random.randrange(start=6, stop=9) for i in range(num_points)]

plt.scatter(x1, y1, c='blue')
plt.scatter(x2, y2, c='red')
plt.show()

Random point plot

However, I generated the x and y points independently, which limits me to equations where y = c (where c is a constant). How can I expand this to any y=mx+b?




Processing draw() stalls as soon as accept data via serial port

I build up a lab to test random number generator in MCU. MCU generates randrom in the range of (0,255), and send them to PC. In PC, I wrote a processing pde to read line by line and draw them as x,y to draw the random points.

My MCU prints out as following:

141,188
255,198
193,224
83,138
53,68
231,142
233,232
187,210
221,204
207,86
17,240
...

The random numbers are printed as "%d,%d\r\n". So far RNG in MCU works well.

In PC processing pde code, if I use Math.random() as local RNG, it works well, if I read each line and print to console, it works well, too. However if I merge them together, the draw() will draw some points and then stalls.....

/*
 * Random_Serial_2D.pde
 */

import processing.serial.*;
import java.util.StringTokenizer;

Serial myPort;  // The serial port
String inString = null;

void setup() {
  size(256, 256);

  noSmooth();
  background(0);
  translate(0,0);

  stroke(255);

  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[0], 9600);
}

void draw() {
  int x, y;
  String[] sa = null;
  int sz;

  while (myPort.available() > 0) {
    myPort.bufferUntil('\n');
    if (inString != null){
      //print(inString);
      inString = inString.replace("\r\n","");
      sa = inString.split(",");
      sz = sa.length;

      if (sz==2){
        x = Integer.parseInt(sa[0]);
        y = Integer.parseInt(sa[1]);        
        point(x,y);      
      }
      inString = null;
    }
  }
}

void serialEvent(Serial p){
  inString = p.readString();
}

I picked Processing because it is designed for interaction, maybe there is a bug in the code, but I have no clue about it.

Should I implement it as two seperate threads, one for reading and push to queue, and the other for drawing?




Split a String variable into a random substring with a specified length

In java. It should use the random number generator to return a randomly chosen substring of text that has the specified length. If the length is either negative or greater than the length of text, the method should throw an IllegalArgumentException. For example, chooseSubstring("abcde", 4, new Random()) should return "abcd" about half the time and "bcde" about half the time.

public static String chooseSubstring (String text, int length, Random rand)
{
    int randomNum = rand.nextInt(length);
    String answer = text.substring(randomNum);
    return answer;
}

Basically, I want to return a substring from the variable text. The substring must be the length of the variable length. The beginning of this substring should start at a random location determined by a random number generator. My problem is that the random number generator is not making sure the substring is the correct length.

        System.out.println(chooseSubstring("abcde", 4, new Random()));

Should return abcd and bcde about the same amount of times. Instead it is returning: bcde cde de abcde. Any info about how to solve this would greatly help thanks!




Shell Sort of Array Filled with Random Integers, c++

having a lot of trouble trying to implement a shell sort on an array filled with random numbers (using c_time). The size of the array is given by user input but is never less than ten, and there is no limit to how large the numbers are.

I am fairly certain that the issue is the swapping part of the algorithm because even though I have chosen a proper gap, my method of doing so has left me fairly confused as to how to reposition the intended values. Here is my code:

void sort(T a[], size_t n, U cmp) {                                             //init gap, counter, and pointer variables
int gap, j;
int z = a[n-1];
int b = a[n - 3];
int c = a[n / 2];
int d = a[1];
static int gap_sequence[] = { z,b,c,d };

for (int i = 1; gap = gap_sequence[i]; i++)
    std::cout << gap_sequence[i] << "  ";
     {                                  //gap is various elements in array
    for (int i = 0; i < n; i++) {   
        for (j = 0; gap < a[j]; j++) {  //loop means the swap only happens if j is bigger than the selected gap
            if (j == 0) {
                std::swap(a[j], a[n-1]);
            }
            else
            std::swap(a[j], a[j-1]);
        }
    }
}

}

I am also thinking that because the gaps are in an unsorted order the sort isn't really sorting in relation to anything. But if so, how do I chose my gap values?

Like I said, I'm not sure how to go about finding the index of the gap again. Maybe this method is completely wrong and I'm an idiot, I don't know. I am very much still in the learning process and am all alone here. If anyone could help me out I'd very much appreciate it. If you want my testing algorithm then please let me know.




Searching for answer, found after six years binary is not minimalistic

I have found a mapping technique that allows me to compress random and non random numbers by as much as 15%...i have been searching for this answer for over six years. What do you suggest should be my next step. This transform which i choose not to give away at this time works on any stream of high or low entropy.

Awaiting your answer

Jon Hutton




numpy.random.normal() generates the same set of values when called repeatedly in a loop

My goal is to generate a different set of values using numpy.random.normal(). I have the above inside a function() which is called repeatedly inside a loop. The setup looks something similar to the following when stripped down:

import numpy as np

def errorFn():
    val =  np.random.normal(0, 5., 10)
    print val

for i in range(5):
    errorFn()

And when I run this particular bare-bones version of my program it works as expected and gives me a different set of values every time.

However my actual program is much more complex, and use a ton of additional parameters, functions and the like. But when I put the same exact np.random.normal(0, 5., 10) inside of a function in my code (note that the values I pass to normal() does not depend on any other parameters and are constants.), it generates the exact same set of values every time. Following is how it looks like:

def myFunction(#multiple parameters here):
    # Additional stuff
    print np.random.normal(0, 5., 10)

# call the function like so:

for t in range(5):
    # lots of other stuff
    # myFunction()

What could be the problem? I have defined the functions in a separate script and import them in my program. Could that be the reason? Any help is greatly appreciated.




How to display my random number to the screen -- C#

I don't know how to do this. I want to display my random number to the Console screen, but I don't know how. I have researched, but I can't find an answer.
Here is my code: Click this link for image of my code




Quantum Fuzzy Logic Random 5 Number Generator

Essentially I believe random doesn't really exist and that all events and numbers has a frequency. I want to use random generator with a text file of known numbers to manipulate a known frequency of numbers (without human bias). Where the two ideas meet results in a projection of future outcome. So, what code can randomly select a number from a txt file list of numbers? 1. Numbers are in no particular order 2. The amount of numbers in the text file can vary each execution -So, it needs to count the amount each time to prevent overflow 3. The goal is to randomly pick 5 different numbers from the text file




Javascript string to object error? random array var not aloowed

I want create a array from array by random, but i'm starting on javascript. Here is my question.

//array
var t = ["house","pen","table","eletronic"];

//-> selected a name option 0

var w = t[0]; // selected

var x = w;
var y = 0 to 3; // random

var house =["red","blue","orange","black"];
var pen   =["silver", "gold", "cooper","plastic"];
var table =["marble","oak","yep","pine"];
var eletro=["computer","mobile","mac","tablet"];


// what i wish
var z = house[0]; // return red  // x = typeof return object

//x this is the error type string not reconize list array querry
var z = x[y]; // x = typeof return string 
var z = "house"[0]; // return h - return string - not object

//after make a defaut

var a = x[y]; //y != y
var b = x[y]; //y != y

document.getElementById("demo1").innerHTML=z; // blue house;
document.getElementById("demo2").innerHTML=a; // silver pen;
document.getElementById("demo3").innerHTML=b; // marble table;
<p id "demo1"></p>
<p id "demo2"></p>
<p id "demo3"></p>

I think i must convert doble quotes - "house" - string to object - house - to convert to a var and before feed the system?




Java Random number getting repeat issue

I have a system which communicate to external system via webservices in which we used to send random nos as msg id and same is getting stored as a primary key of table in our database. Problem here is since we have approx 80-90 k call on daily basis i have seen so many exceptions saying that duplicate primary key. I am generating random nos in java. How can i be sure that whatever random number i will generate will not be duplicated.

below is code for the generating random nos:

private static int getRandomNumberInRange(int min, int max) {

    if (min >= max) {
        throw new IllegalArgumentException("max must be greater than min");
    }

    Random r = new Random();
    return r.nextInt((max - min) + 1) + min;
}




How do I write a Python Password Checker and Generator Program

The program needs to let the user check the strength of passwords and generate strong passwords. The program should check the strength of a password based on a point scoring system. So, once a pw is entered points are awarded based on the length of the pw and the types of characters in the pw.

5 points are given if the pw contains at least 1 UC letter, 1 LC letter, 1 digit (o-9) and one of the allowed symbols. If the password contains at least one of all of these then an additional 10 points are added.

5 points are deducted if the pw only contains 1 UC and LC letter, contains only digits, contains only one of the allowed symbols, if the pw contains three consecutive letters based on the layout of a QWERTY keyboard then 5 points are deducted from the score for each set of three. E.g- tYu= -5 or asdFG=-15

The point score is then used to show if the pw strength is weak, medium or strong. If the point score is >20 then its strong. If the point score is 0 or less than 10 the pw is weak. The pw strength and point score should be displayed to the user. Then they should be returned to the menu.

Password Checker Program -It has to check the pw only contains: Uppercase Letters, Lowercase letters, digits(0-9) and symbols(!"£$%^&*()-+ ). If a prohibited character is in the pw an error message is displayed and the user is returned to the menu. A point score is calculated for the entered pw. the score is set to the length of the pw. E.g- if the pw is 12 characters long then score is 12)

Generating password program- the program must generate a random number between 8 and 12. this number will be the length of the pw. Then the program must generate a random sequence of characters using letters, digits and allowed symbols to make a pw of the length generated. This should be repeated until the pw is strong. The generated pw and point score should then be displayed and the user is returned to the menu.

If anyone can write this whole program out for me in PYTHON in a fairly simplied form that would be great I am currently doing a course in Computing at college and I am struggling.




Intel DRNG giving only giving 4 bytes of data in stead of 8

I am trying to implement Intel DRNG in c++.

According to its guide to generate a 64 bit unsigned long long the code should be:

int rdrand64_step (unsigned long long *rand)
{
    unsigned char ok;
    asm volatile ("rdrand %0; setc %1"
                  : "=r" (*rand), "=qm" (ok));
    return (int) ok;
}

However the output of this function rand is only giving me an output of only 32 bits as shown.

        bd4a749d
        d461c2a8
        8f666eee
        d1d5bcc4
        c6f4a412

any reason why this is happening?

more info: the compiler I'm using is codeblocks




Why are the mean values not much closer to the original weightings?

I run the following program and a typical console output is as follows.

Mean percentage points for weighting 0 is: 57.935590153643616
Mean percentage points for weighting 1 is: 42.06440984635654

Why are these printed means not much closer to 60 and 40?

public static void main(String[] args) {
    Random rand = new Random();

    int numCycles = 5000;

    double[] weightings = {60.0, 40.0};
    double[] weightedRandoms = new double[weightings.length];
    double[] totPercentagePoints = {0.0, 0.0};

    for (int j = 0; j < numCycles; j++) {

        for (int k = 0; k < weightings.length; k++) {
            weightedRandoms[k] = (rand.nextInt(10) + 1) * weightings[k]; // +1 to the random integer to ensure that the weighting is not multiplied by 0
        }

        for (int k = 0; k < weightings.length; k++) {
            totPercentagePoints[k] += weightedRandoms[k] / DoubleStream.of(weightedRandoms).sum() * 100;
        }
    }

    for (int i = 0; i < weightings.length; i++) {
        System.out.println("Mean percentage points for weighting " + i + " is: " + totPercentagePoints[i] / numCycles);
    }
}




How do you divide a list (indefinite length) randomly into 3 subgroups?

Lets say that my program asks a user to input a number indefinitely and I appended it in a list.

#Given Example:
List = [105, 167, 262, 173, 123, 718, 219, 272, 132]

what I wanted to do is to randomly pick any of the numbers so my sample output would be:

first = [105, 262, 173]
second = [167, 123, 132]
third = [718, 219,272]

Having said, since the user input would be indefinite there will be chances that it would be an odd number.

I am currently using random.sample to choose a number from that list and append it in a list, after that I'll append the sub-groups of list to create a list within a list.

Would be a great help if anyone answers, thanks!




Mongoose get a random element except one

I have a collection of articles in mongodb. I choose an article that i want to render, and I want two other articles chosen randomly. I want to pick two articles in my collection that are not the same, and are not the article I have chosen before. Been on this problem for hours, search for a solution but only found how to pick an element randomly, but not except one...

Here is what I have now :

article.find({}, function(err, articles{   
    var articleChosen = articles.filter(selectArticleUrl, articleUrl)[0];
    article.find({})
    .lean()
    .distinct("_id")
    .exec(function(err, arrayIds){  
      var articleChosenIndex = arrayIds.indexOf(articleChosen._id);
      arrayIds.splice(articleChosenIndex, 1);
      chooseRdmArticle(arrayIds, function(articleRdm1Id){
        var articleRmd1 = articles.filter(selectArticleId, articleRdm1Id)[0];
        var articleRdm1Index = arrayIds.indexOf(articleRdm1Id);
        arrayIds.splice(articleRdm1Index, 1);
        chooseRdmArticle(arrayIds, function(articleRdm2Id){
          var articleRmd2 = articles.filter(selectArticleId, articleRdm2Id)[0];
          // do stuff with articleChosen, articleRmd1 and articleRmd2
        })
      })
    })
  })

where the function which choose rdm article is :

function chooseRdmArticle(articles, callback){
  var min = Math.ceil(0);
  var max = Math.floor(articles.length);
  var rdm = Math.floor(Math.random() * (max - min)) + min;
  callback(articles[rdm])
}

and the function which select the article from its url is :

function selectArticleUrl(element){
  return element.url == this
}

My idea was to work on the array containing all the ObjectId (arrayIds here), to choose two Ids randomly after removing the articleChosen id. But I understood that arrayIds.indexOf(articleRdm1Id); couldn't work because ObjectIds are not strings ... Is there a method to find the index of the Id I want? Or any better idea ?

Thanks a lot !




dimanche 24 septembre 2017

Generating a random value between a set range in java [duplicate]

This question already has an answer here:

I am currently working on a java project that requires me to generate a random percentage within a range values a high (stored in a variable called max) and a low (stored in a variable of min) I am fairly new to java and cannot figure out the errrors i am getting, when I am able to get the code to compile it generates a 0.0. Any help would be appreciated.

public static void runSimulation() {
    Random randInvest = new Random();
    randInvest = minSalRange + (float)(Math.random() * maxSalRange);
    System.out.println("The random generated number was"+randInvest);
}

Here is the version I am able to run which kicks out 0.0 every time

public static void runSimulation() {
    randInvest = minSalRange + (float)(Math.random() * maxSalRange);
    System.out.println("The random generated number was"+randInvest);
}




Random 'GUID' and Possible Duplicates

(I am using 'guid' as a term for a random series of letters/numbers.)

I am using a function to create a GUID that will be unique. The function is:

function guid() {
    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X',
                  mt_rand(0, 65535), mt_rand(0, 65535),
                  mt_rand(0, 65535), mt_rand(16384, 20479),
                  mt_rand(32768, 49151), mt_rand(0, 65535),
                  mt_rand(0, 65535), mt_rand(0, 65535));
  }

This returns a value like 'A881264F-AB87-4592-BFC1-714AFFDEE698'. The function is used to assign a (hopefully) unique filename to an uploaded picture. (The actual image file name is stored along with the GUID value in a row in the table.) The intent is that each picture's file name will be unique.

This has worked well in this application for several years. Lately I've been getting what I think are duplicate file names, so that a record doesn't point to the original picture filename, but a newer picture that randomly got (re-used) an existing filename.

I am aware that I may need to add additional characters to the filename, like a date/timestamp, so that I can ensure that the filename is (and always will be) unique.

My question is related to the 'chances' of there being a duplicate GUID generated over a long period of time.

Assuming that the GUID is created as the function above, and results are like 'A881264F-AB87-4592-BFC1-714AFFDEE698', what are the chances (maybe not the right term) that the function might come up with the same result?

Note that this is not about 'how many' different results there will be, but what are the chances that the function will return the same result?




Calculating variance of a simple expression with sympy random variables

Two U(0,1) random variables, X1 and X2, and I want the variance of max(2,X1)+X2.

And I want it using sympy. Yes, I know it's too easy. However, I would like to know if there are built-in ways of handling problems like this one, and how to use them.

>>> from sympy.stats import Uniform, Variance
>>> from sympy import symbols, Integral
>>> X1 = Uniform('X1', 0, 1)
>>> X2 = Uniform('X2', 0, 1)

sympy seems to dislike max; it expresses the same distaste for the if statement.

>>> Variance(max(2, X1) + X2)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python34\lib\site-packages\sympy-1.0.1.dev0-py3.4.egg\sympy\core\relational.py", line 195, in __nonzero__
    raise TypeError("cannot determine truth value of Relational")
TypeError: cannot determine truth value of Relational

The problem is trivial, though, and I could simplify it sufficiently.

>>> Variance(2 + X2)
Variance(X2 + 2)
>>> Variance(2 + X2).evaluate_integral()
1/12

I am usually pretty thick unfortunately. How would I handle probability calculations involving conditionals?




R - how to pick a random sample with specific percentages

This is snapshot of my dataset

A B
1 45 1 67 1 56 0 55 0 10 0 34 0 98 I am trying to create a sample where there are 2 1s and 3 0s in the sample along with their respective B values. Is there a way to do that? Basically how to get a sample with specific percentages of a particular column? Thanks




Multiple if statements to categorize a random number in a partitioned interval

I am partitioning a random number to be in one of 2 cases to simulate a roll of a die. The problem is that sometimes, there is more than one step per loop. Please see the MWE below:


    count = 0
    n = random.random()

    while count = 1/2:
            n = random.random() # generate a new random number
            print("   Tails")

        count = count + 1

Output


    Count = 0
       Heads
       Tails
    Count = 1
       Heads
    Count = 2
       Heads
       Tails
    Count = 3
       Heads
       Tails
    Count = 4
       Heads
    Count = 5
       Heads
    Count = 6
       Heads
       Tails
    Count = 7
       Tails
    Count = 8
       Tails
    Count = 9
       Tails
    Count = 10
       Tails




2D random walk fill all cells (java)

Simulate how many steps its take a random walker starting at the center of an 10x10 grid to visit every cell of the grid. If the walker tries to go outside of the grid then it doesn't move in that step. Write a java program which simulates th steps of the random walker, and keeps hold about the grid with 2D boolean array and write out the steps when the random walker have walked all the cells.

But I have two problems. The walker seems to walk outside of the array/grid.

And it keeps counting the steps when it walks outside of the grid.

The code should not count the step when he tries to go outside of the grid. Any idea how I can fix it?

The code I've come up with so far is:

public class RandomWalk { 

public static void main(String[] args) {
    int n = Integer.parseInt(args[0]);
    int[] x = new int[n];
    int[] y = new int[n];
    int cellsToVisit = n*n;
    int steps = 0;
    boolean[][] a = new boolean[n][n];

    for(int i = 0; i < n; i++) {
        x[i] = n/2;
        y[i] = n/2;
    }
    a[n/2][n/2] = true;
    cellsToVisit--;

    while (ctv > 0) {

        double r = Math.random();
        for(int i = 0; i < n; i++) {
            if(r < 0.25){ 
                x[i]--;
            } else if(r < 0.50){
                x[i]++;
            } else if(r < 0.75){ 
                y[i]--;
            } else if(r < 1.00){ 
                y[i]++;
            }

            if(x[i] < n && y[i] < n && x[i] >= 0 && y[i] >= 0 && !a[x[i]][y[i]]) {
                cellsToVisit--;
                fylki[x[i]][y[i]] = true;          
            }

            steps++;
           System.out.println(cellsToVisit + "     " + steps + "    " + x[i] + " " + y[i]); 
        }
    }
    System.out.println(steps);
}

}




Generating Random Numbers Under some constraints

I happen to have a list y = [y1, y2, ... yn]. I need to generate random numbers ai such that 0<=ai<=c (for some constant c) and sum of all ai*yi = 0. Can anyone help me out on how to code this in python? Even pseudocode/logic works, I am having a conceptual problem here. While the first constraint is easy to satisfy, I cannot get anything for the second constraint.




Create random resource name in Terraform

I'm using Terraform to create stuff in Azure,

In ARM I used to use uniqueString() to generate storage account names,

So is it possible to generate random name for storage account using Terraform?




Generating Random string

Can anyone tell me how can I generate a random string containing only letters in c#? I basically want a Random value and fill it in my form. I want this value to contain letters only? How can I do this?




Generating "random" number after creating the Random instance [duplicate]

This question already has an answer here:

In my project, players can perform an action and this action requires a random number to count the chance.

I use the following code:

 int random =new Random().Next(3, data.Length);

but of course, this yields the same results (I guess because it is everytime created and queried, the result are always 1 or 2.

Is there a way to create Random instance and let it produce truly random (different than in previous runs) number?




How to save a struct, so that even when the app is closed the values don´t change?

I want to save my struct, so that the order of the items doesn´t get changed if the user closes the app. When he opens it again the order should continue, like he has never left.

Here is my code:

 struct RandomItems
    {
        var items : [String]
        var seen  = 0
        
        init(_ items:[String])
        { self.items = items }
        
        mutating func next() -> String
        {
            let index = Int(arc4random_uniform(UInt32(items.count - seen)))
            let item  = items.remove(at:index)
            items.append(item)
            seen = (seen + 1) % items.count
            return item
        }
    }



Random time between to `LocalTime` (or `UTCTime`) in Haskell

I'm running round in circles with the need to generate a random time between two given LocalTime values (but this can be UTCTime if necessary, as I can convert).

I achieve the generation of a number in the range (0, n) like this:

randomSeconds :: RandomGen g => g -> NominalDiffTime -> NominalDiffTime
randomSeconds rg max = realToFrac $ fst (randomR (0, max) rg)

and this is used like so:

randomTimeBetween :: RandomGen g => TimeZone -> LocalTime -> LocalTime -> g -> UTCTime
randomTimeBetween tz s e rg = addUTCTime (randomSeconds rg (diff tz s e)) (localTimeToUTC tz s)

where diff is

diff :: TimeZone -> LocalTime -> LocalTime -> NominalDiffTime
diff tz st en = diffUTCTime (localTimeToUTC tz st) (localTimeToUTC tz en)

However I'm in the endless cycle of compilation errors where it could not deduce Random NominalDiffTime or can't convert from NominalDiffTime because there's no instance for (Fractional Int) etc

What's the most appropriate/simplest/whatever way of me generating a random NominalDiffTime so I can then add that amount using addUTCTime x utc?




samedi 23 septembre 2017

How to count number of values in the randomly generated list?

I have created a random list by below command:

import random a=[random.randrange(0,100) for i in xrange(50)] print a

Now, what could be the command for counting the number of values that are between 0 and 9, 10 and 19, 20 and 29, and so on.

I can print them as below:

import random a=[random.randrange(0,100) for i in xrange(50)] for b in a: if 10

But, I don't know how to write a command to count the number of the values after printing b. Thanks for your comments.




Select random item and index using numpy.random.choice()

I tried to implement the numpy.ramdom.choice() on a list, but I'm getting the following error:

ValueError: a must be 1-dimensional

I have the following list of values like: [-0.192, 0.23923, 0.8271, .... 0.229]

and I want to select one those elements randomly. I also need to retrieve the index of that random element, but I'm failing on the first step.

My code block is:

        values = []
        values.append(np.corrcoef(X, Y)[-1, :-1])

        i_column = np.random.choice(values)

Any advice with explanation is more than welcome.

Thanks




Cannot display a random image file

I am trying to write some code that will play a sound, ask the user to identify the correct sound, and then show the image if the user is either correct or wrong. However, when I do so I get this error:

Traceback (most recent call last): File "C:\LearnArabic\Program\LearnArabicprogram2.4.1.py", line 42, in answers(question, possAnswers) File "C:\LearnArabic\Program\LearnArabicprogram2.4.1.py", line 37, in answers label = Label(master, image=IL, anchor = E) File "C:\Program Files (x86)\Python36-32\lib\tkinter__init__.py", line 2760, in init Widget.init(self, master, 'label', cnf, kw) File "C:\Program Files (x86)\Python36-32\lib\tkinter__init__.py", line 2293, in init (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: image "C:\LearnArabic\alphabet\Image\Dal.png" doesn't exist

The program currently opens a blank tk window but as the error suggests, no image is displayed. I've tried using png files and gif files but I get the same error. Why doesn't it recognize my file path?

Here is my code:

import os, random
from random import choice
import winsound
import time
from tkinter import *

master = Tk()

question = "What is the correct Arabic letter?"

Imagepath = "C:\\LearnArabic\\alphabet\\Image\\"         
Soundpath = "C:\\LearnArabic\\alphabet\\Sound\\"
Letter = random.choice(os.listdir(Soundpath))               
winsound.PlaySound((Soundpath)+ (Letter), winsound.SND_FILENAME)

def answers(question, possAnswers):
    print(question)
    answerList = ["answer1", "answer2", "answer3", "correct"]
    random.shuffle(answerList)

    for i,j in enumerate(answerList):
        print("%s: %s" %(i, possAnswers[j]))

    inp = int(input(">>> "))

    if answerList[inp] == "correct":
        print("Correct!")
        IL = (Imagepath + (Letter.rsplit(".", 1)[0])+ ".png")
        label = Label(master, image=IL, anchor = E)
        label.image = (IL)
        label.grid(row = 2, column = 0, sticky = S)

    if answerList[inp] != "correct":
        print("Try again fool")
        print("The corect answer was: ", Letter)
        IL = (Imagepath + (Letter.rsplit(".", 1)[0])+ ".png")
        label = Label(master, image=IL, anchor = E)
        label.image = (IL)
        label.grid(row = 2, column = 0, sticky = S)

possAnswers = {"answer1" : random.choice(os.listdir(Soundpath)), "answer2" : random.choice(os.listdir(Soundpath)), "answer3" : random.choice(os.listdir(Soundpath)), "correct" : Letter}
answers(question, possAnswers)