dimanche 31 décembre 2017

for each cell in range, run randomly through number 1 to 20 to find best outcome

I have not found any similar question like this so far. As I am new to VBA, I wasn't able to put anything real together. This is why I'm posting this here.

I have a dynamic range - Salesrng = Range(Cells(10, 6), Cells(10, Columns.Count).End(xlToLeft)) Now, for each cell in the range exactly one row below the Salesrng, I want the numbers 1 to 20 to run randomly through all cells in order to find the maximum outcome. This outcome is on a different sheet.

I hope somebody can help me because it feels like, this is way too complicated for my vba skills.




How can I count numbers of value occurrences in list with list comprehension?

model = [random.randint(0,1) if model.count(0) < 20 else 1 for _ in range(40)]

Of course model.count(0) is wrong. Here we go for right code, but w/o list comprehension.

model = list()
for i in range(40):
   if model.count(0) < 20:
       model.append(random.randint(0,1))
   else:
       model.append(1)

I'm just love list comprehensions it makes me easier to work with NLP and massives. So it would be cool to find new features.




samedi 30 décembre 2017

Generating Ongoing Looping Links without Repeats using JavaScript

I am trying to create a button that sends users through a 'loop' of links, and keeps going through it anywhere, perhaps with its own 'memory'.

(REFERENCE CODE BELOW) For example, I want the first click to go to the first item, /roles/mafia, then the second click (from another tab, browser, or device) to go to the second one, /roles/doctor, and so on. When the button has been clicked six times (so the list has finished), the seventh time should loop back to the first one.

So if Bob clicks on the button with his Mac, it will take him to /roles/mafia. But then seconds later, if Jill clicks on it with her iPhone, it will link to /roles/doctor, and so forth.

Here is my JS, but this doesn't work since this is a pseudo-random system, rather than forming a loop.

<script type="text/javascript">
    var urls = [
        "/roles/mafia",
        '/roles/doctor',
        '/roles/cupid',
        '/roles/mafioso',
        '/roles/pimp',
        '/roles/detective'
    ];

    function goSomewhere() {
        var url = urls[Math.floor(Math.random()*urls.length)];
        window.location = url; // redirect
    }
</script>

And then the HTML button:

<a href="#" onClick="randLink(); return false;" class="play-btn">JOIN SERVER</a>

I am aware this won't have a quite simple solution, and I'm very new to the concept of JavaScript and memory, so any help, even just a snippet to inspire another coder to find the answer, is enough.

Thanks for any help in advance :)




Get random items from firebase min 3 max 5

I am trying to get random items from my firebase database and it almost works, sometimes I only get one or two items when the minimum is 3 and max is 5. Every item has an index and it's getting the items that startAt(startindex) and endAt(startIndex+randomNumber).

Is there any other way to do this other than using an index on each item in the database?

Here is how the code looks now:

    randomNumber = getRandomInt(3,5);
    listView = (ListView)view.findViewById(R.id.listView);
    int startIndex = (int)(Math.random() * childs+1);

    adapter = new FirebaseListAdapter<TraningData>(getActivity(),TraningData.class,R.layout.layout_traning_item,ref_1
    .orderByChild("index")
    .startAt(startIndex)
    .endAt(startIndex+randomNumber)) {
        @Override
        protected void populateView(View view, final TraningData td, int i) {
            //Populating over here!
        }
    };
    listView.setAdapter(adapter);




Weighted random: roll dice 1 to 1000, averages to 100

I want to roll a dice from 1 to 1000. However, over many trials, I want the average to be 100.

How?




More about Random in Java: get almost real randomization [duplicate]

This question already has an answer here:

I was experimenting with Random class in Java and, as many others here on Stack Overflow, I noticed that using a seed will always give the same result (and it's okay, seems logic), but I still have a (theoretical) question: what's the real difference between giving a chosen seed and System.currentTimeMillis as seed? Testing the same program, the same time of the day, won't give me the same results after multiple tries?

I know it's really hard for me to obtain the same exact result, but if my program were to be used by millions, or billions of people, few could get the same results in terms of randomization, for example: Imagine a getpoints.exe where you have to click a bottom and get a random amount of points depending on the time of the day. Using Random(System.currentTimeMillis) won't be random over all because two people clicking at the same exact time will get the same amount, so the result won't be really random. The same applies if 1mln people press it simultaneously.

So the original question: are there pseudo-real but more accurate ways to get random numbers?




Add value to session array

I try to create an array and add a value to it each time a new random number is generated.

When I generate a number, but the array stays at one value.

<?php
session_start();
$numbers = array();
$_SESSION["numbers"] = $numbers;

function getNumber() {

$getNumber = rand(1, 75);
return $getNumber;

}

?>

<?php 
if(isset($_POST['submit'])) {
    $numbers[] = getNumber();
    array_push($_SESSION["numbers"], $numbers);
    echo $numbers[0] . "<br>";
}
?>

How can I create a array which is filled each time a number is generated? Or do I need to create a db for this?




PHP code for random number using /dev/random

Im running Ubuntu Server 16.04.3 LTS with TrueRNG V3 USB and rng-tools setup to use the hardware random number generator. I am not worried about blocking with this setup. My understanding is that the hardware RNG will fill /dev/random not /dev/urandom.

What code could I use in PHP to get a random number between min and max that uses /dev/random and thus my hardware RNG. There are plenty of articles about why not to use /dev/random, the use of mt_rand, etc but I cannot find any code on using /dev/random now that I have the hardware RNG installed.

I have done a lot of research but come up empty this time.

Can anyone help?




Store Random ID for MySql Table

I have a large (1.5M-2M) record MySql table which I am indexing into Sphinx.

I need the IDs to be random/non-sequential due to the fact I am doing a two-level order (order by FieldA DESC,FieldB DESC) which then by default orders by ID. This gives me undesirable results since I store my data by Vendor and I'd like more random vendors once the FieldA and FieldB Order is implemented.

Since I could not figure out how to do this on the fly I tried the following which I tested on small tables to generate random unique integers:

Update IGNORE Table Set ID=FLOOR(RAND() * 2000000)

But after an hour or so gave up on that approach :|

Is there some efficient way to generate random IDs?




Is there a way to randomize search results (record ids) with Sphinx?

I have a complex SphinxQL query which, at the end, orders results by a specific field, Preferred, so that all records with that indexed value of Preferred=1 come before all records w Preferred=0. I also order by weight() so basically I end up with:

Select * from idx_X where MATCH('various parameters') ORDER by Preferred DESC,Weight() Desc

The problem is that, though Preferred records come first I end up with records sorted by ID which puts results from one field, Vendor, in blocks so for instance I get:

Beta Shipping Beta Shipping Beta Shipping Acme Widgets Acme Widgets Acme Widgets Acme Widgets Acme Widgets

Which doesn't serve my purposes in this case well (often one 'Vendor' will have 1000 results)

So I'm looking to essentially do:

ORDER BY Preferred DESC,weight() DESC,ID RANDOM

So that after getting to Preferred Vendors whose weight is (e.g.) 100, I will get random Vendors vs blocks of them.




How can I generate random numbers in slabs of a range in Python3?

Suppose I want to generate 10 random numbers between 1 to 100. But I want to pick numbers randomly from each number of sets like 1-10, 11-20, 21-30,.... So that It does not come out like this: 1, 7, 26, 29, 51, 56, 59, 89, 92, 95. I want to pick numbers randomly like this: 7, 14, 22, 39, 45, 58, 64, 76, 87, 93.

I have created a code sample. But I can't figure out later part of the problem.

import random

def getInteger(prompt):
    result = int(input(prompt))
    return result

range1 = getInteger("Please Enter Initial Range: ")
range2 = getInteger("Please Enter Ending Range: ")
range3 = getInteger("Please Enter the Range size: ")

myList = random.sample(range(range1, range2), range3)

myList.sort()

print ("Random List is here: ", myList)

I am new to programming. I googled about it, but did not find any solution. Thank you guys in advance...




Use ONE random data type but generate different results? Please help [NEW TO CODING]

This is my first time using C# and our teacher required us to create a turn-based game as our finals exam. She only taught us basic codes so I'm only going on what I've learned from the Internet and I need help.

Below is the code I used to declare the variables:

        Random x= new Random();
        int xval;
        string xresult;

        xval = x.Next(4);
        string[] xlist = {
            "ZERO",
            "ONE",
            "TWO",
            "THREE",
        };
        xresult = xlist[xval];

My problem is that the result is the same for all the times I used it. I want it to change or reset each time. If you can help, it'd really be appreciated. Thanks.




Android java create buttons positioned randomly without exceed screen size

I'm trying to create an Activity that contains 10 buttons that are generated programmatically and are positioned in random places on the screen but without exceed the screen size.

I tried doing so but most of the buttons exceeded from the screen size (I couldn't see it).

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);
    Random rnd = new Random();

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int height = displaymetrics.heightPixels;
    int width = displaymetrics.widthPixels;

    for(int x = 0;x<10;x++) {

        Button btn = new Button(this);

        int Xpoistion = rnd.nextInt(width - 100) + 100;
        int Yposition = rnd.nextInt(height - 100) + 100;

        btn.setX(Xpoistion);
        btn.setY(Yposition);

        btn.setText(x +")"+width + "," + height + " | " + Xpoistion + "," + Yposition);

        linearLayout.addView(btn);

    }

So i'm trying to create the "limits of the screen" from height and width but for some reason I can't figure it out.

I played with Xposition and Yposition a lot but nothing seems to work for me.

Thank for very much for your help.




vendredi 29 décembre 2017

Random Number Generation in python, and how to store the random numbers [on hold]

Hey this program I wrote is horrible, and I already re-wrote it and it works thanks to one of the great answers, but the site has informed me that what I am asking is unclear, so I will take the liberty of editing it. What I was trying to ask was how do I make a game where you guess a number between 1 and 20. And also if I was correctly using the random number generating commabnd I am sorry I didn't clarify in my writing

from random import randint
Number_list=['(randint(0,20))']
a1=input("Guess a number between 1 and 20")
if (a1 == Number_list) :
    print("You are right!")
else :
    print("Incorrect nice try!")




Difficulty initiating Random with Float to Integer

For my program, I am trying to get a random range with variables I can input, but it seems to cause the program to crash when I try to work it. I have pinpointed where the main problem is, though:

float flux = stability/100;
int max = (int)(attack * (1 + flux));
int min = (int)(attack * (1 - flux));
for (int i = 0; i < attacksPerMinute; ++i) {
    damage = 0;
        for (int j = 0; j < ammo; ++j) {
            damage += damageFlux(min, max);
        }
    minuteDamage += damage;
}

damageFlux is thus:

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

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

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

Now, in my head, the min and max should work, but its not. It causes the error to be thrown, most likely because its not doing the math to cause the pair to be different. Here are a couple variables on how it should work:

If attack is 10 and the flux is .20, then max should be (10 * (1 + .20) = 12 and min should be (10 * (1 - .20) = 8. However, if I am getting the error thrown by the damageFlux call, then it means they are most likely matching the same value.




How do I accept input from the user? [on hold]

from random import randint
print ("let me role your dice")
print("how many dice do you want to role")
ranNum = randint(0,6)
x = input

this is a random number generator. I have tried many things like using elif and if, else.




Sum of random numbers from a string character count

So I have been working on this problem for a few days now. I have tried several things and done a lot of searching, but I just can't figure this one out. So my question is does anyone have an idea of a way to add the 5 random numbers together and print the sum? I was trying to assign them to an array, so far no luck. Any help would be greatly appreciated.

    #include <iostream>  
    #include <string>  
    #include <cstdlib>  
    #include <ctime>
    int main()
    {
    std::string str;  
    std::getline(std::cin, str);  
    int y = str.size();  
    std::srand(time(0));  
    for (int x = 1; x <= 5; x++)  
    {     
        std::cout<<1 + (std::rand() % y)<<std::endl;  
    }  
    return 0;  
    }  




Create a identical "random" float based on multiple data

I'm working on a game (Unity) and I need to create a random float value (between 0 and 1) based on multiple int and/or float.

I think it'll be more easy to manually create a single string for the function, but maybe it could accept a list of int and/or float.

Example of result:

  • "[5-91]-52-1" > 0.158756..

Important points:

  • The distribution of results (between 0 and 1) must be equals (don't want 90% of results between 0.45 and 0.55)
  • Asking 2 times for the same string must return the exact same result.
  • Results have no need to be unique.

Bonus Point:

  • Sometime I need that close similar string return close result, but not everytime. It's possible for "random generation" to handle a boolean with this feature ?



C++ Program stops Debugging "randomly" no Error

I created a program that generates Random Number between 1 and 12, with several restrictions. the function counter12 counts the steps between the last number and the current one. the function isValid checks if the random Number is valid with my parameters. I created a while(1) loop for endless test, to check the counters. I run this, it runs several (randomly) times, but then stops before printing the counter (zfs_ges). Here is my Code, it would be really nice if you can help me. With "It stops" i mean the debugger (I am using VS2017) with f10 and f11 runs throuugh, but just stops debugging, i cant go any step further. Maybe it is Time related?

// mex1.1.cpp: Definiert den Einstiegspunkt für die Konsolenanwendung.
//

#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
#include <time.h>

bool isValid(int zfz, int zfz_v)
{
    if (abs(zfz - zfz_v) < 5 || abs(zfz - zfz_v) > 7) {
        return true;
    }
    return false;
}

int counter12(int zfz, int zfz_v)
{
    int counter = 0;
    if (zfz < zfz_v) // neue Zahl kleiner als alte Zahl
    {
        while (zfz_v != 12)
        {
            zfz_v++;
            counter++;
        }
        while (zfz != 0)
        {
            zfz--;
            counter++;
        }
        if (counter > 6)
        {
            counter = abs(counter - 12);
        }
        return counter;
    }
    else if (zfz > zfz_v) // neue Zahl größer als alte Zahl
    {
        while (zfz != 12)
        {
            zfz++;
            counter++;
        }
        while (zfz_v != 0)
        {
            zfz_v--;
            counter++;
        }
        if (counter > 6)
        {
            counter = abs(counter - 12);
        }
        return counter;
    }
    else
    {
        return 0;
    }
}

int main()
{
    while (1)
    {
        srand((unsigned)time(NULL));
        int e = 55;
        int mai;
        int zfz, zfz_v, zfz_ges, temp, liste[12];
        float d;
        mai = 12;
        zfz_v = 1;
        zfz_ges = 0;
        temp = 0;
        d = 0;
        for (size_t i = 0; i < mai; i++)
        {
            liste[i] = i + 1;
        }

        while (temp < 12)
        {
            zfz = rand() % 12 + 1;
            if (isValid(zfz, zfz_v)) {
                for (size_t i = 0; i < mai; i++)
                {
                    if (zfz == liste[i])
                    {
                        liste[i] = 0;
                        temp++;
                        zfz_ges += counter12(zfz, zfz_v);
                        printf("%d\n", zfz);
                        zfz_v = zfz;
                        i = 12;
                    }
                }
            }
        }
        printf("%d\n", zfz_ges - 1);

        e--;
    }
}




jeudi 28 décembre 2017

Array for loops and RNG in Java

I'm attempting to write a simple for loop that generates three integers and assigns each value to an array index. The second for loop in my code returns unexpected results. Can someone explain to me what's going on?

import java.util.Random;

public class Main {

public static void main(String[] args) {

    //variables
    int[] array = new int[3];
    Random rand = new Random();

    //all else

    for(int item : array) {                     
            array[item] = rand.nextInt(100)+1;
            System.out.println(array[item]);                                
    }       

    System.out.println("\n " +  array[0] + " " + array[1] + " " + array[2]);

    for(int i = array.length; i > 0; i--){
        System.out.println(array[i-1]);         
    }       

}

}




.Net Framework is much slower than .Net Core? [duplicate]

This question already has an answer here:

So i build this code in .Net Core and it works wonderfully good But when i use this code in .NetFramework It's really slow and not picking up the pace

    static int wichOneIsBigger(Random rand, int number)
    {
        //65-90 (Upper) 97 122 (Lower)
        Exception e = new Exception("Number must be 0 for lower case and 1 for upper case");
        if (number != 0 && number != 1)
            throw e;
        else
            if (number == 0)
            return rand.Next(97, 122);
        else
            return rand.Next(65 - 90);
    }
    static void Main()
    {
        string txt = null;

        Random rand = null;
        int length = 0;
        Console.WriteLine("Please type a number that is above 1: ");

        txt = Console.ReadLine();
        length = Convert.ToInt32(txt);

        string[] words = new string[length];
        for (int i = 0; i < length; i++)
        {
            rand = new Random();
            int characters = rand.Next(4, 10);
            int randCharacter = 0;
            int wichOne = 0;
            string word = "";
            for (int num = 0; num < characters; num++)
            {
                wichOne = rand.Next(0, 1);
                randCharacter = wichOneIsBigger(rand, wichOne);

                word += Convert.ToChar(randCharacter);
            }
            words[i] = word;
        }

        foreach (string item in words)
            Console.WriteLine(item);

        GC.Collect();
        Console.ReadKey();
    }

when im using .Net Core it's giving me this result for example the length is 5:

gaerantd
dxunjxtw
gevnyiqb
xhpsvfqu
gnnkaulxg

But when im using .Net Framework it giving me this

aist
aist
aist
aist
aist

Why in the .Net Framework it wont picking up the pace? I didnt programmed for 2.5 years and i dont remmember .Net Framework being this slow

By the way do you guys have any suggestion of my code? Can i write it better and etc?

Thanks for the help :)




Numpy random choice function gives weird results

I have a list of numbers and other list of probabilities which corresponds to these numbers. I am trying to select a number from numbers list based on probability. For this purpose I use random.choice function from Numpy library. As far as i know random.choice function doesnt have to select 1st entry based on its probability(it is equals to zero). However after several iteration it selects first entry. Can anybody help me out?enter image description here

Please see this ss from terminal




Sliding weighted randomization from number range?

When picking a random number from a range, I'm doing rand(0..100). That works all well and good, but I'd like it to favor the lower end of the range.

So, there's the highest probability of picking 0 and the lowest probability of picking 100 (and then everything in between), based on some weighted scale.

How would I implement that in Ruby?




How can I make the unique random numbers from this code appear on my page?

Someone showed me the following code which generates 3 random numbers between 1 and 10:

var limit = 10,
    amount = 3,
    lower_bound = 1,
    upper_bound = 10,
    unique_random_numbers = [];

if (amount > limit) limit = amount; //Infinite loop if you want more unique
                                    //Natural numbers than exist in a
                                    // given range
while (unique_random_numbers.length < limit) {
    var random_number = Math.floor(Math.random()*(upper_bound - lower_bound) + lower_bound);
    if (unique_random_numbers.indexOf(random_number) == -1) { 
        // Yay! new random number
        unique_random_numbers.push( random_number );
    }
}
// 

How could I make these numbers appear in place of elements with a corresponding class? The code below is clearly wrong, but hopefully it illustrates what I'm trying to achieve:

<script type='text/javascript'>
    var random_number1 = random_number1(); 
    $('.random_number1').html(random_number1);

    var random_number2 = random_number2(); 
    $('.random_number2').html(random_number2);
</script>

<span class="random_number1"></span>  <span class = "random_number2"></span>




Best php rand() alternatives in Golang?

Can anyone help me to convert this code to Golang from php

<?php 
echo rand(100);
echo rand(10,50);
?>

Thanks




Find, replace and print out updated string

I am trying to create a python script that has 10-20 lines of fixed data in a string with 2 special character's that need to be replaced with a different, random string using randomword()

import random, string

def randomword(length):
   letters = string.ascii_lowercase
   return ''.join(random.choice(letters) for i in range(length))


junk = """
random_string1 = {};
random_string2 = {};
random_string3 = {};
random_string4 = {};
random_string5 = {};
"""

stra = string.replace(junk, '{}', randomword(40))
print (stra)

The two special characters in the string are {}, I would like to iterate through the string to find those characters and replace them with a different random string generated by randomword()

Above is as far as I got, this piece of code replaces all of the occurrences of {} with a random string, but they have the same values, I would like to have differing values for each {}.

I don't know how to put this into a loop. Any help is appreciated.




creating a site for a medical study, need to seperate users into two groups randomly but evenly

I have this problem im trying to figure out. At first i thought about seperating users just by their user id by odds and evens. But my client says it needs to be a little bit more random then that.

if($user_id % 2 == 0) {

        $u->add_role( 'control' );
    }else{
        $u->add_role( 'study' );
    }

Users need to be placed into a control group, and a study group, out of 10 there need to be 5 in each, out of 100, 50 etc. But it apperantly something like 1 3 5 7 and 9 cant go in one while 2 4 6 8 10 go in the other. It should be more like

1 3 5 6 7 go in one 2 4 8 9 10 go in the other.

Im having trouble figuring out how to do that in a way that scales




How to set a vector of "discrete_distribution" c++

I'm trying to make a simulation of something like a Markov chain and using discrete_distribution to simulate the change of state s_i to s_j. But of course, this is a Matrix, not a vector. So I try.

By the way, there is a better way to initialize a vector of vectors?

std::vector <uint16_t> v1 {..., ..., ...}; // the dots are  numbers
std::vector <uint16_t> v2 {..., ..., ...};
...
std::vector <uint16_t> vn {..., ..., ...};

std::vector <std::vector <uint16_t> v {v1, v2, ..., vn};
std::vector <std::discrete_distribution <uint16_t> > distr(n, std::distribution <uint16_t> (v.begin(), v.end()) );

but this doesn't work.

note: if I try just 1 vector, this is a vector of uint16_t works

// CHANGE v by v1    
std::vector <std::discrete_distribution <uint16_t> > distr(n, std::distribution <uint16_t> (v1.begin(), v1.end()) );

I now that

std::vector <std::discrete_distribution <uint16_t> > distr(n, std::distribution <uint16_t> (v.begin(), v.end()) );

is not correct, but I say about the change v1 to v. to demonstrate that is possible use a vector of discrete distributions




New list every While loop

I want to create two lists ("lstA", "lstB") each comprised of 50 random numbers. I then want to compare the two lists and any overlap that is present I want put into a third list ("lstOvrlp"). I then would like to take the length of that third list and place it into a fourth list ("lstC").

Next I want that basic program to loop 10 times (I'll add user input for this part later).

This is the code I have so far:

    def main():

        import random

        lstA = []
        lstB = []
        lstC = []



        lstA = random.sample(range(1, 101), 50)
        lstB = random.sample(range(1, 101), 50)

        lstOvrlp = set(lstA) & set(lstB)

        while len(lstC) <= 10:
            print("This is list A:", lstA)
            print("\n")
            print("This is list B:", lstB)
            print("\n")
            print("This is the overlap between the two lists:", lstOvrlp)

            numinC = len(lstOvrlp)
            print("Number in common: ", numinC)
            print("\n")

            lstC.append(numinC)
            print(lstC)



    main()

The issue is that rather than spitting out random numbers each time through the loop the program just re-uses the same numbers over and over again resulting in the same overlap numbers and consequently the same lengths in "lstC". Perhaps there is some other function in Random that I just don't know about, but I can't find it.

I'd like there to be a new batch of numbers in "lstA" and "lstB" each time the program loops so that "lstC" ends up with varied entries. I'm trying to get some practice working with data and eventually I'll be running some simple statistics analysis on this information such as averages and what not.

While I can't point out the errors that are here, I can guarantee there are plenty of them so please be patient.

Thanks




Random string generated with random spacing in between

I would like to create a pattern the contains uppercase letters and numbers, also random spacing in between as OI00 XKB or IT IEEW 88 ... etc

I have started with this code it generate random code but the spacing is constant between as {}{}{}{} {}{}{}

code

def codeGen():
 return "{}{}{}{} {}{}{}".format(
        random.choice(common.LETTERS),
        random.choice(common.LETTERS),
        random.choice(common.DIGITS),
        random.choice(common.DIGITS),
        random.choice(common.LETTERS),
        random.choice(common.LETTERS),
        random.choice(common.LETTERS))

how I can apply randomness on format

Thanks, in advance




c++ async : how to shuffle a vector in multithread context?

Running a multithreaded program, I noticed that the program was running faster using 1 thread compared to 4 threads, despite the CPU having 4 cores.

After investigating, I found out that the issue appears only when shuffling something.

Below the minimal program I created to reproduce the problem:

#include <math.h>
#include <future>
#include <ctime>
#include <vector>
#include <iostream>
#include <algorithm>

#define NB_JOBS 5000.0
#define MAX_CORES 8

static bool _no_shuffle(int nb_jobs){
  bool b=false;
  for(int i=0;i<nb_jobs;i++){
    std::vector<float> v;
    for(float i=0;i<100.0;i+=0.01) v.push_back(i);
    float sum = 0;
    // no meaning, just using CPU
    for(int i=0;i<v.size();i++) sum+=pow(sin(v[i]),1.1);
    if(sum==100) b=true;
  }
  return b;

}

static bool _shuffle(int nb_jobs){
  bool b=false;
  for(int i=0;i<nb_jobs;i++){
    std::vector<float> v;
    for(float i=0;i<100.0;i+=0.01) v.push_back(i);
    std::random_shuffle(v.begin(), v.end()); // !!! 
    if (v[0]==0.0) b=true;
  }
  return b;
}

static double _duration(int nb_cores){

  auto start = std::chrono::system_clock::now();

  int nb_jobs_per_core = rint ( NB_JOBS / (float)nb_cores );

  std::vector < std::future<bool> > futures;
  for(int i=0;i<nb_cores;i++){
    futures.push_back( std::async(std::launch::async,_shuffle,nb_jobs_per_core));
  }
  for (auto &e: futures) {
    bool foo = e.get();
  }

  auto end = std::chrono::system_clock::now();
  std::chrono::duration<double> elapsed = end - start;

  return elapsed.count();

}


int main(){

  for(int nb_cores=1 ; nb_cores<=MAX_CORES ; nb_cores++){

    double duration = _duration(nb_cores);
    std::cout << nb_cores << " threads: " << duration << " seconds\n";

  }

  return 0;

}

which prints:

1 threads: 1.18503 seconds
2 threads: 9.6502 seconds
3 threads: 3.64973 seconds
4 threads: 9.8834 seconds
5 threads: 10.7937 seconds
6 threads: 11.6447 seconds
7 threads: 11.9236 seconds
8 threads: 12.1254 seconds

Using threads slow down the program !

on the other hand, when replacing:

std::async(std::launch::async,_shuffle,nb_jobs_per_core));

with:

std::async(std::launch::async,_no_shuffle,nb_jobs_per_core));

then:

1 threads: 3.24132 seconds
2 threads: 1.62207 seconds
3 threads: 1.1745 seconds
4 threads: 1.09769 seconds
5 threads: 1.03182 seconds
6 threads: 0.892274 seconds
7 threads: 0.782815 seconds
8 threads: 0.704777 seconds

which seems as expected, indicating shuffling is indeed the issue.

Is shuffling not thread friendly, and if so, how to shuffle a vector in a multi-threaded program ?




Python module random has no attribute choices working on local server but not on live server

I have a script which selects a random number form available list at random. I have been testing it on django's local server and it worked fine but when I moved it to a live server I keep getting this error:

AttributeError: 'module' object has no attribute 'choices'

Here's my code:

import json

class singlePull(TemplateView):
template_name = 'gacha/singlepull.html'

def randomStar(self):
    choice = [5,4,3]
    probability = [0.1, 0.2, 0.7]
    star = random.choices(choice, probability)
    return star


def post(self, request):
    result = self.randomStar()
    for key in result:
        character = Characters.objects.filter(stars=key).order_by('?')[:1]
        for obj in character:
            name = obj.name
            stars = obj.stars
            series = obj.series
            image = obj.image
    return JsonResponse({'name': name, 'stars': stars, 'series': series, 'image': image}, safe=False)

How come I keep getting this error? What could be wrong here?




How to play next random song of the array of songs

I have an array of songs, My app play songs randomly when an activity is open but when the song is finished I would like to play another random song from the array, does anyone can help with it?

public MediaPlayer mediaPlayer;
private int songs[];


   songs = new int[] {
           R.raw.track1,
           R.raw.track2,
           R.raw.track3,
           R.raw.track4,
           R.raw.track5,
           R.raw.track6,
           R.raw.track7,
           R.raw.track8,
           R.raw.track9,
           R.raw.track10,
           R.raw.track11,
           R.raw.track12,
           R.raw.track13,
           R.raw.track14,
           R.raw.track15,
           R.raw.track16,
           R.raw.track17,
   };


    int randomSong =  new Random().nextInt(songs.length);
    mediaPlayer = MediaPlayer.create(this, songs[randomSong]);
    mediaPlayer.start();




How to construct predefined random number generator and seed sequence in constructor?

Background

I'm building a discrete selector, e.g. given a sequence, it picks randomly one element with probability according to given weights. You can think of it as a pair of PredefinedRandomGenerator and std::discrete_distribution. I'd like the selector to be portable, and provide sane entropy. It will not be used in cryptographic context, I just want better randomness (sorry if I messed up terminology here).

Problem

std:random_device on MinGW on Windows always yields the same number. As a workaround, I use

//assume using namespace std::chrono
std::seed_seq seq{std::random_device{}(), 
                  duration_cast<nanoseconds>(system_clock::now()).count(),
                  42};

The problem is that the constructor of PredefinedRandomGenerator expects lvalue-reference, so I cannot initialize it in member initializer list as follows:

template <typename InputIterator>
discrete_selector(InputIterator weights_first,
                  InputIterator weights_last):
        generator(std::seed_seq{/*...*/}),
        distribution(weights_first, weights_last)
{}

So now there is at least one source of more or less random number.

What I tried

//somewhere in namespace details
std::seed_seq& get_new_sequence()
{
    static std::unique_ptr<std::seed_seq> sequence;
    sequence = std::make_unique<std::seed_seq>(std::random_device{}(), 
                                            duration_cast<nanoseconds>(system_clock::now()).count(),
                                            42);
    return *sequence;
}

The above should work, but I believe there should be a better way of doing that.


Side question

Why does constructor take the std::seed_seq by lvalue reference? It could at least use rvalue-reference.




[Unity3D]How to make a random terrain with random forest and random grass

I want make a war game with random map. I already generate map with random height, but I don't know how to generate random location tree and grass by Unity terrain's place tree and paint detail tool.

Can terrain paint detail with random location?




Mathematical function that has more chance to return small number, than large

I need to get random element in array, but I want to get element with smaller index more frequently than element with large index. Is there any way to do that?

Example: sqrt(x) will return big indexes frequently

1: 1 2: 2 3: 2 4: 2




mercredi 27 décembre 2017

synchronize.js used with express js

I want to generate a random number between 0-3(included) and that number shouldn't be generated before e.g. the number generated was 1, saved in an array, then 3, saved in an array, then again 3, oh-oh it exists in the array so again generated 0, saved in array, then 2 and finally all are saved in the array in the order of 1,3,0,2. But sometimes luck isn't on my side and the function returns the random number before comparing with the numbers present in the array. This is the code I have tried so far:-

  //using synchronized.js
    function f1(choices){
  sync.fiber(function(){
    var options = {     //rand for a choice
      min: 0,
      max:  3,    //choice can be from 0-3 index
      integer: true
    };
    var randomnumber=rn(options);     //random number for choice placement here
    for(var i=0;i<choices.length;i++){
      if(randomnumber==choices[i]){   //if exists, generate the number again
        console.log("rnd generated is: ",randomnumber);
        randomnumber=rn(options);
        i=0;
      }
    }
    console.log("rnd got is: ", randomnumber);
    choices[choices.length]=randomnumber;
    return randomnumber;
  }, function(err,result){
    console.log("sync index is: ",result);
  });
}

But the above solution isn't working i.e. I am getting repeated indices. I have also tried this solution using deasync :-

function randomChoiceNumber(choices){
  var flag=true;
  var count=0;
  return new Promise(function(resolve,reject){
  var options = {     //rand for a choice
    min: 0,
    max:  3,    //choice can be from 0-3 index
    integer: true
  };
  var randomnumber=rn(options);     //random number for choice placement here
  for(var i=0;i<choices.length;i++){
    if(randomnumber==choices[i]){   //if exists, generate the number again
      flag=false;
      randomnumber=rn(options);
      i=0;
      count=0;
    }else{
      count++;
    } 
  }
  while(count != choices.length && choices.length>0) {
    deasync.sleep(100);
  }
  choices[choices.length]=randomnumber;
  resolve(randomnumber);
  });
}

Both aren't working the deasync one goes to sleep lol generates only 1 to 2 indices. Please help me in achieving what I want, I am stuck on this thing for hours. Thank you.




How to manipulate and randomise a variable in a while loop condition?

I have a while loop with a condition inside called card1Hp and it is a new instance variable defined at the top of the class called Game.

    public int card1Hp = 100;
    public int card2Hp = 80;
    public int card3Hp = 90;
    public int card4Hp = 70;

and there's a method in the class with a while loop:

 while(card1Hp > 0)

I have a method in the class that generates a specified random number for me where I can go:

someVar= Game.getRandIntBetween(1,5);

and it generates randVar = 1 or 2 or 3 or 4 or 5. Is there any way I can put this into my while loop condition. Basically I want it to be:

while(card1Hp > 0)

replaced with some kind of way like this

 while(card(randVar)Hp > 0)

I know that isn't the way to write it in java but that's the effect I want to try and generate the random number I want in my cardHp. What's a good way to achieve this? I plan for hundreds of cardhp variables in my game as well to randomize.




Why my codes result 'module' object is not subscriptable?

I get an error while I wanted to change python random.sample array index. I would like to change my random.sample array index by increasing +1

x=0
randomarray = random.sample(range(1, len(codelist) - len(Genx1) - len(Genx2)), 3*len(s))


while (x < len(s)):

    randomarray.sort()
    print(randomarray)
    if ((codelist[randomarray[x]]=='B' ) and (s[x]=='A') or (codelist[randomarray[x]]=='A' ) and (s[x]=='B')):

            codelist[randomarray[x]] = s[x]
            x = x + 1

    else:

        random[x]= random[x]+1
        x=x

line 403, in ... random[x]= random[x]+1 TypeError: 'module' object is not subscriptable




Cannot make a static reference to the non-static method and specialChars cannot be resolved errors

So I searched if someone before me wanted to know how a typing text works and found this here how-to-add-java-typing-text but the code from Vogel612 gives me errors on "Random.nextInt(40)..." and specialChars.contains...". Btw im a beginner so pls answer like you would answer a beginner xD.

Here is the code I have in my class:

import java.util.Random;
public class Buildingtext {
public static void main(String[] args) {

    // TODO Auto-generated method stub
    String text="bla zzz  ´` asdasdasda y yyyx sdsy sddx";
    for (char c : text.toCharArray()) {
        // additional sleeping for special characters
        if (specialChars.contains(c)) {
           Thread.sleep(Random.nextInt(40) + 15);
        }
        System.out.print(c);
        Thread.sleep(Random.nextInt(90) + 30);
    }
}
}

The "specialChars" error says : specialChars cannot be resolved.

Both Random.nextInt() errors say : cannot make a static reference to the non-static method nextInt(int) from the type Random.

I really need help thanks guys D´:




When i have two same values in array I get Fatal error: Maximum execution time of 30 seconds exceeded in C:/Apache24/htdocs/index.php on line 18

<?php
$numbers = array("2","1","4");
$numberofelements = count($numbers);
$factorial = 1;
for ($i=1; $i<=$numberofelements; $i++)
{
         $factorial *= $i;
}
$quantitycombinations = $factorial;
$numbersdrawn = array();
while(true)
{
    $exists = false;
    $numberdrawn1 = "";
    shuffle($numbers);
    $numberdrawn1 = implode("", $numbers);
    strval($numberdrawn1);
    foreach ($numbersdrawn as $value) {
            if(strval($value)==$numberdrawn1)
            {
                $exists = true;
            }
        }
    if(!$exists){
        array_push($numbersdrawn, $numberdrawn1);
        if(count($numbersdrawn)==$quantitycombinations)
        {
            foreach($numbersdrawn as $item)
            {
                echo $item."<br>";          
            }
            break;
        }
    }
}
?>

When i change this code:

$numbers = array("2","1","4");

To

$numbers = array("2","2","4");

I get error
This code prints all combinations of the given numbers (values from array).
I changed time in php.ini file, but it didn't help.
I can not find a solution.
PLEASE HELP!!!




Randomization exercise in Python 2.7 [on hold]

Write a program that reads from the user the number of patients in the control group and the number of patients in the treatment group. Make sure that the program only accepts nubmers in the range of 0-20. Create a randomization plan and produce output of the form: Patient 1 is assigned to the control group Patient 2 is assigned to the treatment group Patient 3 is assigned to the treatment group and so on..

Do you have any ideas guys how can i solve it in Python???




How to make a dice test program in Java?

I've made a dice with Java in applets and I would like to test my dice with a small test program in java by using loops for instance with values between 100 and 1000. The dice must not go below the 1 and above the 6. How do I make this test program to test my dice?




Random char* args[] to pass to execv

I need to create a char* array[] that i then have to pass to execv.

  • the first element would be the path "./exec_test"
  • for the second argument: pick randomly between A/B
  • for the third argument: pick a random letter A - Z
  • for the fourth argument: pick random integer between [2, 2+A_CONST]
  • Then NULL

    void perform_exec(){
        char *type= 'A' + (random() % 2);
        char *name= 'A' + (random() % 64);
        int rand_num= rand(); 
    
        char *args[5];
        args[0]= "./test_exec";
        args[1]= name;
        args[2]= type;
        args[3]= rand_num;
        args[4]= NULL;
    
        execv(args[0], args);
        printf("you souldn't see this. exec error\n");
        exit(EXIT_FAILURE);
    
    

    }

I know there is something terribly wrong with this code, but can't actually figure out what it is.

i get Error #014: Bad address.




mardi 26 décembre 2017

Why Go rand.Int() always returns the same number?

I am very new and interested person in Golang. I have completed only basics arithmetic in Golang.

Now I am trying to generate random number in Go But it always returns the same number.

I have imported math/rand.

And my code to write a random number is:

fmt.Print(rand.Int())

It always returns 134020434

And I have also tried

fmt.Print(rand.Intn(100))

It always returns the number 81

Even I tried the online playground of Go.

The result is same.

Can anyone explain, what's happening here ?




Insert random string into each instance of whitespace

I'm trying to insert a randomly selected string into each instance of whitespace within another string.

var boom = 'hey there buddy roe';
var space = ' ';
var words = ['cool','rad','tubular','woah', 'noice'];
var random_words = words[Math.floor(Math.random()*words.length)];

for(var i=0; i<boom.length; i++) {
  boom.split(' ').join(space + random_words + space);
}

Output comes to:

=> 'hey woah there woah buddy woah roe'

I am randomly selecting an item from the array, but it uses the same word for each instance of whitespace. I want a word randomly generated each time the loop encounters whitespace.

What I want is more like:

=> 'hey cool there noice buddy tubular roe'

Thanks for taking a look.

(This is beta for a Boomhauer twitter bot, excuse the variables / strings 😅)




display three most often random numbers c#

Hy, I'm learning c# and I need some help with code. I'm doing two aplications, first aplication displaying 4 random number every second and writing them in txt file, second aplication must read numbers from txt file and show 3 most often displayed random numbers. I done the first aplication:

//my code


namespace Zreb
{
    class Program
    {
        static void Main(string[] args)
        {
            //timer 1 second
            Timer timer = new Timer(TimerCallback, null, 0, 1000);
            Console.ReadLine();     

        }
           //random numbers
            private static void TimerCallback(object o)
            {
            string filename = @"zreb.txt";
            Random rnd = new Random();
            int rndNumber=0;
            int rndNumber2=0;
            int rndNumber3=0;
            int rndNumber4=0;

            //  writing in file
            using (StreamWriter writer = new StreamWriter(filename, false, Encoding.UTF8))
            {
                for (int i = 1; i < 1500; i++)
                {
                    rndNumber = rnd.Next(1, 81);
                    rndNumber2 = rnd.Next(1, 81);
                    rndNumber3 = rnd.Next(1, 81);
                    rndNumber4 = rnd.Next(1, 81);

                    string num1 = rndNumber.ToString();
                    string num2 = rndNumber2.ToString();
                    string num3 = rndNumber3.ToString();
                    string num4 = rndNumber4.ToString();



                    //writing in text file 4 rnd num
                    writer.WriteLine("{0}, {1}, {2}, {3}", num1, num2, num3, num4);

                    GC.Collect();
                }
                    //writing in console
                  Console.WriteLine("{0}, {1}, {2}, {3}", rndNumber, rndNumber2, rndNumber3, rndNumber4);
                writer.Flush();
                writer.Close();
            }
        }

    }
 }

First aplication is every thing ok, but the second aplication i don't know how to compare numbers and show 3 most often...this is my code for second aplication...but i don't know how to continue....Please help me....

FileStream fs;
StreamReader srIn;

try
{
    fs = new FileStream(@"c:\\Users\bojan\source\repos\Zreb\Zreb\bin\Debug\zreb.txt", FileMode.Open);
    srIn = new StreamReader(fs);
    string line = srIn.ReadLine();

    while (line != null)
    {
        line = srIn.ReadLine();
        Console.WriteLine(line);              
}
srIn.Close();




C# Program to read and Sort integers

I'm sorry if my question seems easy or dumb to some of you. I'm only a beginner in the programming world and I'm self-learning multiple programming languages so I have no one to consult.

I'm supposed to write this program:

Create a console project. Add a C# class named TerminalSort. Within TerminalSort, create 2 static functions GenerateRandomData and Sort. GenerateRandomData should take in an integer parameter and return a list of random numbers containing the requested number of elements. Sort should accept a list of integers as a parameter and return back the list sorted by terminal digit. The console project should prompt the user for a number, generate random data based on that number, and then print out the sorted list to the console.

This is what I wrote so far and I'm currently stuck. Any help would be appreciated. Thank you in advance.

    namespace Project1
    {
        public static class TerminalSort
        {
            static int GenerateRandomData()
            {
                Console.Write("Enter a number: ");
                string userInput1 = Console.ReadLine();
                int number = Convert.ToInt32(userInput1);
                for (int i=0; i < number; i++)
                {
                    Random random = new Random();
                    Console.Writeline(random);
                }
            }

            static void Sort()
            {
                for (int i = 0; i < 5; i++)
                {
                    Console.Write("Enter a number: ");
                    string userInput2 = Console.ReadLine();
                    int number2 = Convert.ToInt32(userInput1);
                }

            }

            static void Main(string[] args)
            {
                System.Console.WriteLine(GenerateRandomData());
                System.Console.ReadKey();
            }
}
}

Again, I apologize if the question seems dumb or too easy to some of you.




How to find previous randomly generated number using Math.random in a setInterval function?

I am generating a random number between 1 and 13. This works fine. What I want to do is not generate the same number as the immediate previous number.

function showRandomDotIcon() {
    var randomDot = Math.floor(Math.random() * 13) + 1;
    console.log(randomDot);
}

setTimeout(showRandomDotIcon, 3500);

So something like:

if(randomDot == previousDot) {
    // skip to next number
}




Pick random numbers from List based on specified condition C#

I'm trying to generate a unique random numbers from the list. Here user will input the followings:

  1. Number of random numbers required
  2. Number C1, C2 and C3 items.

Example: 10 Random numbers with C1-5, C2-4, and C3-1.

So based on these conditions a random number list need to generate.

My list looks like this

1   C1
2   C2
3   C3
4   C3
5   C2
6   C1
7   C2
8   C3
9   C1
10  C2
11  C1
12  C3
13  C3
14  C1
15  C2
16  C2
17  C4
18  C3
19  C4
20  C4
21  C4
22  C1
23  C2
24  C3
25  C4
26  C3
27  C4

My code looks like this:

protected void BtnGenerate_Click(object sender, EventArgs e)
{
            List<string> labels; // Holds all Labels (unique)
            List<string> values; // Holds all numbers of labels
            Random r = new Random();
            StringBuilder sb=new StringBuilder(100);

            sb.Clear();
            var randoms = values.OrderBy(x => r.Next()).Take(Convert.ToInt16(txtNumberOfRandomNumbers.Text));
            foreach (var item in randoms)
            {
                sb.Append(item.ToString() + ",");
            }

            lblRandomNumbers.Text = sb.ToString().Remove(sb.ToString().LastIndexOf(","));
}

I'm stuck with how to add these conditions to Random function. Please help me on this.




Mysql - select random 4 data from a column, distinct by 2 different columns

I'm trying to select 4 different random data from a table on Mysql but I want some fields unique, for example;

I've got a table

Table name 'videos' and the data is ;

id f2  f3  f4
-- --  --  --
1  a   q   C  
2  a   w   Y
3  b   e   C
4  b   r   Y
5  c   t   C
6  c   y   Y
7  d   u   C
8  d   o   Y

I want to select 4 data randomly from f3 but f2 must be Unique. And the f4 must be unique for every f2, I mean I must get randomly 'u' or 'o' not both. So in the end I want to get 2xC data column from unique f2, and 2xY data from unique f2. Result I want to get is like;

f3      f3        f3
--      --        --
q   or|  q   or|  w
r   or|  e   or|  r
t   or|  y   or|  t
o   or|  o   or|  u

Here's a sample that I created in MsSql but cant convert it to Mysql;

select e.* from (select top 4 f2,ROW_NUMBER() OVER (ORDER BY newId()) AS RowNumber from (select distinct(f2) from videos) x) a inner join (
select top 4 ones.n,ROW_NUMBER() OVER (ORDER BY newId()) AS RowNumber FROM (VALUES('C'),('Y'),('C'),('Y')) ones(n)) b on a.RowNumber = b.RowNumber
inner join videos e on a.f2 = e.f2 and b.n =e.f4




How to generate random 64-digit hexadecimal number in R?

To apply in a blockchain application, I needed to generate random 64-digit hexadecimal numbers in R.

I thought that due to the capacity of computers, obtaining such an 64-digit hexadecimal number at once is rather cumbersome, perhaps impossible.

So, I thought that I should produce random hexadecimal numbers with rather low digits, and bring (concatenate) them together to obtain random 64-digit hexadecimal number.

I am near solution:

.dec.to.hex(abs(ceiling(rnorm(1) * 1e6)))

produces random hexadecimal numbers. The problem is that in some of the instances, I get 6-digit hexadecimal number, in some instances I get 7-digit hexadecimal number. Hence, fixing this became priority first.

Any idea?




neo4j get random path from known node

I have a big neo4j db with info about celebs, all of them have relations with many others, they are linked, dated, married to each other. So I need to get random path from one celeb with defined count of relations (5). I don't care who will be in this chain, the only condition I have I shouldn't have repeated celebs in chain.

To be more clear: I need to get "new" chain after each query, for example:

  • I try to get chain started with Rita Ora
  • She has relations with Drake, Jay Z and Justin Bieber
  • Query takes random from these guys, for example Jay Z
  • Then Query takes relations of Jay Z: Karrine Steffans, Rosario Dawson and Rita Ora
  • Query can't take Rita Ora cuz she is already in chain, so it takes random from others two, for example Rosario Dawson
  • ...
  • And at the end we should have a chain Rita Ora - Jay Z - Rosario Dawson - other celeb - other celeb 2

Is that possible to do it by query?




lundi 25 décembre 2017

Generate Random numbers by min,max,mean (normal distribution) c#

Is there anyway to generate random numbers (normally distributed), by using min , max and given mean. (without standard deviation.)

I saw many examples that can use, but they are using mean and standard deviation.




how to avoid repetition of the same page in a random loading page script

i found this free script on the web that allows me to load a different webpage each time i refresh the tab , i have edited it but i don't know how to avoid repetition of the same site multiple time until every site is visited once . can you help me , thanks . ( in the snippet you have 3 websites but i have more than 100 in my version ).

<!-- ONE STEP TO INSTALL RANDOM PAGE:

 
<HEAD>

<SCRIPT LANGUAGE="JavaScript">


<!-- Begin
var howMany = 2;  // max number of items listed below
var page = new Array(howMany+1);

page[0]="first-random-page.html";
page[1]="second-random-page.html";
page[2]="third-random-page.html";

function rndnumber(){
var randscript = -1;
while (randscript < 0 || randscript > howMany || isNaN(randscript)){
randscript = parseInt(Math.random()*(howMany+1));
}
return randscript;
}
quo = rndnumber();
quox = page[quo];
window.location=(quox);
// End -->
</SCRIPT>
</HEAD>



Get 10>15 random lines (php)

How do I generate 10>15 random Lines From text file

lines.txt . (27 lines)

aaaaaa
zzzzzz
eeeeee
rrrrrr
tttttt
yyyyyy
uuuuuu
iiiiii
oooooo
pppppp
qqqqqq
ssssss
dddddd
ffffff
gggggg
hhhhhh
jjjjjj
kkkkkk
llllll
mmmmmm
ùùùùùù
wwwwww
xxxxxx
cccccc
vvvvvv
bbbbbb
nnnnnn

Random.php

<?php 
$lines = file("lines.txt"); 
shuffle($lines); 
echo implode('|', $lines);
?>

I want like this :

10 lines The Random Result : 10

jjjjjj|dddddd|oooooo|iiiiii|hhhhhh|gggggg|yyyyyy|zzzzzz|tttttt|ùùùùùù

11 lines The Random Result : 11

wwwwww|nnnnnn|llllll|jjjjjj|aaaaaa|oooooo|yyyyyy|qqqqqq|zzzzzz|gggggg|kkkkkk

15 lines The Random Result : 15

eeeeee|aaaaaa|rrrrrr|kkkkkk|ùùùùùù|pppppp|ssssss|bbbbbb|tttttt|zzzzzz|llllll|vvvvvv|cccccc|wwwwww|mmmmmm




How to generate 5 different numbers in javasripct

I have a click function so that when i click on a button it should put 5 different numbers into a table. The problem here is that the five aren't always different.

$("button").click(function () {
$("table:eq(2)").show();
y = 0;
while (y < 5) {
    x = Math.floor((Math.random() * 50) + 1);
    klo = 0;
    kolonija[y] = x;
    if (tru==1)
    {

        while(klo<5){

            while(kolonija[y]==rezerva[klo])
            {
                x = Math.floor((Math.random() * 50) + 1);
                kolonija[y] = x;
            }


            klo++
        }
        rezerva[klo] = x;
    }
    else if (tru == 0)
    {
        rezerva[y] = x;
        tru == 1;
    }


    $("table:eq(2) td:eq(" + y + ")").text(x);


    y++;
}
});




Get different color from the current one every time, Unity

I have 4 colors. I want to make it so that the player can't be the same color 2 times in a row. When a player collides with an object, the RandomColor() is called. So this function is called many times during the game and sometimes the player does not change his color.

 using UnityEngine;

 public class ColorManager : MonoBehaviour {

     public SpriteRenderer player;
     public string playerColor;

     public Color[] colors = new Color[4];


     private void Awake()
     {
         RandomColor();        
     }

     public void RandomColor()
     {
         int index = Random.Range(0, 4);

         switch (index)
         {
             case 0:
                 player.color = colors[0]; //colors[0] is orange
                 playerColor = "orange";
                 break;

             case 1:
                 player.color = colors[1]; //colors[1] is pink
                 playerColor = "pink";
                 break;

             case 2:
                 player.color = colors[2]; //colors[2] is blue
                 playerColor = "blue";
                 break;

             case 3:
                 player.color = colors[3]; //colors[3] is purple
                 playerColor = "purple";
                 break;
             }    
     }    
 }

Tried using while loop, do while loop, but I'm obviously doing it wrong, since I receive the same color twice in a row sometimes. It would be great if anyone figures it out and explains how/why it works, because I spent a big chunk of time on the issue and I am very curious.




Return a random value

Build a piece of code in c# language : (method/function) Which returns a random value between 1 & 6 except those numbers which are passed at the time of calling.

Just as . . .

//Definition

Private int rdm (int [] )
{


return int
}

//calling

rdm(new int {3,5} )

//output
4
Or
2
Or
6
Or
1




dimanche 24 décembre 2017

How do we unit-test functions which use randomness?

I am interested in best-practice techniques, if any, for unit-testing functions which use randomness. To be clear, I am not concerned with testing the distribution of random number generators.

As a toy example, let's consider this function:

// Returns a random element from @array. @array may not be empty.
int GetRandomElement(int[] array);

Answers to this question suggest that we may inject a mock source of randomness, which makes sense. But I'm not sure exactly how I might use the mock. For example, let's assume that we have this interface:

// A mock-friendly source of randomness.
interface RandomnessSource {
  // Returns a random int between @min (inclusive) and @max (exclusive).
  int RandomInt(int min, int max);
}

...And change the signature of GetRandomElement() to this:

// Returns a random element from @array, chosen with @randomness_source.
// @array may not be empty.
int GetRandomElement(int[] array, RandomnessSource randomness_source);

All right, now a test could look like:

MockRandomnessSource mock = new MockRandomnessSource();
mock.ExpectCall(RandomnessSource::RandomInt(0, 5)).Return(2);
AssertEquals(GetRandomElement({0, 10, 20, 30, 40}, mock), 20);

...which could work fine, but only if the implementation looks like this:

// A fairly intuitive implementation.
int GetRandomElement(int[] array, RandomnessSource randomness_source) {
  // Pick a random number between [0..n), where @n is the @array's legnth.
  return array.Get(randomness_source.RandomInt(0, array.Length()));
}

...But nothing in the function specification prevents an implementation like this:

// Less intuitive, but still a conforming implementation.
int GetRandomElement(int[] array, RandomnessSource randomness_source) {
  // Pick a random number between [1..n+1), only to subtract 1 from it.
  return array.Get(randomness_source.RandomInt(1, array.Length() + 1) - 1);
}

One idea which leaps to mind is that we may further constrain the function's contract, like this:

// Returns a random element from @array, chosen with @randomness_source by
// by calling @RandomnessSource::RandomInt to pick a random index between
// 0 and the length of @array.
int GetRandomElement(int[] array, RandomnessSource randomness_source);

...But I can't quite get over the impression that this is placing too heavy a constraint on the function contract.

I also suspect that there might be better ways to define the interface RandomnessSource to make its callers more amenable to unit tests, but I'm not quite sure what/how.

...Which brings me to the question: What are the best-practice techniques (if any) for unit-testing functions which use randomness?




Curl is not printing the random number generated by rand() function

I am trying to send a OTP using Ringcaptcha and using the following code.

$randnum = rand(100000,1000000);
$cmd = 'curl -k -X POST --data-urlencode "api_key=xxxxxxxxx" --data-urlencode "phone=+911234567890" --data-urlencode code=$randnum http://ift.tt/2zr7DoJ';
exec($cmd,$result);

this code doesn't out put a random number everytime.

$echo randnum 

outputs a different number everytime, but curl doesn't do that.

I tried all the combinations like ' , " and "code=".$randnum etc. Can somebody help me?




I can not sample well using "tf.boolean _ mask."

My Enviroment Windows10 Anaconda Tensorflow 1.1.0 Python 3.5

I classify images using a neural network. I use an image of 1024 * 768 pixels, but since the calculation amount is enormous when using all the pixels, I introduced a random mask to randomly sample 1000 pixels. However, this kind of error has occurred and it has not been successfully sampled successfully

”ValueError: Dimensions must be equal, but are 786432 and 1728 for 'fc1/MatMul' (op: 'MatMul') with input shapes: [?,786432], [1000,10].”

Why does it look like this? Could you tell me if there is a solution?

All codes are posted below.

import sys
sys.path.append('/usr/local/opt/opencv3/lib/python3.5.4/site-packages')
import cv2
import numpy as np
import tensorflow as tf
import tensorflow.python.platform
import tensorboard as tb   
import os
import math
import time
import random
start_time = time.time()



# TensorBoard output information directory
log_dir = '/tmp/data1'  #tensorboard --logdir=/tmp/data1

#directory delete and reconstruction
if tf.gfile.Exists(log_dir):
    tf.gfile.DeleteRecursively(log_dir)
tf.gfile.MakeDirs(log_dir)



# Reserve memory
config = tf.ConfigProto(
   gpu_options=tf.GPUOptions(
       allow_growth=True
   )
)
sess = sess = tf.Session(config=config)




NUM_CLASSES = 2
IMAGE_SIZE_x = 1024
IMAGE_SIZE_y = 768
IMAGE_CHANNELS = 1
IMAGE_PIXELS = IMAGE_SIZE_x*IMAGE_SIZE_y*IMAGE_CHANNELS
SAMPLE_PIXELS = 1000

flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('train', 'train.txt', 'File name of train data')
flags.DEFINE_string('test', 'test.txt', 'File name of train data')
flags.DEFINE_string('image_dir', 'data', 'Directory of images')
flags.DEFINE_string('train_dir', '/tmp/data', 'Directory to put the training data.')
flags.DEFINE_integer('max_steps', 20000, 'Number of steps to run trainer.')
flags.DEFINE_integer('batch_size', 10, 'Batch size'
                     'Must divide evenly into the dataset sizes.')
flags.DEFINE_float('learning_rate', 1e-5, 'Initial learning rate.')


# 

def inference(images_placeholder, keep_prob):
    """ Function to create predictive model

   argument:
        images_placeholder: image placeholder
        keep_prob: dropout rate placeholder

    Return:
        y_out: 
    """
    # Initialie with normal distribution with weight of 0.1
    def weight_variable(shape):
      initial = tf.truncated_normal(shape, stddev=0.1)
      return tf.Variable(initial)

    # Initialized with normal distribution with bias of 0.1
    def bias_variable(shape):
      initial = tf.constant(0.1, shape=shape)
      return tf.Variable(initial)

# Random mask
mask = np.array([False]*IMAGE_PIXELS)
inds = np.random.choice(np.arange(IMAGE_PIXELS),size = SAMPLE_PIXELS)
mask[inds] = True

# Sample input
x_image = tf.boolean_mask(images_placeholder,mask)

    # input
    with tf.name_scope('fc1') as scope:
        W_fc1 = weight_variable([SAMPLE_PIXELS,10])
        b_fc1 = bias_variable([10])
        h_fc1 = tf.nn.relu(tf.matmul(x_image,W_fc1) + b_fc1)

    # hidden
    with tf.name_scope('fc2') as scope:
        W_fc2 = weight_variable([10,10])
        b_fc2 = bias_variable([10])
        h_fc2 = tf.nn.relu(tf.matmul(h_fc1,W_fc2) + b_fc2)


    # output
    with tf.name_scope('fc3') as scope:
        W_fc5 = weight_variable([10,2])
        b_fc5 = bias_variable([2])

    # softmax regression
    with tf.name_scope('softmax') as scope:
        y_out=tf.nn.softmax(tf.matmul(h_fc4, W_fc5) + b_fc5)

    # return
    return y_out

def loss(logits, labels):
    """ loss function

    argument:
        logits: logit tensor, float - [batch_size, NUM_CLASSES]
        labels: labrl tensor, int32 - [batch_size, NUM_CLASSES]

    return value:
        cross_entropy:tensor, float

    """
    # cross entropy
    cross_entropy = -tf.reduce_sum(labels*tf.log(tf.clip_by_value(logits,1e-10,1.0)))
    # TensorBoard
    tf.summary.scalar("cross_entropy", cross_entropy)
    return cross_entropy

def training(loss, learning_rate):

    #Adam
    train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)
    return train_step

def accuracy(logits, labels):

    correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) #original
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))#original
    tf.summary.scalar("accuracy", accuracy)#original
    return accuracy#original


if __name__ == '__main__':
    f = open(FLAGS.train, 'r')
    # array data
    train_image = []
    train_label = []
    for line in f:
        # Separate space and remove newlines
        line = line.rstrip()
        l = line.split()
        # Load data and resize
        img = cv2.imread(FLAGS.image_dir + '/' + l[0])
        img = cv2.resize(img, (IMAGE_SIZE_x, IMAGE_SIZE_y))
        #transrate grayscale
        img_gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # transrate one row and 0-1 float
        train_image.append(img_gry.flatten().astype(np.float32)/255.0)
        # Prepare with label 1-of-k method
        tmp = np.zeros(NUM_CLASSES)
        tmp[int(l[1])] = 1
        train_label.append(tmp)
    # transrate numpy
    train_image = np.asarray(train_image)
    train_label = np.asarray(train_label)
    f.close()

    f = open(FLAGS.test, 'r')
    test_image = []
    test_label = []
    for line in f:
        line = line.rstrip()
        l = line.split()
        img = cv2.imread(FLAGS.image_dir + '/' + l[0])
        img = cv2.resize(img, (IMAGE_SIZE_x, IMAGE_SIZE_y))
        #transrate grayscale
        img_gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        #  transrate one row and 0-1 float
        test_image.append(img_gry.flatten().astype(np.float32)/255.0)
        tmp = np.zeros(NUM_CLASSES)
        tmp[int(l[1])] = 1
        test_label.append(tmp)
    test_image = np.asarray(test_image)
    test_label = np.asarray(test_label)
    f.close()

    with tf.Graph().as_default():
        # Put the image Tensor
        images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS))
        # Put the label Tensor
        labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES))
        # Put dropout rate Tensor
        keep_prob = tf.placeholder("float")
        # Load inference() and make model
        logits = inference(images_placeholder, keep_prob)
        # Load loss() and calculate loss
        loss_value = loss(logits, labels_placeholder)
        # Load training() and train
        train_op = training(loss_value, FLAGS.learning_rate)
        # calculate accuracy
        acc = accuracy(logits, labels_placeholder)
        # save
        saver = tf.train.Saver()
        # Make Session
        sess = tf.Session()
        # Initialize variable
        sess.run(tf.global_variables_initializer())
        # TensorBoard
        summary_op = tf.summary.merge_all()
        summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph)




# Start training
for step in range(FLAGS.max_steps):
    for i in range(int(len(train_image)/FLAGS.batch_size)):
        batch = FLAGS.batch_size*i
        sess.run(train_op, feed_dict={
          images_placeholder: train_image[batch:batch+FLAGS.batch_size],
          labels_placeholder: train_label[batch:batch+FLAGS.batch_size],
          keep_prob: 0.5})

    # Accuracy calculation for every steps
    train_accuracy = sess.run(acc, feed_dict={
        images_placeholder: train_image,
        labels_placeholder: train_label,
        keep_prob: 1.0})
    print("step %d, training accuracy %g" %(step, train_accuracy))


    # Added value to be displayed in Tensorflow every 1step
    summary_str = sess.run(summary_op, feed_dict={
        images_placeholder: train_image,
        labels_placeholder: train_label,
        keep_prob: 1.0})
    summary_writer.add_summary(summary_str, step)

    # Display accuracy on test data after training
    print("        test accuracy     %g"%sess.run(acc, feed_dict={
        images_placeholder: test_image,
        labels_placeholder: test_label,
        keep_prob: 1.0}))

    duration = time.time() - start_time

    print('%.3f sec' %duration)

    # Save model
    save_path = saver.save(sess, os.getcwd() + "\\model.ckpt")




JQuery Display Random Image from page 2 on page 1

First, I am not a jquery efficiando; I do understand some basics.

I would like simple approach to display a random image from "page 2" on "page 1" via direct page URLs on the same site. All targeted images on page 2 have a like style class of "premade".

Any assistance to set me on the right path would be helpful.




Scrambling a string in Python without using random.shuffle()

I'm trying to scramble a string, "string", without using random.shuffle(), but my code keeps producing output that has missing and repeating characters, e.g. gtrgtg, gnrtnn, etc. I'm not sure what I'm doing wrong.

    import random
    s = "string"
    new_s=[]
    for c in s:
      if random.choice(s) not in new_s:
        new_s.append(random.choice(s))

    print(''.join(new_s))




make cointoss 10times auto in python

now I'm trying to make auto coin toss and draw cumulative graph

i copy and understand here

import random
rest = []
toss = [random.randint(0,1) for t in range(10)]
    for i in toss:
        if i == 0:
            rest.append('0')
        else:
            rest.append('1')
print rest

i got list like [1,0,0,0,1,1,0,0,0,1]

so now i have to make list like this for 10 (10 times repeat coin toss) And how many '0' is appended into list so i wanna return result [3,7,5,6,3,3,4,5,8,9] this list mean each list got how many '0'is appended

Help please and thank you




samedi 23 décembre 2017

Producing a random sequence of number... 30 times

Happy holidays! I have a question that I haven’t been able to figure out.

I need to produce a set of integers (from 1 to 20) of random length, and this needs be reproduced 30 times. To generate the random-length list, I use the “runif” function, which works. However, when I use the “rep” function to repeat this random list, it simply repeats the same list 30 times. What I want is the following: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 2 3 etc.

Insted, the runif produces a list and rep repeats it 30 times, so it looks like this: 1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7 etc.

I’d ideally like R to run the “runif” command 30 times. Now, I don’t know how to write a loop for this, and I also don’t know how to use something more elegant than loops. I tried using “repeat” function, but that one doesn’t produce integers, but lists which I cannot use for the computation I need.

Any help/advice/ideas would be greatly appreciated!

Thank you.




generate random message from a list

I need some help with a Python code

So I'm using this code to pick 3 words to form a message from the 5 words randomly.

def randomMessage():    
    word = ['Animal', 'Dog', 'Cat', 'Queen', 'Bird']

    return (random.sample(word, 3))

and then in a later part of the code, i want to put this in a message using

" + randomMessage() + "

But it gives me error saying "must be str, not a list"

How can i fix this?




Random character and number generator doesn't work in the way I want

        import java.util.Random;
        public class Test {
        public static void main(String[] args) {
        randomIDGenerator();
        }

 public static String randomIDGenerator() {
        Random r = new Random();

        char a = 0;
        for (int i = 0; i < 3; i++) {
             a = (char) (r.nextInt(26) + 'a');
        }
        int b = 0;
        for (int j = 0; j < 2; j++) {
            b = r.nextInt(10);
        }
        String h = "" + b;
        String n = a + h;

        System.out.println(n);
         return n;
 }
 }

I am writing a code in Java and I want my output to be 3 characters from a to z and 2 numbers from 0 to 9 (e.g. abc01) but the program gives me 1 character and 1 number (e.g. a1). Why does the program do this despite i've put 3 and 2 into loops? From all i know the first loop must operate 3 times and the second one must operate 2 times. So at the end my output have to be 3 characters and 2 numbers. Thanks!




Python Random Global Instance vs Local Instances vary wildly

I'm building a simulation engine which requires me to use Random Distributions heavily. Initially I was using the global instance of random in Python, but then I noticed something weird.

I added another feature to the Simulation engine behind a feature flag. With the flag off it the engine should provide the same result. However, we did not add a call to random.uniform() behind the flag.

When we ran the engine with the flag off, the results were drastically (5-10%) different than before. After removing the call to random.uniform() it was back to the previous results.

I know that the same PRNG returns worse results over time, but the number of calls to it cannot be more than a 100k.

Are there any best practices to using Python's random (like seeding, reuse global instance or always create new ones)? Or should we skip it and maybe use Numpy? Because of the drastic variation it is hard to tell which results are correct and which are wrong.




vendredi 22 décembre 2017

Drawing random numbers with draws in some pre-defined interval, `numpy.random.choice()`

I would like to use numpy.random.choice() but make sure that the draws are spaced by at least a certain "interval":

As a concrete example,

import numpy as np
np.random.seed(123)
interval = 5
foo = np.random.choice(np.arange(1,50), 5)  ## 5 random draws between array([ 1,  2, ..., 50])
print(foo)
## array([46,  3, 29, 35, 39])

I would prefer these be spaced by at least the interval+1, i.e. 5+1=6. In the above example, there should be another random draw, as 35 and 39 are separated by 4, which is less than 6.

The array array([46, 3, 29, 15, 39]) would be ok, as all draws are spaced by at least 6.

numpy.random.choice(array, size) draws size number of draws in array. Is there another function used to check the "spacing" between elements in a numpy array? I could write the above with an if/while statement, but I'm not sure how to most efficiently check the spacing of elements in a numpy array.




C# Randomly generated values are not really random

I am making a simple game in C# and using Random class to generate a random number every 2 seconds, but it gives numbers that I can guess in advance because it increments by a certain number each time.

private int RandomNumber;

//This Timer function runs every 2 seconds
private void TmrGenerateRandomNum(object sender, EventArgs e)
{
    Random r = new Random();
    RandomNumber = r.Next(50, 200); //Trying to get random values between 50 and 200
    Label1.Text = RandomNumber.ToString();
}

This is literally the only code I have, and I am displaying the value each time through Label1. The problem is, for example, if I first get 52, the next "randomly"-generated value is 71 or 72, and the next one is 91 or 92, and the next one is 111 or 112. As you can see, it is incrementing by 20ish. Then it suddenly gets a real random value again like, say, 163. But then the next generated number is 183, again incremented by 20. Since 183+20 exceeds the range, it gets a real random value again, say 83. But the next number generated is again 103, or 104, and then 123 or 124...

This is not "Random" because you can tell around what number the next one is going to be... and this is driving me crazy. Do you know why it does this, and is there a fix for this?




Python type error with a random number

I have the following code in my views in Django:

class singlePull(TemplateView):
template_name = 'gacha/singlepull.html'

def randomStar(self):
    choice = [5,4,3]
    probability = [0.1, 0.2, 0.7]
    star = random.choices(choice, probability)
    return star


def post(self, request):
    result = self.randomStar()
    character = Characters.objects.filter(stars=result).order_by('?')[:1]
    return JsonResponse(result, safe=False)

With this code I first randomly select a number from the available list(5,4,3) and the number selected is used as a variable in mysql query as a value. For example if number 3 is selected then the query will look for all characters in database that have stars set to 3 and order them randomly and display only one. When I run this code I keep getting the following error:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

When I send result in Jsonresponse I get a random number and it's not a list. How come when I enter it in the query it sees it as a list? How can this be redone to work?

Thanks




Junit Test using Math.Random and strings involved

Im stuck on testing this little section of code and i have no idea how i would start with testing it? Can anyone help!?

TBH i dont even know if this is right?

  public int FindRandomNumber(){
          int index = (int) (Math.random() * (Bournemouth.bison.length / 3));
          String what = Bournemouth.bison[index * 3];
          String who = Bournemouth.bison[1 + index * 3];
           System.out.printf("%s said \"%s\"", who, what);

        return index;




Can I make random mask with Numpy?

I'm doing image processing using Python.

I am trying to randomly extract some pixels from the image.

Is it impossible to make random mask with Numpy?

What I'm thinking now is to make 1000 elements of the 10000 line array True and all else False, is it possible to realize this?

Also, if impossible, is there any other way to make a random mask? Thank you.




Swapping of randomly chosen elements gone wrong

I'm trying to write an algorithm in C++ that produces a sequence of five consecutive distinct numbers from 1 to 25 by initializing an array of 25 elements to their corresponding index value and then iteratively generate two random numbers, one of which in the range 1-5 and the other in the range 6-25, and then swap the two elements corresponding to these two random values. It's basically a random-sorting algorithm of the numbers 1-25, and I only care about the ones that end up on the first five positions. However, when I output the result in Xcode, I get a weird number on the last line, like:

16
12
11
6
-272632008

The code I have is this:

 #include <iostream>

 using namespace std;

  int main(int argc, const char * argv[]) {
  int numbers[26];
  int randomnum1, randomnum2;

  for(int i=0;i<=25;i++) {
    numbers[i] = i;
  }

  srand(time(NULL));

  int temp;


  for(int i=1;i<=25;i++) {
    randomnum1 = 1 + rand() % 5;
    randomnum2 = 6 + rand() % 25;
    temp = numbers[randomnum1];
    numbers[randomnum1] = numbers[randomnum2];
    numbers[randomnum2] = temp;
  }

  for(int i=1;i<=5;i++) {
      cout<<numbers[i]<<"\n";
  }
    return 0;
  }

Any advice on how to solve this problem would be appreciated.




How to randomly generate a string and color that string randomly in Android studio

I'm trying to make a program generate a text randomly and let thta text be color randomly too but I don't know how. Can be in either Java or Kotlin.




Randomly find numbers from 1-12 without repeat

I have three variable integers, and I have the following code that randomizes their value:

Randomize()

    number = Int(Rnd() * 12) + 1
    AssignImagesToSquares()

    number2 = Int(Rnd() * 12) + 1
    AssignImagesToSquares()

    number3 = Int(Rnd() * 12) + 1
    AssignImagesToSquares()

And AssignImagesToSquares is a Private Sub where I use them. However, the problem that I am facing is that numbers can be repeated. I could not figure out how to do it, but in psuedocode,

'Randomize the integer "number"

'Randomize the integer "number2" where number2 <> number

'Randomize the integer "number3" where number3 <> number2 <> number.

I thought of maybe using a loop to repeat the process until a match is found but how exactly can that be done?




random.choice not acting random at all

I have been working on a silly magic item creator that makes use of diffrent lists with stuff that can happen, feelings, coluers and so on. i have been using random.choice to pick from these lists but somehow the items generated do not really seem random at all.

when i run it 10 times in a row i get stuff like:

A feather that causes horrible visions of an impending disaster, when starring at it

A lamp that makes you feel drunk when you lick a person who has something you want

A feather that makes you feel drunk when you lick a person who has something you want

A dagger that makes you feel drunk when you lick a person who has something you want

A feather that causes horrible visions of an impending disaster, when starring at it

A lamp that glows white when you touch a person thinking of you

A book that makes you feel drunk when you lick a person who has something you want

A cane that makes you feel drunk when you lick a person who has something you want

A marble that makes you feel drunk when you lick a person who has something you want

A needle that makes you feel drunk when you lick a person who has something you want

the first variable, item seems random enough, but from then on it starts repeating it self, the you feel drunk, is one possibility of a list of 10+ possibilities and the lick is from a list of 5.

makesyous = ["sad", "happy", "cold", "warm", "itchy", "laugh", "cough", "sing", "tired", "dizzy", "feel drunk", "uncomfortable", "feel like the opposite gender"]
sences = ["you see", "you smell", "you hear", "you touch", "you lick"]

they are all of them called thorugh a sceries of linked functions (thats is not the order the lilts and functions are wridden in the code, this is just to illustrate how i do stuff)

def generate():
    string = "A " + item() + " that " + action()
    return string

def item():
    x = random.choice(items)
    return(x)

def action():
    x = random.choice(actions)
    return(x)

actions = [short(), makesyou() + " "+ when(), random.choice(dostuff)]

def makesyou():
    x = "makes you " + random.choice(makesyous)
    return(x)

def when():
    x = random.choice(whens) + " " + sence()
    return(x)

am i doing somthing wrong (i know my code is horriblei structured, sorry about that) or is the random.choice working as intented?




jeudi 21 décembre 2017

Math game issues with randomly generated numbers for equations

Hello My fellow coders i am in desperate need of some help as im not sure how to address making a multiple choice game with randomly generated math equations. My current coding is not returning any answers or numbers even inside the console. Please help me out without telling me exactly how to do it. I would love some pointers and explanations:) So my original angle on how to do this is that there would be two randomly generated numbers using a Math.random object and multiplying it by 10 so that i get whole numbers from 0-10 that are in the equation then i want to display them inside the box marked question with an id tag. Thank you so much in advance! Right now i really need help on just getting the equation to pop up lmao and i would like the simplest code to do it I have only been doing javascript for 2 months now and havent quite gotten the hang of it yet! Also How might i go about reffering to the answer so that i can place it in a box later

Heres the html:

<head>
    <title>Math Game</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
    <link rel="stylesheet" href="styling.css">
</head>

<body>      
    <div id="title">
            The Matheroo
        </div>
    <div id="sunYellow">
        <!--Because the score value is going to change as the user plays the game we need to place it in a span and refer to it later with some JAVA-->

        <div id="score">
            Score: <span id="scorevalue">0</span>
        </div>
        <div id="correct">
            Correct!
        </div>
        <div id="wrong">
            Try Again
        </div>
        <div id="question">
            <span id="firstInt"></span><span id="secondInt"></span>
        </div>
        <div id="instruction">
            Click on the Correct Answer
        </div>
        <div id="choices">
            <div id="box1" class="boxes"></div>
            <div id="box2" class="boxes"></div>
            <div id="box3" class="boxes"></div>
            <div id="box4" class="boxes"></div>
        </div>
        <div id="startreset">
            Start Game
        </div>
        <div id="time-remaining">
            Time Remaining: <span id="timer-down">60</span> sec
        </div>
        <div id="game-over">
            Game Over
        </div>
    </div>

    <!--It is good practice to write the java at the end of the body element so all the divs load. Also use an external file for the javascript for clarity-->
    <script src="Javascript.js"></script>
</body>

heres the javascript:

    var gameOn = false;
var score;
var interval;

function stopGame() {
  gameOn = false;
  if (interval) {
    clearInterval(interval);
    interval = null;
  }
  document.getElementById("startreset").innerHTML = "Start Game";
  document.getElementById("time-remaining").style.display = "";
}


//if we click on the start/reset
document.getElementById("startreset").onclick = function () {
  //if we are not playing
  if (gameOn) {
    stopGame();
  } else {
    //change mode to playing
    gameOn = true;

    //set score to 0
    score = 0;

    document.getElementById("scorevalue").innerHTML = score;

    //show countdown box
    document.getElementById("time-remaining").style.display = "block";
    document.getElementById("startreset").innerHTML = "Reset Game";

    var counter = 60;

    //reduce time by 1sec in loops
    interval = setInterval(timeIt, 1000);
    function timeIt(){
      document.getElementById("timer-down").innerHTML = counter;
      counter--;

        //timeleft?
        //no->gameover
        if ( counter === 0) {
        stopGame();
        document.getElementById("game-over").style.display = "block";
      }
    }
      //generate new Q&A
      function generateQ(){
    var a = Math.floor(Math.random()*10);
    var b = Math.floor(Math.random()*10);
    var result = +a + +b;
    document.getElementById("firstInt").innerHTML = a;
    document.getElementById("secondInt").innerHTML = b;
    console.log(result);
  }
      }

  }
}

Here's the CSS stylesheet:

html{
    height: 100%;
    background: radial-gradient(circle, #fff, #ccc);
}

#title{
    width: 400px;
    padding: 0px 20px;
    margin-left: 350px;
    margin-top: 50px;
    background-color: #84FFE3;
    color: white;
    border-radius: 10px;
    font-size: 3em;
    letter-spacing: 2.7px;
    font-family: cursive, sans-serif;
    text-align: center;
    box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
    -moz-box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
    -webkit-box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
}

/*The container for the game in the center of the page*/
#sunYellow{
    height: 400px;
    width: 550px;
    background-color: #FFDC00;
    /*Top and bottom margin is set to 100px and the left and right margin is set to auto so that the left and right margin gets bigger and bigger until the box is centered*/
    margin: 90px 280px 0px 280px;
    padding: 20px;
    border-radius: 10px;
/*    Reference for 'box-shadow' [horizontal offset(if the number is positive then the shadow will be on the right side of our box)] [vertical offset(if the number is positive then the shadow will be on the bottom of our box, if negative it will be the opposite)] [blur radius(This is how blurry or sharp the shadow will be)] [optional spread radius(how big the shadow is)] [color]*/
    box-shadow: 4px 4px 0px 0px rgba(248,151,74, 0.8);
    -moz-box-shadow: 4px 4px 0px 0px rgba(248,151,74, 0.8);
    -webkit-box-shadow: 4px 4px 0px 0px rgba(248,151,74, 0.8);
    position: relative;
}


#score{
    background-color: #84FFE3;
    color: #2F4F4F;
    padding: 10px;
    position: absolute;
    left: 500px;
    /*Whenever using a 'box-shadow' add the cross browser compatibility syntaxs for mozilla and safari*/
    box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
    -moz-box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
    -webkit-box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
}

#correct{
    position: absolute;
    left: 260px;
    background-color: #00FF0D;
    color: white;
    padding: 11px;
    display: none;
}

#wrong{
    position: absolute;
    left: 260px;
    background-color: #EF0200;
    color: white;
    padding: 11px;
    display: none;
}

#question{
    width: 450px;
    height: 150px;
    margin: 50px auto 10px auto;
    background-color: #00F5FF;
    box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
    -moz-box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
    -webkit-box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
    font-size: 100px;
    text-align: center;
    font-family: cursive, sans-serif;
    color: black;
}

#instruction{
    width: 450px;
    height: 50px;
    background-color: #00FF0D;
    margin: 10px auto;
    text-align: center;
    line-height: 50px;
    box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
    -mox-box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
    -webkit-box-shadow: 4px 3px 0px 0px rgba(49, 79, 79, 0.5);
}

#choices{
    width: 450px;
    height: 100px;
    margin: 5px auto;
}

.boxes{
    width: 85px;
    height: 85px;
    background-color: white;
    float: left;
    margin-right: 36px;
    border-radius: 3px;
    cursor: pointer;
    box-shadow: 4px 3px 0px 0px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 4px 3px 0px 0px rgba(0, 0, 0, 0.2);
    -webkit-box-shadow: 4px 3px 0px 0px rgba(0, 0, 0, 0.2);
    text-align: center;
    line-height: 80px;
    position: relative;
    transition: all 0.2s;
    -webkit-transition: all 0.2s;
    -moz-transition: all 0.2s;
    -o-transition: all 0.2s;
    -ms-transition: all 0.2s;
}

.boxes:hover, #startreset:hover{
    background-color: #00F5FF;
    color: white;
    box-shadow: 4px 3px 0px 0px #266df2;
    -moz-box-shadow: 4px 3px 0px 0px #266df2;
    -webkit-box-shadow: 4px 3px 0px 0px #266df2;
}

.boxes:active, #startreset:active{
    box-shadow: 0px 0px #266df2;
    -moz-box-shadow: 0px 0px #266df2;
    -webkit-box-shadow: 0px 0px #266df2;
    top: 4px;

}

#box4{
    margin-right: 0px;
}

#startreset{
    width: 83px;
    padding: 8px;
    background-color: rgba(255, 255, 255, 0.5);
    margin: 0px auto;
    font-weight: bold;
    border-radius: 3px;
    cursor: pointer;
    box-shadow: 4px 3px 0px 0px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 4px 3px 0px 0px rgba(0, 0, 0, 0.2);
    -webkit-box-shadow: 4px 3px 0px 0px rgba(0, 0, 0, 0.2);
    text-align: center;
    position: relative;
    transition: all 0.2s;
    -webkit-transition: all 0.2s;
    -moz-transition: all 0.2s;
    -o-transition: all 0.2s;
    -ms-transition: all 0.2s;
    /*This doesnt allow a user to select text for all browsers*/ 
    user-select: none;
    -webkit-user-select: none;     
    -moz-user-select: none;
    -ms-user-select: none; 


}

#time-remaining{
    width: 157px;
    padding: 7px;
    position: absolute;
    top: 395px;
    left: 400px;
    background-color: #84FFE3;
    border-radius: 3px;
    box-shadow: 4px 3px 0px 0px #00ad99;
    -moz-box-shadow: 4px 3px 0px 0px #00ad99;
    -webkit-box-shadow: 4px 3px 0px 0px #00ad99;
/*    visibility: hidden;*/
    display: none;
}

#game-over{
    height: 200px;
    width: 500px;
    background: linear-gradient(#F8974A, #3EB8C5);
    color: white;
    font-size: 2.5em;
    text-align: center;
    text-transform: uppercase;
    position: absolute;
    top: 100px;
    left: 45px;
    /*Giving the 'game-over' div a higher z-index ensures it is on top of the other elements, which the default is 0*/
    z-index: 2;
    display: none;
}




randomly swapping the values between two columns but still maintaining row identity

I have a data set with responses for before and after. that looks something like this...

before <- c(2,4,5,4,3) after <- c(4,4,5,4,4) and so on but in a data frame of rows and columns .

I want to do a permutation test where each value will stay in its row but could switch columns randomly. Not every row needs to switch but it will be random every time. I want to do it a lot of times in a for loop I think to asses the mean and how it changes. How can I do this?




Python-Selecting Words and inserting into sentence framework

I was wondering if anyone familiar with python could help me with selecting random words and inserting them into a sentence framework, with that sentence then printed in a single line.

Sentence framework example: VERB " of the " NOUN " People"

Verbs: Attack, Invasion, Rise, Revenge, Retreat, Defeat, Escape, Return, Subjugation

Nouns: Mole, Space, Saucer, Vampire, Carrot, Monkey, Alligator, Zombie, Moon, Robot, Snake, Slime

I've tried a few random.choice iterations and can't seem to get it to work. Any help would be appreciated.




Creating a Character Array with a Certain Number of Vowels and Consonants (Java)

I am trying to create a program that outputs ten lowercase letter characters - five vowels and five consonants. In order to do this, I have started by creating a char array with a range between 'a' and 'z' called letters[] with size 10. Once the array is filled, I will print the output with the use of a format string containing everything in the array.

My question is, how would I make the program output exactly five of each type (and keep the order of the characters printed completely random)? I have considered using the switch statement with a case each for consonants and vowels, but my ideas so far seem over-complicated and inelegant.




Random NPC (Entity) Smooth Movement in Java. The entity is shaking

I have this class and I can't seem to find the answer to my question.

I'd like to create a smooth, random movement for this entity. But when I run the program, the entity goes crazy, and it continues to change direction and won't move at all (well, it moves but it shakes). How can I make it change direction more slowly?

Here's the code (and sorry for my bad english):

package praisethesun.code.entities;

import java.util.Random;

import praisethesun.code.graphics.Sprite;

public class OrganicVillager extends Organic{

    private Random direction = new Random();

    public OrganicVillager(String name, Sprite sprite, float posX, float posY, float width, float height, int speed, double velocity) {
        super(name, sprite, posX, posY, width, height, speed, velocity);    
    }

    public void update(){
        move();
    }

    private void move(){

        float moveX = 0;
        float moveY = 0;

        switch(direction.nextInt(4)) {
        case 0:
            moveY += getSpeed();
            setDirection(Direction.DOWN);

            setCurrentSprite(0,0);
            break;
        case 1:
            moveX -= getSpeed();
            setDirection(Direction.LEFT);

            setCurrentSprite(0,1);
            break;
        case 2:
            moveY -= getSpeed();
            setDirection(Direction.UP);

            setCurrentSprite(0,2);
            break;
        case 3:
            moveX += getSpeed();
            setDirection(Direction.RIGHT);

            setCurrentSprite(0,3);
            break;
        default: break;
        }

        setPosX(getPosX() + moveX);
        setPosY(getPosY() + moveY);

        setBounds((int)getPosX(), (int)getPosY());
    }
}