jeudi 30 juin 2016

difference between numpy randint and floor of rand

num_draws = int(1e6)
arr1 = np.random.randint(0, 10, num_draws)
arr2 = np.floor(10*np.random.rand(num_draws))

Could someone with expertise in the internals of numpy.random comment on whether arr2 obeys formally equivalent statistics to arr1? In experiments I have done, the distributions appear to have the same first few moments, but that's all I have checked thus far.




MS SQL Server: extract unique ids and then get all rows matching a random sample of those unique ids

I'd like to do something similar to How to select random IDs and all transactions within those random IDs in SQL but all within Microsoft SQL Server 2011. My very large master table has travel records by individual and month:

FileDate     PersID     Location...
200001          1           A
200001          2           B
200001          3           A
200002          1           C
200002          2           C
200003          1           D
200004          1           A

There are about 260 million rows in the master table and about 4.2 million unique PersIDs.

To get started, I'm trying to just return the random sample of unique PersIDs. I've tried a number of things, the simplest of which is

SELECT distinct PersID FROM mastertbl
TABLESAMPLE (1 percent);

I've also tried wrapping the "SELECT distinct PersID" query as a subquery within another query and applying TABLESAMPLE in the outer query.

All of my attempts return about 1.7 million rows, which is 40% of the unique PersIDs not 1%. This makes me suspicious that my sampling method is sampling the master table and then applying the distinct criteria, but I can't figure out how to fix it.




random number js min max

I'm trying to get random number between 2 numbers from input in JavaScript. When I put numbers instead of max.value and min.value it works, but not with variable. I can't understand how does random in js work, in other programming languages I know it's easy done like random(min,max) so I totally don't understand why is it so hard in JS. Thank you.

function genRanNumb() {
  document.getElementById('demo').innerHTML=Math.floor(Math.random()*(max.value-min.value+1)+min.value);
}
<input type="text" id="min">
<input type="text" id="max">
<button id="btn" onclick="genRanNumb()">button</button>
<p id="demo"></p>



Select random string from array unless it equals something

I pick a random color in a foreach loop, how do i make sure that the chosen color isnt the last color that was chosen?

This is an example of my current code:

$array = array('a', 'b', 'c', 'd', 'e');
$colors = array('#61AE24', '#EAE672', '#00A1CB', '#E54028', '#E59B28', '#28E4E5', '#DB28E5');
foreach($array as $val) {
    $color = $colors[array_rand($colors)];
    echo '<div style="color: '.$color.';">'.$val.'</div>';
}

I need to make sure that the same color isnt used next to eachother.

Thanks




Pick random observation for each by group in SAS

I have two datasets: form and pool having similar table structure.

a) Dataset form enter image description here

b) Dataset pool pool dataset

  • List item

The above two datsets have three columns where each Key and Level combination in form dataset have 4 rows.

  • List item

Also Sub-Level data in form and pool data is mutually exclusive at Key and Level level.

  • Sub-Level values has a particular Level assigned to them i.e. Level and Sub-Level follows a hierarchy.

I want to populate the null values under Sub-Level column in form dataset with Sub-Level values in pool dataset where a Sub-Level in pool dataset shoud belong to same Key and Level of form dataset.

How can be this done in SAS ?




Weird RNG behavior

I'm trying to make a black box method to test if my project is working correctly, but I'm running into some problems with the random number generation.

I have got the method laid out like this:

public static MathObject generateBlackBoxObject() { 
        double functionChance = 0.5;
        double maxValue = 10;
        double minValue = -10;

        if (rng.nextDouble() < functionChance)
        {
            double random = rng.nextDouble();

            if (random < 1/3)
            {
                return Add.apply(Utility.generateBlackBoxObject(), Utility.generateBlackBoxObject());
            }
            else if (random < 2/3)
            {
                return Multiply.apply(Utility.generateBlackBoxObject(), Utility.generateBlackBoxObject());
            }
            else
            {
                return Exponentiate.apply(Utility.generateBlackBoxObject(), Utility.generateBlackBoxObject());
            }
        }
        else
        {
            double random = rng.nextDouble();

            if (random < 1/2)
            {
                return Constant.create(rng.nextDouble() * (maxValue - minValue) + minValue);
            }
            else
            {
                return Variable.create(rng.nextDouble() * (maxValue - minValue) + minValue);
            }
        }
    }

It makes use of a single java.util.Random, but the problem I'm having is that it is most likely to select the Variable.create ... path, and then the Exponentiation.apply ... path. It is kind of unlikely to go for Multiply and never (!) calls Add.apply or Constant.create

It kind of seems like the rng likes to pick the higher values more often than lower or somehow the previous random double influences the next to be higher.

Can anyone tell from this what is happening and (most likely) what I'm doing wrong here?




RandomStringUtils.random strange behavior in web application

I am generation a random password with RandomStringUtils.random. It seems to has a strange behavior when generate the password while the application is running, it always create a password with this structure: [C@1c3f05e5, [C@2b15e4de, [C@18c628b6. It always repeat the three first characters. My code to generate the password is:

char[] password = RandomStringUtils.random(10, 0, 0, true, true, null, 
                new SecureRandom()).toCharArray();

If I execute this code in a main method, it seems work well.




Making sure you can win by testing obstacle spawns

I am currently trying to code an android game (I will not describe it in detail as it is irrelevant) in which I am faced with something I have no idea how to do:

In this game, you control a point on a 4x4 square (like a 4x4 chess board for example).

You can only move 1 square in each turn. Obstacles spawn on a random side-square (on the outer limits) of the board, and travel from one side to the other (so their direction is the same throughout their whole life-span), moving 1 square each turn. They disappear once they've reached the other side of the board. More than 1 obstacle can spawn each turn.

You lose the game instantly if you end up colliding with an obstacle.

My problem is the following : How do I make sure the obstacles always spawn so that there is at least one way of succeeding in dodging all of them? What are the tests I should operate on their spawn location that would ensure that?

The answer may be simple but I do not have a lot of experience in this kind of mathematics-applied-to-programming problems.

Thanks in advance!

(PS: I wasn't sure if Stack Overflow was the right Stack Exchange forum to ask this question, please do tell me if I should ask somewhere else.)




How can I generate an random string with exactly length in PHP?

I have a command to generate an random string as :

$random = sprintf('%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535))

But when I test it, sometime they return the string with 10, 11 or 12 length. Anyone can fix this command to always return exactly a string with 12 length (not 10 or 11, etc...). Because of my project, I only can use this command, so please help me fix it and without use a new solution. Thanks all and sorry for my bad English.




Create mock Object from WSDL

I'am create a SOAP WS, and now I've some WSDL.

I'm searching a tool or similar to create random Object from WSDL.

This tool exist? Any idea?

Tnx in advance!




mercredi 29 juin 2016

Why rand() is generating negative numbers?

I have a function to generate numbers between 0-255 but rand() is also generating negative values. Any advice, please.

char* generateRandomNumbers()
{
    static unsigned char random[9];
    srand(0);
    static int i = 0;
    for(;i<9;i++)
    {
        random[i] = rand() % (256);
    }

    return (char*)random;
}




list fo random numbers separated by commas

Okay so I am making a mario inspired game with randomly generating terrain, It is all working fine however the array of random numbers that randomises the terrain must be the same each time so that the user can enter a seed which is then merged with the larger list to provide a set of random numbers based off of the seed however I cannot think of any way to make this array the same each time without writing it out, and even then making an array of 1000 numbers will be timely. Can anyone suggest a fast way (number generators online dont format it in one single line of numbers separated by numbers so cannot use them) or could someone provide me with a list that is on a single line separated by numbers that i can easily copy and paste into an array thanks! :)




Strange behavor of C++11 normal_distribution()

I have a problem, for some predefined stddev value random number generators d1 and d2 behave very differently.

 mt19937 generator;
 std::normal_distribution<long double> d1(0.0,stddev);
 std::normal_distribution<long double> d2(0.0,1.0);

 d1(generator);
 stddev*d2(generator);

I used this generators as part of a Monte Carlo simulation and expected to get similar results but this was not the case. I was wondering if someone also had similar experience.




Random User Interaction generator - Akka actors

I am now starting to learn the actor programming model. For practice I'm planning to use the Akka actors to generate random user interactions.

For starters I'm thinking of implementing a simple state machine like: user login, then perform 0 or more actions and then go to a final state (logout).

enter image description here

I'm thinking of the following actor hierarchy. The OrchestratorActor receives a config of the traffic specs it should generate and then delegates to one of the actors involved in the start states. Then, for each "level" the actors delegate to a random actor from the layer beneath.

enter image description here

Questions:

  1. What do you think of the actor hierarchy proposed?
  2. I'm going to use the scheduler to delay the "actions". The OrchestratorActor must ensure the traffic it generates matches the given conditions (e.g. 80% legit, 20% fraudulent traffic or something like that). How can I do that? Splitting the traffic into chunks (10 minute) and making sure that the conditions are met for the current chunk?

Thank you in advance! I don't need code, only ideas no matter how smart/crazy :)




randomly subtract desired percentage from a array using php

I have a array which contains 40 elements like this

$i = array('1','2','3','4','5','6','7','8','9','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23','24',
'25','26','27','28','29','30','31','32','33','34','35',
'36','37','38','39','40');

now i have 4 variations like 5%, 10%, 15%, 20%

The requirement is i need to take array values randomly after subtracting the desired variation.

Lets say i used 5% variation so i need to separate 5% from the array ie 2 elements i need to remove randomly from the array and keep the rest 38 element in a new array randomly.so both the resulted array as well subtracted elements need to be in two different array.

I need a function with two parameter ie one is variation and another is required array ie resultant array or subtracted elements array.

This same sequence follows to all other variations.




Is there any method which generate random numbers with complexity O(1)

I am looking for one efficent way to generate random numbers using java . I want it to be fast and highly secured. Unfortunately SecureRandom class in java and its method nextBytes() generate highly secured random numbers but this method takes me quite time . I am looking if there is any implementation of a method with the same aim as the one above which has complexity O(1) or worst case O(n).




how to render random objects from an array in react?

I just started learning React in my work and I need to build a Blog using react. I need to show random posts as "recommendedPosts", after doing some research I found a possible solution which is using Math.random() but I could not figure it out how to implement it in my component. This is my code:

RecommendedPost/index.js

import React from 'react';
import { Link } from 'react-router';

class RecommendedPosts extends React.Component {

render() {
return (
  <ul>
    {this.props.posts.map((post, idx) => {
      return (
        <li key={idx}>
          <p>{post.title}</p>
          <p>{post.text}</p>
          <p>{post.category}</p>
          <Link to={`/blog/post-1/:${post.id}`}>Weiter lesen</Link>
        </li>
      );
    })}
  </ul>
);
}
}
RecommendedPosts.propTypes = {
posts: React.PropTypes.array,
};
export default RecommendedPosts;

Then I use this component in my container: BlogPage/SinglePostPage/index.js

import React from 'react';
// ...other imported stuff
import RecommendedPosts from 'components/Blog/RecommendedPosts';

class PostPage extends React.Component {

render() {
  // dummy-recomended-posts
const posts = [
  {
    id: 1,
    title: 'How to Cook Blue Meth',
    description: 'Lorem ipsum dolor sit amet, turpis at, elit',
    thump: 'thump.jpg',
    hero: '/img/',
    category: 'k1',
    fullname: 'Walter White',
    published: '10.05.2016, 15:30pm',
  },
  {
    id: 2,
    title: 'Passenger',
    description: 'Lorem ipsum dolor sit amet, turpis at, elit',
    thump: 'thump.jpg',
    hero: '/img/',
    category: 'k2',
    fullname: 'Chino Moreno',
    published: '10.05.2016, 15:30pm',
   },
    // ...and more dummy posts(about 7)
   ];
return (
   <div>
   // here, I pass the posts array to my component
   <RecommendedPosts posts={posts} />
   </div>
  );
  }
 }
}
export default connect(null, mapDispatchToProps)(PostPage);

My idea is to render the posts randomly using the id as a ref but again I can find the way. Hope some one can help me, and sorry if the answer is too obvious for everyone.




Random Sample of a subset of a dataframe in Pandas

Say i have a dataframe with 100,000 entries and want to split it into 100 sections of 1000 entries.

How do i take a random sample of say size 50 of just one of the 100 sections. the data set is already ordered such that the first 1000 results are the first section the next section the next and so on.

many thanks




Algorithm for creating random lists from an existing list in bash

I have a list of IDs like below:

xxx_date1
xxx_date2
xxx_date3
yyy_date1
yyy_date2
zzz_date1
xyy_date1
xyy_date1
...
...

xxx_date1 and xxx_date2 means that subject xxx had separate visits at date1 and date2. I need to write a script in bash to create random lists (of equal size) of only unique IDs. an example would be like below:

xxx_date1
yyy_date1
zzz_date1
xyy_date1
...

a second list could be:

xxx_date2
yyy_date1
zzz_date1
xyy_date1
...

How can I create all possible lists of unique IDs? I appreciate any hint or idea.

Thank you!




Math.random() and .replace() cross-browser

I recently wrote the code to generate 10 characters randomly. Math.random() gives a decimal to toString(36) and all the numbers will be replaced.

Math.random().toString(36).replace(/[^a-z]+/g,'').substr(1,10);

Does anybody have a hint why Firefox (47.0) and Chrome (51) don't handle this equally?

Chrome tests:

Math.random().toString(36).replace(/[^a-z]+/g,'').substr(1,10);
"spkcirhyzb"
"gcqbrmulxe"
"sallvbzqbk"
"pcdcufhqet"
"knfffqsytm"

Firefox tests:

Math.random().toString(36).replace(/[^a-z]+/g,'').substr(1,10);
"zxntpvn"
"hebfyxlt"
"zclj"
"ormtqw"
"cfbsnye"

Live version:

for (var n = 0; n < 5; ++n) {
  console.log(Math.random().toString(36).replace(/[^a-z]+/g,'').substr(1,10));
}



Generation of random Image by tapping on imageView

I simply wants to generate a random image from drawable images when i tap on the imageView.Whenever i run this code, app on the emulator gets crashed. whats wrong with this code.

package com.example.surya.musicpleer;

import android.app.Activity;
import android.graphics.Typeface;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends Activity {

ImageView i1;
Random r = new Random();
int target = r.nextInt(3);
String drawablename = "photo" + target;

int resID = getResources().getIdentifier(drawablename, "drawable",  getPackageName());

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    i1 =(ImageView)findViewById(R.id.imageView);
    i1.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            i1.setImageResource(resID);
        }
    });
        }

}




mardi 28 juin 2016

Selecting Random Item from List given probability of each item

Sorry about badly phrased title....

I have an object called NGram

class NGram
{
     //other properties
     double Probability {get; set;} //Value between 1 and 0 
}

Now suppose I have a list of these objects such that...

List<NGrams> grams = GetNGrams();
Debug.Assert(grams.Sum(x => x.Probability) == 1);

How can I select a random item from this list while factoring in the probability distribution.

For instance, suppose grams[0].Probability == 0.5 then there should be a 50% chance of selecting grams[0]

I figured I may need something like rand.NextDouble() but I am at loss.




rand() making same number even with srand in main function with 1 second delays

Test file: Number generated is always 30, I had it working yesterday but I dont remember what I changed that made it stop again... Checked other threads but didn't really see a solution...

    #include "stdafx.h"
    #include <iostream>
    #include <stdio.h>
    #include <Windows.h>
    #include <ctime>


    int main()
    {
        srand((unsigned int)time(NULL));

        int randomnumber = 0;

        while (true) {

            randomnumber = rand() % 1 + 30;
            std::cout << "Rand number: " << randomnumber << std::endl;
            Sleep(2000);
        }

        return 0;
    }




How do you set a seed using boost?

I am writing a mex file in which I need to essentially recreate Matlab's "randn" function. I used boost to do this, but am uncertain how to set the seed. Thus far I have:

boost::mt19937 rng; boost::normal_distribution<> nd(0, 1); boost::variate_generator >var_nor(rng, nd);

double rand_number = var_nor();

however, if I run a loop on this, I get the same sequence of random normals. I know I must seed it but am unsure how - I am getting an error if I use time(0)




random effects or OLS

I am really sorry but I am quite confused.

I have panel data (200 firms over the time period of 2002 - 2014). I ran a test whether I should use fe or re; and I think I got the result of random effects, which makes sense since my sample is drawn from different industries. The result made me think I need to use random effects.

code:

. hausman fe re

             ---- Coefficients ----
                (b)          (B)            (b-B)     sqrt(diag(V_b-V_B))
                 fe           re         Difference          S.E.

zchangeinROA  -.0078418    -.0094914        .0016495        .0002656
Narcissimi~    .004696    -.0003595        .0050556        .0030671
interaction   -.0008962    -.0005818       -.0003144        .0003695
zlntotal_a~    .0674206    .0044034        .0630172        .0163112
zlnrevenue    -.0052717    -.001084       -.0041878        .0122064
zrole       -.0097101    -.0096499       -.0000602         .001937

    b = consistent under Ho and Ha; obtained from xtreg
 B =    inconsistent under Ha, efficient under Ho; obtained from xtreg

Test:  Ho:  difference in coefficients not systematic

chi2(6) = (b-B)'[(V_b-V_B)^(-1)](b-B)
        =        3.92
Prob>chi2 =      0.6881
(V_b-V_B is not positive definite)

Now I did a Breusch and Pagan test to see if I could use pooled OLS instead of random effects. As I understood it, I reject the Null and thus need to do a random effects. Could you help me if I did the right decisions? This is for my thesis, so any help or explanatio is appreciated.

Breusch and Pagan Lagrangian multiplier test for random effects

workforcechange[firm_ID,t] = Xb + u[firm_ID] + e[firm_ID,t]

Estimated results:
| Var sd = sqrt(Var)
---------+-----------------------------
workfor~e | .0253792 .1593084
e | .0232228 .1523903
u | .0019666 .0443464

Test: Var(u) = 0
chibar2(01) = 88.06
Prob > chibar2 = 0.0000

I posted the same question here; but have not gotten a reply yet.

http://ift.tt/293lf0L




Python - drop rate in games, random with assigned probability

Lets say I 30 numbers
I need to assign them random but with drop chances
Ex: There's 2% for number 1, 1.5% for number 2, 1.1% for number 3, 1.7% for number 4 etc...
I'm genereting random numbers with this

from random import randint import string import random

print(randint(1,30)) // generates random number from 1 to 30


But need to assign probability for every number
I don't mind manually assigning percentage to every number
Just need to know how to assign percentage to a random number




PHPSESSID same attribution possible?

Is it possible for a webserver to assign a PHPSESSID currently used by another client at the moment of attribution?

Or a check is made before attribution ?




Add button which brings user to random page

I am building a website with information about all sorts of countries. I want to add a button that brings the user to a random country page within my website. How could I do this and what programming language(s) do I need?




How to revert change of ArrayList after using List.set() JAVA

I have an ArrayList of items (each item with weight and profit):

ArrayList itemList: [{Weight: 3, Profit: 10}, {Weight: 15, Profit: 50}, {Weight: 7, Profit: 25}, {Weight: 6, Profit: 15}, {Weight: 4, Profit: 10}]

Then I have a random bitStrings representing which items to be taken given maximum weight to be taken is 20 (capacity = 20).

Let's say the initial random bits obtain is [1,1,0,0,0] which means Item 1 and Item 2 are taken which give:

TotalWeight = 3 + 15 = 18 [<= capacity]

Then I have a random bit to be flipped (if the bit is 1 -> 0, and if the bit selected to flip is 0 -> 1). Let's say the order to flip the bits is [3,2,1,4,0].

So firstly, the bit at index 3 will be flipped and count the total weight like this:

[1,1,0,0,0] --> [1,1,0,1,0]

Hence, the new bitstring after bit[3] flip: [1,1,0,1,0].

Then count the total weight again:

Total Weight of new bitstring = 3 + 15 + 6 = 24 [> capacity]

So the total exceeds capacity and I want the new bitstring to assign back to the previous bitstring before it is flip:

[1,1,0,1,0] --> return back to previous state: [1,1,0,0,0].

After return back to state: [1,1,0,0,0] the next bit will be flip from the order just now [3,2,1,4,0] but now I have to flip the bit at index 2 according to the order from left to right. This becomes:

From [1,1,0,0,0] --> flip bit[2]:

[1,1,0,0,0] --> [1,1,1,0,0]

Then do the same calculate weight etc.

if the total still exceeds it will return back to previous state but if it does not exceeds it will add the new solution to a new ArrayList.

I have done some codings on it but my problems are to get back to the previous state and at adding the accepted bit strings to ArrayList improve. It stores the latest updated solution only and the other accepted solutions is being replaced as shown in the output I obtain.

This is my codes: '

  public class KnapsackHC {
    public static void main (String[] args){
    int n = 5, capacity = 20, pointer, toFlip;
    //Item items = new Item();
    ArrayList<Item> itemList = new ArrayList<Item>();
    ArrayList<Integer> solution = new ArrayList<Integer>();
    ArrayList<Integer> currentSolution = new ArrayList<Integer>();
    ArrayList<Integer> flipOrder = new ArrayList<Integer>();
    ArrayList<ArrayList<Integer>> improve = new ArrayList<ArrayList<Integer>>();
    //ArrayList<Integer> temp = new ArrayList<Integer>();

    itemList = getProblem();
    solution = initialSolution(n);
    currentSolution = solution;
    flipOrder = randomFlipOrder(n);

    System.out.println("List of Items: " + itemList);
    System.out.println("Initial solution: " + solution);
    System.out.println("Current solution: " + currentSolution);
    System.out.println("Random order: " + flipOrder);

    for (int i = 0; i < flipOrder.size(); i++){
        int totalWeight = 0, totalProfit = 0;

        pointer = flipOrder.get(i);
        toFlip = solution.get(pointer);

        for (int j = 0; j < solution.size(); j++){
            if (solution.get(j) == 1){
                totalWeight += itemList.get(j).getWeight();
                totalProfit += itemList.get(j).getProfit();
            }
        }
        System.out.println();
        System.out.println("Updated Solution: " + currentSolution);
        System.out.println("Total Weight Solution " + (i+1) + " : " + totalWeight + " | Total Profit Solution " + (i+1) + " : " + totalProfit);

        if (totalWeight <= capacity){
            System.out.println("----------NOT EXCEED-----------");
            currentSolution = solution;
            System.out.println("currentSolution BEFORE FLIP: " + currentSolution);
            improve.add(currentSolution);
            System.out.println("Improve: " + improve);

            if (toFlip == 1){
                solution.set(pointer, 0);
            }
            else if (toFlip == 0){
                solution.set(pointer, 1);
            }
            System.out.println("solution AFTER FLIP from Random Order [" + flipOrder.get(i) + "] : " + solution);

            currentSolution = solution;
            //solution = new ArrayList<Integer>();
            System.out.println("--------------------------------");
        }
        else{
            System.out.println("----------EXCEED!!!!------------");
            //currentSolution = solution;
            System.out.println("currentSolution BEFORE FLIP {return back to previous state}: " + currentSolution);

            if (toFlip == 1){
                solution.set(pointer, 0);
            }
            else if (toFlip == 0){
                solution.set(pointer, 1);
            }
            System.out.println("solution AFTER FLIP from Random Order [" + flipOrder.get(i) + "] : " + solution);

            System.out.println("--------------------------------");
        }

    }

}
/*
public static ArrayList<Integer> calcFitness(ArrayList<Integer> currentSolution, ArrayList<Integer> solution, ArrayList<Item> itemList, int capacity){
    System.out.println("\nAfter Flip: " + solution);
    System.out.println("Current Solution: " + currentSolution);

    int totalWeight = 0; 
    int totalProfit = 0;

    for (int i = 0; i < solution.size(); i++){
        if (solution.get(i) == 1){
            totalWeight += itemList.get(i).getWeight();
            totalProfit += itemList.get(i).getProfit();
        }
    }
    System.out.println("Total Weight: " + totalWeight + " || Total Profit: " + totalProfit);


    if (totalWeight <= capacity){
        currentSolution = solution;
        System.out.println("Solution change: " + currentSolution);
        System.out.println();
        return solution;
    }
    else{

        System.out.println("Solution NO change: " + currentSolution);
        System.out.println();
        return currentSolution;
    }

}*/

public static ArrayList<Item> getProblem(){
    ArrayList<Item> itemsArr = new ArrayList<Item>();

    try {
        BufferedReader in = new BufferedReader( new FileReader("knapsack_problem_5.txt" ) );

        int i = 0;
        String str;
        while ( (str = in.readLine() )!= null ) {
            String[] item = str.split( "," );
            //System.out.print("Weight #" + i + " : " + Integer.parseInt(item[0]));
            //System.out.print("Profit #" + i + " : " + Integer.parseInt(item[1]));
            int weight = Integer.parseInt(item[0]);
            int profit = Integer.parseInt(item[1]);

            itemsArr.add(i,new Item(weight,profit));

            i++;
        }
        in.close();
    } catch ( IOException ex ) {
        System.err.println( "Error: Can't open the file for reading." );
    }

    return itemsArr;
}

//generate initial solution(bits) randomly
public static ArrayList<Integer> initialSolution(int length){
    Random r = new Random();
    ArrayList<Integer> solution = new ArrayList<Integer>(length);

    // generate some random boolean values
    boolean[] booleans = new boolean[length];
    for (int i = 0; i < booleans.length; i++) {
      booleans[i] = r.nextBoolean();
    }

    for (boolean b : booleans) {
      if (b == true){
          solution.add(1);
      }
      else{
          solution.add(0);
      }
    }

    return solution;

}

public static ArrayList<Integer> randomFlipOrder(int length){
    ArrayList<Integer> order = new ArrayList<Integer>();
    Random r = new Random();

    for (int i = 0; i < length; i++){
        order.add(i);
    }

    Collections.shuffle(order);

    return order;
   }
  }

'

My textfile consists the following (weight, profit):

3,10

15,50

7,25

6,15

4,10

My output obtained (the initial bit strings and random order to flip bit will be randomly generated):

List of Items: [{Weight: 3, Profit: 10}, {Weight: 15, Profit: 50}, {Weight: 7, Profit: 25}, {Weight: 6, Profit: 15}, {Weight: 4, Profit: 10}]

Initial solution: [1, 0, 0, 1, 0]

Current solution: [1, 0, 0, 1, 0]

Random order: [2, 4, 0, 1, 3]

Updated Solution: [1, 0, 0, 1, 0]

Total Weight Solution 1 : 9 | Total Profit Solution 1 : 25

----------NOT EXCEED-----------

currentSolution BEFORE FLIP: [1, 0, 0, 1, 0]

Improve: [[1, 0, 0, 1, 0]]

solution AFTER FLIP from Random Order [2] : [1, 0, 1, 1, 0]


Updated Solution: [1, 0, 1, 1, 0]

Total Weight Solution 2 : 16 | Total Profit Solution 2 : 50

----------NOT EXCEED-----------

currentSolution BEFORE FLIP: [1, 0, 1, 1, 0]

Improve: [[1, 0, 1, 1, 0], [1, 0, 1, 1, 0]] It doesn't store the previous accepted solution but replace it with new one

solution AFTER FLIP from Random Order [4] : [1, 0, 1, 1, 1]


Updated Solution: [1, 0, 1, 1, 1]

Total Weight Solution 3 : 20 | Total Profit Solution 3 : 60

----------NOT EXCEED-----------

currentSolution BEFORE FLIP: [1, 0, 1, 1, 1]

Improve: [[1, 0, 1, 1, 1], [1, 0, 1, 1, 1], [1, 0, 1, 1, 1]]

solution AFTER FLIP from Random Order [0] : [0, 0, 1, 1, 1]


Updated Solution: [0, 0, 1, 1, 1]

Total Weight Solution 4 : 17 | Total Profit Solution 4 : 50

----------NOT EXCEED-----------

currentSolution BEFORE FLIP: [0, 0, 1, 1, 1]

Improve: [[0, 0, 1, 1, 1], [0, 0, 1, 1, 1], [0, 0, 1, 1, 1], [0, 0, 1, 1, 1]]

solution AFTER FLIP from Random Order [1] : [0, 1, 1, 1, 1]


Updated Solution: [0, 1, 1, 1, 1]

Total Weight Solution 5 : 32 | Total Profit Solution 5 : 100

----------EXCEED!!!!------------

currentSolution BEFORE FLIP {return back to previous state}: [0, 1, 1, 1, 1] ==> This should return back to [0,0,1,1,1] where the capacity is not exceeded

solution AFTER FLIP from Random Order [3] : [0, 1, 1, 0, 1] ==> this should be flipped from [0,0,1,1,1] and bcomes -> [0,0,1,0,1]


And lastly, once it has becomes [0,0,1,0,1] it should display the total weight again and display but it's not displaying.

I'm not sure where are the mistakes. Please help. Thank you.




Numpy rand not random?

I'm coding some things on Python, and I need random numbers. I'm using the Numpy library to generate this random numbers. I have a code for a random move of an entity:

def moverse(self, Ltilda, it):
    self.historia[it] = self.pos 
    chig = abs(np.random.randn()) 
    angulo = np.random.rand() * 2.0 * np.pi 
    self.pos += np.multiply([np.cos(angulo), np.sin(angulo)], chig*Ltilda) 
    return

So I generate a gaussian variable for lenght and a uniform variable for angle. Then I call the function inside a loop. My entities can reproduce, following this:

def dividirse(self, it):
    r = np.random.rand()
    if (r < self.divide):
        return Entidad(self.pos, self.dividirse, it, len(self.historia))
    else:
        return None

If I create two different entities, the trajectories are independent. But the "childs" of entities always follow more or less the same trajectory as the parent! I have no idea why this happens. Why is the numpy.random function not giving me independent results in this case? How can I fix this? Thank you.

PS. Example for reference:

b1 = Entidad(np.array([1.0,1.0]), 0.1, 0, Nits)
aux = None
while aux == None:
    aux = b1.dividirse(0)
b1hija = aux
b2 = Entidad(np.array([1.0,1.0]), 0.1, 0, Nits)

for i in range(Nits):
    b1.moverse(0.03,i) 
    b1hija.moverse(0.03,i) #This two follows same path (more or less)
    b2.moverse(0.03,i) #This follows completely different path




lundi 27 juin 2016

How many base cases can we have for a recursive function?

I have rand2() method that returns 0 or 1 randomly.
I am trying to create a method rand3 which will use rand2() and return 0,1,2 with an equal probability.
I came up with a recursive solution that considers 4 combinations of 0,1.
All in all I wrote this function, with more than 1 base case, in a hope that it will work,
but it seems like recusive functions can't have more than one base case.
What am I missing?

public static int rand3(){
        String str = "";
        str+= rand2();
        str+= rand2();
        System.out.println(str);

        if(str=="00")
            return 0;
        else if(str=="11")
            return 1;
        else if( str=="01")
            return 2;          
        else
            return rand3();


    }




Generate a String for a given size

How can I generate a String of a given size?

int someLimit = GlobalLimits.BULK_SIZE;

I want 3 Strings which satisfy the below conditions.

- RandomStr.length < someLimit.length

- RandomStr.length = someLimit.length

- RandomStr.length > someLimit.length

This is what I have tried so far.

private String getLowerRandomString(int upto){
  StringBuilder sBuilder = new StringBuilder();
  for (int i = 0; i < upto; i++){
    sBuilder.append("A");
  }

  return sBuilder.toString();
}

The problem what I see is, if my limit = 10000, it still loop up-to 9999 which is unnecessary. Share if you know a better approach than this. Thank you.


FYI: I was writing a unit test for a simple helper method.

public boolean isBulk(String text){
 int bulkLimit = ImportToolkit.getSizeLimit();
 if (text != null && text.length() > bulkLimit){
  return true;
 }
 return false;
}

So, I want to pass different sizes of strings as parameters to this method and want to assert whether it gives me expected results.




Does `std::shuffle` guarantees same order with same seed on different vectors?

I have two vectors with the same number of elements, but their types have completely different sizes. I need to shuffle them so that both have the exact same order after shuffling (each element in one vector is related each element in the other). The way I found to do it was:

// sizeof(a[0]) != sizeof(b[0])
// a.size() == b.size()
{
    std::mt19937 g(same_seed);
    std::shuffle(a.begin(), a.end(), g);
}
{
    std::mt19937 g(same_seed);
    std::shuffle(b.begin(), b.end(), g);
}

Can I rest assured that both vectors will be shuffled the same way? Is this implementation dependent? Do I have such guarantee from std::shuffle specification?




How do you make a list of random numbers

I'm working with python to create a game that the computer will pick numbers from 1 to 10 and the player can choose which numbers they want to keep or delete..The sum of the random numbers must add up to 21 and the player has only 10 tries.What would be the code I use to create the list of random numbers to equal 21 and let the player delete numbers they want.Thank you!!!

I've already started on some of it..The program I use Python 2.7.5 on Mac...

import random
import time
name = raw_input("Hello, What's your name?")
print "Welcome," ,name, "Time to play Catch 21!"
time.sleep(1)
tries = 0
tries_remaining = 10
while tries < 10:
          tries += 1
          tries_remaining -= 1
from time import sleep
total = 0
for i in range(10):
    total = total + random()
print total
while True:
    print "Your card is"
    values = ["2","3","4","5","6","7","8","9","10"]
    print(random.randint(1,10))
    print"Do you want to keep or delete this card?"
    card = raw_input("K = Keep.  D = Delete. ")
    from time import sleep
    time.sleep(1)




Dont repeat after shown (Random)

I have a button when its pressed it shows a random text. I have another button thats when pressed it will remove the case so it wont be displayed again. How to do that? Here is my code :

    public class TasksActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_tasks);

    final Button tasksbtn = (Button)findViewById(R.id.btnfortasks);
    Button removeCase = (Button)findViewById(R.id.remove_case); 


    tasksbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Random taskRandom = new Random();
            TextView tasksView = (TextView)findViewById(R.id.tasks_textView);
            switch (taskRandom.nextInt() %4) {
                case 0:
                    tasksView.setText("one");
                    break;
                case 1:
                    tasksView.setText("two");
                    break;
                case 2:
                    tasksView.setText("three");
                    break;
                case 3:
                    tasksView.setText("four");
                    break;
                default:
                    break;
            }

        }
    });




Python game created with ovals, while loops, and for loops

Hey guys so I am working on a program that fires a bullet from a cannon after having the user input a degree in order to hit the randomly generated target at its position. The program works fine if you are able to hit the target on the first try every time but it seems if I miss that it creates a new target, like it is supposed to, but does not delete the old one. Any idea on how to correct that?

Also, I want it to display in text if you miss the target, inside the canvas. How can I do that? My code is below. Any help would be appreciated, thanks!

from tkinter import *
import time
import math
import random

master = Tk()

w = Canvas(master, width=800,height=800, bg="white")
w.pack()

#Cannon
Img1 = PhotoImage(file="goldcannon.gif")
Pic1 = w.create_image(85,600, image=Img1)

#Grass
w.create_rectangle(0,645, 800,800, fill="green")
w.update()

Choice = "Yes"
Win = False
while(True):
    if Choice == "No":
        TY = w.create_text(400,400, text="Thank you for playing!", font="arial")
        break
    x = []

    #Cannon Target
    Target_x = 700
    Target_y = random.randrange(100,560)
    Target = w.create_oval(Target_x,Target_y, Target_x+25,Target_y+25, fill="red")


    while(True):
        if Choice == "No":
            break


        #Cannon Degree
        degree = simpledialog.askstring("Cannon Degree", "What is your guess?", \
                                initialvalue="Enter a Degree")

        degree = 90 - int(degree)

        #Cannon Bullet
        bMove = w.create_oval(150,560, 150+10,560+10, fill="black")

        for i in range(90):
            w.move(bMove,math.sin(math.radians(degree))*10, \
                   -math.cos(math.radians(degree))*10)
            time.sleep(0.06)
            w.update()

            x = w.find_overlapping(Target_x-10,Target_y, Target_x+35,Target_y+35)

            if len(x)>1:
                w.delete(bMove)
                Hit = w.create_text(400,400, text="You hit the target!", font="arial")
                Choice = simpledialog.askstring("Hello", "Would you like to play again?", \
                                                initialvalue="Yes or No")
                w.delete(Hit)
                w.delete(Target)

                Win = True

                break

        if Win == True:
            break




Java and Random method

I want to create something like Flashing Light with *.
for being Flashing I decided to use "For" that Repeats 5000 times , also I want the Max * in each line be 25 but my code is not working . Does any body have any suggestion ? my code is

 void test() {

    Random rnd = new Random();
    for (int i = 0; i < 5000; i++) {
        rnd = nextInt(25);

        for (int j = 0; j < rnd; j++) {
            System.out.print(" * ");

        }

    }

}




Creating randomised photo survey in R

I am new to stackoverflow so please bare with me! I have a dataset which includes a reference code for the people in my data, and details about them. I need to create a photograph survey which will give me an image of a child, his/her father, and 2 other men in the same age category. I have already sorted my data in R and have the names of all the children, their fathers and men in that age category, but I don't know how to attach photographs to R...is this possible? If so how can I randomise the 2 men from the same age category?

Many thanks




Making a scheduled function to generate specified number of random numbers from with in a table MYSQL

I'm working on my website where people can do give-a-ways of game items. Now I want to create a scheduled task in mySQL database so when the time of give-a-way is over, it will randomly select a specified number of winners from a join table "participants" in which the id of users (as Uid) and the give-a-way(as gid) in which they have participated is stored. I have tried reading different articles but I don't have a clue how to do that since I haven't studied databases course in my degree.

Any help will be of great use. Thank you.




Missing elements when randomizing order of list items in page

I am trying to develop a little test for an educational website and I want to randomize the order of the questions and exercises and later down the line the order of the answers under each question with a set of radio buttons. I have tried the code I found on two separate questions (namely this one and this one), although both the answers were practically the same. The code that I am using does what I want to some extent, but parts of my test are missing sometimes (most of the time I get 5 questions and 2-3 exercises instead of 6 and 4). How do I correct this? Full code sample in this JSFiddle (some irrelevant things from back-end are there, ignore them - content is placeholder to make debugging easier), as well as the javascript/jQuery code on its own below:

$(document).ready(function () {
        var questions = $('.question');
        for (var i = 0; i < questions.length; i++) {
            var target = Math.floor(Math.random() * questions.length - 1) + 1;
            var target2 = Math.floor(Math.random() * questions.length - 1) + 1;
            questions.eq(target).before(questions.eq(target2));
        }

        var exercises = $(".exercise");
        for (var j = 0; j < exercises.length; j++) {
            var target = Math.floor(Math.random() * exercises.length - 1) + 1;
            var target2 = Math.floor(Math.random() * exercises.length - 1) + 1;
            exercises.eq(target).before(exercises.eq(target2));
        }
    });

P.S. #1: The website's back-end is built with Asp.Net and C#, if that has anything to do with the problem.

P.S. #2: Run the fiddle four or five times and count the number of questions and exercises to reproduce the problem.




How to select an integer randomly from a list containing integers as well as other objects?

I have a list

data=['_','_','A','B','C',1,2,3,4,5]

I need to randomly get an integer among 1,2,3,4,5 The list keeps getting modified so i cant just simply choose from the last 5 members

Here's what i tried but it throws an error retrieving the other members:

inp2=int(random.choice(data))




How to get a specific random number out of three numbers in android

I have three numbers 25,30 & 35 . I want to get a one random number out of these three numbers .

Currently , I know how to get a random number from a range. But in this case i have no idea how to get it .

Have any ideas ?

Thank you .




dimanche 26 juin 2016

Generating random number as user identifier

I have been looking at the Unique ID (UID) generation for Aadhar (an Indian equivalent to Social Security Number)

They generate an 11 digit random number. I am also working on an application where I need to provide unique ID to users which needs to be valid an unique throughout there lifetime (expected number of users 40-60 billion).

When looking over the web for similar schemes, I found that simplest way is to generate each digit randomly and concatenate. So my questions are:

  • Is generating each digit randomly correct way to generate such IDs
  • Are there any established technique for the same ?
  • What considerations one needs to take care of when designing such a scheme ?



FizzBuzz Using Arrays (JAVA)

Preface: This is a homework assignment; I'm not looking for you to do it for me. However, any suggestions or related examples would be greatly appreciated.

Assignment:

You can do this all in the main method. This is using a game called Fizz-Buzz, an ancient programmer’s game.

  1. Start by initializing some variables to set the maximum and minimum value of a random number and for the capacity of an array. (20/100)

  2. Initialize three new arrays, one for a list of random numbers (as integers) and two for String arrays called ‘fizz’ and ‘buzz’.(20/100)

  3. You’ll also need an integer for counting.

  4. Write a for loop that generates a random number for each position in the array. Remember that the range for this will be set by the two variables initialized at the beginning of the file. There are multiple ways to create a random number, just find one that works for you. (20/100)

  5. Using the count of the arrays, create another array that will store all of the fizzes and buzzes without any extra space leftover in the array. (20/100)

  6. Use a for each loop to iterate the array and print all of the fizzes and buzzes, with no other output. (20/100)

What I've accomplished thus far:

import java.util.Random;

/**
 *
 * @author
 */
public class FizzBuzz {

  //2a. Initialize one int array for a list of random numbers.
  private static int[] anArray;

  //2b. Initialize two String arrays called 'fizz' and 'buzz.'
  public static String[] fizz;
  public static String[] buzz;
  public static String[] fizzbuzz;

  //1. Set the maximum and minimum value of a random number.
  private static final int min = 3;
  private static final int max = 3;
  private static int count = 0;
  private static int randomNum;

  public static int[] list() {

    anArray = new int[10];
    //3. Make an integer for counting("counter" in the for loop)
    //4. Write a for loop that generates a random number for
    //   each position in the array.
    for(count = 0; count < anArray.length; count++) {
      anArray[count] = randomFill();
    }
    return anArray;
  }

  public static void print() {

    for(int n: anArray) {
      System.out.println(n + " ");
    }
    for (String f : fizzbuzz) { 
      System.out.println(f + " ");
    }
  }

  public static int randomFill() {

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

  public static String[] GetFizzOrBuzz() {

    fizzbuzz = new String[10];

    int x = 0;
    int counter;

    for(counter = 0; counter < fizzbuzz.length; counter++) {
      if(randomNum % 3 == 0) {
      x = 1;
    }
      if(randomNum % 5 == 0) {
      x = x + 2;
    }
    switch(x) {
      case 1:
        fizzbuzz[counter] = "fizz";
         break;
      case 2:
        fizzbuzz[counter] = "buzz";
      case 3:
        fizzbuzz[counter] = "fizzbuzz";
    }
  }
    return fizzbuzz; 
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    list();
    GetFizzOrBuzz();
    print();
  } 
}

Issue: I'm receiving a null value for all of my String array, fizzbuzz. Why isn't my program returning the design result, or rather, what am I doing wrong?

EDIT I currently had my min/max values set to 3 for purposes of testing my returns. Ideally, I'd like it to function with min/max 0-100. Also, the program works with 3 and 15 currently, but not many other numbers, haha.




Generate Random List of Random Numbers with Duplicates in Python 3.4

I've seen multiple threads on printing lists of random numbers, but not ones with my specific requirements, and I can't seem to get it right.

I want to develop a code that will generate a list of random numbers on some interval, with the list being a random length alone some separate interval, also, duplicates need to be in this list. I also want to do it in 1 line.

I came up with a pretty good attempt using random.sample, but sample doesn't include duplicates, and it also won't let me make the range of numbers inside the list be larger than the list itself. (E.g. It can't generate a list 5 numbers long, but with numbers larger than 1 through 5.)

>> a = random.sample(range(10), random.randint(1,10,1))
>> print(a)
[6, 3, 4, 2, 5, 7, 8]

To get rid of the no duplicate problem, and numbers bigger than length problem, I attempted this, but I can't make the range random, or else I get a TypeError:

>> a = [random.randint(1,20) for x in range(1, 10)]
>> print(a)
[8, 7, 20, 20, 5, 18, 9, 3, 19]

Here is the version I attempted for random range:

>> a = [random.randint(1,20) for x in random.randrange(1,10)]
>> print(a)
    Traceback (most recent call last):

      File "<ipython-input-258-b3a6b0409007>", line 1, in <module>
        a = [random.randint(1,20) for x in random.randrange(1,10)]

    TypeError: 'int' object is not iterable

Not too sure why I can't create a random range on some interval, but I'm a beginner, so I'm sure I'm just missing something.




How to get all possible permutations for 0 and 1 bits in JAVA

I need the output of permutation for bits of length 3 to be (the order doesn't matter as the initial combination of 0 and 1 is generated randomly):

[0,0,0]

[0,0,1]

[0,1,0]

[0,1,1]

[1,0,0]

[1,0,1]

[1,1,0]

[1,1,1]

I have done but it seems that there are duplicates and some possible permutation are not being displayed which I'm not sure why. This is my code:

'

  ArrayList<Item> itemsAvailable = new ArrayList<Item>();
  ArrayList<Integer>bits = new ArrayList<Integer>();
  ArrayList<ArrayList<Integer>> tried = new ArrayList<ArrayList<Integer>>();

    itemsAvailable.add(new Item(5,4));
    itemsAvailable.add(new Item(12,10));
    itemsAvailable.add(new Item(8,5));

    System.out.println("itemsAvailable: " + itemsAvailable);

    Random r = new Random();

    //permutations
    for(int i = 0; i < Math.pow(2,itemsAvailable.size()); i++){
        //Generate random bits

        for(int j = 0; j < itemsAvailable.size(); j++){
            int x = 0;

            if (r.nextBoolean())
                x = 1;

            bits.add(x);

        }


        System.out.println("Added to bits #" + (i+1) + ": " + bits);

        bits = new ArrayList<Integer>();
    }

'

The output that I obtained is:

Added to bits #1: [0, 0, 1]

Added to bits #2: [1, 1, 0] - duplicate

Added to bits #3: [1, 0, 1]

Added to bits #4: [0, 0, 1]

Added to bits #5: [0, 0, 0] - dupicate

Added to bits #6: [1, 1, 0] - dupicate

Added to bits #7: [1, 1, 1]

Added to bits #8: [0, 0, 0] - dupicate

Therefore how can I obtain 8 different permutations as the bits are generated randomly? Please help.

Thank you.




Generating a random 2D array

I want to make a simple program where a user can input "i x y" where x and y are integers, dimensions of the array. I have made a class myarray which makes the matrix. However the output of the program is blank spaces and \n. Does anyone know what can I do to fix it?

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

using namespace std;

class myarray
{
    char** grid;
    int dimX,dimY;
public:
    myarray(){grid=0;}
    myarray(int m,int n) {grid = new char* [m]; for(int i=0;i<m;i++) {grid[i]=new char [n];} dimX=m; dimY=n;}
    ~myarray(){for(int i = 0; i < dimX; ++i) {delete[] grid[i];} delete[] grid;}
    char** fetcharray(){return grid;}

    void display_grid();
    void randomize_grid(){for(int i=0;i<dimX;i++) for(int j=0;j<dimY;j++) grid[i][j]=rand()%10;}
};

int main()
{
    srand(time(NULL));
    bool check(true);
    while(check)
    {
        char a; //a-firstinp;
        int m,n; //m,n-grid size
        cin>>a;

        switch(a)
        {
        case 'i':
        case 'I': {cin>>m>>n;
                  myarray c(m,n);
                  c.randomize_grid();
                  c.display_grid();
                  break;}
        default: {cout<<"Invalid input! Possible commands: i,c,l,v,h,k,f,s,x! Try again: \n";
                  break;}
        }
    }
}

void myarray::display_grid()
{
    for(int i=0;i<dimX;i++)
    {
        cout<<"\n";
        for(int j=0;j<dimY;j++)
            cout<<grid[i][j];
    }
}

Thank you in advance!




Computationally picking a random point on a n-sphere

I need to randomly pick an n-dimensional vector with length 1. My best idea is to pick a random point in the sphere an normalize it:

import random

def point(n):
    sq = 0
    v = []
    while len(v) < n:
        x = 1 - 2*random.random()
        v.append(x)
        sq = sq + x*x
        if sq > 1:
            sq = 0
            v = []
    l = sq**(0.5)
    return [x / l for x in v]

The only problem is the volume of an n-ball gets smaller as the dimension goes up, so using a uniform distribution from random.random takes very long for even small n like 17. Is there a better way to get a random point on an n-sphere.




Executing program again, once finished (Python)

So I'm writing this little piece of code as a small project: It uses the turtle graphics module to draw various shapes. It picks which shape to draw by way of the random module. Here's the code.

import time
import sys
import random
import os
from turtle import *

while True:
    value = 0
    def f():
    global value
    value = 1
onkey(f, "q")
listen()
random = random.choice('123456')
print(random)
if random == "1":
    #Star
    from turtle import *
    hideturtle()
    color('red', 'yellow')
    begin_fill()
    while True:
        forward(200)
        left(170)
        if abs(pos()) < 1:
            textinput("again1", "Again?")
            if textinput == "Yes"or"yes"or"Y"or"y":
                clearscreen()
                break
        if value == 1:
            textinput("again1", "Again?")
            if textinput == "Yes"or"yes"or"Y"or"y":
                clearscreen()
                break
    end_fill()
    done()
elif random == "2":
    #Extending Squares
    from turtle import *
    hideturtle()
    color('red', 'yellow')
    size=1
    begin_fill()
    while (True):
        forward(size)
        right(91)
        size = size + 1
        if value == 1:
            textinput("again2", "Again?")
            if textinput == "Yes"or"yes"or"Y"or"y":
                clearscreen()
                break
elif random == "3":
    #Extending Hexagons
    from turtle import *
    hideturtle()
    color('red','yellow')
    size=1
    while True:
        forward(size)
        right(61)
        size = size + 1
        if value == 1:
            textinput("again3", "Again?")
            if textinput == "Yes"or"yes"or"Y"or"y":
                clearscreen()
                break
elif random == "4":
    #Recursive Star
    import turtle
    from turtle import *
    def star(turtle, n,r):
     """ draw a star of n rays of length r"""
     for k in range(0,n):
        turtle.pendown()
        turtle.forward(r)
        turtle.penup()
        turtle.backward(r)
        turtle.left(360/n)

    def recursive_star(turtle, n, r, depth, f):
     """At each point of the star, draw another smaller star,
     and so on, up to given depth. Rescale the stars by a factor f
     at each generation."""
     if depth == 0:
        star(turtle, n, f*4)
     else:
        for k in range(0,n):
            turtle.pendown()
            turtle.forward(r)
            recursive_star(turtle, n, f*r, depth - 1,f)
            turtle.penup()
            turtle.backward(r)
            turtle.left(360/n)
            if value == 1:
                textinput("again4", "Again?")
                if textinput == "Yes"or"yes"or"Y"or"y":
                    clearscreen()
                    break

    fred = turtle.Turtle()
    fred.speed("fastest")
    fred.color('red','yellow')
    fred.hideturtle()
    recursive_star(fred, 5 , 150, 4, 0.4)
elif random == "5":
    #Honeycombs
    from turtle import *
    color('red','yellow')
    penup()
    setx(-200)
    sety(-150)
    pendown()
    side = 0
    side1 = 0
    begin_fill()
    while True:
        forward(50)
        right(60)
        side = side + 1
        side1 = side1 + 1
        if value == 1:
            textinput("again5", "Again?")
            if textinput == "Yes"or"yes"or"Y"or"y":
                clearscreen()
                break
        if side == 6:
            side = 0
            end_fill()
            begin_fill()
            while True:
                forward(50)
                left(60)
                side = side + 1
                side1 = side1 + 1
                if value == 1:
                    break
                if side == 6:
                    end_fill()
                    side = 0
                    forward(50)
                    left(60)
                    begin_fill()
                    break
        if side1 == 72:
             side1 = 0
             forward(50)
             left(60)
             forward(50)
             right(60)
elif random == "6":
    #Lattice of Squares
    color('red','yellow')
    while True:
        forward(200)
        right(91)
        forward(50)
        right(91)
        forward(50)
        right(91)
        if value == 1:
            textinput("again6", "Again?")
            if textinput == "Y"or"y"or"Yes"or"yes":
                clearscreen()
                break

else: sys.exit()

When the user presses "q" and asks the program to draw another shape, I want the program to go back to the top of the very outermost while loop. I'm using break to do this and it works fine. However, I run into trouble when it gets to:

random = random.choice('123456')

The program gives me an error, saying:

Traceback (most recent call last):
File "C:\Users\aerro_000\Desktop\PrettyShapes.py", line 14, in <module>
random = random.choice('123456')
AttributeError: 'str' object has no attribute 'choice'

How do I fix this? Or is there a way to just restart the entire program? I've also tried using random.randint but I get a similar error. Thanks in advance.




RSA and Perl - how randomness is achieved?

Does anyone have an experience of generating RSA keys with Crypt::OpenSSL::RSA module? The documentation seems to be vague regarding how randomness is achieved. For example, is it mandatory to call

Crypt::OpenSSL::RSA->import_random_seed();

before every call to

Crypt::OpenSSL::RSA->generate_key

or maybe calling import_random_seed once is enough even with multiple subsequent calls to generate_key?

And what about Crypt::OpenSSL::Random::random_seed($good_entropy)? It's said to be not necessary if there is /dev/random, but what if it's Windows?




samedi 25 juin 2016

Random numbers and while loop issues

I have to generate two random numbers for 52000 instances in an ArrayList, attack 1 and attack 2, where attack 1 must be greater than attack 2, so i have to put them in the list. This is my sample code:

do{
            atk_p1 = (int) (Math.random() * (5000-500+1)+500);
            atk_p2 = (int) (Math.random() * (5000-500+1)+500);
}while(atk_p1 <= atk_p2);
data.add(String.valueOf(atk_p1));
data.add(String.valueOf(atk_p2));

My problem is that the above code sometimes works (thus atk_p1 is greater than atk_p2) but other times not (thus atk_p2 is greater than atk_p1). I'm trying to solve the issue. Thank you for your help.




PHP - Help creating a PHP number generator [on hold]

I am working on a school assignment that currently needs me to build a random number generator.

The user types in a number, and the program has to create that many random numbers between 1 and 20. It shows all the numbers, together with the average, and also keeps track of how many times each number has been used in total.

I do not need anybody to write the complete code for me, I'll be able to find the syntax and the ways methods work, but I have no clue where to start. What do I use? a For loop? an if or a return, an array? nothing seems to really work.




Big random numbers on GNU Octave or matlab

I need to generate random numbers between 0 and 1e37. I've tried these codes:

numbers = [];
numbers= [numbers; unifrnd(0,1e37, numSamples, 1)];

_

numbers = [];
for i=1:numSamples 
numbers= [numbers;  0 + (9-0)*rand(1) * 10**(0 + (35 - 0)*rand(1))];
endfo

Both codes generate an array [numSamples,1] full of random numbers but when I plot the results, or see their values, I realize that most part of them are between 1e36 and 1e37. What I'm looking for is a normal or gaussian distribution, I mean, I want most part of those random numbers to be between 1e15 and 1e30 for example, but I don't know how I could achieve this.

I've tried this on GNU Octave but it doesn't matter if someone gives a solution on Matlab.

Forgot to say that I'm trying with 1e3 < numSamples < 1e7




Fixed seed random number between 0 and 1

I want to generate list of fixed random numbers by giving a seed between 0 and 1 in python. For example, l = [0.1, 0.5, 0.6, 0.9, 0.75]. I can get this by using random.random(). But every time it gives a new random number list. I want to fix it by giving some some seed.

How can I do that. Thanks in advance!




strange random seed behavior in Python3

Outputting a set of numbers does not give the same sequence even after using random.seed(myseed). This only occurs in Python3, not in Python2 (both on a Debian stable system). Is it a bug or something wrong with my code ?

import random
seed=20.0
random.seed(seed)
print("seed: {}".format(seed))
test = [str(random.randint(0,1000)) for _ in range(10)]
print(', '.join(test))
ss = set(test)
print(', '.join(ss))

Below Python3 gives a different sequences at each run, but Python2 gives similar sequences across all runs(as expected).

$ python3 --version
Python 3.4.2
$ python2 --version
Python 2.7.9

#same sequences
$ python2 randtest.py 
seed: 20.0
906, 686, 767, 905, 260, 636, 905, 873, 573, 169
906, 636, 905, 573, 767, 873, 260, 169, 686

$ python2 randtest.py 
seed: 20.0
906, 686, 767, 905, 260, 636, 905, 873, 573, 169
906, 636, 905, 573, 767, 873, 260, 169, 686

$ python2 randtest.py 
seed: 20.0
906, 686, 767, 905, 260, 636, 905, 873, 573, 169
906, 636, 905, 573, 767, 873, 260, 169, 686

#diff sequences
$ python3 randtest.py 
seed: 20.0
927, 740, 702, 805, 784, 901, 926, 154, 266, 690
926, 690, 784, 702, 740, 927, 266, 154, 901, 805

$ python3 randtest.py 
seed: 20.0
927, 740, 702, 805, 784, 901, 926, 154, 266, 690
702, 926, 784, 901, 154, 266, 805, 690, 740, 927

$ python3 randtest.py 
seed: 20.0
927, 740, 702, 805, 784, 901, 926, 154, 266, 690
805, 926, 901, 784, 740, 927, 154, 690, 266, 702




Why isnt this script actually randomizing as it should be? (BATCH)

The code below is suppose to take 1 file out of each sub directory in d:\test and put them in f:\source, it does this but the randomization part isn't working. Each file from each folder gets picked based on creation date, and the last "created" file in each folder is always the ones that appear in f:\source.

Any ideas why?

setlocal EnableDelayedExpansion cd D:\test set t=0 for /d %%i in () do ( cd "%%i" set /A t+=1 set n[!t!]=0 for %%f in (.) do ( set /A n[!t!]+=1 set "file[!n!]=%%f" ) set /A "rand=(n[!t!]%random%)/32768+1" copy "!file[%rand%]!" f:\source cd.. ) pause




Recreate a random array to set into Gridview after using OnItemClickListener

I'm trying to make a simple game using a random array and put it in gridview. But after click on item of gridview, i can't generate a new array because next random array must be inside the OnItemClickListener- can't setAdapter like outside OnCreate method.I need anysolution from you guys. Here is my code:

 for (int j=1;j<25;){
        int random=((int)(Math.random()*25))+1;
        if (!list.contains(random)){
            list.add (random);
            j++;

        }
    }
     list.add(a);

    gridView = (GridView) findViewById(R.id.gridView);
    final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,
            android.R.layout.simple_list_item_1,list);

    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
           gridView=(GridView)findViewById(R.id.gridView);
            Integer values=Integer.parseInt(gridView.getItemAtPosition(position).toString());
            y.setText(String.valueOf(value));
            if (a==values){

                for (int j=1;j<25;){
                    int random=((int)(Math.random()*25))+1;
                    if (!list.contains(random)){
                        list.add (random);
                        j++;
                    }
                }
                list.add(a);



                Collections.shuffle(list);
               adapter.notifyDataSetChanged();
                a=a+r.nextInt(11);
                x.setText(String.valueOf(a));
                System.out.println(a);

                Toast.makeText(getApplicationContext(),
                        "OK", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getApplicationContext(),
                        "Failed", Toast.LENGTH_SHORT).show();
            }

        }
    });

}




How can start a DAG in random time

I have a DAG that triggered by airflow scheduler and runs at 1 min passed midnight every day. I want to change the start time every day to be dynamic, one day to start at 1:00 am , the next day at 00:16 and etc. Is there any configuration in airflow to do this? If not what can I do?




how to make random city map?

I make 2d roguelike game in Unity, and I want to make random city map like this.

http://ift.tt/28U1mWS

But I don't know how to make the map like that site. Please help me to know random city map algorithm.




vendredi 24 juin 2016

problems with tr1/random

I tried to create a series of random numbers using uniform distribution whose limits are given from a file.

void initialize ( string file_in_name )
{
  ifstream file_in;
  int i;
  int j;
  //lbound= lower value bound, ubound=upper value bound
  double lbound;
  double ubound;

  file_in.open ( file_in_name.c_str ( ) );

  if ( !file_in )
  {
    cout << "\n";
    cout << "Initialize - Fatal error!\n";
    cout << "  Cannot open the input file!\n";
    exit ( 1 );
  }
//
//  Initialize variables within the bounds
//
  for ( i = 0; i < NVARS; i++ )
  {
    file_in >> lbound >> ubound;

    for ( j = 0; j < POPSIZE; j++ )
    {

      population[j].lower[i] = lbound;
      population[j].upper[i]= ubound;
      population[j].value[i] = randval ( population[j].lower[i],population[j].upper[i] );
    }
  }

  file_in.close ( );

  return;
}

where randval is the following function

double randval ( double low, double high )
{
  double val;
  mt19937 generator;
  uniform_real<double> distribution(low, high);
  val = distribution(generator);
  return ( val );
}

The distribution I use is from tr1/random, but every time I use execute the code, the results are out of bounds. To be more specific, the file I give has lower and upper bounds equal to -180 and 180 respectively and the values are of order 10^12.

What could be the problem?




Why does /dev/random on ubuntu generate data slower than on debian?

During test of a copy function I've copied data from /dev/random to /dev/null and measured the throughput. On my Debian testing machine, I'm getting about 200 kb/s consistently. On Ubuntu 14.04, Ubuntu testing and a server running Linux 3.12.53-40 (no name) I'm getting 2 bytes/s.

Wiki says that /dev/random only has a limited entropy pool and blocks when that is empty. However I can't find anything on why Debian generates that much faster?

Any pointers would be appreciated.




Efficient way to randomize data model in Rails

Creating a programming schedule based on videos in object model. I want to run a task every day to shuffle this model so the programming each day would be different.

I am aware of product.shuffle.all for ex. but I want the order to be saved one time each day to do so vs on each server call.

I am thinking to add an attribute to each product, named order which would be an integer to order by. How would I shuffle just product.order for all products in this case?

Would this be the most efficient way? Thanks for the help!




Randomly Load URL From List Into IFrame Every X Seconds

I'm currently using the below code - which is exactly what I want - bar one thing, I'd like it to randomly select a url as appose to it's current sequential action…

Any tips on how to achieve this will be super greatly appreciated…

    // start when the page is loaded
window.onload = function() {

  var urls = [
    "http://url.club/one",
    "http://url.club/two",
    "http://url.club/three"
  ];

  var index = 1;
  var el = document.getElementById("raves");

  setTimeout(function rotate() {

    if ( index === urls.length ) {
      index = 0;
    }

    el.src = urls[index];
    index  = index + 1;

    // continue rotating iframes
    setTimeout(rotate, 5000);

  }, 5000); 
};




How to add random shapes on click using canvas animation

For this animation On click I need a different shapes to be made I need 5 different shapes in total. Also Ive had a hard time doing these things,

add a random motion vector to every circle

add an interval timer that redraws the background and each circle in its new position every 30 milliseconds

Check if any circle is outside the canvas width and height, and if so reverse its direction back onto the screen

also maybe If I can have some random text to fade in and fade out every couple of seconds too

this is in my body

<canvas id='canvas' width=500 height=500></canvas>

this is my script

<script>
  var canvas;
  var context;
  var circles = [];
  var timer;
  function Circle(x, y, color) {
    this.x = x;
    this.y = y;
    this.dx = Math.random()*4-2;
    this.dy = Math.random()*4-2;
    this.color = color;
  }
  function init() {
    canvas = document.getElementById('canvas');
    context = canvas.getContext("2d");

    window.addEventListener('resize', resizeCanvas, false);
    window.addEventListener('orientationchange', resizeCanvas, false);
    resizeCanvas();
    canvas.onclick = function(event) {
        handleClick(event.clientX, event.clientY);
    };
    timer = setInterval(resizeCanvas, 20);
  }
  function handleClick(x, y) {
     var found = false;
     for (var i=0; i<circles.length; i++) {
        d = Math.sqrt((circles[i].x - x)*(circles[i].x - x) + (circles[i].y - y)*(circles[i].y - y));
        if (d <= 30) {
            circles.splice(i, 1);
            found = true;
        }
     }
     fillBackgroundColor();
     if (!found) {
        var colors = ["red", "green", "blue", "orange", "purple", "yellow"];
        var color = colors[Math.floor(Math.random()*colors.length)];
        circles.push(new Circle(x, y, color));
    }
    for (var i=0; i<circles.length; i++) {
        drawCircle(circles[i]);
    }
  }
  function drawCircle(circle) {
     context.beginPath();
     context.arc(circle.x, circle.y, 30, 0, degreesToRadians(360), true);
     context.fillStyle = circle.color;
     context.fill();
     if (circle.x + circle.dx > canvas.width || circle.x + circle.dx < 0)
        circle.dx = -circle.dx;
     if (circle.y + circle.dy > canvas.height || circle.y + circle.dy < 0)
        circle.dy = -circle.dy;
     circle.x += circle.dx;
     circle.y += circle.dy;
  }
  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    fillBackgroundColor();
    for (var i=0; i<circles.length; i++) {
        drawCircle(circles[i]);
     }
  }
  function fillBackgroundColor() {
     //var colors = ["white", "yellow", "blue", "red"];
     //var bgColor = colors[Math.floor(Math.random() * colors.length)];
     context.fillStyle = 'black';
     context.fillRect(0, 0, canvas.width, canvas.height);
}
function degreesToRadians(degrees) {
    //converts from degrees to radians and returns
    return (degrees * Math.PI)/180;
}
window.onload = init;




Why is rand() not giving me a random sequence of numbers?

I'm trying to make a Tetris game using the SDL-library. When a new shape appears I want it to be random, so therefore I've tried to make a function that takes a takes a random number between 0 to 4, which is later used to decide what shape that will appear. Here's the function so far:

int EventHandler::setShapeType() {

if (m_seeded == false) {
    srand(time(NULL) * SDL_GetTicks()); //SDL_GetTicks returns the number of miliseconds since the SDL_library was initialized
    m_seeded = true;
}

int shapeType = (int) (((double) rand()/RAND_MAX) * 4.999);

cout << shapeType << endl;

return shapeType;

}

m_seeded is a method variable in EventHandler and is set to false in the constructor, so the first if-statement only runs once.

As you can see the function is not complete yet, and the printing of shapeType is solely there for debugging purposes, but so far it should atleast be able to generate a random number... Which it doesn't seem to do. In my main function I made a 10000 iteration loop in which counted how often every number between 0 to 4 was returned, and afterwards printed out the final result as percentage relative to the maximum number of iterations. Here's the result:

  • Zero: 29.8
  • One: 23.9
  • Two: 19.2
  • Three: 14.7
  • Four: 12.4

Now, I thought that for 10000 iterations every number would appear around the same number of times, but they don't! With small differences, this is the result I get every time. I know that rand() in fact just takes numbers from a premade list, and that the "randomness" comes from what seed you use, but shoudn't I get more varied results than what I'm getting? Well, I'm lost, I'd love some help on this.




PRBS23 & PRBS31 algorithm / code

Can anyone explain how PRBS23 & 31 works? How can I generate N numbers using this algorithm? I have tried to modify a few code examples on the internet, but didn't work.




Accelerate calls to pnorm

Is there a way to optimize a call to pnorm ? I am having some bottleneck in my code and after a lot a optimization and benchmark I realized that it comes from the call to pnorm on relatively big vectors.

With microbenchmarking I got on my machine that if length(u) ~ 1e7 then pnorm(u) takes 1 sec.

Also I noted that using pnorm on one vector on cutting the problem with sapply does not change anything.

Is there a way to use Rcpp here ? or the built-in pnorm is already optimized ?

Any ideas welcome

NOTE I have found these posts on SO: Use pnorm from Rmath.h with Rcpp and How can I use qnorm on Rcpp? but as far as I understood their purpose is to use the R functions into Cpp code




For ANY neighbouring Element do c++ random

I'm trying to implement an Algorithm, that depends on choosing any Element of the neighbouring six Elements, that is stored in an 8bit uint. At the Moment I compare

if ((temp & 16) != 0){ //do something }

for 1, 2, 4, 8, 16 and 32 to compare the corresponding Bits. If this Element is in the list it executes the code, but at the Moment it always chooses the same Element from the List (the last one overwrites the results of the previous ones).

Is there an elegant way to choose a random Element from the Elements in the list? So it doesn't take the same Element in every Iteration. The Code is in C++. Thanks in advance.

Edit:

        if ((temp & 1) != 0){
            if (lHeight[sX-1][sY][sZ] < lHeight[sX][sY][sZ]){
                lNf = 1;
                lDist[sX][sY][sZ] = lDist[sX - 1][sY][sZ] + 1;
                lLabel[sX][sY][sZ] = lLabel[sX - 1][sY][sZ];
                lHeight[sX][sY][sZ] = lHeight[sX - 1][sY][sZ];
                state[k] = false;
            }
            else{
                if (lLabel[sX][sY][sZ] > lLabel[sX - 1][sY][sZ]){
                    lLabel[sX][sY][sZ] = lLabel[sX - 1][sY][sZ];
                }
            }
        }
        if ((temp & 2) != 0){
            if (lHeight[sX +1][sY][sZ] < lHeight[sX][sY][sZ]){
                lNf = 2;
                lDist[sX][sY][sZ] = lDist[sX + 1][sY][sZ] + 1;
                lLabel[sX][sY][sZ] = lLabel[sX + 1][sY][sZ];
                lHeight[sX][sY][sZ] = lHeight[sX + 1][sY][sZ];
                state[k] = false;
            }
            else{
                if (lLabel[sX][sY][sZ] > lLabel[sX + 1][sY][sZ]){
                    lLabel[sX][sY][sZ] = lLabel[sX + 1][sY][sZ];
                }
            }
        }
        if ((temp & 4) != 0){
            if (lHeight[sX][sY-1][sZ] < lHeight[sX][sY][sZ]){
                lNf = 4;
                lDist[sX][sY][sZ] = lDist[sX][sY-1][sZ] + 1;
                lLabel[sX][sY][sZ] = lLabel[sX][sY-1][sZ];
                lHeight[sX][sY][sZ] = lHeight[sX][sY-1][sZ];
                state[k] = false;
            }
            else{
                if (lLabel[sX][sY][sZ] > lLabel[sX][sY-1][sZ]){
                    lLabel[sX][sY][sZ] = lLabel[sX][sY-1][sZ];
                }
            }
        }
        if ((temp & 8) != 0){
            if (lHeight[sX][sY+1][sZ] < lHeight[sX][sY][sZ]){
                lNf = 8;
                lDist[sX][sY][sZ] = lDist[sX][sY+1][sZ] + 1;
                lLabel[sX][sY][sZ] = lLabel[sX][sY+1][sZ];
                lHeight[sX][sY][sZ] = lHeight[sX][sY+1][sZ];
                state[k] = false;
            }
            else{
                if (lLabel[sX][sY][sZ] > lLabel[sX][sY+1][sZ]){
                    lLabel[sX][sY][sZ] = lLabel[sX][sY+1][sZ];
                }
            }
        }
        if ((temp & 16) != 0){
            if (lHeight[sX][sY][sZ-1] < lHeight[sX][sY][sZ]){
                lNf = 16;
                lDist[sX][sY][sZ] = lDist[sX][sY][sZ-1] + 1;
                lLabel[sX][sY][sZ] = lLabel[sX][sY][sZ-1];
                lHeight[sX][sY][sZ] = lHeight[sX][sY][sZ-1];
                state[k] = false;
            }
            else{
                if (lLabel[sX][sY][sZ] > lLabel[sX][sY][sZ-1]){
                    lLabel[sX][sY][sZ] = lLabel[sX][sY][sZ-1];
                }
            }
        }
        if ((temp & 32) != 0){
            if (lHeight[sX][sY][sZ+1] < lHeight[sX][sY][sZ]){
                lNf = 32;
                lDist[sX][sY][sZ] = lDist[sX][sY][sZ+1] + 1;
                lLabel[sX][sY][sZ] = lLabel[sX][sY][sZ+1];
                lHeight[sX][sY][sZ] = lHeight[sX][sY][sZ+1];
                state[k] = false;
            }
            else{
                if (lLabel[sX][sY][sZ] > lLabel[sX][sY][sZ+1]){
                    lLabel[sX][sY][sZ] = lLabel[sX][sY][sZ+1];
                }
            }
        }

I set the Bits if the Grayvalues of the neighbouring Pixels are the same. But now I want to choose any of the Elements and not the last one.




jeudi 23 juin 2016

What is the correct way to implement THIS action into my Sprite-Kit Game?

I have a birdNode(spriteNode) traveling horizontally across a portrait scene.

The birdNode is dropping an egg(spriteNode) towards a cgPoint at the bottom of the screen.

I want the birdNode to randomely drop his egg at any time/position.

I have considered creating an NSTimeInterval with a random number between 2 seconds(time it takes birdNode to travel across screen), making the eggNode spawn at birdNode position, and invoking dropEgg function.

I have also considered generating a random CGPoint, loading the eggNode at

birdNode.position.x = randomPoint

and then invoking the dropEgg function.

My question is should I use a certain approach over another? Where exactly should I call the dropNode function. Right now i can not get it to work.

I have tried to consider randomTime/randomPosition in the currentTime update function below and drop the Node, but it makes eggs at every frame render so I don't think thats the right way.

override func update(currentTime: CFTimeInterval) {
}

Here is my code for dropping the egg, and creating a random dropPoint float, and bird flying across screen.

    func dropEgg(){

    //aim
    let dx = eggNodeTarget.position.x - birdNode.position.x
    let dy = eggNodeTarget.position.y - birdNode.position.y
    let angle = atan2(dy, dx)
    dragonProjectileNode.zRotation = angle

    //Seek
    var vx = turretNode.position.x
    var vy = turretNode.position.y

    //creates eggNodeSprite
    loadEggNode()  

    //shoot
    let shootAction = SKAction.moveTo(CGPointMake(vx, vy),duration: 0.75)
    eggNode.runAction(shootAction)

}

func loadRandDropLocationX() -> CGFloat{

    //or minNodeTimeValue?
    var MinNodeSpawnValue = self.frame.size.width * 0.2

    //or maxNodeTimeValue?
    var MaxNodeSpawnValue = self.frame.size.width * 0.8

    //or randomTime?
    var randomPointUInt32 = UInt32(MaxSpawnValue - MinSpawnValue)
    return (CGFloat(arc4random_uniform(randomPointUInt32)) + MinNodeSpawnValue)
}

func dragonMoveRight(){
    let moveDragon = SKAction.moveTo(loadRandDestinationRight(), duration: 2.3)
    dragonNode.runAction(moveDragon)
}




get /dev/random in kernel module

I need to get both /dev/random and /dev/urandom within kernel module.

get_random_bytes API provided to get /dev/urandom.

But there is no API for /dev/random so I tried to ioctl and read file in kernel space.
Here is what I have done.

  1. using RNDGETPOOL ioctl

in include/linux/random.h
RNDGETPOOL is declared

/* Get the contents of the entropy pool.  (Superuser only.) */
#define RNDGETPOOL      _IOR( 'R', 0x02, int [2] )

but, It won't work so I checked driver/char/random.h noticed RNDGETPOOL is gone!!

static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
    int size, ent_count;
    int __user *p = (int __user *)arg;
    int retval;

    switch (cmd) {
    case RNDGETENTCNT:
            /* inherently racy, no point locking */
            if (put_user(input_pool.entropy_count, p))
                    return -EFAULT;
            return 0;
    case RNDADDTOENTCNT:
            if (!capable(CAP_SYS_ADMIN))
                    return -EPERM;
            if (get_user(ent_count, p))
                    return -EFAULT;
            credit_entropy_bits(&input_pool, ent_count);
            return 0;
    case RNDADDENTROPY:
            if (!capable(CAP_SYS_ADMIN))
                    return -EPERM;
            if (get_user(ent_count, p++))
                    return -EFAULT;
            if (ent_count < 0)
                    return -EINVAL;
            if (get_user(size, p++))
                    return -EFAULT;
            retval = write_pool(&input_pool, (const char __user *)p,
                                size);
            if (retval < 0)
                    return retval;
            credit_entropy_bits(&input_pool, ent_count);
            return 0;
    case RNDZAPENTCNT:
    case RNDCLEARPOOL:
            /* Clear the entropy pool counters. */
            if (!capable(CAP_SYS_ADMIN))
                    return -EPERM;
            rand_initialize();
            return 0;
    default:
            return -EINVAL;
    }
}

I searched google and find out ioctl RNDGETPOOL is removed. done! (http://ift.tt/28U8qXl)

  1. using random_read function (driver/char/random.c:997 static ssize_t random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos))

here is my kernel module's function accesses to /dev/random.

static void read_file()
{
  struct file *file;
  loff_t pos = 0;
  //ssize_t wc;
  unsigned char buf_ent[21]={0,};
  int ent_c;
  int i;
  ssize_t length = 0;

  mm_segment_t old_fs = get_fs();
  set_fs(KERNEL_DS);

  file = filp_open("/dev/random", O_WRONLY, 0);
  file->f_op->unlocked_ioctl(file, RNDGETENTCNT, &ent_c);
  if(ent_c < sizeof(char))
  {
    printk("not enough entropy\n");
  }
  printk("ent counter : %d\n", ent_c);

  //file->f_op->unlocked_ioctl(file, RNDGETPOOL, &ent_st.buf);
  length = file->f_op->read(file, buf_ent, ent_c/ 8, &pos);
  if(length <0)
  {
    printk("failed to random_read\n");
  }
  printk("length : %d\n", length);
  printk("ent: ");
  for(i=0;i<length; i++)
  {
      printk("%02x", buf_ent[i]);
  }
  printk("\n");
  filp_close(file,0);
  set_fs(old_fs);
}

outputs seems to be random

first try [1290902.992048] ent_c : 165
[1290902.992060] length : 20
[1290902.992060] ent: d89290f4a5eea8e087a63943ed0129041e80b568

second try [1290911.493990] ent_c : 33
[1290911.493994] length : 4
[1290911.493994] ent: 7832640a

by the way random_read function argument has __user keyword. Buf buf in code is in kernel space.

Is appropriate using random_read function in kernel space??




Macro to auto calculate selective excel sheet where RAND Between formula is being used

I have a rand between formula on my sheet and would like to auto compute selective area of excel sheet without changing the value again in rand between cell.

The issue I am getting is when the form is set to auto calculate, field value of RANDBETWEEN also refreshes.




Set value in random ViewController (random segue)

I have 12 ViewControllers. My code gives a random segue to one of these ViewControllers (1-12)

let segues = ["View1", "View2", "View3", "View4", "View5", "View6", "View7", "View8", "View9", "View10", "View11", "View12"]
    let index = Int(arc4random_uniform(UInt32(segues.count)))
    let segueName = segues[index]
    self.performSegueWithIdentifier(segueName, sender: self)

.

Now, I want to change a variable in the random ViewController that has been chosen (var firstSegue = false) but I can't figure out how?

.

Could someone change this into something that will work?

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    let destinationVC = segue.destinationViewController as UIViewController
    destinationVC.firstSegue = true
}




How to refer to a randomly generated button's elements

I need to randomly generate a button and then grab elements from it from the activity that the button opens. Specifically the universal ID of a "character" that I have specified in PersistentData. (That whole class works fine, though. The problem is between this activity and the next.) The child activity has multiple activities that can call it. (There are several activities with lists made from different characters from a pool, and each list has these buttons that are shown below, which all point to the same activity that loads information from PersistentData based on the data that its supposed to pull from said button.) The following 1 block of code is in the onCreate method for this activity. (Automatically generated, I just added this in after I called the layouts from the XML file)

for (fID = 0; fID < PersistentData.fName.size(); fID++) {

        if (PersistentData.fName.get(fID) != null) {
            Button[] Btn = new Button[PersistentData.fName.size()];
            Btn[fID].setHeight(200);
            Btn[fID].setWidth(200);
            Btn[fID].setTextSize(40);
            Btn[fID].setText(PersistentData.fName.get(fID));
            Btn[fID].setTag(fID);
            Layout.addView(Btn[fID]);
            Btn[fID].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    int btnID = fID;
                    gotoActivity(v);

                }

            });

        } else continue;

    }

Here is gotoActivity(). (In the class, not onCreate)

public void gotoActivity(View view) {
    Intent intent = new Intent(this, TargetActivity.class);
    startActivity(intent);
    intent.putExtra("btnClicked", /*IDK WHAT TO PUT RIGHT HERE*/);
}

I have put several things there, actually. Mostly, they have been various ways of declaring a variable on the creation of the button.

Here's the TargetActivity.class

public class Fighter extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fighter);

    Intent intent = getIntent();
    Bundle bundle =
            intent.getExtras(); //line ***
    **


    TextView viewName = (TextView) findViewById(R.id.fighterName);

    viewName.setText(PersistentData.fName.get(fID));

    }

}

What should I put in the other class that I should get here**? (fID) is the thing that I'm trying to get. I have tried putting and getting fID using the methods as described in the Create an Activity page from Android and it continued to give me a NullPointerException at line *** (I split the line to be precise.)

Any help is appreciated. I would not be surprised if there is a better way to do this, requiring me to scrap all my work and restart. I would prefer not to, though lol. I will be checking this post periodically throughout the day, so if you have any questions or require more detail, just post or message me. Thank you beforehand.




Strange python behaviour random

This small script generates a random float beween 0 and 1 and then if its less than "0.000111111111111" it will print the message "found it"

import random

value = 0.4 / 3600
print value

while True:
    rand = random.random()

    print "RAND IS: " + str(rand) + "----- VAL IS " + str(value)
    if rand < value:
        print "found it"

So seemingly the script runs and it never actually "finds it", however when I comment out the print statement before the if statement the command line is FILLED with "found it" even though the rand value isn't less than value. What the hell?




randomized element-wise multiplication in R

I've been digging around the site for an answer to my question, and I'm new with R so I'm hoping this is even possible. I have two large matrices of simulations (A = 100,000 x 50 and B = 10,000 x 50) that I would like to randomly multiply element-wise by row.

Essentially I would like each row in A to randomly select a row from B for element-wise multiplication.

A:

      [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    1    1    1    1    1
[3,]    1    1    1    1    1
[4,]    1    1    1    1    1
[5,]    1    1    1    1    1
[6,]    1    1    1    1    1
[7,]    1    1    1    1    1
[8,]    1    1    1    1    1
[9,]    1    1    1    1    1
[10,]   1    1    1    1    1

And B:

      [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
[4,]    4    4    4    4    4
[5,]    5    5    5    5    5

Is there an operator that could go through A's rows and randomly select a row from B to pair for element wise multiplication? For results something like this:

 C <- A&*&B
 C
 A[1,]*B[3,]
 A[2,]*B[1,]
 A[3,]*B[2,]  
 A[4,]*B[5,] 
 A[5,]*B[3,]  
 A[6,]*B[4,] 
 A[7,]*B[1,]  
 A[8,]*B[5,] 
 A[9,]*B[2,] 
 A[10,]*B[2,]

Thanks!




select count with 2 conditions

hy.

i got 2 tables, med and viz with the following structure:

med

  CREATE TABLE med 
     (id_med INT AUTO_INCREMENT PRIMARY KEY,
     name_m VARCHAR(50),
     surname_m VARCHAR(50),
     spec VARCHAR(50),
     UNIQUE (surname_m,name_m));

viz

     CREATE TABLE viz
        (id_m INT NOT NULL,
        id_p INT  NOT NULL,
        id_c INT  NOT NULL,
        dt DATETIME)

i need a select query that would give the full name from med where count of id_p<250 and year from dt is 2010.

the following query gives me a bad result :

    select count(id_p)<250 as no_p,
       (select distinct concat(name_m,' ',surname_m) from med where id_med=id_m) as fullname
       from viz where year(dt)=2010;




How to replace from regex with random value at each occurrence?

I have this kind of sentences:

var str = 'The <adjective> <noun> and <noun> <title>';

I would like to replace each <pattern> by a random value from their related array.

In my previous example I'd like to get something similar to:

var adjectives = ['big' 'small' 'funny'];
var nouns = ['dog', 'horse', 'ship'];
var title = ['bar', 'pub', 'club'];

var str = 'The <adjective> <noun> and <noun> <title>';
var r = str.replacePatterns({ noun: nouns, adjective: adjectives, title: titles });
console.log(r); // The big horse and ship club

I almost get it by didn't tough about same pattern (e. g. <noun>) twice in the same sentence. So I generate only one random value for each pattern...

String.prototype.replacePatterns = function (hash) {

    var string = this,
        key;

    for (key in hash) {
        if (hash.hasOwnProperty(key)) {
            var randomValue = hash[key][Math.floor(Math.random() * hash[key].length)];
            string = string.replace(new RegExp('\\<' + key + '\\>', 'gm'), randomValue);
        }
    }

    return string;
};

Could you help me to get something replacing each pattern by a random value instead of a global replacement?

I don't know how to loop result of a regex to replace the matches in the original sentence (with random value each time).




Insert a number to the random position in an array of random number

I'm developing a simple game to add 2 number and select a result in a gridview. But i'm only put a number to 1st or last position of my list's Array. How to add my result to the random position without give it an exactly index? Here is my code

  x=random.nextInt(11);
  a=a+x;

    for (int j=1;j<25;){
        int random=((int)(Math.random()*25))+1;
        if (!list.contains(random)){
            list.add (a+random);
            j++;

        }

    }