samedi 31 mars 2018

Random ordered Questions from a list of objects

I have a list of objects(Question objects).I need specific number of objects in a random order.For example i have 100 objects and i need 50 of them but in a random order.How to achieve it using Spring boot?




Create lists with different amounts of random numbers Python 3

I am needing to create lists of random numbers (being either 0 or 1) with different lengths. I need lists with lengths of 10 numbers, 20 numbers, etc. all the way to 500. This is what I have:

import random
list1 = []
for x in range(10,501,10):
    list1.append(random.randint(0,1))
    print(list1)
    list1.clear()

So I'm getting 50 lists of only one random number. I understand that the range() is my problem because it is only an iterator, so what would I do to avoid writing 50 for loops to get all of these lists?




Java 2D array doesn't modify when it should

I'm trying to remove values in a 2D array to create a sudoku grid that people can solve but when I call the method in my other class, it doesn't do anything to the grid. There is another method that checks if the grid is perfect, turns the generated 1D grid into a 2D grid and then the holes should be added. Here is the method and how I call it:

public int[][] generateHoles(int[][] fullGrid, int difficulty){
    int[][] holes = new int[9][9];
    for(int i = 0; i < 81; i++) {
        holes[i/9][i%9] = fullGrid[i/9][i%9];
    }
    int nbrCellulesAEnlever;

    switch(difficulty){
    case 1: //Grille façile
        rand = new Random();
        nbrCellulesAEnlever = (int) 0.57*(fullGrid.length*fullGrid[0].length); //Enlève 57% des nombres
        while(nbrCellulesAEnlever != 0) {
            int i = rand.nextInt(81);
            System.out.println(i);
            holes[i/9][i%9] = 0;
            nbrCellulesAEnlever--;
        }
        break;
    case 2: // Grille facile-moyenne
        rand = new Random();
        nbrCellulesAEnlever = (int) 0.61*(fullGrid.length*fullGrid[0].length); //Enlève 61% des nombres
        while(nbrCellulesAEnlever != 0) {
            int i = rand.nextInt(81);
            holes[i/9][i%9] = 0;
            nbrCellulesAEnlever--;
        }
        break;
    case 3: // Grille moyenne
        rand = new Random();
        nbrCellulesAEnlever = (int) 0.64*(fullGrid.length*fullGrid[0].length); //Enlève 64% des nombres
        while(nbrCellulesAEnlever != 0) {
            int i = rand.nextInt(81);
            holes[i/9][i%9] = 0;
            nbrCellulesAEnlever--;
        }
        break;
    case 4: // Grille moyenne-difficile
        rand = new Random();
        nbrCellulesAEnlever = (int) 0.68*(fullGrid.length*fullGrid[0].length); //Enlève 68% des nombres
        while(nbrCellulesAEnlever != 0) {
            int i = rand.nextInt(81);
            holes[i/9][i%9] = 0;
            nbrCellulesAEnlever--;
        }
        break;
    case 5: // Grille difficile
        rand = new Random();
        nbrCellulesAEnlever = (int) 0.72*(fullGrid.length*fullGrid[0].length); //Enlève 72% des nombres
        while(nbrCellulesAEnlever != 0) {
            int i = rand.nextInt(81);
            holes[i/9][i%9] = 0;
            nbrCellulesAEnlever--;
        }
        break;
    default: // Grille de difficulté random
        double random = ThreadLocalRandom.current().nextDouble(0.5, 0.79); //Crée un % entre 50% inclus et 79% exclus
        nbrCellulesAEnlever = (int) random*(fullGrid.length*fullGrid[0].length);
        while(nbrCellulesAEnlever != 0) {
            int i = rand.nextInt(81);
            holes[i/9][i%9] = 0;
            nbrCellulesAEnlever--;
        }
        break;
    }
    return holes;
}

And I call it in another class like this:

SudokuGenerator sg = new SudokuGenerator();
if(sg.isPerfect(sg.generateGrid())) {
    affichage(sg.generateHoles(sg.transform(sg.generateGrid()), 1));
}




Set random color on TextView field inside ListView

So basically, this is my simple_adapter_view, which i import to the listView. I have TextView(letter),TextView(name&surname) and ImageView(send image) I have 5 contacts in my list, and i need to change BackgroundColor of the TextView(letter) only. It has to be random for each of my 5 contacts, every time i run the app. Can you help me?




VB.NET how to get a random string value

I'm making a Texas Hold Em' game and I just started rewriting it, and I ran into a problem trying to get a random string value. My string arrayCard() is 2 of spades to Ace of Diamonds and I don't know what random function I have to write because I only know how to get a random integer value = Math.Floor(Random () * 51).

CODE:

Public Class Form1

    Dim arrayCard() As String = {"2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "11S", "12S", "13S", "14S", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "11C", "12C", "13C", "14C", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "11H", "12H", "13H", "14H", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "11D", "12D", "13D", "14D"}

    '*_CARD & SUIT RANDOM_*
    Dim card As Integer = Equals(Rnd() * arrayCard.Length)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        cmdBestHand.Visible = False
        cmdBestHandPvP.Visible = False
        cmdHit.Visible = False
        cmdHitX.Visible = False
        cmdWin.Visible = False
        picHit1.Visible = False
        picHit2.Visible = False
        'Randomize()
    End Sub

    Private Function callCard()
        Do While arrayCard.Length > 0
            arrayCard(card) = Math.Floor(Rnd() * 51)
            ReDim Preserve arrayCard(card)
        Loop
        Return "-1" 'error = deck empty
    End Function

    'while my arrayCard is greater then 0
    'put random card and suit
    'call the card + suit
    'after it calls the card and suit, save that card, put it as used, and delete the card from the array
    're dim the suit and save the array as 51 cards now
    'repeat till the array = -1 then say ERROR out or cards
    'eventually Re-Loop it To be Like 2 arrays so When it equals -1 To back To 52 For a full deck
    'DO IN FUNCTION so i can call the card in the picturebox and display the RIGHT CARD

    Private Sub cmdExit_Click(sender As Object, e As EventArgs) Handles cmdExit.Click
        Application.Exit()
    End Sub

    Private Sub cmdNewGame_Click(sender As Object, e As EventArgs) Handles cmdNewGame.Click
        'arrayCard(card) = random string value
        arrayCard(card) = arrayCard(value)
        picUser.Image = My.Resources.ResourceManager.GetObject("_" & arrayCard(card))
        picUserX.Image = My.Resources.ResourceManager.GetObject("_" & arrayCard(card))
        picStart.Image = My.Resources.ResourceManager.GetObject("_" & arrayCard(card))
        picStartX.Image = My.Resources.ResourceManager.GetObject("_" & arrayCard(card))
        picStartX2.Image = My.Resources.ResourceManager.GetObject("_" & arrayCard(card))
        cmdBestHand.Visible = True
        cmdBestHandPvP.Visible = False
        cmdHit.Visible = True
        cmdHitX.Visible = False
        cmdWin.Visible = False
        txtP1.Text = arrayCard(card)
        'txtP1.Text = "The Bridge has been made. Click Best Hand to see your fate."
        txtP2.Text = "Press Player VS Player to add a 2nd Player."
    End Sub
    Private Sub cmdPvP_Click(sender As Object, e As EventArgs) Handles cmdPvP.Click
        txtPvP.Text = "Player 2"
        txtP2.Text = "The Bridge has been made. Click Best Hand to see your fate."
        picDealer.Image = My.Resources.ResourceManager.GetObject("_" & arrayCard(card))
        picDealerX.Image = My.Resources.ResourceManager.GetObject("_" & arrayCard(card))
        cmdBestHandPvP.Visible = True
    End Sub

    Private Sub cmdBestHand_Click(sender As Object, e As EventArgs) Handles cmdBestHand.Click
    End Sub

    Private Sub cmdBestHandPvP_Click(sender As Object, e As EventArgs) Handles cmdBestHandPvP.Click
    End Sub

    Private Sub cmdHit_Click(sender As Object, e As EventArgs) Handles cmdHit.Click
        picHit1.Visible = True
        picHit1.Image = My.Resources.ResourceManager.GetObject("_" & arrayCard(card))
        cmdHitX.Visible = True
        txtP1.Text = "Have you checked your hand lately? Click Best Hand to see your fate."
        txtP2.Text = "Have you checked your hand lately? Click Best Hand to see your fate."
    End Sub

    Private Sub cmdHitX_Click(sender As Object, e As EventArgs) Handles cmdHitX.Click
        picHit2.Visible = True
        picHit2.Image = My.Resources.ResourceManager.GetObject("_" & arrayCard(card))
        cmdWin.Visible = True
        txtP1.Text = "Is your hand strong? Click Best Hand to see your fate."
        txtP2.Text = "Is your hand strong? Click Best Hand to see your fate."
    End Sub

    Private Sub cmdWin_Click(sender As Object, e As EventArgs) Handles cmdWin.Click
        'determines who has better hand and winner
    End Sub
End Class




Creating a unique listing_no (Java/PostgreSQL)

I am working on a option in a Menu function that posts the car for the sale in a database. The option asks for the user to enter the year, make, condition and price, which is then inserted into the table car_sale in the database. However, a unique listing_no must also be generated during this option. I cannot define my tables to uniquely generate the 10 digit number the option but I must code the program to insert uniquely generated listing_no. Below you will find the code of me trying to do this, however the code only works in Oracle but I cannot use Oracle. I can only PostGreSQL and Java. Therefore, my problem arises as the functions and relations I am using cannot be used in PostGre.

Code to Generate Listing No:

 public int generateListingNo() throws SQLException
 {
  int listingSeq = 0;
  Statement select = connection.createStatement();
  result = select.executeQuery("select (to_char(sysdate,'yyyymmdd')||AUDIT_SEQ.NEXTVAL)valnext from dual");;
  if(result.next())
  {
     listingSeq = result.getInt(1);
  }

  int seq = listingSeq;

  return seq;
 }

Code in The Option Function to insert the lisitng_no generated from generateListingNo()

public void option() throws SQLException
   {
int listing_no = generateListingNo();
         // insert information into books_for_sale table
         sql_insert = "INSERT INTO car_sale VALUES(" + listing_no +", "
                       + "'" + year + "'" + ", " +
                       "'" + make + "'" +", " +
                       "'" + condition + "'" + ", "
                       + price + ")";




Function that contains alert of random number on button click - Javascript

I have this code to try and make an alert pop up on the web page that says "your number is" + "(1-25)". Nothing happens when I press the button. Does math.random only produce a number to the console or why does this not work. Here is my code.

function rGen () {
 let rNum = (Math.floor(Math.random() * 25))
 alert(rNum + "is your number")
}


let button1 = document.getElementById('button1');
button1.addEventListener('click' rGen)




vendredi 30 mars 2018

Discord JavaScript bot. How can I let it send a random Picture from a folder?

I tried several things but nothing works... how can I let my Discord Bot send a random Image from a Folder after I gave a command. (like the Folder contains img.1 img.2 and img.3 and it chooses randomly)




adding column in Oracle SQL table that is random sample from another column/table

I have a preexisting table (MYORIGTABLE) in SQL and I would like to add a column which is a random sample from a column in another table (RANDNUM10). The other table is a 1 column sample of random numbers I've predetermined and would like to sample from; column name is RANDVAL. I've tried the following

select (select randval from (SELECT randval FROM RANDNUM10 ORDER BY dbms_random.value) where rownum=1) as mynum from MYORIGTABLE

But unfortunately this just gives me the same random number which was sampled from RANDNUM10 repeated for the entire length of MYORIGTABLE. How can I perform the sampling so that every line of MYORIGTABLE gets a newly generated sample?

Thanks, Christie




Outputting A Sentence Configured Via Random Pieces Using Pointer Arrays

I am new to coding and we're just learning pointers, and I'm unsure of why this code is not storing the bits of the sentence to the sentence array throughout the program, or why it is not able to print the data,

This is for a school assignment, and I normally just spend hours attempting different methods, but I figure it will be better to ask for advice so i can learn to do this correctly.

#include "stdio.h"
#include "stdlib.h"
#include "time.h"
#include "string.h"
#define SIZE 4



void nounPick(const const char *nPTR, char *sPTR );
void verbPick(const const char *vPTR, char *sPTR );
void prepPick(const const char *pPTR, char *sPTR );
void artiPick(const const char *aPTR, char *sPTR );


int main(void){


   char *noun[SIZE];
   char *verb[SIZE];
   char *prep[SIZE];
   char *arti[SIZE];
   char *sent[SIZE];


   noun[0] = "cat ";
   noun[1] = "dog ";
   noun[2] = "truck ";
   noun[3] = "plane ";
   noun[4] = "skateboard ";

   verb[0] = "drove ";
   verb[1] = "jumped ";
   verb[2] = "ran ";
   verb[3] = "walked ";
   verb[4] = "flew ";

   prep[0] = "to ";
   prep[1] = "from ";
   prep[2] = "over ";
   prep[3] = "under ";
   prep[4] = "on ";

   arti[0] = "a ";
   arti[1] = "one ";
   arti[2] = "some ";
   arti[3] = "any ";




   const char *nPTR = noun[0];
   const char *vPTR = verb[0];
   const char *pPTR = prep[0];
   const char *aPTR = arti[0];
   char *sPTR = sent[0];

    srand( time(NULL));
    for(int c = 0; c< SIZE; c++)
        *(sent + c) = 0;

    nounPick(nPTR, sPTR);
    verbPick(vPTR, sPTR);
    prepPick(pPTR, sPTR);
    artiPick(aPTR, sPTR);

    printf("Made it through the picking\n");
    printf("Your Random Sentence Is As Follows:\n");


    for(int i = 0; i < SIZE; i++){
        if(*(sent + i) == 0)
            i = SIZE;
        else
            printf("%s", *(sent + i));
    }


return 0;

}

void nounPick(const const char *nPTR, char *sPTR ){

    int i = 0;
    int l = rand() % 5;
    printf("%d, is L\n", l);

    do{
            switch(*(sPTR + i)){
                case 0:
                *(sPTR + i) = *(nPTR + l);
                break;

                default:
                i++;
                break;
            }
    } while (i < SIZE);
}

void verbPick(const const char *vPTR, char *sPTR ){

    int i = 0;
    int l = rand() % 5;
    printf("%d, is L\n", l);

    do{
            switch(*(sPTR + i)){
                case 0:
                *(sPTR + i) = *(vPTR + l);
                break;

                default:
                i++;
                break;
            }
    } while (i < SIZE);
}

void prepPick(const const char *pPTR, char *sPTR ){

    int i = 0;
    int l = rand() % 5;
    printf("%d, is L\n", l);

    do{
            switch(*(sPTR + i)){
                case 0:
                *(sPTR + i) = *(pPTR + l);
                break;

                default:
                i++;
                break;
            }
    } while (i < SIZE);
    printf("\n\n%s\n\n", sPTR);
}

void artiPick(const const char *aPTR, char *sPTR ){

    int i = 0;
    int l = rand() % 5;
    printf("%d, is L\n", l);

    do{
            switch(*(sPTR + i)){
                case 0:
                *(sPTR + i) = *(aPTR + l);
                break;

                default:
                i++;
                break;
            }
    } while (i < SIZE);
}




sampling based on specified column values in R

I have a data like this, where Average is the average of X, Y, and Z.

head(df)
ID  X   Y   Z   Average
A   2   2   5   3
A   4   3   2   3
A   4   3   2   3
B   5   3   1   3
B   3   4   2   3
B   1   5   3   3
C   5   3   1   3
C   2   3   4   3
C   5   3   1   3
D   2   3   4   3
D   3   2   4   3
D   3   2   4   3
E   5   3   1   3
E   4   3   2   3
E   3   4   2   3

To reproduce this, we can use

df <- data.frame(ID = c("A", "A", "A", "B", "B", "B", "C", "C", "C", "D", "D", "D", "E", "E", "E"),
                     X = c(2L, 4L, 4L, 5L, 3L,1L, 5L, 2L, 5L, 2L, 3L, 3L, 5L, 4L, 3L),
                     Y = c(2L, 3L, 3L, 3L,4L, 5L, 3L, 3L, 3L, 3L, 2L, 2L, 3L, 3L, 4L), 
                     Z = c(5L, 2L, 2L,1L, 2L, 3L, 1L, 4L, 1L, 4L, 4L, 4L, 1L, 2L, 2L), 
                     Average = c(3L,3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L))

From this, I want to extract one observation per ID such that we don't get same (as much as is possible) values of the combination of X, Y, and Z. I tried

library(dplyr)
df %>% sample_n(size = nrow(.), replace = FALSE) %>% distinct(ID, .keep_all = T)

But, on a larger dataset, I see too many repetitions of the combination of X, Y, Z. To the extent possible, I need the output with equal or close to equal representation of cases (i.e. the combination of X, Y, Y) like this:

   ID   X   Y   Z   Average
    A   2   2   5   3
    B   5   3   1   3
    C   2   3   4   3
    D   3   2   4   3
    E   4   3   2   3




Random number generator for python based discord bot

What I am trying to do is when someone enters the command !random (argument) I want the bot to generate a number between 1 and what they put as the argument. But whenever I try to do this it gives me around 6 different errors that are very long and make no sense to me. My current code for this command is below.

@Bot.command(pass_context=True) async def random1and10(ctx, number): arg = random.randint(1, number) if number: await Bot.say(arg) else: await Bot.say('Please select a valid number')




How can replace a column of all records with random strings?

I have a table customers_info in my MySQL having a column 'address'.

I would like to replace the values of 'address' in all the rows with random texts (anything, for example, like xwdjduhyrmdz) for the privacy reason.

I found this SQL and tried it on phpmyadmin but didn't work for me.

UPDATE customer_info
SET address = LEFT(REPLACE(CAST(NEWID() AS CHAR(40)), '-', ''), @Characters)

How can I do this ?




random generator function javascript

I'm making a guessing game for class. I pretty much have it done with the biggest problem I've had was making the string randomize itself after the game ends. It picks a random letter if the page refreshes but the objective is to keep track of stats so refreshing is out.

Here's my javascript code:

var lettersChar = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", 
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

function randomFunc() {
    var randomMath = lettersChar[Math.floor(Math.random() * 
    lettersChar.length)];
    return randomMath;
}

//variables
var randomChar = randomFunc();

//array where user input will be stored
var userChoices = [];

var wins = 0;

var losses = 0;

var guesses = 9;

//keypress event
document.onkeyup = function (event) {

var userGuess = event.key;

    var userOptions = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", 
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", 
"z"];

//if guess is correct, +1 to win and refresh game and generate new letter
if (userOptions.indexOf(userGuess) > -1) {

    if (userGuess === randomChar) {
        wins++;
        guesses = 9;
        randomFunc();
        console.log(wins);
    }
    //if guess is incorrect, then print wrong guess and -1 to guesses left
    else if (userGuess !== randomChar) {
        guesses--;
        userChoices.push(userGuess);
    }
    //If guess reaches to 0 add +1 to loss and restarts game
    if (guesses === 0) {
        losses++;
        guesses = 9;
        userChoices = [];
        randomChar;
    }
}

I've tried invoking the function and it doesn't appear to work for me at this moment. Any help is appreciated!




jeudi 29 mars 2018

NameError for importing random and numpy.random, but nothing else

I've run into a strange case in my Python code, and I'm trying to figure out why this occurs.

from numpy.random import uniform
for r in range(1, rounds):
    sample = {item: uniform() < probability for item in items}

When I run the above code, I get the following NameError:

File "sample.py", line 6, in <module>
  sample = {item: uniform() < probability for item in items}
File "sample.py", line 6, in <dictcomp>
  sample = {item: uniform() < probability for item in items}
NameError: name 'uniform' is not defined

This is very strange, since I am importing uniform directly before using it in the following line. I got the same error using the random module. I'm using other packages in my code (including argparse and pickle) but only the random number generation is giving me errors. I'm running Python 3 on a Windows machine. I also get the same error when I move the import statement inside the for loop.

for r in range(1, rounds):
    from numpy.random import uniform
    sample = {item: uniform() < probability for item in items}

What could be causing this error?




java.lang.ArrayIndexOutOfBoundsException: 0 When using ArrayList

For some reason this exception is being thrown when I try to run this code and I have no idea how to fix it. I understand that it is to do with the contents of the list however I have declared them outside this method and it but the exception continues to be thrown.

public class Deck {
private int i;
Random rand = new Random();
public String[] playerHand = {};
private String[] computerHand = {};
public String[] deck = {"CA", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10", "CJ", "CQ", "CK", "DA", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D10", "DJ", "DQ", "DK", "HA", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "H10", "HJ", "HQ", "HK", "SA", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "S10", "SJ", "SQ", "SK2"};
private  ArrayList<String> deckList = new ArrayList<String(Arrays.asList(deck));
private String[] pile = {};
ArrayList<String> pileList = new ArrayList<String>(Arrays.asList(pile));

public void startGame(){
   for(i = 0; i < 5; i++){
       playerHand[i] = deckList.get(rand.nextInt(deckList.size()));

       deckList.remove(playerHand[i]);
   }
    for(i = 0; i < 5; i++){
       computerHand[i] = deckList.get(rand.nextInt(deckList.size()));
       deckList.remove(computerHand[i]);
    }
    pile[0] = deckList.get(rand.nextInt(deckList.size()));
    deckList.remove(pile[0]);

}

The exception thrown is "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at card.game.Deck.startGame(Deck.java:28)"

Not sure but the random function may have something to do with it.




Random numbers are the same after every loop

My program is supposed to display a pair of dice for every roll, which works as planned. I'd like it to repeat multiple times but every time it repeats it's no longer random and just repeats the assigned number from line 2 and 3. If I roll a 2 and a 3, it repeats a 2 and 3 every time. How can I make it so that a new random number is assigned each time it loops?

import random
dice1 = random.randrange(1,6)
dice2 = random.randrange(1,6)

... [I cut out the code for displaying the dice]

def start():
    confirmation = input("Would you like to roll the dice? (Y/N): ")
    if confirmation == "Y" or confirmation == "y":
        print ("You've rolled:",dice1,"and", dice2), showdice()
        return start()
    else:
        print("Goodbye")
start()




Optimize Random Forest parameters in weka?

I am trying to optimize random forest parameters using weka, the java class is as the following:

package pkg10foldcrossvalidation;

import weka.core.*;
import weka.classifiers.meta.*;
import weka.classifiers.trees.RandomForest;
import java.io.*;
public class RF_Optimizer {



     public static void main(String[] args) throws Exception {
      // load data
      BufferedReader reader = new BufferedReader(new FileReader("C:\\Prediction Results on the testing set\\Dataset.arff"));
      Instances data = new Instances(reader);
      reader.close();
      data.setClassIndex(data.numAttributes() - 1);

      // setup classifier
      CVParameterSelection ps = new CVParameterSelection();
      ps.setClassifier(new RandomForest());
      ps.setNumFolds(10);  // using 10-fold CV
      ps.addCVParameter("C 0.1 0.5 5");

      // build and output best options
      ps.buildClassifier(data);
      System.out.println(Utils.joinOptions(ps.getBestClassifierOptions()));
   }

}

But I am facing difficulty of understanding which parameters should replace the "C" and how the range of each one could be determined? And is it workable to use .addCVParameter several times for several parameter at the same time?

I tried to search for some youtube or website tutorials that explain how to change random forest parameters in java but nothing found.

Thank you




User-Friendly Dice Rolling Simulator in C++

I have a problem with my "User-Friendly Random Number Generator" in C++

When I run the program it runs fine but however for the last part of the program which is designed to look for a specific number of the numbers that were randomly generated. When I type in a number that was generated the only output of the program is the number "16". What I was hoping the output would be something like this:

Enter how many numbers do you want to be on your dice 6 Enter the number of dice you want to roll 10 3 1 6 1 4 4 6 2 2 1

Do you want to know how many times a number was the outcome of your rolls

Please enter the number you want to be counted for 1 The number 1 showed up 16 Times

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

int rand_0toN1(int dice_rolls);

int main() {
    int dice_rolls;
    int num_on_dice;
    int x = 1;
    int output;
    int analysis_num;
    int analysis_counter;
    std::string analysis;

    srand(time(NULL));

    cout << "Enter how many numbers do you want to be on your dice" << endl;
    cin >> num_on_dice;
    while(num_on_dice < 2){
        cout << "" << endl;
        cout << "The amount of numbers on a dice cannot be less than 2" << endl;
        cout << "Re-Enter:" << endl;
        cin >> num_on_dice;
     }
    while(num_on_dice > 1000000){
            cout << "" << endl;
            cout << "The amount of numbers on a dice cannot exceed 1000000" << endl;
            cout << "Re-Enter:" << endl;
            cin >> num_on_dice;
        }



    cout << "Enter the number of dice you want to roll" << endl;
    cin >> dice_rolls;
    while(dice_rolls > 1000000000000){
        cout << "" << endl;
        cout << "For testing purposes the number of dice you can roll cannot exceed 100" << endl;
        cout << "Re-Enter:" << endl;
        cin >> dice_rolls;
    }
    while(dice_rolls < 1){
            cout << "" << endl;
            cout << "The number of dice you can roll cannot be less than 1" << endl;
            cout << "Re-Enter:" << endl;
            cin >> dice_rolls;
        }



    while(x <= dice_rolls){
        output = rand_0toN1(num_on_dice) + 1;
        cout << output << endl;
        if(output == analysis_num){
            analysis_counter++;
        }
        x++;
    }





    cout << "" << endl;
    cout << "Do you want to now how many times a number was the outcome of your rolls <Type yes or no>" << endl;
    cin >> analysis;
    if(analysis == "no"){
        cout << "Good-Bye, I hope I will see you again later" << endl;
    }

    if(analysis == "yes"){
        cout << "Please enter the number you want to be counted for" << endl;
        cin >> analysis_num;
        while(analysis_num > num_on_dice){
            cout << "The number that you want to be searched cannot exceed the number that you entered for how many <how many numbers do you want to be on your dice>" << endl;
            cout << "Re-Enter:" << endl;
            cin >> analysis_num;
        }
        cout << "The number " << analysis_num << " showed up " << analysis_counter << " Times" << endl;
}
return 0; 
}

int rand_0toN1(int dice_rolls){
    return rand() % dice_rolls;
}




Output Random Number > range when using rand() function in C

My Specific question is when i input a range like 90 as the lower value and 100 as the higher value i get output random number sometimes less than 90.In my code below , x<y. My code is:

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

#define Null 0

void main(){
int x,y,a,b;
printf("Insert two numbers to create a range\n in which you want a random number to be generated:\n"); 
scanf("%d%d",&x,&y);
srand(time(Null));
a =( rand() + x)%y ;
printf("The Randomly Generated Number is %d.\n",a);


}   




Can I create a local numpy random seed?

There is a function, foo, that uses the np.random functionality. I want to control the seed that foo uses, but without actually changing the function itself. How do I do this?

Essentially I want something like this:

bar() # should have normal seed
with np.random.seed(0): # Doesn't work
    foo()
bar() # should have normal seed




Groupby and Sample pandas

I am trying to sample the resulting data after doing a groupby on multiple columns. If the respective groupby has more than 2 elements, I want to take sample 2 records, else take all the records

df:

col1   col2   col3   col4
A1     A2     A3     A4
A1     A2     A3     A5
A1     A2     A3     A6
B1     B2     B3     B4
B1     B2     B3     B5
C1     C2     C3     C4

target df:

col1   col2   col3   col4
A1     A2     A3     A4 or A5 or A6
A1     A2     A3     A4 or A5 or A6
B1     B2     B3     B4
B1     B2     B3     B5
C1     C2     C3     C4

I have mentioned A4 or A5 or A6 because, when we take sample, either of the three might return

This is what i have tried so far:

trial = pd.DataFrame(df.groupby(['col1', 'col2','col3'])['col4'].apply(lambda x: x if (len(x) <=2) else x.sample(2)))

However, in this I do not get col1, col2 and col3




How can I achieve on reload a responsive random image gallery where the position is randomly chosen? (Javascript)

I really want to know how I can achieve something similar like this page:

http://pleasedonotbend.co.uk/

  • The thumbnails are on random positions on reload
  • The content is responsive

Obviously I need to use Javascript, but I have no idea how I would do this.

Thank you for your help.




mercredi 28 mars 2018

Picking a random item from an array?

so I'm making a small game on the HTML5 Canvas. I have an array of images which are displayed on the canvas, and a button (which is just an event listener checking if a certain area of the canvas is clicked.) When this button is clicked, I would like a random image to be selected so that I can have it perform a task (running a function, and an animation, which I will implement after the random selection is sorted).

I am assuming I can use some variant of math.random() to randomly select an image, but do I first need to assign each of the images to a value, e.g. if there was 5 images, 0 to 4?

Here is the array code:

        var imageArray = new Array();
        imageArray[0] = "./assets/1.png";
        imageArray[1] = "./assets/2.png";
        imageArray[2] = "./assets/3.png";
        imageArray[3] = "./assets/4.png";
        imageArray[4] = "./assets/5.png";

        var box = new Image();
        box.onload = function () {
            ctx.drawImage(box, 50, 180, 150, 133);
            ctx.drawImage(box, 220, 180, 150, 133);
            ctx.drawImage(box, 390, 180, 150, 133);
            ctx.drawImage(box, 50, 320, 150, 133);
            ctx.drawImage(box, 220, 320, 150, 133);
            ctx.drawImage(box, 390, 320, 150, 133);
            ctx.drawImage(box, 50, 460, 150, 133);
            ctx.drawImage(box, 220, 460, 150, 133);
            ctx.drawImage(box, 390, 460, 150, 133);
        };
        box.src = imageArray[4];




Generate 100 random numbers such that only 25 out of 100 numbers will be greater than 0.(remaining will be 0)

This is the code to print 100 random numbers in a 2-d grid.

[[random.randint(1,25) for i in range(10)] for j in range(10)]

How do I print the random numbers such that out of 100 randomly printed numbers, only 25 will be of value greater than 0 ? Remaining all 75 numbers should be 0, in random positions of the grid.




How i can gues the comming value of random array on javascript? [on hold]

I need to know how i can guess the comming random value of array on javascript.

this is an exmple of my code


 const peices = 'ILJOTSZAW';
 matrix = createpeices(peices[peices.length * Math.random() | 0]);

from the array i wanna alert or show de goming value.




Excel VBA : Finding random combinations across 3 columns that match preset sums

I need to randomly pick individual and repeated entries from a list that has 3 separate integers, whose sum must equal separate particular values.

I've worked a bit with VBA before, but this is stumping me. I have seen examples with how to use Solver for a single row, but have not figured out how to get it to process stage by stage.

DATA: (stored on an invisible tab)

    name        Col A Col B Col C
    -----------------------------------
    Red           2    3    4
    Yellow        2    4    5
    Blue          3    1    2
    Green         1    1    1
    Purple        1    4    1
    Orange        0    2    5
    Black         4    4    4
    White         1    1    1
    Brown         3    3    3
    Pink          0    1    0
    Blaze Orange  0    0    0
    Ultraviolet   1    0    0
    Crystal       5    1    0

I'm trying to find Random combination of items that whose sums equal the respective target result values for each column. (selected by preset dropdowns)

Say for example, I'd want Column A to equal 10, Column B to equal 12, and Column C to equal 8.

The output might look like this.

    Green         1    1    1
    Purple        1    4    1
    Purple        1    4    1
    Crystal       5    1    0
    Orange        0    2    5
    Ultraviolet   1    0    0
    Ultraviolet   1    0    0
    -------------------------
    SUM          10   12    8

I'd guess that the results should be random each time, if it's a random search for the answer. The solver would likely work for this, but it'd have to be a nest of conditionals.

Something like:

    :START
    Calc Column A. If random sampled solution across Column A = desiredA, 
    then Record names of A, then Calculate Col B. 
    If Col B = desiredB, then Record names of B, then Calculate Column C. 
    If Col C = desired C, then Record names of C, Print 
    Value1:Value2:Value3. 
    If no solution found, goto START.

Any tips would be appreciated, thank you. Apologies for the code block abuse. It makes the formatting more consistent.




Randomize JavaScript Array of Objects Based on Certain Key

I have a JavaScript array similar to this:

arrTest = [
  {qId: 1, text:"test a", order: 1},
  {qID: 2, text:"test b", order: 2},
  {qID: 3, text:"test c", order: 3},
  {qID: 4, text:"test d", order: 4}
];

I would like to randomize just the order key so that all other keys remain the same and the original order of the array stays as is:

arrTest = [
  {qId: 1, text:"test a", order: 3},
  {qID: 2, text:"test b", order: 1},
  {qID: 3, text:"test c", order: 4},
  {qID: 4, text:"test d", order: 2}
];

I have found lots or randomize array discussions and functions, but can't seem to find one that targets a specific key and leaves everything else the same.

Any assistance is appreciated.

Thank you!




Generate random int in 3D array

l would like to generate a random 3d array containing random integers (coordinates) in the intervalle [0,100].

so, coordinates=dim(30,10,2)

What l have tried ?

coordinates = [[random.randint(0,100), random.randint(0,100)] for _i in range(30)]

which returns

array([[97, 68],
       [11, 23],
       [47, 99],
       [52, 58],
       [95, 60],
       [89, 29],
       [71, 47],
       [80, 52],
       [ 7, 83],
       [30, 87],
       [53, 96],
       [70, 33],
       [36, 12],
       [15, 52],
       [30, 76],
       [61, 52],
       [87, 99],
       [19, 74],
       [37, 63],
       [40,  2],
       [ 8, 84],
       [70, 32],
       [63,  8],
       [98, 89],
       [27, 12],
       [75, 59],
       [76, 17],
       [27, 12],
       [48, 61],
       [39, 98]])

of shape (30,10)

What l'm supposed to get ?

dim=(30,10,2) rather than (30,10)




formula to pick every pixel in a bitmap without repeating

I'm looking for an algorithm, I am programming in swift now but any reasonably similar "C family" syntax will do.

Imagine a large list of values, such as pixels in a bitmap. You want to pick each one, one at a time, and never pick the same one twice, and always end up picking them all.

I used it before in a Fractal generator so that it was not just rendering line by line, but built it up slowly in a stochastic way, but that was long ago, in a Java applet, and I no longer have the code.

I do not believe it used any pseudo-random number generator, and the main thing I liked about it is that it did not make the rendering time take longer than the just line by line approach. Any of the shuffling algorithms I looked at would make the rendering take longer with such a large number of values to deal with, unless I'm missing something.




What is the mechanism of random functions?

i need to know the mechanism of the random functions , and how the computer generate random numbers using specific lines of code ?

Note : any suggestion actually will help me thank you




XOR Encryption with "Padded Key"

I read that XOR encryption can be considered very safe as long as two conditions are fulfilled.
1. The length of the key is as long (or longer) than the data
2. The key is not following a notable pattern (i.e. it's a random jumble of characters)

In that case, how about this: Before the XOR operations you use the (short) key to generate a seed for a Random Number Generator. You then use this Generator to create characters which are added to the end of your key until it's as long as the data you want to encrypt.
Then you use this new key to XOR the data.

I have tested this and it does seem to have no problem working as intended (it can encrypt and decrypt without corruption of the data).
My question is how "secure" such an encryption would be. Anyone have an estimate of how hard it'd be to break/decrypt that data?




How do I implement my randomly generated word into a condition? - C

I am creating simple heads or tails game, however, I am trying to come up with a condition where if you insert "h" and the randomly generated answer is heads, the code prints that you get the answer correct. The randomly generated heads or tails is working fine, however, I do not know how to refer to the result of the flip, in the if condition at the end of my code.

Here's my code so far:

#include<stdio.h>
#include<unistd.h> //for sleep function
#include <stdlib.h> //for array
#include <time.h> //for random array

    //Array 
  int cool(void) {
    int i;
    int ht;

    i = 2;
    ht = 0;
    srand((unsigned)time(NULL));
    ht = rand() % i;
    return ht;
}

int main(int argc, char **argv)

And the second part

const char* o[2] = { 
     "Heads", "Tails"       //Where the words heads and tails are stored 
     };

//Coin Flip begins
    printf("\nType 'h' for heads & 't' for tails\n");
    printf("\nHeads or Tails? \n");
    scanf("%c", &a);
    //sleep(3);
    printf("%s\n",o[cool()]); //random heads or tails generated
    //sleep(3);


    if ( o == "Heads" && a == 'h' || o== "Heads" a == 'H' )
    {
        printf("\nCorrect!\n");

    }

    return 0;

}

Apologies if this has been asked before or I have asked incorrectly. I am new to coding and stack so feedback would be helpful




mardi 27 mars 2018

Java:Counting the times each number is rolled on a die

public class Die {
  public static void main(String[] args) {

    Random r = new Random();    

    int dieOne=0, dieTwo=0, dieThree=0, dieFour=0, dieFive=0, dieSix=0;

    Scanner input = new Scanner(System.in);

    System.out.println("How many times would you like the die to roll?: ");
        int numRoll = input.nextInt();  

    for (int i=0; i < numRoll; i++) {
        int rNum=r.nextInt(6)+1;

        if (rNum==1); {
            dieOne++;
        } 
        if (rNum==2); {
            dieTwo++;
        }
        if (rNum==3); {
            dieThree++;
        }
        if (rNum==4); {
            dieFour++;
        }
        if (rNum==5); {
            dieFive++;
        }
        if (rNum==6); {
            dieSix++;
        }
        System.out.println("Number:" + rNum);
    }

    System.out.println("'1' was rolled:" + dieOne + "times.");
    System.out.println("'2' was rolled:" + dieTwo + "times.");
    System.out.println("'3' was rolled:" + dieThree + "times.");
    System.out.println("'4' was rolled:" + dieFour + "times.");
    System.out.println("'5' was rolled:" + dieFive + "times.");
    System.out.println("'6' was rolled:" + dieSix + "times.");
    }
}

So if I run the program and enter 2. I'll get this:

Number:6
Number:3
'1' was rolled:2times.
'2' was rolled:2times.
'3' was rolled:2times.
'4' was rolled:2times.
'5' was rolled:2times.
'6' was rolled:2times.

But my desired output is this:

Number:6
Number:3
'1' was rolled:0times.
'2' was rolled:0times.
'3' was rolled:1times.
'4' was rolled:0times.
'5' was rolled:0times.
'6' was rolled:1times.

Using this same method what is solution to this problem?




Continuous random number generator adding numbers to max - PHP

I have a random number generator that spits out a number between 1 and 5. This thing does so every five minutes using a simple script "random.php".

<?php
header("Refresh:1");
$num = rand(1,5);

What I want to do is to have another script look at this one, retrieve the $num number and drop that to a $total, and keep doing to until that total reaches 20. Adding up the numbers is not an issue, the problem is to keep getting the new random numbers? What I want to do is along the lines of this but I cannot figure out how:

<?php
require("random.php");

$max = 20;
$now = 0;

while ($now <= $max){
    $new = [get new randon number somehow] 
    $now = $now + $new;
    echo "$now<br>";
}

I want to solve this in PHP if possible, not interested in JS or CURL solutions at the moment. I need to exhaust this in PHP.




Should I generate massive amounts of SQL data on the client or in SQL Server?

I am writing a program to generate a massive amount of data and populate tables in SQL Server. This is data that spans across multiple tables with potentially multiple foreign key constraints, as well as multiple 'enum' like tables, whose distribution of values need to be seemingly random as well and are referenced often from other tables. This leads to a lot of ORDER BY NEWID() type code, which seems slow to me.

My question is: which strategy would be more performant:

1) Generate and insert data in SQL Server, using set based operations and a bunch of ORDER BY NEWID() to get randomness

2) Generate all the data on a client (should make operations like choosing a random value from an enum table much faster), then import the data into SQL Server

I can see some positives and negatives from both strategies. Obviously the generation of random data would be easier and probably more performant in the client. However getting that data to the server would be slow. Otherwise, importing the data and inserting it in a set based operation should be similar in scale.

Has anyone done something similar?




is there any good books on gamedevelopment?

I Have been trying to get into game development, I would like it if I had a reference book to read from is there anything like that. I tried looking on the internet but all I found was articles are there really no books on this subject




Decrypt an tex file encrypted with rand()

Question I'm trying to solve

The approach I want to take is to bruteforce all possible keys (seeds) until I find the right one. I know the first characters in the tex file so these are what I'm testing against. When I find the right sequence, I would stop the program and output the key.

/* The ISO/IEC 9899:1990 edition of the C standard */

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

//#define RAND_MAX 32767
static unsigned long int next = 1;
int rand(void) // RAND_MAX assumed to be 32767
{
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
}
void srand(unsigned int seed)
{
    next = seed;
}

using namespace std;

//Return a byte at a time of the rand() keystream
 char randchar() { 
  static int key;
  static int i = 0;

  i = i % 4;
  if (i == 0) key = rand();
  return ((char *)(&key))[i++];
}

int main(int argc, const char* argv[]) {


  for (unsigned int i = time(NULL); i >= 0; i--) //Try all possible return values of time(NULL) since today
  {

      srand(i); 

      cout << "Trying with time(NULL) = " << i << endl;

      FILE *input, *output;
      input = fopen("Homework1b-Windows.tex.enc", "r");
      output = fopen("Homework1b.tex", "w");

      int c,rc, test;
      int pos;
      pos = 0;
      bool pos0, pos1, pos2, pos3, pos4, pos5;
      pos0 = pos1 = pos2 = pos3 = pos4 = pos5 = false;
      char temp1, temp2;

      while ((c = fgetc(input)) != EOF) {
        rc=randchar();
        fputc(c^rc,output);

        test = c^rc;

        temp1 = (char)test;


        temp2 = '\\';

        if ((pos == 0) && (temp1 == temp2))
        {
                 pos0 = true;
        } 

        temp2 = 'd';

        if ((pos == 1) && (temp1 == temp2))
        {
                 pos1 = true;
        }

        /*

        temp2 = 'o';

        if ((pos == 2) && (temp1 == temp2))
        {
                 pos2 = true;
        }

        temp2 = 'c';

        if ((pos == 3) && (temp1 == temp2))
        {
                 pos3 = true;
        }

        */

        temp2 = 'u';

        if ((pos == 4) && (temp1 == temp2))
        {
                 pos4 = true;
        }

        temp2 = 'm';
        if ((pos == 5) && (temp1 == temp2))
        {
                 pos5 = true;
        }

        pos++;

      }
      fclose(input);
      fclose(output);

      if (pos0 && pos1 && pos4 && pos5)
      {
         cout << endl << "Cracked. The seed is time(NULL) = " << i << endl;
         break;
      }
  }

  system("pause");


}

I know that the decrypted tex file starts with "\document".

The problem I'm facing is that the code never terminates. It never finds the right key (seed).

Any help?

Thank you.




RandomForest Classifier object in arguments

I'm currently working on a random forest classifier, using gridsearch to get the best parameters

So when I get my parameters they are in my var :

params = {'bootstrap': 'True', 'criterion': 'entropy', 'max_depth': 'None', 'max_features': '3', 'min_samples_leaf': '4', 'min_samples_split': '3'}

And I would like to do something like that :

clf = RandomForestClassifier(params)

But here params take the place of n_estimators so I have some errors like :

ValueError: n_estimators must be an integer, got <class 'dict'>.

Any idea on how I could do this ?

Thank you !




Generate new random number every 5 seconds PHP

I need to update a variable number $x with a new random value every 5 seconds (length not really important). I know how to do it with a finite loop, however if I want it to be continuous and always just update. I know how to do it with just updating the header, but since I dont want the entire page to reload that is not really an option. Below Ive tried to trick it with a infinite loop (not the best way), but what I am also seeing running this is that it gives me the same number over and over.

Any ideas?

    <?php

echo "Random Number Updating <br>";
$n = 5;
$x = rand(1,10);

function random() {
    $interval = 5; // Interval in seconds
    srand(floor(time() / $interval)); 
    $x = rand(0, 10); 
    echo "$x";
}

while ($x <= 6){
 random();   
}


?>




How to generate rectangle (plateformes) with random position

With a friend we are coding a Doodle Jump javafx but we have a problem we want to randomly generate rectangles (which will serve as platforms)in a specific area of the scene.

For now, we have created a menu with buttons and when we click on the first we arrive in a new window.

If you have tips we are takers!




lundi 26 mars 2018

Random but not repeating sampling between two dataframes

I have two dataframes:

DF1:

    UNIQUE_ID   City
k5WjB6MQa5Cru Skopje
k4Yq5QqXwoL4e Skopje
S9jGzT5qMZLyF Skopje
mhSHSuxic58Sf Skopje
MU7eys8NKXQog Skopje
GUBe1scNsXQog Bitola
S9jGzT5qMZLyF Kumanovo

DF2:

  ADDRESS                        City  
 РАТКО МИТРОВИЌ 5 БР.29-ДРАЧЕВО Skopje
 УЛ. МЕТОДИЈА ПАТЧЕВ БР.17А     Skopje
 УЛ ДРАЧЕВСКА 123               Skopje
 УЛ.ДОМАЗЕТОВСКА БР. 24         Skopje
 ДРАЧЕВО УЛ. ЈАНКО МИШИЌ БР. 3  Skopje
 УЛ. ПАРТИЗАНСКИ ПАТ 2 БР. 1    Skopje

I want to assign a random address for each unique ID in DF1. The assignment should fulfill two criteria:

  1. The address should not repeat until all unique addresses from DF2 are used up;
  2. The address should be pulled for the respective city.

So the desired output would look like:

New_DF

    UNIQUE_ID   City   ADRESS
k5WjB6MQa5Cru Skopje   РАТКО МИТРОВИЌ 5 БР.29-ДРАЧЕВО
k4Yq5QqXwoL4e Skopje   УЛ. МЕТОДИЈА ПАТЧЕВ БР.17А
S9jGzT5qMZLyF Skopje   УЛ ДРАЧЕВСКА 123
mhSHSuxic58Sf Skopje   УЛ.ДОМАЗЕТОВСКА БР. 24
MU7eys8NKXQog Skopje   ДРАЧЕВО УЛ. ЈАНКО МИШИЌ БР. 3
GUBe1scNsXQog Bitola   NA
S9jGzT5qMZLyF Kumanovo NA

Any ideas?




Random in java doesn't work right

enter image description here

I'm trying to generate random numbers for the x and y pos of the ball (to put it inside a rectangle), and the random doesn't seem to work right (with numbers, and with parameters)

public Ball createBall(int upper, int lower, int radius){
    Random rand = new Random();
    int temp = lower + radius;
    int temp2 = upper - radius;
    int x = rand.nextInt(600) + 450;
    int y = rand.nextInt(temp2) + temp;
    Ball ball = new Ball(new Point(x,y), radius, Color.BLACK);
    return ball;
}




List.remove(x) not in list? How to remove object from array once it has been selected?

I am trying to make a program to randomly assign each day 2 topics for a project. Can anyone help identify the error in this code/ explain how i'd go about doing this.

import random


x=0 
days_ahead = 30
sting_array = [ 'Respiration', 'Microbiology', 'Population size and ecosystems', 'Human Impact on the environment', 'Sexual Reproduction in humans', 'Sexual Reproduction in plants', 'Inheritance', 'Variation and evolution',
                'Application of reproduction and genetics', 'Homeostasis', 'nervous system', 'chemical elements and biological compounds', 'cell structure and organisation', 'cell membrane and transport', 'Enzymes', 'Nucleic Acids and Their functions'
                'The cell cycle and cel division', 'Classification and biodiversity', 'Adaptations for gas exchange', 'Adapt for trans animals', 'Adapt for trans plants', 'adapts for nutrition',         ]
lele = [ 'Rates of reaction', 'Equilibrium', 'Acids and Bases', 'Buffers and neutrilisation', 'Enthalpy and Entropy', 'Redox and Electrode Potentials', 'Transition Metals',
         'Periodicity', 'Enthalpy', 'Reactivity Trends', 'Reaction rates and equilibrium', 'Alkanes', 'Alkenes', 'Alcohols', 'Haloalkanes', 'Organic Synthesis', 'Aromatic Chemistry',
         'Carbonyls and Carboxylic Acids', 'Amine, aminio acid and proteins', 'Chromatography and Spectroscopy']


while x< 30:
    x+=1
    pee_pee = random.choice(sting_array)
    wee_wee= random.choice(sting_array)
    sting_array.remove(wee_wee)
    sting_array.remove(pee_pee)
    oui_oui = pee_pee + " and " + wee_wee
    print ("day " +str(x)+ " study " + (oui_oui))

if x==30:
    print ("Render complete, terminate")

I was going to copy the same code for sting_array for the lele- to clarify so that each day would be assigned 2 topics of biology and 2 of chemistry. However before I get that far list.remove(x) error appears! ANY methods on how to randomly select string items and then remove them from the list would be very helpful thnx.

ben.




Python quiz program. Could you help me identify where I've gone wrong? Thanks

This is a small quiz program that loops 5 times, every time it loops a different totally random question is asked. I keep getting an error that says (rand_quiz() ) function not defined, although I have defined it. I think I've done it wrongly. Could you help me correct it. Code is below.

import random
import operator

operators = {
            "+":operator.add,
            "-":operator.sub,
            "*":operator.mul,
            "/":operator.truediv,
            }

questions = 0
star = 0


def star_score():

    while questions <= 4:
        star = star + 1
        return star


    def check_ans():

        if que_ans == que:
            print("Correct! You earned yourself a star.")
            star_score()

        elif que_ans != que:
            print("Wrong! Better luck next time.")


        def rand_quiz():
            rand_num1 = random.randint(9, 999)
            rand_num2 = random.randint(9, 999)

            ops = random.choice(list(operators.keys()))

            que = int(operators[ops](rand_num1, rand_num2))

            print("What is",rand_num1, ops, rand_num2)
            que_ans = input(">>>")

            if que_ans.isdigit():
                check_ans()

            else:
                return("Error! Invalid input.")    


def quiz_loop():

    while questions <= 4:
        rand_quiz()


quiz_loop()




Serialize stochastic hashing function to be language-agnostic

I'm using the hashing function from here as part of a machine learning model. I need to use the trained model in C++, and thus I need the hashing function to be independent of the language (in this case Python/C++). How do I serialize a stochastic hashing function such that I can recreate the exact same hashing with same stochasticity in another language (C++)?




How can I generate a random assembly instructions?

I need a way to generate a random 16-bit assembly command in C (doesn't matter if hex or text I can just convert it)... but the thing is that I can't have any non-existent or illegal commands to execute, any way to do that?

Criteria:

  1. Totally random command
  2. Has to be an executable command
  3. Has to be a 16-bit command
  4. Has to be able to prodouce it in C

Plese help me.




Justification of constants used in random.sample

I'm looking into the source code for the function sample in random.py.

The idea is simple:

  • If a small sample (k) is needed from a large population (n): Just pick k random indices, since it is unlikely you'll pick the same number twice as the population is so large. And if you do, just pick the number again.
  • If a relatively large sample (k) is needed, compared to the total population (n): It is better to keep track of what you have picked.

My Question

There are a few constants involved, setsize = 21 and setsize += 4 ** _log(3*k,4). The critical ratio is roughly k : 21+3k. The comment says # size of a small set minus size of an empty list and # table size for big sets.

  • Where have these specific numbers come from? What is there justification?

The comments shed some light, however I find they bring as many questions as they answer.

  • I would kind of understand, size of a small set but find the "minus size of an empty list" confusing. Can someone shed any light on this?
  • what is meant specifically by "table" size, as apposed to say "set size".

Looking on the github repository, it looks like a very old version simply used the ratio k : 6*k, as the critical ratio, but I find that equally mysterious.

The code

def sample(self, population, k):
    """Chooses k unique random elements from a population sequence or set.

    Returns a new list containing elements from the population while
    leaving the original population unchanged.  The resulting list is
    in selection order so that all sub-slices will also be valid random
    samples.  This allows raffle winners (the sample) to be partitioned
    into grand prize and second place winners (the subslices).

    Members of the population need not be hashable or unique.  If the
    population contains repeats, then each occurrence is a possible
    selection in the sample.

    To choose a sample in a range of integers, use range as an argument.
    This is especially fast and space efficient for sampling from a
    large population:   sample(range(10000000), 60)
    """

    # Sampling without replacement entails tracking either potential
    # selections (the pool) in a list or previous selections in a set.

    # When the number of selections is small compared to the
    # population, then tracking selections is efficient, requiring
    # only a small set and an occasional reselection.  For
    # a larger number of selections, the pool tracking method is
    # preferred since the list takes less space than the
    # set and it doesn't suffer from frequent reselections.

    if isinstance(population, _Set):
        population = tuple(population)
    if not isinstance(population, _Sequence):
        raise TypeError("Population must be a sequence or set.  For dicts, use list(d).")
    randbelow = self._randbelow
    n = len(population)
    if not 0 <= k <= n:
        raise ValueError("Sample larger than population or is negative")
    result = [None] * k
    setsize = 21        # size of a small set minus size of an empty list
    if k > 5:
        setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
    if n <= setsize:
        # An n-length list is smaller than a k-length set
        pool = list(population)
        for i in range(k):         # invariant:  non-selected at [0,n-i)
            j = randbelow(n-i)
            result[i] = pool[j]
            pool[j] = pool[n-i-1]   # move non-selected item into vacancy
    else:
        selected = set()
        selected_add = selected.add
        for i in range(k):
            j = randbelow(n)
            while j in selected:
                j = randbelow(n)
            selected_add(j)
            result[i] = population[j]
    return result

(I apologise is this question would be better placed in math.stackexchange. I couldn't think of any probability/statistics-y reasons for this particular ratio, and the comments sounded as though, it was maybe something to do with the amount of space that sets and lists use - but could't find any details anywhere).




Create a simple java random number pick with in a certain range

I tried searching on here for something similar, but failed to find it, maybe using wrong keywords let me know, but here is the deal.

I am fairly new with java and wanted to make something useful myself. My idea was to create a random number picker within a range with. So let's say range is from 1-50, and I want 5 random number in this range, and they have to be all different. I have worked with Random before, but not sure what I am doing wrong, here is the code I have so far, please push me in the right direction if possible. I want to create an array or list with the number, or is there a better way to do this?

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

public class Randomizer {
    static Random rnd = new Random();
    static int rnd(int a, int b){
        return a+rnd.nextInt(b-a+1);
    }

    public static void nPicker(){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter start of range: ");
        int start = sc.nextInt();
        System.out.println("Enter end of range: ");
        int end = sc.nextInt();
        System.out.println("Enter amount of numbers to pick: ");
        int c = sc.nextInt();
        sc.close(); 
        rnd(start,end);
        int[] randomArrays = new int[c];

        for(int i = 0; i>randomArrays.length; i++){
            randomArrays.add();
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        nPicker();
    }

}

sorry if my code is messy.




python random customerID

everyone, I have an OrderID as shown below in the first column. In the second column, I need to assign Customer ID on random basis based on the following criteria:

Given same OrderID, the CustomerID should be same; CustomerID can repeat more than 1 times but be limited by 5 times since customer can buy more than once. For example, customer 123 has two OrderID: A01 and A03.

OrderID CustomerID
A01 123
A01 123
A02 145
A03 123
A02 145

the following is my try but did not meet my purpose.

np.random.seed(0)
df['CustomerID'] = np.random.randint(100, 999, len(df))




predictable pseudo-random list with multiprocessing

I have a script which uses multiprocessing to create a list of pseudo random numbers. A simplification of which looks like this:

import os, multiprocessing
import numpy as np    

def generate_random_number(i):
    np.random.seed()
    return np.random.uniform(0, 100)

pool = multiprocessing.Pool(os.cpu_count() - 1)
rand_list = pool.map(generate_random_number, range(10))
print(rand_list)

And the output looks like that:

[77.57457867285069, 72.53197844139046, 13.197630136723138, 64.9476430895216, 61.91057931216751, 43.436320344539446, 0.16208332066368625, 11.226294184830632, 20.325312826899765, 28.020558284894005]

In order to do regression testing, I want to be able to seed the randomness, in a fashion which will still give me pseudo random numbers, but the same numbers every time. I tried the following:

def generate_random_number(i):
    return np.random.uniform(0, 100)

    np.random.seed(123)
    pool = multiprocessing.Pool(os.cpu_count() - 1)
    rand_list = pool.map(generate_random_number, range(10))
    print(rand_list)

but then all workers start with the same seed, so I get:

[69.64691855978616, 69.64691855978616, 69.64691855978616, 69.64691855978616, 69.64691855978616, 69.64691855978616, 28.613933495037948, 28.613933495037948, 28.613933495037948, 28.613933495037948]

The same number is always repeated as many times as the pool has workers.

Is there a way for me to seed the randomness in such a way that will always give me the same list, but with a seemingly random list, regardless of the amount of workers?




Randomly changing numbers

this is my first post here. I come from an art background and am an extremely interesting in intersecting both art and programming. I am currently working on a project where I wish to alter numbers from a list by adding a +1 or -1 to that number to a few (lets say 500) randomly selected numbers out of thousands of numbers. I am familiar with the random number generator, however unsure what my next step to alter current numbers would be. Thanks.

These are a few of the numbers I wish to edit:

-0.588700 -0.394800 2.730300 -0.491500 -0.284200 2.716800 -0.629800 -0.231300 2.574700 -0.588700 -0.394800 2.730300 -0.629800 -0.231300 2.574700 -0.711400 -0.404200 2.647700 -0.491500 -0.284200 2.716800 -0.359600 -0.120500 2.692200 -0.513300 -0.040000 2.517700 -0.491500 -0.284200 2.716800 -0.513300 -0.040000 2.517700 -0.629800 -0.231300 2.574700 -0.359600 -0.120500 2.692200 -0.213300 0.069200 2.663800 -0.375400 0.168200 2.469000 -0.359600 -0.120500 2.692200 -0.375400 0.168200 2.469000 -0.513300 -0.040000 2.517700 -0.213300 0.069200 2.663800 -0.057400 0.270200 2.639300 -0.219000 0.379800 2.436900 -0.213300 0.069200 2.663800 -0.219000 0.379800 2.436900 -0.375400 0.168200 2.469000




Reproducibility of a ML project?

I am working on tensorflow, numpy for some NLP projects. I can't reproduce results though I have used tensorflow and numpy random seed.

I have 4 *.py file.

Then I do the following things blindly but it's also not working.

At the beginning of the each of the file I have added the following code,

import tensorflow as tf
tf.set_random_seed(1234)
import numpy as np
np.random.seed(1000)

Is there anyting I need to do more?

Note: I have also used Adversarial Learning for the project. [I'm not sure if this is relevant or not to this problem.]




Random in Java often generating same value

enter image description here

I'm using this to generate values between 5 to 13

 int randomGeneratedLevelValue = ThreadLocalRandom.current().nextInt(5, 13);

How to make same matches fewer?




Random Sampling from a dataset

I have financial data with values like: "Volume", "Profit/Loss", "Cost", etc

Now, it is safe to assume that every record in this data set is a "realization" or outcome of a single random variable, hence we may model this dataset as a set of iid random variables.

Now, I want to leverage this data set to model the underlying distribution of this random variable.

Can anyone point me in the right direction?




Performance of for-loop with high number of cases

I have 88.000 observations, coded with 1:

obs <- rep(1,88000)

In addition, I have the following function in which a random experiment is performed. A value p is compared with a random number; depending on the result, x changes (+ 1) or stays the same.

rexp <- function(x,p){
  if(runif(1) <= p) return(x + 1)
  return(x)
}

Beside "obs" and "rexp" an empty dataframe "dat" with 500 rows and 0 columns is given. There is also a placeholder "result":

dat <- data.frame(row.names = 1:500)
dat$result <- rep(',',500)

I use following loop to apply the function "rexp" (with p = 0.03) 500 times to the vector "obs" and save the number of changes of "obs" caused by the random experiment as "result" in the dataframe "dat":

for(i in 1:500){
  x <- sapply(obs,rexp,0.03)
  x <- table(x)
  x <- x[names(x) == 2]
  dat$result[i] <- x
}

Now to the problem: The for-Loop above basically works, but its performance is very bad. The execution takes very long and often the loop even gets stuck. In the example above, there are only 88.000 observations used, working with like 880.000 seems almost impossible. I'm not sure why the performance is so poor. For example, on my device the same procedure is possible in less than a minute in stata (even with 880.000 observations). I know that for-loops should be bypassed in r anyway, but I do not know how to perform the procedure otherwise. I would be grateful for any hint to explain and improve the performance of the described loop!




I am trying to make the code to make the next page randomized

I am a beginner on java. I need help on how to make the codes making the sequence of JPanels to be random. I have 10 Jpanels named as P1, P2, P3 to P10

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String ans = text.getText();

    if (ans.equals("Uruguay"))
    {
        JOptionPane.showMessageDialog(null, "Your Answer is Correct", "Congradulations!", JOptionPane.PLAIN_MESSAGE);
        scount++;
        text.setText(null);
        P1.setVisible(false);
        P2.setVisible(true);


    }
     else if (ans.contains(""))
    {
        rcount++;
        JOptionPane.showMessageDialog(null, "Sorry, your answer is incorrect", "Incorrect Answer", JOptionPane.ERROR_MESSAGE);
        text.setText(null);
        P1.setVisible(false);
        P2.setVisible(true);
    }  
        Gamescore();
}    




PHP Slot Machine for 3x5

There is a class for slot game in php(3x3)size and I need to make it 3x5.I have done some modifications but did not work .Can anybody tell me How can I make it 3x5.Thank you. https://www.phpclasses.org/package/9052-PHP-Emulate-a-slot-machine.html




Tests suits for PRNG

I am going to generate a Pseudo Random Number Generator for encryption perposes, each random number generates from previous one, but I have the following questions:
1-What the tests should I use to measure my PRNG quality (random)?
2-What's the tests measure the period of the generated PRNG?
I have the the three most popular NIST tests (frequency,block,runs), also I have (shannon entropy code) but I am not sure if they are suitable for PRNG?
Finally I am sorry if my questions are not in the proper place (stackoverflow)




Bootstrap network in R and igraph

I have an iGraph network object, and I've been searching for options to do bootstrapping on that network for statistics such as degree centrality, etc... I do know that I don't post any examples (as I don't have any specifics to present). This question is not specifically directed to one network, but to packages, or iGraph options to bootstrap any kind of network objects.

The main goal is to be able to validate by getting Confidence Intervals for A network's property such as closeness or centrality.




Python 3.x: I am getting repeated sequences on randint [duplicate]

This question already has an answer here:

This is the code:

from random import randint
import time, random


class Individual:  # Create a new class for the individual composed of:
    fitness = 0  # This measures how evolved is the Individual. The higher the better.
    geneLength = 4  # This is the length of the gene that will evolve and mutate over time.
    genes = []  # This will be the list of genes of the said individual

    def __init__(self):  # This operation creates a new instance of the class individual
        random.seed(time.time())
        print ("New:")
        for x in range(self.geneLength):  # In the beginning the genes will be random
            self.genes.append(randint(0,1))
            print(self.genes[x])

    def calcFitness(self):  # This operation calculates the fitness of the individual
        self.fitness = 0  # Put to 0 so last generation doesn't interfere
        for x in range(self.geneLength):  # The fitness is calculated as the number of 1s in the genes array
            if self.genes[x] == 1:
                self.fitness += 1
        return self.fitness

ind = Individual()
ind2 = Individual()

but the output is repeated instead of two different sequences




dimanche 25 mars 2018

printing random list with the possibility of repeating items in Python [duplicate]

This question already has an answer here:

If I have a list of 10 items like ["item1", "item2", "item3", ..., "item10"]

random.sample(range(10), 4)

would return a list of 4 unique items within the range.

Is there another "random" method that returns a random list with the possibility of repeating items?

Thanks :)




How do I assign parts of a text file to indexs of an array?

I have a question text file and answer text file, both have 100 lines. I'm very new to c++. I'm trying to assign an array index to each line so I generate random lines of the text file to display. I've tried researching this but was unable to figure it out. Any help would be appreciated. Thank you.




Understanding srand(time(0)) behaviour [duplicate]

Given below is my attempt to create a simple high-low game. I just don't understand why the code given below behaves differently when I place the srand(time(0)) inside the do-while loop, i.e, why does the modified code generate the same random number in each iteration of the loop?

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

int main(){
    int c;
    srand(time(0));
    do{
        int i, num;
        int min = 1;
        int max = 10;
        float fraction = 1.0 / (RAND_MAX+ 1); 
        num = min + (max-min + 1) * (rand() * fraction);
        for (int j=0;j<20;j++){
            std::cout<<"*";

        }
        std::cout<<"THE GUESSING GAME!";
        for (int j=0;j<20;j++){
            std::cout<<"*";

        }

        std::cout<<"\nRange of guess should be 1 to 10 inclusive\n ";
        std::cout<<"Guess a number: ";
        std::cin>>i;

        while(1){
            if (i==num){
                std::cout<<"Yeah! you guessed it right! "<<i<<" is the right number "<<std::endl;
                break;
            }else if (i<num){
                std::cout<<"Too low\n";
                std::cout<<"Guess another number: ";
                std::cin>>i;

            }else{
                std::cout<<"Too high\n";
                std::cout<<"Guess another number: ";
                std::cin>>i;

            }

        }

        std::cout<<"\nWanna play again? Press 1 to continue and 0 to exit: ";
        std::cin>>c;
    }while(c);
        return 0;
}




Generate a random int in Python without any limits

I'm looking for a function that would give me a random number without having to specify an upper limit. I've looking at the random function for Python, and I can't find one that seems to suit me. I suppose that I could set my upper limit to something ridiculously large, but I wanted to know if there was a way that I don't have to do that.




Python, math quiz. The questions being asked aren't accepting answers

I'm trying to write a small python program that asks random math question, but i'm stuck. The random questions being asked aren't accepting the answers even if the answer is correct. Plus it keeps repeating the question. Could you please review my code and let me know what i'm missing?

import random
import operator
import time

name = input("Type your name: ") #user name is stored inside name variable
print ("Hi",name,"This math quiz will test your basic math ability.") #Quick 
intro
print ("Please press 'Enter' after every input")
print (" ")

time.sleep(1)

operators = {
           '+': operator.add,
           '-': operator.sub,
           '*': operator.mul,
           '/': operator.truediv
           }

randNum1 = random.randint(9, 999)
randNum2 = random.randint(9, 999)

ops = random.choice(list(operators.keys()))

question = 0
star = 0

def ask_Question():

    que = randNum1, ops, randNum2
    print ("What is", randNum1, ops, randNum2)
    que_ans = int(input(">>>"))

    if que == que_ans:
        print ("Congrats! You earned your first star.")
        print (" ")

    elif que != que_ans:
        print ("Error! Better luck next time.")

def main():

    while question <= 4:
        ask_Question()

main()




Index was outside the bounds of the array when use random c#

I create a question pool from where I choose random question to apply some algorithm, anyway when I debug the program I get Index was outside the bounds of the array error.

to have a clear idea about what I am talking about, here is my class for question:

Firstly I define class Gene represent question

public class Gene
{
    public string question { get; set; }
    public string CLO { get; set; }
    public string type { get; set; }
    public string Answer { get; set; }
    public string mark { get; set; }
    public string chapter { get; set; }
    public Gene(string s, string t, string i, string a, string m, string c)
    {
        this.question = s;
        this.type = t;
        this.CLO = i;
        this.Answer = a;
        this.mark = m;
        this.chapter = c;

    }
}
List<Gene> QuestionList = new List<Gene>();

then I bring question from database

protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
    string sub = DropDownList5.Text;


    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Sondos\Downloads\For the project\suz\ExamGenerationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
    string s = "select * FROM QuestionBank WHERE (Cource_Code = '" + DropDownList5.SelectedItem.Text + "') ORDER BY RAND()";
        SqlCommand cmd = new SqlCommand(s, con);
        SqlDataReader dr;
        con.Open();
        dr = cmd.ExecuteReader();
        dr.Read();
        while (dr.Read())
        {
            string ques = dr["Question"].ToString();
            string questype = dr["Question_Type"].ToString();
            string quesCLO = dr["CLO"].ToString();
            string quesAnswer = dr["Answer"].ToString();
            string quesMark = dr["Mark"].ToString();
            string quesChapter = dr["Chapter"].ToString();
            QuestionList.Add(new Gene(ques, questype, quesCLO, quesAnswer, quesMark, quesChapter)); 
        }
}

then I make the question Pool

 Gene[] QuestionPool { get { return QuestionList.ToArray(); } }

and when I try to choose question randomly using this :

private System.Random randome;
     private Gene GetRandomQuestion()
            {
                int i = randome.Next(QuestionPool.Length);
                return QuestionPool[i];
            }

the error Index was outside the bounds of the array was in line

 return QuestionPool[i];




Generating random numbers based on a +/- input

I’d like to generate a random number in a given range based on an input of positive or negative. The positive input would pick a positive number between x and y (4 and 42 actually), the negative between -6 and -72. In other words, if input+ rand(4,42), if input- rand(-6,-72), I’m just not sure how to string it all together !!

Many thanks in advance !!!




Fails Decode Message from Image

i have a project to embed message to image with random pixel selected, when i select the pixel with squential method there is no problem, but when i make it random with PRNG, i got different message when i decode it, i think the position when i embed and decode is not different and there is no problem for PRNG code, but why i still got different byte of message, what's wrong with my code, here my embed code:

public byte[] encode_text(byte[] image, byte[] addition, int offset) {
    if (addition.length + offset > image.length) {
        throw new IllegalArgumentException("File tidak cukup di sisipi pesan!");
    }

    String pass= "apam";
    int[] posisi = keygen(pass.toCharArray(), image.length-32);

    for (int i = 0; i < addition.length; ++i) {
        int add = addition[i];
        for (int bit = 7; bit >= 0; --bit) {
            int b = (add >>> bit) & 1;
            image[posisi[i]] = (byte) ((image[posisi[i]+offset] & 0xFE) | b);

        }
    }

    return image;
}

and this is decode :

public byte[] decode_text(byte[] image) {

    int length = 0;
    int offset = 32;
    for (int i = 0; i < 32; ++i) {
        length = (length << 1) | (image[i] & 1);
    }

    byte[] result = new byte[length];

    String pass= "apam";
    int[] posisi = keygen(pass.toCharArray(), image.length-32);

    for (int b = 0; b < result.length; ++b) {
        for (int i = 0; i < 8; ++i) {
            result[b] = (byte) ((result[b] << 1) | (image[posisi[b]+offset] & 1));
        }
    }
    return result;
}




Firebase Firestone Random Document from Database

Here is my Firebase FireStone Database Structure:

MainPosts

-7YBc5LhUwU2wQB4ZybOl -

-IcInT5YEPKL2TVSAADP2

-tiUCi5IUuuCA2BT5Ldda

This is my Code:

firebaseFirestore.collection("MainPosts").addSnapshotListener(SingleVideoActivity.this, new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

            for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
                if (doc.getType() == DocumentChange.Type.ADDED) {
                    String blogPostId = doc.getDocument().getId();

                    BlogPost blogPost = doc.getDocument().toObject(BlogPost.class).withId(blogPostId);

                    blog_list.add(blogPost);
                    blogListRecyclerAdapter.notifyDataSetChanged();
                }
            }

        }
    });

What i want to do to get random document like from this three :-

-7YBc5LhUwU2wQB4ZybOl

-IcInT5YEPKL2TVSAADP2

-tiUCi5IUuuCA2BT5Ldda




How to get the value of a variable from java class to JUnit

I am testing the function of my calculator:

//Calculator.java (Pseudo)

parameter 1: int

parameter 2: int

parameter 3: a random number generator 0-3 (0:add, 1:subtract, 2:multiply, 3:divide)

sample: parameter1 (random parameter 3) parameter2

Now, I am having problems in assert because of the parameter 3 (random). Here is my sample code:

//TestCalculator.java
@Test
public void testCalculate() {
    Calculator test = new Calculator();
    int resultCalculate = test.calculate(2, 2);
    actual = //<how can i get the parameter 3 in here to compute the actual result>
    assertEquals(actual, resultCalculate);
}

I can't input a static value in assert, I need to get the value of random first. Help!




samedi 24 mars 2018

random string appeared at end of URL - Wordpress

I recently installed the Master Slider plugin.

I noticed shortly after that there was a random string appearing at the end of my URLs:

www.mysite.com/?v=79cba1185463 and www.mysite.com/products/?v=79cba1185463 ...

I decided to remove the plugin, clear the cache etc...

The random string is still showing a the end of my URLs

Does anyone know if Master Slider was in fact to blame. and how to remove this string?




in js, generating a powerball ticket, need no repeat numbers

Here is my code for generating a powerball ticket based off a set string of numbers that will be entered by the user in an app.

num1 = ""
num2 = ""
num3 = ""
num4 = ""
num5 = ""
num6 = ""

var numString = "1325102719740829201002101968241083020081601103414208523811"
function megaNum(numString){
    numType1 = [(Math.floor(Math.random() * 6 ))];
    if (numType1 == 0){
        do{
         num1 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (num1 == 0);
        num1 = "0" + num1

    }

    if (numType1 != 0){
        do{
            digit1 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (digit1 > 6 || digit1 == 0);
        digit2 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        num1 = digit1.concat(digit2)
    }
    numType2 = [(Math.floor(Math.random() * 6 ))];
    if (numType2 == 0){
        do{
         num2 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (num2 == 0);
        num2 = "0" + num2

    }

    if (numType2 != 0){
        do{
            digit3 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (digit3 > 6 || digit3 == 0);
        digit4 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        num2 = digit3.concat(digit4)
    }

    numType3 = [(Math.floor(Math.random() * 6 ))];
    if (numType3 == 0){
        do{
         num3 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (num3 == 0);
        num3 = "0" + num3

    }

    if (numType3 != 0){
        do{
            digit5 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (digit5 > 6 || digit5 == 0);
        digit6 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        num3 = digit5.concat(digit6)
    }
    numType4 = [(Math.floor(Math.random() * 6 ))];
    if (numType4 == 0){
        do{
         num4 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (num4 == 0);
        num4 = "0" + num4

    }

    if (numType4 != 0){
        do{
            digit7 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (digit7 > 6 || digit7 == 0);
        digit8 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        num4 = digit7.concat(digit8)
    }
    numType5 = [(Math.floor(Math.random() * 6 ))];
    if (numType5 == 0){
        do{
         num5 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (num5 == 0);
        num5 = "0" + num5

    }

    if (numType5 != 0){
        do{
            digit9 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (digit9 > 6 || digit9 == 0);
        digit10 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        num5 = digit9.concat(digit10)
    }
    numType6 = [(Math.floor(Math.random() * 6 ))];
    if (numType6 == 0){
        do{
         num6 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (num6 == 0);
        num6 = "0" + num6

    }

    if (numType6 != 0){
        do{
            digit11 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (digit11 > 2 || digit11 == 0);
        do{
        digit12 = numString.split('')[(Math.floor(Math.random() * numString.length ))];
        }
        while (digit12 > 6);
        num6 = digit11.concat(digit12)
    }
    return (num1 + "-" + num2 + "-" + num3 + "-" + num4 + "-" + num5 + "-" + num6)


}

My question is how do I set the condition that numbers 1 - 5 must be unique - can't repeat? I tried using a while loop but got stuck in an infinite loop. Ive tried a bunch of different ways but can't get it to come out right. I know I need an if statement of some kind but not sure of the syntax that would work to make sure the first five numbers were unique.




Randomized Selection Quicksort

I made the randomized selection for quick sort algorithm in C++, and when I use the function in the main it does not do the right sorting. Can someone tell me where I coded wrong please?

I really cannot figure out by myself and I've tried for hours..

Here is my code :

int partition(int a[], int left, int right) {
int pivot = a[right]; int aux;
int i = left - 1;
for (int j = left; j <= right - 1; j++) {
    if (a[j] < pivot) {
        i++;
        aux = a[i];
        a[i] = a[j];
        a[j] = aux;
    }
}
aux = a[i+1];
a[i+1] = a[right];
a[right] = aux;
return (i+1);

}

  int randomized_partition(int a[], int left, int right) {
int aux;
srand(time(NULL));
int i = rand() % right; //(right+1) + left
aux = a[right];
a[right] = a[i];
a[i] = aux;
return partition(a, left, right);

}

 void randomized_quicksort(int a[], int left, int right) {
if (left < right) {
    int pivot = randomized_partition(a, left, right);
    randomized_quicksort(a, left, pivot - 1);
    randomized_quicksort(a, pivot + 1, right);
}

}

int randomized_select(int a[], int left, int right, int i) {
int pivot, k;

if (left == right)
    return a[left];
pivot = randomized_partition(a, left, right);
k = pivot - left + 1;
if (i == k)
    return a[pivot];
else if (i < k)
    return randomized_select(a, left, pivot-1, i);
else if (i > k)
    return randomized_select(a, pivot + 1, right , i - k);

}




Need to generate a unique 5 digit number from 00001 to 99999 in C++

We will modify part of the existing menu logic to generate an ID for the user. This user ID will be of the type int, and will be 5 digits in length. The values are 00001 – 99999, and should appear with all 5 digits (leading zeroes) on the display upon generating them. Do not change the data type from that of an int. Check out the setfill manipulator as a possible helper for this. Setfill allows you to set a fill character to a value using an input parameter, such as ‘0’ for leading zeroes. Researching it, you’ll see that you will need to reset the fill character after use too, or you will be printing a lot of zeroes on the display! Your program also should guarantee an absolutely unique user ID has been generated for each new activity that is added. Think about how this works...

Currently I've been trying to get the following code to work

srand(time(0));
cout << setfill('0') << setw(5) << rand() %99999 << endl;

Problem is that this doesn't seem random at all (it's just slowly counting up based on the computers internal clock right?) and the first digit is always zero. Like the instructions say it should be between 00001 and 99999.




Flask Python and css variable

I currently trying to build an online random color generator with python and flask. I have created my function which generate a random hex color code and I struggle to pass it into the css background color.

def random_color():
def r():
    return random.randint(0, 255)
return ('#%02X%02X%02X' % (r(), r(), r()))

BR

Edouard




trying pull generate a random number with conditions; get caught in infinite loop

I am trying to draw a random number where if it is a single digit number, the number appears with a "0" in front like 09, and if it is a double digit number, the first digit can't be higher than 6. For some reason I'm getting stuck in an infinite loop.

var numString = "737328293048463535555282930405857826161711829203049848347362626171192190203948576767574738383920201101010929383484757576765646454535354343434444444444444444444444444444444444444736262796345690602935069823598326590862350968235896235098632596346509"
ranNum = numString.split('')[(Math.floor(Math.random() * numString.length ))];

function megaNum(numString){
    var numType = Math.floor(Math.random() * 6)
    // one out of seven chance to be a single digit number
    if (numType == 0){
        // if single digit number
        do{
        num1 = ranNum
        }
        while(ranNum == 0);
        // keep drawing numbers till ranNum is not 0
        num1 = "0" + num1
        // inserts a "0" in front of ranNum
    }


    if (numType > 0){
        // if double digit number
        firstDigit = ""
        secondDigit = ""
        do{
            firstDigit = ranNum
        }
        while(ranNum >= 7);
        // first digit must be 6 or less

        secondDigit = ranNum
        num1 = firstDigit.concat(secondDigit)

    }
    return (num1)
}




Function with random experiment related to value pairs

I have two vectors x1 and p:

x1 <- c(1,2,3,1,2,3)
p <- c(0.1,0.9,0.9,0.1,0.5,0.7)

Both vectors form pairs of values, see df1:

df1 <- data.frame(x1,p)
> df1
  x1   p
1  1 0.1
2  2 0.9
3  3 0.9
4  1 0.1
5  2 0.5
6  3 0.7

Following function is used to update vector df1$x1 to a vector df1$x2, depending on a random experiment and a probability p:

rexp <- function(x,p){
  if(runif(1) <= p) return(x + 1)
  return(x)
}

Using lapply, the function "rexp" is applied to every df1$x1 value. Depending on the random experiment, the value for x2 remains equal x1 or increases by + 1. In the follwing example, p equals 0.5:

set.seed(123)
df1$x2 <- unlist(lapply(df1$x1,rexp,0.5))

> df1
  x1   p x2
1  1 0.1  2
2  2 0.9  2
3  3 0.9  4
4  1 0.1  1
5  2 0.5  2
6  3 0.7  4

Now to my problem: I want the argument "p" in "rexp" to refer to the vector df1$p. For example, p for df1$x1[1] should be 0.1 (as can be seen in df1$p[1]): unlist(lapply(df1$x1[1],rexp,df1$p[1])). p for df1$x1[5] should be df1$p[5], which is 0.5: unlist(lapply(df1$x1[5],rexp,df1$p[5]))

Desired output should be something like:

> unlist(lapply(df1$x1,rexp,df1$p))
[1] 1 3 4 1 2 4
#where 1 refers to rexp(df1$x1[1],df1$p[1]),
#3 refers to rexp(df1$x1[2],df1$p[2]),
#4 refers to rexp(df1$x1[3],df1$p[3]) and so on... 

Doing that "manually" leads to:

set.seed(123)
> unlist(lapply(df1$x1[1],rexp,df1$p[1]))
[1] 1
> unlist(lapply(df1$x1[2],rexp,df1$p[2]))
[1] 3
> unlist(lapply(df1$x1[3],rexp,df1$p[3]))
[1] 4
> unlist(lapply(df1$x1[4],rexp,df1$p[4]))
[1] 1
> unlist(lapply(df1$x1[5],rexp,df1$p[5]))
[1] 2
> unlist(lapply(df1$x1[6],rexp,df1$p[6]))
[1] 4

How can "rexp" be adjusted so that the function uses the specific df1$p-value for each df1$x1-value? Note: At this point, using "lapply" is important, because for every df1$x1-value in the function "rexp" a new random number should be drawn. I am happy about any help!




How to make it not to repeat WORDS? [duplicate]

This question already has an answer here:

I have an application where words are randomly selected, but at least once, two words are repeated. How should I not do it again?

My code:

https://docs.google.com/document/d/1smXzY4vKsCvZnIXwOveLDzg0A1_-mvxr_Ykia9J__Hw/edit?usp=sharing

If you ask why the code is not in the problem, but in the online document, because it can not be inserted there.




Single Java Random number trying to get the fixed range

I'm trying to generate a random number generator that has a fixed 1-100 range being int min = 1 and int max = 100. I managed to get this code so far. Using BlueJ as the environment.

import java.util.Random; 

public class RandomNumber { 
    public static int getRandomNumberInts(int min, int max) { 
        Random random = new Random(); 
        return random.ints(min,(max+1)).findFirst().getAsInt(); 
    }
} 

Is there any other way I can get a fixed number within my range without the need to enter the range myself?




vendredi 23 mars 2018

KeyListener with switch on loop for coin toss game in Java

I'm having a problem with a coin toss simulation. I've been working with java for just a few hours so bear with me. What I want the program to do is show the title once, give the menu (press T....) run the random simulation and loop back to the menu unless player presses Q. Everything worked as I was testing every addition individually. The random generator, the printing but as you can probably tell, I have no idea how to implement a KeyListener. How do I make make it work?

import java.util.Random;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class CoinToss
{

    public void menu implements KeyListener
    {
        addKeyListener(this);
        System.out.println("*******************************************************");
        System.out.println("**********************WELCOME**************************");
        System.out.println("*******************TO COIN TOSS************************");
        System.out.println("*******************************************************");
    }
    @Override
    public void keyPressed(KeyEvent e) 
    {
        boolean gameOn = true;
        while (gameOn == true)
        {
            Random rand = new Random();
            System.out.println("PRESS T TO TOSS A COIN \nPRESS Q TO QUIT");
            switch(e.getKeyCode())
            {
                case KeyEvent.VK_T:
                int n = rand.nextInt(2);
                if(n == 0)
                {
                    System.out.println("HEADS");
                }
                if(n == 1)
                {
                    System.out.println("TAILS");
                }
                if(n == 2)
                {
                    gameOn = true;
                }
                break;
                case KeyEvent.VK_Q:
                System.out.println("GOOD BYE! \nSEE YOU NEXT TIME!");
                gameOn = false;
                break;
            }    
        }
    }
    @Override
        public void keyReleased(KeyEvent e) 
        {

        }
     @Override
        public void keyTyped(KeyEvent e) 
        {

        }

}




Efficient list building in Python

Being a long-time Matlab user, I am accustomed to getting a caution whenever I build a list/array/anything with multiple elements in a loop such that it changes size every time, because that slows things down.

As I teach myself Python 2.7, I'm wondering if such a rule applies here to strings. I know exactly how long I want my string to be, and I have a specific list of the characters I want to build it from, but otherwise I want it to be random. My favorite code I've written so far is:

freq = 0.8
seq = '0'*length
for ii in range(length):
    num = np.random.rand(1)
    if num < freq:
        cha = '1'
        seq = seq[:ii] + cha + seq[ii+1:]

I already tried seq[ii] = '1', but, to put it in IPython's words, TypeError: 'str' object does not support item assignment.

So, am I doing this the most Pythonic way, or is there some sleight of hand that I haven't seen yet - maybe a random string or list generator to which I can directly give a list of characters I want it to randomly choose between, the probability I want each possibility to have, and how long I want this string or list to be?

(I've seen other questions about random strings, but while they do address how to make it the right length, they are generally trying to generate passwords, with all ASCII characters being equally likely. That's not what I want.)