vendredi 31 juillet 2015

how does the Random() deals with those milliseconds when in reality they are out of range to the function???

Okay, i understand that the Random() in Java gets its seed from the system date and time by default in milliseconds. having said that, if im not mistaking, a seed in milliseconds it looks like the fallowing: 967884300000. That is 09/23/2000 9:45:00. i keep getting out of range when i do Random dice = New Random(967884300000); i understand it is out of range but thats an actual seed at some point when using the system time. Is there something i am missing? how does the Random() deals with those milliseconds when in reality they are out of range to the function??? please help




Change randomly indexed vowel in a string:bound must be positive

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;


 public class MachinePedagogy {


     public static void main(String[] args) throws IOException {
         changeVowel("dictionary.txt");

}
private static void changeVowel(String path) throws IOException {
    char ch;

    BufferedWriter bWriter = new BufferedWriter(new FileWriter(new File("changevowel.txt")));
    String aeiou = "aeiou";
    char[] vowels = aeiou.toCharArray();
    BufferedReader bReader = new BufferedReader(new FileReader(new File(path)));
    for(String temp = bReader.readLine(); temp != null; temp = bReader.readLine()){
        int counter = 0;
        char[] characters = temp.toCharArray();
            for(int i = 0; i < temp.length(); i++){

                ch = temp.charAt(i);


                if(
                ch == 'a' || 
                ch == 'e' || 
                ch == 'i' || 
                ch == 'o' || 
                ch == 'u'){
                    counter++;
                    }
                }
            Random rand = new Random();
            int vIndex[] = new int[counter];
            int index = 0;  
            for (int j = 0; j <temp.length(); j++){
                ch = temp.charAt(j);
                if(
                        ch == 'a' || 
                        ch == 'e' || 
                        ch == 'i' || 
                        ch == 'o' || 
                        ch == 'u'){
                    vIndex[index] = j;
                    index++;
                }
            }
            int random2 = (rand.nextInt(vIndex.length));
            int random1 = (rand.nextInt(vowels.length));
            characters[vIndex[random2]] = vowels[random1];
            temp = String.valueOf(characters);
        bWriter.write(temp + "\n");
    }
    bReader.close();
    bWriter.close();
     }
 }

I want to edit a random vowel in a string and change it to another random vowel, preferably different from what it was previously. Dictionary.txt is just a Stanford dictionary if you need that to compile the code.

Many examples I have found in replacing vowels follow this logic.

temp.replaceAll( "[aeiou]", "?" );

I don't want to replace all the vowels, just a single randomly indexed vowel. I think it might have something to do with nextInt() but I am confused when I read the documentation Random#nextInt(int) as to why that might be. What I have read from other StackOverflow questions asked is that this is a valid way of producing random indexes for an array.

I wrote a spell checker and want to test its capabilities for accuracy with a commonly made error of changing a single vowel of a word. I plan on removing correct words from the big list that I've created by running the changevowel.txt against dictionary.txt later & removing correct words from changevowel.txt but that is unimportant to the immediate problem at hand.




how to randomize my image view?

i want every time when i hit the button next a random image different of the current

this is the code that i use but sometime the image didn't update:

    @IBAction func nextBarButton(sender: UIBarButtonItem) {


    var image1 = UIImage(named: "RedBalloon1.jpg")
    var image2 = UIImage(named: "RedBalloon2.jpg")
    var image3 = UIImage(named: "RedBalloon3.jpg")
    var image4 = UIImage(named: "RedBalloon4.jpg")

    var images = [image1, image2, image3, image4]
    var indexPath = Int(arc4random_uniform(UInt32(images.count)))
    currentIndex = indexPath
    if currentIndex == indexPath {
        indexPath = Int(arc4random_uniform(UInt32(images.count)))
    }

    self.imageView.image = images[indexPath]
    self.balloonLabel.text = "\(count++) Balloon"


}




Random number generator using Joblib

I need to generate random number in a function which is paralleled using Joblib. However, the random number generated from the cores are exactly the same.

Currently I solved the problem by assigning random seeds for different cores. Is there any simple way to solve this problem?




jeudi 30 juillet 2015

Inserting a unique random alphanumeric number in mysql

I want to generate a unique random alphanumeric number in mysql so that every entry in the database is retrieved by that number and moreover it wont be a sequence which the client can recognise. Please let me know how can I generate such a number.




Random number generator of any length

How to generate any random number of any width in C?? Like, to generate a number of width 3 it should be between 100 to 999. So how to code this?




Random image from directory with no repeats?

I am successfully able to get random images from my 'uploads' directory with my code but the issue is that it has multiple images repeat. I will reload the page and the same image will show 2 - 15 times without changing. I thought about setting a cookie for the previous image but the execution of how to do this is frying my brain. I'll post what I have here, any help would be great.

$files = glob($dir . '/*.*');
$file = array_rand($files);
$filename = $files[$file];
$search = array_search($_COOKIE['prev'], $files);

if ($_COOKIE['prev'] == $filename) {
    unset($files[$search]);
    $filename = $files[$file];
    setcookie('prev', $filename);
}




Random Number Issue C#

I am learning to use C# at the moment, and am just making random things I think of, so basically this is a "credit card generator" which obviously doesn't make real card numbers, just a random 16 digit number, with the CVV and Exp date.

So far, I can get it to print the Exp date, but as for the credit card number, I am getting an error which says -

"Cannot convert from long to int" and also a message stating the best overloaded method.

I am also having some problems with the date function, I can get it to generate 6 numbers ok, eg, day and year, but if i try to add another 2 numbers, it spits out 6 still.

Here is my code, sorry if this makes no sense, like I said, I am new to this :)

Thanks in advance for any help.

private void button1_Click(object sender, EventArgs e)
    {


        Random rnd = new Random();
        double cardNumber = rnd.Next(4572000000000000, 4999999999999999);
        int cvv = rnd.Next(001, 999);
        int expDay = rnd.Next(1, 30);
        int expMonth = rnd.Next(1, 12);
        int expYear = rnd.Next(2011, 2015);

        textBox1.Text = cardNumber.ToString();
        textBox2.Text = cvv.ToString();
        textBox3.Text = expDay.ToString() + expMonth.ToString() + expYear.ToString();

    }

I will say this again just to make this clear, this in no way makes real credit card numbers, they are just randomly generated digits.....




How can I append random numbers and display then on imagebuttons?

I'm trying to do the following but i am stuck and need help.

Currently what i want is,

  1. To be able to hide Random Numbers in my circle ImageButton
  2. To be able to display them once clicked.

I am generating random prime numbers to which i have. Code is here.

    public class hidden {
    int pRandom;

    private int generateNumber(int max) {
        Random rand = new Random();
        return rand.nextInt(max);
    }
}

Now i want to be able to append the random numbers hidden in my imagebutton and once clicked the random numbers apper:

My main activity.

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageButton ib = (ImageButton) findViewById(R.id.imageButton1);
        ib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hidden.setVisibility(View.Visible);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

I have tried this but it is not working. Any help will be appreciated.

my Xml

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:background="#fffaf4f0">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />

    <ImageButton

        android:id="@+id/imageButton1"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:background="@drawable/circle"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="128dp" />

</RelativeLayout>




Fill up fields with random names with iMacro

I currently use iMacro for Firefox for quick form filling with random letters.

SET !VAR1 EVAL("var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z']; var string = ''; for(var i = 0; i < 11; i++){string += letters[parseInt(Math.random() * 25)]}; string")
EVENT TYPE=CLICK SELECTOR="#namex" BUTTON=0
EVENTS TYPE=KEYPRESS SELECTOR="#namex" CHARS="{{!var1}}"

Result is e.g. adionudmeai.

I have a text file that containing one hundred thousand names in this format.

johny.hunter
tim.davies
emil.bernadette

I want to use this names instead of the random combinations with two additional random numbers at the end.

The end result should look like bill.cayne32.




SpriteKit update, how to best call random functions?

I have three functions within my SpriteKit update loop that I want to call at 3 different random intervals, what I am currently doing is generating random numbers each time round the update loop and checking them to see when each function should be called:

let randomCheer = GKRandomSource.sharedRandom().nextIntWithUpperBound(100)
if randomCheer == 99 { print(“CALL: Cheering … Quite a bit”) }

let randomClap = GKRandomSource.sharedRandom().nextIntWithUpperBound(500)
if randomClap == 99 { print(“CALL: Clapping … Not so often”) }

let randomWave = GKRandomSource.sharedRandom().nextIntWithUpperBound(1000)
if randomWave == 99 { print(“CALL: Waving … Very rarely”) }

I could also do something like this and use only one random number.

let randomInt = GKRandomSource.sharedRandom().nextIntWithUpperBound(100)
switch randomInt {
case 0...9:
    print("Often")
case 10...12:
    print("Sometimes")
case 13:
    print("Almost Never")
default:
    continue
}

Is there a better way of doing this that I am maybe missing?




Fill bins according to probability distribution in numpy

I have a integer that needs to be split up in to bins according to a probability distribution. For example, if I had N=100 objects going into [0.02, 0.08, 0.16, 0.29, 0.45] then you might get [1, 10, 20, 25, 44].

import numpy as np
# sample distribution
d = np.array([x ** 2 for x in range(1,6)], dtype=float)
d = d / d.sum()
dcs = d.cumsum()
bins = np.zeros(d.shape)
N = 100
for roll in np.random.rand(N):
    # grab the first index that the roll satisfies
    i = np.where(roll < dcs)[0][0]  
    bins[i] += 1

In reality, N and my number of bins are very large, so looping isn't really a viable option. Is there any way I can vectorize this operation to speed it up?




How to assign value of Guid and stop random with condition

I have variables mifarecard.ID generate values with Guid type.

When people in parking lot of supermarket, I swipe card give them and it will auto generate ID for mifare card. They will hold this card and give back to me, I will swipe card and authentication. It's simple.

My struct program is:

private void startThread()
{
     while(mifarecard.Connect())   //Application connect to Mifare reader.
     {
          if(mifarecard.BindCard(true))    //When swipe card
          {
               mifarecard.ID = System.Guid.NewGuid().ToString("N");   //Create random ID.
               // ???
          }
      }
}

But my problem appear in function. When swipe card, ID auto generate new 32 character.

I want it save ID until they give back and I can check it. If ID match, authentication success.

But when swipe card, it auto generate, when they give back, I swipe card and it generate new ID. I can't compare two ID.

Why I'm must generate random ID? Because I want 1 card have 1 ID. And when they give back card to me, I use this card to swipe new people go in supermarket, it will random new ID. Thank you!!!




How to create a random video player with javascript

I have a probleme, my probleme is "I create a video player with javascript and the video play automatically" but i want to play video with a random value but I don't know how i can do this with javascript (I use javascript css and html5 only)

Thank you :)




Is there any guarantee that the algorithm behind java.util.Collections.shuffle() remains unchanged in future Java releases?

Is the following programm guaranteed to produce a list with the same contents and ordering in future java releases?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class Test {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
    Collections.shuffle(list, new Random(42));
  }
}

The javadoc of the java.util.Random class guarantees that it will always return the same random numbers if intialized with the same seed in all future java releases.

But are there any guarantees regarding the algorithm behind the java.util.Collections.shuffle() utility function? The Javadoc for this utility function does not say anything about this.

I need this guarantee, because I want to be sure that persisted data will not be useless with any future java release.




mercredi 29 juillet 2015

Boost Geometry RTree poor query performance under MSVS 2013/2015

I am trying to run the following piece of code in Visual C++ 2013 and 2015. But the performance for query is no good. It takes about 3,000 seconds to finish 1 million searches. I compile the same piece of code in Clang under OS X 10.10 and g++ on under ubuntu 15.04. The query part only takes less than 0.3 second under os x or linux. The difference is about 10,000 times. Something is not right. Any idea is greatly appreciated!

The compiler options I used for VS is as follows:

/Yu"stdafx.h" /GS /GL /analyze- /W3 /Gy /Zc:wchar_t /Zi /Gm- /O2 /sdl /Fd"Release\vc140.pdb" /Zc:inline /fp:precise /D "_NO_DEBUG_HEAP=1" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /Gd /Oy- /Oi /MD /Fa"Release\" /EHsc /nologo /Fo"Release\" /Fp"Release\ConsoleApplication1.pch" 

Below is the code:

// TestSpatialIndex.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/algorithms/distance.hpp>

#include <chrono>
#include <ctime>
#include <tuple>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>

namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;

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

    using Point = bg::model::d2::point_xy<double>;
    using Box = bg::model::box<Point>;
    using Value = std::pair<Point, int>;
    using RTree = bgi::rtree<Value, bgi::rstar<8>>;

    std::vector<Value> vv;
    std::vector<Box> vb;

    for (size_t i = 0; i < 1000000; ++i) {
        auto x = (rand() % 360000000) / 1000000.0 - 180;
        auto y = (rand() % 180000000) / 1000000.0 - 90;
        vv.push_back(std::make_pair(Point(x, y), i));
    }

    for (size_t i = 0; i < 1000000; ++i) {
        auto x = (rand() % 360000000) / 1000000.0 - 180;
        auto y = (rand() % 180000000) / 1000000.0 - 90;
        vb.push_back(Box(Point(x, y), Point(x + 0.005, y + 0.005)));
    }
    std::chrono::duration<double> elapsed_seconds;
    std::chrono::time_point<std::chrono::system_clock> start, end;
    start = std::chrono::system_clock::now();

    RTree rt2(vv.begin(), vv.end());

    end = std::chrono::system_clock::now();

    elapsed_seconds = end - start;

    std::cout << "finished rt2 computation in "
        << "elapsed time: " << elapsed_seconds.count() << "s\n";

    start = std::chrono::system_clock::now();
    for (auto &it : vb) {
        std::vector<Value> v_res;
        rt2.query(bgi::intersects(it), std::back_inserter(v_res));
    }
    end = std::chrono::system_clock::now();
    elapsed_seconds = end - start;

    std::cout << "finished rt2 query in "
        << "elapsed time: " << elapsed_seconds.count() << "s\n";

    return 0;
}

Update: I found statements like auto x = (rand() % 360000000) / 1000000.0 - 180; are the culprits. The original purpose was to return latitude and longitude coordinates with 6 decimal places. But RAND_MAX in MSVC is 32767, so (rand() % 360000000) / 1000000.0 is equivalent to rand()/1000000.0 which returns a value ranging from 1e-6 to 0.032767. Therefore a 0.005x0.005 region encloses a lot of points. On the other hand in clang and gcc RAND_MAX is 2147483647, which is the largest signed integer representable in 32 bits. The above code will generate uniformly distributed latitude and longitude pairs under clang and gcc. Hence the number of points returned from a intersection query in MSVC is way much more than that from clang or gcc. And that's why it is 10k times slower in MSVC. In VC, I changed (rand() % 360000000) / 1000000.0 to (rand() % 36000) / 100.0 and (rand() % 180000000) / 1000000.0 to (rand() % 18000) / 100.0, the performance is now comparable.




How to use random variable to choose correct button in swift

The title might not be the best explanation of what I want but I couldn't think of a better way to describe it.

@IBOutlet var button0: UIButton!
@IBOutlet var button1: UIButton!
@IBOutlet var button2: UIButton!

var num = (arc4random()%3);

basically I want to use the variable 'num' to choose which button and make it hidden based off the random number. Is there a way to use the variable in a a simple line like "button(num).hidden = true" or something like that?




What does rand() do in C?

What does rand() do in C? I don't use C++, just C. Visual Studio 2012 tells me that its return type is int __cdecl And it is part of stdlib.h It does not take any parameters. What does this do? Your answers are greatly appreciated




NullPointerException when trying to print random values in android studio

I keep getting a null pointer exception at lines 99 and 77, which is where I attempt to print the random values created by the random class (line 99), and where I call my setQuestion method (line 77. randomNum to the layout_game xml file. I'm not sure why I am getting a null value because when i log the values to the console it says that values are being generated.

package com.grantsolutions.mathgamechapter1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;


public class GameActivity extends Activity implements OnClickListener {
int correctAnswer;
Button buttonObjectChoice1;
Button buttonObjectChoice2;
Button buttonObjectChoice3;
TextView textObjectPartA //it says that textObjectPartA and B are never used;
TextView textObjectPartB;
TextView textObjectScore;
TextView textObjectLevel;
int currentScore;
int currentLevel = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_game);






    //declaring variables for game

    //no longer being declared

    /*int partA = 2;
    int partB = 2;
    correctAnswer = partA * partB;
    int wrongAnswer1 = correctAnswer - 1;
    int wrongAnswer2 = correctAnswer + 1;
    /*this is where we link the variables
    from  the java code to the button UI in
     activity_game xml itself
     */
    TextView textObjectPartA = (TextView) findViewById(R.id.holdTextA);

    TextView textObjectPartB = (TextView) findViewById(R.id.holdTextB);
    textObjectScore = (TextView) findViewById(R.id.textLevel);
    textObjectLevel = (TextView) findViewById(R.id.textScore);

    buttonObjectChoice1 =
            (Button) findViewById(R.id.choice1);

    buttonObjectChoice2 =
            (Button) findViewById(R.id.choice2);

    buttonObjectChoice3 =
            (Button) findViewById(R.id.choice3);
    /*Use the setText method of the class on our objects
    to show our variable values on the UI elements.
    Similar to outputting to the console in the exercise,
    only using the setText method*/


    //telling the console to listen for button clicks from the user
    buttonObjectChoice1.setOnClickListener(this);
    buttonObjectChoice2.setOnClickListener(this);
    buttonObjectChoice3.setOnClickListener(this);
    setQuestion();



}


void setQuestion() {
    Random randomNum;
    randomNum = new Random();

    int partA = 0;
    int numberRange = currentLevel * 3;
    partA = randomNum.nextInt(numberRange) + 1;
     //removes possibility of a zero value
    int partB = randomNum.nextInt(numberRange) + 1;

    correctAnswer = partA * partB;
    Log.i("info", ""+partA);
    Log.i("info", ""+partB);
    Log.d("info", ""+partA);
    int wrongAnswer1 = correctAnswer - 2;
    int wrongAnswer2 = correctAnswer + 2;
    Log.i("info", ""+partA);
    Log.i("info", ""+partB);
    textObjectPartA.setText(""+partA); //error here
    textObjectPartB.setText(""+partB);
    //case for setting multiple choice buttons
    int buttonLayout = randomNum.nextInt(3);
    switch (buttonLayout) {
        case 0:
            buttonObjectChoice1.setText("" + correctAnswer);
            buttonObjectChoice2.setText("" + wrongAnswer1);
            buttonObjectChoice3.setText("" + wrongAnswer2);
            break;
        case 1:
            buttonObjectChoice2.setText("" + correctAnswer);
            buttonObjectChoice1.setText("" + wrongAnswer1);
            buttonObjectChoice3.setText("" + wrongAnswer2);
            break;
        case 2:
            buttonObjectChoice3.setText("" + correctAnswer);
            buttonObjectChoice1.setText("" + wrongAnswer1);
            buttonObjectChoice2.setText("" + wrongAnswer2);
            break;
    }


}

void updateScoreAndLevel(int answerGiven) {
    if (isCorrect(answerGiven)) {
        for (int i = 1; i <= currentLevel; i++) {
            currentScore = currentScore + i;

        }
    } else {
        currentLevel = 1;
        currentScore = 0;

    }

    currentLevel++;

}


boolean isCorrect(int answerGiven) {
    boolean correctTrueOrFalse = true;
    if (answerGiven == correctAnswer) {//YAY!
        Toast.makeText(getApplicationContext(), "Well Done", Toast.LENGTH_LONG).show();

    }
    else {//If wrong print this instead
        Toast.makeText(getApplicationContext(), "You're wrong", Toast.LENGTH_SHORT).show();
    }  //case for each button being made
    correctTrueOrFalse = false;

    return correctTrueOrFalse;
}


    @Override
    public void onClick (View view){
        //declaring a new int to use in all cases
        int answerGiven;

        switch (view.getId()) {
            //case for each button being made

            case R.id.choice1:
                //button1 information goes here
                //initialize a new integer with the value
                //contained in buttonObjectChoice1
                answerGiven = Integer.parseInt("" +       buttonObjectChoice1.getText());
                //check if the right answer

                break;

            case R.id.choice2:
                //button2 information goes here
                answerGiven = Integer.parseInt("" + buttonObjectChoice2.getText());


                break;

            case R.id.choice3:
                //button 3 information goes here
                answerGiven = Integer.parseInt("" + buttonObjectChoice3.getText());
                break;


        }

    }


}

code snippet for lines 99 and 77 here

line 77

  @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_game);







    TextView textObjectPartA = (TextView) findViewById(R.id.holdTextA);

    TextView textObjectPartB = (TextView) findViewById(R.id.holdTextB);
    textObjectScore = (TextView) findViewById(R.id.textLevel);
    textObjectLevel = (TextView) findViewById(R.id.textScore);

    buttonObjectChoice1 =
            (Button) findViewById(R.id.choice1);

    buttonObjectChoice2 =
            (Button) findViewById(R.id.choice2);

    buttonObjectChoice3 =
            (Button) findViewById(R.id.choice3);
    /*Use the setText method of the class on our objects
    to show our variable values on the UI elements.
    Similar to outputting to the console in the exercise,
    only using the setText method*/


    //telling the console to listen for button clicks from the user
    buttonObjectChoice1.setOnClickListener(this);
    buttonObjectChoice2.setOnClickListener(this);
    buttonObjectChoice3.setOnClickListener(this);
    setQuestion(); //code error shown in this line



}

line 99

   Log.i("info", ""+partA);
    Log.i("info", ""+partB); 
    textObjectPartA.setText(""+partA); //error here
    textObjectPartB.setText(""+partB);

the layout_game file

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="2"
    android:id="@+id/holdTextA"
    android:layout_marginTop="44dp"
    android:textSize="50sp"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginLeft="44dp"
    android:layout_marginStart="44dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="X"
    android:id="@+id/textView4"
    android:layout_alignTop="@+id/holdTextA"
    android:layout_centerHorizontal="true"
    android:textSize="50sp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="4"
    android:id="@+id/holdTextB"
    android:textSize="50sp"
    android:layout_above="@+id/textView6"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginRight="53dp"
    android:layout_marginEnd="53dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="="
    android:id="@+id/textView6"
    android:layout_marginTop="118dp"
    android:layout_below="@+id/textView4"
    android:layout_alignLeft="@+id/textView4"
    android:layout_alignStart="@+id/textView4"
    android:textSize="60sp" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/choice1"
    android:text="2"
    android:textSize="40sp"
    android:layout_alignParentBottom="true"
    android:layout_alignRight="@+id/holdTextA"
    android:layout_alignEnd="@+id/holdTextA"
    android:layout_marginBottom="37dp" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="4"
    android:id="@+id/choice2"
    android:layout_alignBottom="@+id/choice1"
    android:layout_alignLeft="@+id/holdTextB"
    android:layout_alignStart="@+id/holdTextB"
    android:textSize="40sp" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="3"
    android:id="@+id/choice3"
    android:layout_alignBottom="@+id/choice1"
    android:layout_centerHorizontal="true"
    android:layout_alignTop="@+id/choice1"
    android:textSize="40sp" />




Need help creating random explosions

I am creating a spaceship game where you go along and shoot down asteroids. I have created a couple of explosion classes, however no matter what I do I cannot get them show up randomly.

So what happens is I run my main program I shoot an asteroid and the first explosion is random, but for every explosion after that is the same as the first one. What is driving me crazy is that the sounds are playing randomly, but the visual explosion is not random. Both the sound and visual are in the same part of my "if, else" logic, but they don't match.

Here is the part of the code that I use that I am talking about:

for self.bullet_shot in self.bullet_list:
       bullet_hit_evil_space_ship = pygame.sprite.spritecollide(self.bullet_shot,self.enemy_list,True)
            self.explosion_pick = random.randint(0,1)
            for enemy in bullet_hit_evil_space_ship:

                if self.explosion_pick == 0:
                    explosion = explosions.Explosion_10()
                    explosion.rect.x = self.bullet_shot.rect.x - 10
                    explosion.rect.y = self.bullet_shot.rect.y - 60
                    self.explosion_list.add(explosion)
                    self.all_sprites_list.add(explosion)
                    constants.explosion_3.play()

                elif self.explosion_pick == 1:
                    explosion = explosions.Explosion_9()
                    explosion.rect.x = self.bullet_shot.rect.x - 10
                    explosion.rect.y = self.bullet_shot.rect.y - 60
                    self.explosion_list.add(explosion)
                    self.all_sprites_list.add(explosion)
                    constants.explosion_2.play()


                self.bullet_shot.kill()

So again, the sound plays randomly, but the explosion that appears is only random once (the first explosion) then they all are the same after that.

Any ideas on what is going on?




Getting random data from database with conditions

so here I'm trying to get a random question from my table where the column "stat" is 0, anyway the problem here is that it won't accept the random int so c.moveToPosition(rnd) makes the error or I don't now and it causes the app to crush. This's the code please help!

public String[] databasetostring ()  {
    String dbstring = "";
    String optstring = "";
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_QUESTIONS + " WHERE 1";

    Cursor c = db.rawQuery(query, null);
    c.moveToFirst();

    while (!c.isAfterLast()){
        if (   c.getInt(c.getColumnIndex("stat")) != 1   ){
                dbstring += c.getString(c.getColumnIndex("question"));
                dbstring += "\n";
                optstring += c.getString(c.getColumnIndex("answer"));
                optstring += "\n";

        }
        int rnd = new Random().nextInt(c.getCount());
        c.moveToPosition(rnd);
    }
    db.close();
    c.close();
    return new String[] {dbstring, optstring};

}

This is the logcat, it keeps going into that loop!

07-29 22:40:07.352  10939-10949/com.example.bibiwars.digital D/dalvikvm GC_FOR_ALLOC freed 0K, 23% free 6057K/7824K, paused 20ms, total 20ms
07-29 22:40:07.352  10939-10939/com.example.bibiwars.digital D/dalvikvm GC_FOR_ALLOC freed 2061K, 49% free 3995K/7824K, paused 0ms, total 0ms
07-29 22:40:07.362  10939-10939/com.example.bibiwars.digital D/dalvikvm﹕ GC_FOR_ALLOC freed <1K, 39% free 4820K/7824K, paused 10ms, total 10ms
07-29 22:40:07.362  10939-10939/com.example.bibiwars.digital D/dalvikvm﹕ GC_FOR_ALLOC freed 824K, 34% free 5232K/7824K, paused 0ms, total 0ms




RNG schema with unordered required, optional and arbitrary tags

This is a follow-up question to XSD schema with unordered required, optional and arbitrary tags

I am trying to make a RNG schema with the following constraints:

  1. There is no ordering
  2. Some elements must appear exactly once
  3. Some elements may appear zero or unbounded times
  4. Allow unrecognized elements (do not validate them)

Using the example in the previous question, I came up with the following RNG schema:

<grammar xmlns="http://ift.tt/1mso7nd" ns="" datatypeLibrary="http://ift.tt/1AQVtSM">

  <start>
    <element name="person">
      <interleave>                         <!-- no ordering -->
        <element name="name">              <!-- appears exactly once -->
          <data type="string"/>
        </element>
        <optional>                         <!-- appears 0 or 1 times -->
          <element name="age">
            <data type="integer"/>
          </element>
        </optional>
        <zeroOrMore>                       <!-- appears 0 or more times -->
          <element name="phone">
            <data type="integer"/>
          </element>
        </zeroOrMore>
        <ref name="anything"/>             <!-- allow any element -->
      </interleave>
    </element>
  </start>

  <define name="anything">
    <zeroOrMore>
      <choice>
        <element>
          <anyName>
            <except>
              <name>name</name>
              <name>age</name>
              <name>phone</name>
            </except>
          </anyName>
          <ref name="anything"/>
        </element>
        <attribute>
          <anyName/>
        </attribute>
        <text/>
      </choice>
    </zeroOrMore>
  </define>

</grammar>

It was easy enough to satisfy the first three constraints, but for the 4th (allowing unrecognized elements), I wasn't able to find a great solution. What I do is define "anything" to be one or more unrecognized elements, and then I reference it in the <person> element. The problem is that I have to explicitly specify exceptions in <anyName>: it should match any element that is not "name", "age" or "phone". If I leave out the <except>, I get the following error:

people.rng:5: element interleave: Relax-NG parser error : Element or text conflicts in interleave

The solution of having explicit exceptions looks clumsy and hackish. Is there a better way of allowing any element that isn't recognized? Is there anything similar to XSD's <any>? Thanks in advance for any help.




Shuffle Cards and display 10 java applet

In this assignment you will use an applet to display images of playing cards. The applet should load a deck of 52 playing card images from the "images" folder that you downloaded. The applet should shuffle the deck (use a random number generator) and display the first 10 cards of the shuffled deck. Display the cards in two rows of five cards each.

My applet works partially, but when I run the applet viewer the display is just the same card ten times. Here is my code:

package CTY;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Random;

public class Exercise12 extends Applet {

    Image c1;
    Image c2;
    Image c3;
    Image c4;
    Image c5;
    Image c6;
    Image c7;
    Image c8;
    Image c9;
    Image c10;

    public void init() {
        Random random = new Random();
        String cards[][] = {
                { "cards/c1.gif", "cards/c2.gif", "cards/c3.gif", "cards/c4.gif", "cards/c5.gif", "cards/c6.gif",
                        "cards/c7.gif", "cards/c8.gif", "cards/c9.gif", "cards/c10.gif", "cards/cj.gif",
                        "cards/ck.gif", "cards/cq.gif" },
                { "cards/s1.gif", "cards/s2.gif", "cards/s3.gif", "cards/s4.gif", "cards/s5.gif", "cards/s6.gif",
                        "cards/s7.gif", "cards/s8.gif", "cards/s9.gif", "cards/s10.gif", "cards/sj.gif",
                        "cards/sk.gif", "cards/sq.gif" },
                { "cards/d1.gif", "cards/d2.gif", "cards/d3.gif", "cards/d4.gif", "cards/d5.gif", "cards/d6.gif",
                        "cards/d7.gif", "cards/d8.gif", "cards/d9.gif", "cards/d10.gif", "cards/dj.gif",
                        "cards/dk.gif", "cards/dq.gif" },
                { "cards/h1.gif", "cards/h2.gif", "cards/h3.gif", "cards/h4.gif", "cards/h5.gif", "cards/h6.gif",
                        "cards/h7.gif", "cards/h8.gif", "cards/h9.gif", "cards/h10.gif", "cards/hj.gif",
                        "cards/hk.gif", "cards/hq.gif" } };

        int Card[] = new int[10];
        int Suit[] = new int[10];
        int suit = random.nextInt(4);
        int card = random.nextInt(10);
        boolean newCard = false;

        for (int i = 0; i < 10; i++) {
            while (newCard == false) {
                newCard = true;
                suit = random.nextInt(4);
                card = random.nextInt(13);

                for (int j = 0; j < i; j++) {
                    if (Card[j] == card && Suit[j] == suit ) {
                        newCard = false;
                    }
                }
            }

            Card[i] = card;
            Suit[i] = suit;
        }

        c1 = getImage(getDocumentBase(),
                cards[Suit[0]][Card[0]]);
        c2 = getImage(getDocumentBase(),
                cards[Suit[1]][Card[1]]);
        c3 = getImage(getDocumentBase(),
                cards[Suit[2]][Card[2]]);
        c4 = getImage(getDocumentBase(),
                cards[Suit[3]][Card[3]]);
        c5 = getImage(getDocumentBase(),
                cards[Suit[4]][Card[4]]);
        c6 = getImage(getDocumentBase(),
                cards[Suit[5]][Card[5]]);
        c7 = getImage(getDocumentBase(),
                cards[Suit[6]][Card[6]]);
        c8 = getImage(getDocumentBase(),
                cards[Suit[7]][Card[7]]);
        c9 = getImage(getDocumentBase(),
                cards[Suit[8]][Card[8]]);
        c10 = getImage(getDocumentBase(),
                cards[Suit[9]][Card[9]]);
    }

    public void paint(Graphics graphics) {
        graphics.drawImage(c1, 30, 30, this);
        graphics.drawImage(c2, 30, 150, this);
        graphics.drawImage(c3, 120, 30, this);
        graphics.drawImage(c4, 120, 150, this);
        graphics.drawImage(c5, 210, 30, this);
        graphics.drawImage(c6, 210, 150, this);
        graphics.drawImage(c7, 300, 30, this);
        graphics.drawImage(c8, 300, 150, this);
        graphics.drawImage(c9, 390, 30, this);
        graphics.drawImage(c10, 390, 150, this);
    }
}




How to assign a specific char to a randomly generated position in 2d array? (java)

This is the first time I'm using java and I'm supposed to create a game using this program. The 2d array's 10 by 10, 5 specific chars are C,M,W,F and E. There are 15 C,M,W,F each, the remaining 40 boxes are occupied by E. The positions are randomly generated. Any ideas?




mardi 28 juillet 2015

Randomly generated rectangles do not fully complete separation, yet the program moves on

I am working on a random generation system for my game. I wanted to create a given number of randomly placed rooms that do not intersect. I've mocked up some code to do this for me, but there is one problem: it tells the program that it is finished separating long before it actually is. Here is some pseudo-code for you wonderful people:

generate all things required to draw properly on canvas

set how many rooms are to be placed
grab possible room sizes

new 'rooms' array
for numRoomsToPlace
    select random location on the canvas, clamped towards the center
    create a room of random size at location and push to rooms array

continueLoop = true
loopTimeout = 20
while continueLoop = true
    noIntersection = true
    loop through all active rooms (variable q)
        loop through all active rooms so that we have a pair (variable j)
            get room 1 (represented as q)
            get room 2 (represented as j)
            check if rooms intersect on both axes
            if rooms intersect
                noIntersection = false
                if it would be shorter to move along the x axis
                    shift both rooms half the distance required in opposite directions
                else, it would be shorter to move along the y axis
                    shift both rooms half the distance required in opposite directions
    loopTimeout--;
    if noIntersection || loopTimeout<=0
        continueLoop = false

draw all the things

So now that is finished, here is a working demo in javascript: http://ift.tt/1LVWjFt

I cannot for the life of me figure out why the rooms are not fully separating. The while loop is NOT timing out. I put in detection and the program thinks that it is fully separating the rooms. I'm sure there is a simple solution and that I've just been looking at this problem for too long. The more brains the better, so that's why I'm here! Thank you guys for helping in advance, you are always awesome.




Setting max x and y values for Swift

I was trying to put a random number generator in my code today and I was going to use the maximum x and y values for it. Here is a snippet of my code:

var rand_x = CGFloat(arc4random_uniform(maxXValue)) 
var rand_y = CGFloat(arc4random_uniform(maxYValue)) 

But I continue to get the error message:

Use of unresolved identifier 'maxXValue' Use of unresolved identifier 'maxYValue'

Any tips to fix this problem? Thanks!




Select Top N Random rows from table then ordering by column

I need to get 3 random rows from a table and then order those rows by a the BannerWeight column.

So if the data is:

BannerID     BannerWeight
   1               5
   2               5
   3               10
   4               5
   5               10

I want the results to be:

BannerID     BannerWeight
   5               10
   2               5
   4               5

So far I have:

SELECT TOP 3 b.BannerID, b.BannerWeight FROM CMS_Banner b
INNER JOIN CMS_BannerCategory c ON b.BannerCategoryID = c.BannerCategoryID
WHERE c.BannerCategoryName LIKE 'HomepageSponsors'
ORDER BY NEWID()

I just can't figure out how to order those 3 random rows once I get them. I've tried doing

 ORDER BY BannerWeight, NEWID()

But this just gets me 3 random rows where the BannerWeight is 5.

Here is an SQLFiddle: http://ift.tt/1LQN73E




Random Number Generator for X,Y Coordinates

I was writing code today and I stumbled across a problem with my random number generator. I am trying to make a generator much like the one in Fruit Ninja, I am also writing in swift. Here is a snippet of my code:

var rand_x = arc4random() 
var rand_y = arc4random()
node!.position = CGPoint(x: rand_x, y: rand_y)

My problem is I am getting the error:

Cannot find an initializer for type 'CGPoint' that accepts an argument list of type '(x: UInt32, y: UInt32)'

Any tips how to fix this? Thanks!




need help in batch programming

ok, so im trying to make a batch file that creates a serial number like this: x-x-x-x-x only this time I replaced each "x" with %random%.. so my only problem is, I want each random number to be 4 digits not 5, anyone has any idea how can I make it generate such a number? heres my source code:

@echo off
goto a
:b
echo it's a 5 digits number!
:a
set "x=%random%-%random%-%random%-%random%-%random%"
if %random% gtr 9999 goto b
echo it worked
echo %x%
pause

thanks for any help in advanced...




Using ifelse with random variate generation in a function applied to a vector

I want to create a function that generates a random number based on its input and apply it to a boolean vector.

f <- function(x, p) ifelse(x, runif(1)^p, runif(1)^(1/p))
f(c(T,T,T,F,F,F), 2)   

What I get is not what I wanted.

[1] 0.0054 0.0054 0.0054 0.8278 0.8278 0.8278

I'd expect a new random number for every element of my input vector, not two random numbers repeated. Why do I get this result, and how can I get the desired result which would be the same as

c(runif(3)^2, runif(3)^(1/2))

which yields a new random number for every element

0.0774 0.7071 0.2184 0.8719 0.9990 0.8819




C++ random number are not changing

I created this method for generating random numbers in c++ , when I call it in loop, I always get the same random value, what is wrong? Because I expect different value after every loop iteration. I am compiling it with flag -std=c++11.

float CDevice::gaussNoise(float mean, float stddev)
{
    std::default_random_engine generator(time(NULL));
    std::normal_distribution<float> distribution(mean, stddev);
    return distribution(generator);
}

main looks like this:

int main
{
    class CDevice *device;
    device = new CDevice();
    std::vector<float> vec;
    for(uint32_t i = 0; i< 10; ++i)
        vec.push_back(device->gaussNoise(1,5));
    for(uint32_t i = 0; i < vec.size(); ++i)
            std::cout << vec[i] << std::endl;
}

and output is (for example):

3.71254
3.71254
3.71254
3.71254
3.71254
3.71254
3.71254
3.71254
3.71254
3.71254




php generate token synchronized based on time stamp

this is a question a little complicated, I do not know how I will respond,but i try. how can I generate a random token in php every 30 seconds applies for each client making a request to the server php where is running this script? For example:

User 1 connect to server at 17:30:10 and the token is ABC

User 2 connect to server at 17:30:33 and the token is always ABC

the token must be changed every 30 seconds. how can i implements this?




Retain variables when use Guid type

Today, I have problem when create random ID with Guid type in C#.

When I want random ID. And I use:

obj.ID = new Guid(txtID.Text);    //ID type Guid

But when run program. It automatic generate 1 id random when I swipe card.

I want when swipe card. It will random ID and retain this values until I delete it.

Thank you!!!




how to set button in random position when the app start and after click

I've tried this code to change randomly the button position. But i'ts just dimensions, on the first click the button change position but on the other click not. Why?? some help? Thanks

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
final Button btn = (Button) findViewById(R.id.run_button);
        RelativeLayout.LayoutParams absParams = (RelativeLayout.LayoutParams) btn
                .getLayoutParams();

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

        Random r = new Random();

absParams.width = r.nextInt(width);
        absParams.height = r.nextInt(height);
        btn.setLayoutParams(absParams);

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Random r = new Random();
                btn.getX();
                btn.getY();

                btn.setX(r.nextFloat());
                btn.setY(r.nextFloat());

            }

        });




How to generate random numbers correlated to a given dataset in matlab

I have a matrix x with 10,000 rows and 20 columns. I want to generate another new matrix of random numbers , y, where y is correlated to x with correlation coefficient q.

Note that the matrix x is not normally distributed - it has the power law distribution.

I want to perform this in matlab




Numpy array filled with random numbers so that you only change the value by one along the x/y axis

I know how to create a numpy array filled with random numbers, for instance, this : np.random.randint(0, 100, (5, 5)).

But how do you create a numpy array filled with random numbers so that the difference between two adjacent cells is 1 or less ?

Thanks




Why rand() isn't really random?

I wanted to put random points on an image (stars in space for some little fun side project)

I have this simple script.

<?php
$gd = imagecreatetruecolor(1000, 1000);
$white = imagecolorallocate($gd, 255, 255, 255);

for ($i = 0; $i < 100000; $i++) 
{
    $x = rand(1,1000);
    $y = rand(1,1000);

    imagesetpixel($gd, round($x),round($y), $white);
}

header('Content-Type: image/png');
imagepng($gd);
?>

Keep in mind this is just for testing, that is why I put 100000 in for loop so it shows the pattern I noticed emerging. We have 1 million pixel to use, still random X and Y creates this pattern instead: enter image description here

So it is far from random. I know rand is not real random, that is why it isn't good for cryptography. But I find no information about how it works and what should I do to avoid patterns like this.




Log-gamma distribution in SAS

Which Proc statement is used to fit Log-gamma distribution in SAS and How to generate random no.s using these estimated parameters?




lundi 27 juillet 2015

How to get the randrange equivalent of python in Ruby

Please I want to get a random value between say (0 and 20 but skips by 3) like the python equivalent of:

random.randrange(0,20, 3)




Creation of SecureRandom is slow, even in java 8

I searched on this problem. I got impression, it is resolved in java 8. But suddenly, I started getting this problem in my new VM, based of ubuntu 14.04.

2015-07-27 14:56:35.324 INFO 11809 --- [localhost-startStop-1] o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [167,833] milliseconds.

And java version is

java -version java version "1.8.0_45" Java(TM) SE Runtime Environment (build 1.8.0_45-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

Server is ubuntu 14.04.

Another thing is, i running this java process as spring boot application, which has embedded tomcat running.

Any ideas, what could be wrong? I even tried,

-Djava.security.egd=file:/dev/./urandom option




Random number generator output 0-9 [duplicate]

This question already has an answer here:

Hi i am having issues with my code at the moment as i have been stuck for a while now, i am new to java programming. I want the code output to be from 0-9 not 1-10, my code and output is displayed below:

import java.util.Arrays;

public class RandNumGenerator {

public static int RandInt(){
    double n = Math.random()*10;
    return (int) n;
    }

public static void randTest(int n){
    int [] counts = new int [10];
    int sampleSize = 10000;
    int RandNum = RandInt();

    System.out.println ("Sample Size: " + sampleSize);
    String[] intArray = new String[] {"Value","Count","Expected","Abs Diff","Percent Diff"};
    System.out.println(Arrays.toString(intArray));



    for(int i=0;i<n;i++){
        counts[ RandNum ] = counts[ RandNum ] + 1;
        System.out.println(counts[RandNum]);
        } 
    }

public static void main(String[] args) {
    randTest(10);
    }
}

output is 1-10, not 0-9:

Sample Size: 10000
[Value, Count, Expected, Abs Diff, Percent Diff]
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10




Using rand() to generate numbers around a variable?(C++)

I am making a small text-based game in c++ called "House Evolution" for fun. The game consists of 'searching under the couch cushions' to gain credits. When you search, the game is supposed to generate a random number anywhere from creditRate-5 to creditRate+5. How would I go about doing this using the rand() function, no matter what number creditRate is? Here is example code:

#include <iostream>
#include <unistd.h>
#include <string>
#include <cstdlib>
#include <math.h>

int main()
{
    int creditRate = 30; // Just for example.
    int credits;
    int searching;

    while (1) {
        // Yes, I know, infinite loop...
        std::cout << "Credits: " << credits << std::endl;
        std::cout << "Type any key to search for credits: " << std::endl;
        std::cout << "Searching...\n";
        usleep(10000000); // Wait 10 seconds

        searching = rand(?????????); // Searching should be creditRate-5 to creditRate+5

        std::cout << "You found " << searching<< " credits\n";
        credits += searching;
    }
}




generating unique url for each ip [on hold]

i'm trying to create a giveaway page for my website. Each user who visits the giveaway page receives a unique url based on his ip, he is able to share his url with other users, when someone clicks on his url he is awarded with 1 point, while those who clicked on his url are getting their own url as well and they are able to share it too and get points.

Can someone help me making a script for this?




randTest () method that takes a single int n as an argument

Below are the instructions that i must follow for the code, i have done most of the code but i seem to be missing elements that make it compile correctly.

A static void method named randTest that takes a single integer argument, n. This should perform the following actions:

  • Declare an int array of 10 elements named counts. This will be used to record how often each possible value is returned by randInt.

  • Call randInt n times, each time incrementing the count of the element of counts corresponding to the value returned.

    public static void randTest(int n){
    int [] counts = new int [10];
    int sampleSize = 10000;
    //int n = sampleSize;
    int RandNum = RandInt();
    
    System.out.println ("Sample Size: " + sampleSize);
    String[] intArray = new String[] {"Value","Count","Expected","Abs Diff","Percent Diff"};
    System.out.println(Arrays.toString(intArray));
    
    
    
    for(int i=0;i<10000;i++){
        counts[ RandNum ] = counts[ RandNum ] + 1;
        counts[i] = RandInt();
        System.out.println(counts[n]);
        } 
    }
    
    

The information must then be printed out into a results table like so:

enter image description here




Creating a small page that generates 3 random words from 3 seperate lists at the click of a button

I coded a little in college but forget basically everything. I want to create a bare bones page that has a button labeled "Generate" That will give you a 3 word sentence from 3 separate lists...basically :

list one has "1, 2, 3, 4, 5, 6, 7, 8, 9" list two has "a, b, c, d, e, f, g, h, i" list three has "car, horse, gym, fair, boat"

You press "generate" and it puts three of those values into one sentence... example : 4 h boat after pressing generate...how can I do this?




Increasing mean deviation with increasing sample size on Excel's NORMINV()

I have a strange behaviour in my attempt to code Excel's NORMINV() in C. As norminv() I took this function from a mathematician, it's probably correct since I also tried different ones with same result. Here's the code:

double calculate_probability(double x0, double x1)
{
    return x0 + (x1 - x0) * rand() / ((double)RAND_MAX);
}

int main() {

long double probability = 0.0;
long double mean = 0.0;
long double stddev = 0.001;
long double change_percentage = 0.0;
long double current_price = 100.0;
srand(time(0));
int runs = 0;
long double prob_sum = 0.0;
long double price_sum = 0.0;

while (runs < 100000)
{
    probability = calculate_probability(0.00001, 0.99999);
    change_percentage = mean + stddev * norminv(probability); //norminv(p, mu, sigma) = mu + sigma * norminv(p)
    current_price = current_price * (1.0 + change_percentage);
    runs++;
    prob_sum += probability;
    price_sum += current_price;
}
printf("\n\n%f %f\n", price_sum / runs, prob_sum / runs);
return 0;
}

Now I want to simulate Excel's NORMINV(rand(), 0, 0.001) where rand() is a value > 0 and < 1, 0 is the mean and 0.001 would be the standard deviation.

With 1000 values it looks okay:

100.729780 0.501135

With 10000 values it spreads too much:

107.781909 0.502301

And with 100000 values it sometimes spreads even more:

87.876500 0.498738

Now I don't know why that happens. My assumption is that the random number generator has to be normally distributed, too. In my case probability is calculated fine since the mean is pretty much 0.5 all the time. Thus I don't know why the mean deviation is increasing. Can somebody help me?




How to generate a random number in java with array bounds?

I want to ask how to generate a random number in java , i know it is done by random.nextint() but i want to check if the number is not what i wanted then it should be rejected and a new random number should be generated .

I want something like this :

Integer[] in = {1,2,3,4,5};    
int a = new Random().nextInt(10);
for(int i=0;i<in.length ;i++)
   if(a==in[i])
      //new random number

if the number is present in the above array (in) then new random number should be generated




How to add the random number value in swift

sorry, i am started learning swift. I have question:

I want a label display 3 random number from 1 -10 . Each time the displayed number will changed randomly, and the number will appear in the label in 1 second before change to other number. After displaying 3 random number, it will give the total value of 3 numbers it appeared.

for example: when I click button, the label give me a first number, 1 second later, the label give me the second number, 1 second later the label give me the third number then label stop and give me the total number (number1 + number2 + number3 )in the other result label.

could you give me some clues.

thanks mates.




Getting random lines from Trove (TObjectIntHashMap)?

Is there a way to get random lines from a Trove (TObjectIntHashMap)? I'm using Random to test how fast a Trove can seek/load 10,000 lines. Specifically, I'd like to pass in a random integer and have the Trove seek/load that line. I've tried using the get() method, but it requires that I pass a string rather than a random int. I've also considered using keys() to return an array and reading from that array, but that would defeat the purpose as I wouldn't be reading directly from the Trove. Here's my code:

import java.io.IOException;
import java.util.List;
import java.util.Random;

import com.comScore.TokenizerTests.Methods.TokenizerUtilities;

import gnu.trove.TObjectIntHashMap;

public class Trove {

    public static TObjectIntHashMap<String> lines = new TObjectIntHashMap<String>();

    public static void TroveMethod(List<String> fileInArrayList)
            throws IOException {
        TObjectIntHashMap<String> lines = readToTrove(fileInArrayList);
        TokenizerUtilities.writeOutTrove(lines);
    }

    public static TObjectIntHashMap<String> readToTrove(
            List<String> fileInArrayList) {

        int lineCount = 0;

        for (int i = 0; i < fileInArrayList.size(); i++) {

            lines.adjustOrPutValue(fileInArrayList.get(i), 1, 1);
            lineCount++;
        }

        TokenizerUtilities.setUrlInput(lineCount);
        return lines;
    }

    public static void loadRandomMapEntries() {
        Random rnd = new Random(lines.size());

        int loadCount = 10000;

        for (int i = 0; i < loadCount; i++) {
            lines.get(rnd);
        }

        TokenizerUtilities.setLoadCount(loadCount);
    }
}

The method in question is loadRandomMapEntries(), specifically the for-loop. Any help is appreciated. Thanks!




Print random numbers in array size 20 and print number in lndex number

Question:

Write a program to create an array of size 20 to store integers. Then, the program should generate and insert random numbers between 1 and 7, inclusive into the array. Next, the program should print the array as output.
A simple subset is part of an array that consists of a set of 4 elements next to each other. The program will generate a random number between 0 and 19, which represents the location in the array (i.e. index number). Then, the program should print the 4 elements from that location. The program should take into consideration the boundaries of the array. There is no user input for this program.
Your program must include, at least, the following methods:
- insertNumbers, which will take as input one integer array and store the random numbers in it. - computeLocation, which will generate the location random number and return it.

A sample run of the program is shown below:

Sample output #1:
Array: 2 7 4 3 1 5 7 2 3 6 2 7 1 3 2 4 5 3 2 6
Random position: 2
Subset: 4 3 1 5

Sample output #2:
Array: 2 7 4 3 1 5 7 2 3 6 2 7 1 3 2 4 5 3 2 6
Random position: 18
Subset: 2 6 2 7




dimanche 26 juillet 2015

Does this DIEHARD output suggest randomness?

I'm trying to get some context for understanding DIEHARD output, testing a file for randomness. I've read lots about it, but found very little empirical information as to what might constitute a file passing DIEHARD.

I've attached an example output file for a test I ran. I believe that the p values should be reasonably uniformly distributed(?) There are ps close to 1 or 0. I'm unsure what to make of the KS tests. I have no context within which to judge such output.

Has pu256.bin passed DIEHARD?

File @ Dropbox: DIEHARD output text file




How to extract a random sample with multiple conditions that vary by group?

I have a cross-national data set where each respondent has at least one diary. The number of diaries per respondent and diary completion day varies by country.

For example, in one country each respondent completed only 1 diary (half of the respondents completed only on a weekend, while the other half only on a weekday). In another country, each respondent completed 2 diaries (one weekend- one weekday), and in another one everyone completed 7 diaries (one for each day of the week). There are also surveys where some of the respondents returned 2 diaries, while others 3; and there are those where one everyone returned 4 diaries. The data look like this:

dat<-rbind(cbind(rep(1,8),11:18,111:118,1:0),cbind(rep(2,8),c(21,21,22,22,23,23,24,24),c(211,212,221,222,231,232,241,242),1:0),cbind(rep(3,7),c(rep(31,7),rep(32,7)),c(311:317,321:327),c(rep((c(1,1,rep(0,5))),2))),cbind(rep(4,10),c(41,41,41,42,42,42,43,43,44,44),c(411:413,421:423,431,432,441,442),1:0)  )
colnames(dat) <- c('country_id', 'diarist_id', 'diary_id','weekend')
dat

I am trying to draw a random sample of “one person-one diary” from each country. But at the country level I need -approximately- 29% of the diaries to be weekend diaries. How can I draw such a conditional random sample by group?




printing method class randTest (int n)

I am having trouble printing out the method randTest (int n) as errors keep appearing. I want to print this method in the main as i want to print the results in a clear tabular form. The method must stay static void. This is my code below:

public class RandNumGenerator {

    public static int RandInt(){
        double n = Math.random()*10;
        return (int) n;
        }

    public static void randTest(int n){
        int [] counts = new int [10];

        for(int i=0;i<n;i++){
            counts[i] = RandInt();
            System.out.println(counts[i]);
            } 
        }

    public static void main(String[] args) {
        System.out.println(RandInt());
        System.out.println(randTest());
    }
}




Random number generator for C++ popping up with an error?

I am having trouble with my number generator. Syntax wise, everything is working properly. I mainly wanted to use functions to see if they would work properly. When I run the program, a message pops up and says that my variable "guess" is not initialized. Can anyone give insight as to why this may be happening? Also note that even though I didn't include my libraries in the code below, they are present in the actual program itself.

using namespace std;

int game();
string playAgain();

int main(){

game();
playAgain();

return 0;
}

int game(){

int guess;
int guessesTaken = 0;
int number = rand() % 10 + 1;
int count = 0;

cout << "I am thinking of a number between 1 and 10, can you guess it? " << endl;

while (guessesTaken < count){
    cout << "Take a guess: " << endl;
    cin >> guess;
    if (guess > number)
        cout << "Too High. Try again!" << endl;
    if (guess < number)
        cout << "Too Low! Try again!" << endl;
    if (guess == number)
        break;

}count++;

if (guess == number)
    cout << "Congratulations!" << endl;
return 0;
}

string playAgain(){
string play;

cout << "Want to play again?: " << endl;
if (play == "y" || "Y")
    main();
else
    cout << "Thanks for playin" << endl;
return 0;

}




Matlab: Random Signals with Additive Noise

I am learning Randoms Signals as well as MatLab. I have a few questions, as I know little of both topics.

I have no idea how to start this problem...

Problem statement is as follows: I am looking to generate a baseband transmission scheme that is made of binary rectangular pulses. The transmitted signal is contaminated by additive noise. By using mean and variance estimators I am to determine the mean and variance using the generated noise with no signal transmitted. At that point, I look to subtract the estimated mean from the signal yielding a fairly clean signal.

(For entirety, I will post the entire project in this post, yet I aim to resolve the above steps first prior to the ones below.)

Using that signal I have to use a "detector" (not sure of what this is referring to) to decide whether a 0 or 1 was transmitted. Then compare the received string and transmitted string to determine the number of errors and the average probability of error.

I was told I needed to learn how to generate a Gaussian random variable. After following some examples I have this: (Please advise me if it does not pertain to a solution of problem I mentioned above)

close all
clc
%% Generation of a signal bpsk modulation
%This takes a set of random numbers and converts them to bits 0's & 1's
%The 2*X-1 will create -1's in place of the 0's from the bit conversion.
signal_i = 2*(rand(1,10^5)>0.5)-1;
signal_q = zeros(1,10^5);
%In communication systems we have two components
%which is why we have singal i and q
scatterplot(signal_i + signal_q);
%% Combining for complex representation
signal = complex(signal_i, signal_q);
p_signal = mean(abs(signal).^2)
e_signal = (abs(signal).^2);
%% Adding some noise of a known variance
for var = 1/50:1/10:0.5
    noise = 1/sqrt(2)*(randn(1,10^5)+j*randn(1,10^5))*sqrt(var);
      addNoise = signal + noise;
      figure(1);
      plot(real(addNoise),imag(addNoise),'b*');
      drawnow('expose');
  end

I shall stop the questions here as there is much to cover as is. However, eventually I will need to transmit the sequence using two cases with parameters, one Gaussian noise and the other Laplacian.

I was given the sequences of: Equal probabilities: 10001011000111101001 Unequal probabilities: 11001111011011101101

Am I on the right track with the current code vs project requirements? If not, where shall I start?

Thanks in advance.




What is the range of integers produced by a Lehmer random number generator?

Wikipedia says the formula is (http://ift.tt/1LLMmIQ).

My assumption is that the range is anywhere from 1 to n, but I'd like to be sure.




How to generate a random integer using math.random class

I am having trouble with the RandInt() method as it will not return a random integer. The result must be an int ranged 0-9 and must use the math.random class. This is my code below:

public class RandNumGenerator {
    public static int RandInt() {
        int n = (int) Math.random() * 10;
        return n;
    }
    public static void main(String[] args) {
        RandInt();
    }
}




How to generate a true (synchronized) random set of strings in a variable? [duplicate]

This question already has an answer here:

I thought i can generate some random strings but i kept getting the same answer :/, there is a lot complexity with random generation and is the reason why my code sucks, here is what i thought would work:

class Program
{
    static void Main(string[] args)
    { 
            for (int i = 0; i < 10; i++)
            {
                string[] mystrings = "vice|virtue|samuel|fruits".Split('|');
                int choice = new Random().Next(mystrings.Length);                
                Console.WriteLine(mystrings[choice]);                   
            }                
        }
    }

i get the same answer :/, i have researched here for a solution but it's for integers like 0-1000 random number generation, mine is for strings which i could not find in the forums and some keywords i saw were 'synchronized'




Java get a random value from 3 different enums

I am implementing a simple version of the Cluedo game. There are 3 types of cards in the game, Character, Weapon and Room. Since one card is nothing more than a String (i.e no functionality or information other than the name is stored in a card), I chose not to have a Card interface and each type extends Card. Rather I had three enums in my game which are:

public enum Character {Scarlett, Mustard, White, Green, Peacock, Plum;}
public enum Weapon {Candlestick, Dagger, LeadPipe, Revolver, Rope, Spanner;}
public enum Room {Kitchen, Ballroom, Conservatory, BilliardRoom, Library, Study, Hall;}

However there is one case where three types of cards are put together and dealt evenly to each player of the game. For example, one player may have a hand of 2 Characters, 2 Weapons and 1 Room, another player may have 3 Rooms and 2 Characters, so long the total number of cards are even it doesn't matter what type that is.

And that's why I wonder if there is a way to randomly choose one single value from all three enums in Java?

Or I shouldn't do this three enums thing in the first place? (Badly designed)




A Day at the Races - Head first C#

I'm working on C# Lab in Head First C# book.

When I push start button - dogs should run until one of them reach the finish. Each dog should run with random speed, but all of my dogs run with same speed ;/

Dogs initialization:

 GreyhoundArray[0] = new Greyhound(){
            MyPictureBox = GreyhoundPictureBox1,
            StartingPosition = GreyhoundPictureBox1.Left,
            RacetrackLenght = TrackPictureBox.Width - GreyhoundPictureBox1.Width,
            MyRandom = MyRandom                
        };
        GreyhoundArray[1] = new Greyhound(){
            MyPictureBox = GreyhoundPictureBox2,
            StartingPosition = GreyhoundPictureBox2.Left,
            RacetrackLenght = TrackPictureBox.Width - GreyhoundPictureBox2.Width,
            MyRandom = MyRandom
        };
        GreyhoundArray[2] = new Greyhound(){
            MyPictureBox = GreyhoundPictureBox3,
            StartingPosition = GreyhoundPictureBox3.Left,
            RacetrackLenght = TrackPictureBox.Width - GreyhoundPictureBox3.Width,
            MyRandom = MyRandom
        };
        GreyhoundArray[3] = new Greyhound(){
            MyPictureBox = GreyhoundPictureBox4,
            StartingPosition = GreyhoundPictureBox4.Left,
            RacetrackLenght = TrackPictureBox.Width - GreyhoundPictureBox4.Width,
            MyRandom = MyRandom
        };

Start button code:

private void StartButton_Click(object sender, EventArgs e)
    {
        timer1.Enabled = true;
    }

Timer code:

private void timer1_Tick(object sender, EventArgs e)
    {
        for (int i = 0; i < 4; i++)
        {
            if (GreyhoundArray[i].Run())
                timer1.Enabled = true;
            else
                timer1.Enabled = false;
        }
    }

Run method:

public bool Run()
    {
        MyRandom = new Random();

        int distance = MyRandom.Next(1, 5);
        MyPictureBox.Left += distance;

        if(MyPictureBox.Left >= RacetrackLenght)
            return false;
        else
            return true;
    }




samedi 25 juillet 2015

Creating A Text Based Maze Generator In Python

I am a beginner in coding in general, but I know my way around the basics. as a challenge, and possibly a tool for map generation, I wanted to see if I could use python to create a small text based 5x5 maze generator that is isolated (no exits or entrances) that allows both loops and dead ends. I hand drew one as an example:

┌ → ↑ ┌ ┐

├ ─ ┴ ┼ ┤

│ ┌ ┬ ┘ │

├ ┘ │ ← ┤

↓ ← ┴ ─ ┘

(arrows represent dead ends coming from the opposite direction of the arrow)

I was unable to make much progress, and gave up rather quickly, deciding that my coding knowledge was not at the level to create something this complex. now I want to know if there is a simple way to do such a thing. after going down a rabbit hole of spanning trees, visual codes, and the such, 95% of which I barely understood, I couldn't find much to help me. I'm looking for a (hopefully) easy to understand way of creating a piece of code that could achieve this. Ideally I want the answer to be in python, and be something relatively easy to understand for a beginner-medium programmer given enough time. Also, please excuse any horribly vague/overly-complicated parts of this question I have written, they would most likely be due to the fact that I don't know much about this area of coding.

if there is a simpler way to phrase this question, or significantly easier methods of creating a 5x5 maze other than making it text based, these are also very welcome :)




How to create 2 Random objects in 2 consecutive lines of code with different seeds?

I want to make 2 different Random objects in 2 consecutive lines of code. The parameterless constructer of the Random class is like this:

public Random() 
    : this(Environment.TickCount) {
  }

It uses Environment.TickCount as the seed. TickCount represents the amount of time that has passed since the OS is switched on, right?

I tried the following:

Random r1 = new Random ();
Random r2 = new Random ();

And I found out that the 2 Random objects had the same seed because their Next methods return the same number each time. I was surprised by how fast a line of code can be executed. Then I tried:

long tick1 = Environment.TickCount;
for (int i = 0 ; i < 100000 ; i++) {

}
long tick2 = Environment.TickCount;
Console.WriteLine (tick2 - tick1);

And I get 0. So I iterated 100000 times and still, not even 1 millisecond has passed?

I just want to ask how can I create 2 different Random objects or is there another way to generate random numbers?




Randomized Vigenere Cipher with Python

To clarify before beginning: I'm aware there are similar topics, but nothing that has really offered any direct help. Also: this is a class project; so I'm not looking for anyone to code my project for me. Tips and advice is what I'm looking for.

This program is meant to take a user supplied seed, generate a key based on the integer, then to generate a 95 x 95 matrix in which all printable ascii characters are available for encryption/decryption purposes. (Key is all alpha, and capitalized)

The kicker: all the cells most be randomized. See image below: Randomized Vigenere Matrix

I will post my code below (Python is certainly not my forte, though I will definitely take constructive criticisms.):

import random

class Vigenere:
#string containing all valid characters
symbols= """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
matrix = []

#Generate psuedorandom keyword from seed
def keywordFromSeed(seed):
    Letters = []

    while seed > 0:
        Letters.insert(0,chr((seed % 100) % 26 + 65))
        seed = seed // 100
    return ''.join(Letters)

#Contructs a 95 x 95 matrix filled randomly
def buildVigenere():
    n = len(Vigenere.symbols)
    print(n)
    vigenere = [[0 for i in range(n)] for i in range(n)]

    #Build the vigenere matrix
    for i in range(n):
        temp = Vigenere.symbols

        for j in range(n):
            r = random.randrange(len(temp))
            vigenere[i][j] = temp[r]
            temp = temp.replace(temp[r],'')

    Vigenere.matrix = vigenere
    return vigenere

def encrypt(plaintext,keyword):
    ciphertext = ""
    for i in range(len(plaintext)):
        mi = i
        ki = i % len(keyword)
        ciphertext = ciphertext + Vigenere.eRetrieve(Vigenere.matrix,keyword,plaintext,ki,mi)
    return ciphertext

def decrypt(ciphertext,keyword):
    plaintext = ""
    for i in range(len(ciphertext)):
        emi = i
        ki = i % len(keyword)
        plaintext = plaintext + Vigenere.dRetrieve(Vigenere.matrix,keyword,ciphertext,ki,emi)
    print(plaintext)

def eRetrieve(v,k,m,ki,mi):       
    row = ord(m[mi]) - 32
    col = ord(k[ki]) - 32
    return v[row][col]

def dRetrieve(v,k,em,ki,emi):
    n = len(Vigenere.symbols)
    whichRow = ord(k[ki]) - 32
    for i in range(n):
        if v[whichRow][i] == em[emi]:
            print(i, chr(i))
            decryptChar = chr(i + 32)
            print(decryptChar)
            return(decryptChar)

And just in case it helps, here's my main.py:

import argparse
import randomized_vigenere as rv
import random

def main():

#Parse parameters
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--mode", dest="mode", default = "encrypt", help="Encrypt or Decrypt")
parser.add_argument("-i", "--inputfile", dest="inputFile", default = "inputFile.txt", help="Input Name")
parser.add_argument("-o", "--outputfile", dest="outputFile", default = "outputFile.txt", help="Output Name")
parser.add_argument("-s", "--seed", dest="seed", default =7487383487438734, help="Integer seed")
args = parser.parse_args()

#Set seed and generate keyword
seed = args.seed
random.seed(seed)
keyWord = rv.Vigenere.keywordFromSeed(seed)
print(keyWord)

#Construct Matrix
vigenere = rv.Vigenere.buildVigenere()
print(vigenere)

f = open(args.inputFile,'r')
message = f.read()

if(args.mode == 'encrypt'):
    cipher = ""
    data = rv.Vigenere.encrypt(message,keyWord)
    print(data)
    cipher = rv.Vigenere.decrypt(data,keyWord)
    print(cipher)
else:
    data = rv.Vigenere.decrypt(message,keyWord)

o = open(args.outputFile,'w')
o.write(str(data))

if __name__ == '__main__':
    main()

I've just been using the default seed (7487383487438734)

My Plaintext: ABCdefXYZ

What I get as Ciphertext: $[iQ#`CzK

What I recieve after decryption: !TWu.Ck[b

My thoughts are that the error lies somewhere with my matrix generation. But unfortunately, I'm stumped. Any help would very much be appreciated!




Seeding 0.0 to 1.0 uniform pseudorandom generator with value outside of range

How does a random generator handle seeds outside of the bounds it is meant to return? For example, if I seed random in python with 10000 and then 5000 and call random.random() after each seeding, they each return different values.

I'm not familiar with pseudorandom number generating algorithms.

random.random() returns the next random floating point number in the range [0.0, 1.0)




'Random' Sorting with a condition in R for Psychology Research

I have Valence Category for word stimuli in my psychology experiment.

1 = Negative, 2 = Neutral, 3 = Positive

I need to sort the thousands of stimuli with a pseudo-randomised condition.

Val_Category cannot have more than 2 of the same valence stimuli in a row i.e. no more than 2x negative stimuli in a row.

for example - 2, 2, 2 = not acceptable

2, 2, 1 = ok

I can't sequence the data i.e. decide the whole experiment will be 1,3,2,3,1,3,2,3,2,2,1 because I'm not allowed to have a pattern.

I tried various packages like dylpr, sample, order, sort and nothing so far solves the problem.




What is wrong with my defintion of the function prompt_int?

I have been trying to program a maths quiz that both works and is as efficient as possible. Looking over my code I saw I had a lot of integer inputs and that lead to me having the program to ask the question/exit the system if the criteria isn't met, so to help me I thought that it would be useful to create a new function. Here is my attempt:

def prompt_int(prompt=''):
    while True:
        if status == prompt_int(prompt=''):
            val = input(prompt)
            if val in (1,2):
                return int(val)
                return true
        elif status != prompt_int(prompt=''):
            val = input(prompt)
            if val in (1,2,3):
                return int(val)
                return true
        else:
            print("Not a valid number, please try again")

However, when I try to implement this function around my code it doesn't work properly as it says that status isn't defined however, when I do define status it goes into a recursion loop. How can I fix this problem?

Here is my original code before i try to implement this function:

import sys
import random
def get_bool_input(prompt=''):
    while True:
        val = input(prompt).lower()
        if val == 'yes':
            return True
        elif val == 'no':
            return False
        else:
            sys.exit("Not a valid input (yes/no is expected) please try again")
status = input("Are you a teacher or student? Press 1 if you are a student or 2 if you are a teacher")# Im tring to apply the new function here and other places that require integer inputs
if status == "1":
    score=0
    name=input("What is your name?")
    print ("Alright",name,"welcome to your maths quiz."
            "Remember to round all answer to 5 decimal places.")
    level_of_difficulty = int(input(("What level of difficulty are you working at?\n"
                                 "Press 1 for low, 2 for intermediate "
                                    "or 3 for high\n")))
    if level_of_difficulty not in (1,2,3):
        sys.exit("That is not a valid level of difficulty, please try again")
    if level_of_difficulty == 3:
        ops = ['+', '-', '*', '/']
    else:
        ops = ['+', '-', '*']
    for question_num in range(1, 11):
        if level_of_difficulty == 1:
            number_1 = random.randrange(1, 10)
            number_2 = random.randrange(1, 10)
        else:
            number_1 = random.randrange(1, 20)
            number_2 = random.randrange(1, 20)
        operation = random.choice(ops)
        maths = round(eval(str(number_1) + operation + str(number_2)),5)
        print('\nQuestion number: {}'.format(question_num))
        print ("The question is",number_1,operation,number_2)
        answer = float(input("What is your answer: "))
        if answer == maths:
            print("Correct")
            score = score + 1
        else:
            print ("Incorrect. The actual answer is",maths)
    if score >5:
        print("Well done you scored",score,"out of 10")
    else:
        print("Unfortunately you only scored",score,"out of 10. Better luck next time")
    class_number = input("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")
    while class_number not in ("1","2","3"):
        print("That is not a valid class, unfortunately your score cannot be saved, please try again")
        class_number = input("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")
    else:
        filename = (class_number + "txt")
        with open(filename, 'a') as f:
            f.write("\n" + str(name) + " scored " + str(score) +  " on difficulty level " + str(level_of_difficulty))
        with open(filename, 'a') as f:
            f = open(filename, "r")
            lines = [line for line in f if line.strip()]
            f.close()
            lines.sort()
        if get_bool_input("Do you wish to view previous results for your class"):
            for line in lines:
                print (line)
        else:
            sys.exit("Thanks for taking part in the quiz, your teacher should discuss your score with you later")
if status == "2":
    class_number = input("Which classes scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3")
    if class_number not in (1,2,3):
        sys.exit("That is not a valid class")
    filename = (class_number + "txt")
    with open(filename, 'a') as f:
        f = open(filename, "r")
        lines = [line for line in f if line.strip()]
        f.close()
        lines.sort()
        for line in lines:
            print (line)




I am generating a list of coordinates on a square using

#include <random>
using namespace std;

int main(){

random_device rd;
long int seed = rd();
default_random_engine gen(seed);

double max=10.0, min=-10.0;
uniform_real_distribution<double> uni_real(min,max);

double random_x = uni_real(gen);
double random_y = uni_real(gen);

return 0;
}

I would like to ensure that there is a minimum distance between any two points. For my usage, this must hold when periodic boundary conditions are applied.

  • Preferred solution would be a built in method in the <random> library to this. Is there any?
  • Second best, any other package containing a fast way to perform the check (as long as it is easy to make use of).
  • Worst case, I can write my own basic script which would be O(n^2) as I am not too concerned with efficiency right now. Unless, there is some easy algorithm to implement that can do this.

Other questions around where either dealing with the third point or with other environment from <random>.




my program works sometimes but not always

im a beginner at c++ and im doing online tutorials and im doing my first challenge. the problem im having is that the stratergyRoll doesnt seem to work sometimes but does others leading me to believe the problem is with my random number generator. im using code blocks and sorry if the formatting is bad had a bit of trouble

here is the code

#include <iostream>
#include <string>
#include <random>
#include <ctime>

using namespace std;

int AmountOfYourMen(string FactionName1);
int AmountOfEnemyMen(string FactionName2);
int EndStatment(string GeneralName, string FactionName1, string FactionName2, int orgfaction1size, int faction1size, int orgfaction2size, int faction2size);
void BattleSim(int &faction2hp, int &faction1hp, int &faction1attack, int &faction2attack, int &faction1size, int &faction2size, int &orghpfaction1, int &orghpfaction2);

int main()
{

int faction1;
int faction2;
int faction1hp;
int faction2hp;
int faction1attack;
int faction2attack;
int faction1size;
int faction2size;
int orgfaction1size;
int orgfaction2size;
int orghpfaction1;
int orghpfaction2;
string FactionName1;
string FactionName2;
string GeneralName;

int ArmyMove;


mt19937 RandomGenerator(time(NULL));
uniform_int_distribution<int> StratergyRoll(1,4);
uniform_real_distribution<float> yourmove(0.0,1);
uniform_real_distribution<float> trapsuccess(0.0,1);


cout<<"Welcome General What Is Your Name"<<endl;
cin>>GeneralName;
cout<<"Welcome General "<< GeneralName <<endl;
cout<<"choose your faction Rome(1) Spartans(2) Carthage(3) Egypt(4) Greece(5)"<<endl;
cin>> faction1;
cout<<"now choose the enemy faction Rome(1) Spartans(2) Carthage(3) Egypt(4) Greece(5)"<<endl;
cin>> faction2;

if(faction1 == 1){
    FactionName1 = "Romans";
    faction1hp = 120;
    orghpfaction1 = 100;
    faction1attack = 100;
}else
if(faction1 == 2){
    FactionName1 = "Spartans";
    faction1hp = 45;
    orghpfaction1 = 45;
    faction1attack = 100;
}else
if(faction1 == 3){
    FactionName1 = "Carthaginians";
    faction1hp = 80;
    orghpfaction1 = 80;
    faction1attack = 60;
}else
if(faction1 == 4){
    FactionName1 = "Egyptions";
    faction1hp = 80;
    orghpfaction1 = 80;
    faction1attack = 70;
}else
if(faction1 == 5){
    FactionName1 = "Greeks";
    faction1hp = 80;
    orghpfaction1 = 80;
    faction1attack = 80;
}



if(faction2 == 1){
    FactionName2 = "Romans";
    faction2hp = 120;
    orghpfaction2 = 100;
    faction2attack = 100;
}else
if(faction2 == 2){
    FactionName2 = "Spartans";
    faction2hp = 45;
    orghpfaction2 = 45;
    faction2attack = 100;
}else
if(faction2 == 3){
    FactionName2 = "Carthaginians";
    faction2hp = 80;
    orghpfaction2 = 80;
    faction2attack = 60;
}else
if(faction2 == 4){
    FactionName2 = "Egyptions";
    faction2hp = 80;
    orghpfaction2 = 80;
    faction2attack = 70;
}else
if(faction2 == 5){
    FactionName2 = "Greeks";
    faction2hp = 80;
    orghpfaction2 = 80;
    faction2attack = 80;
}

faction1size = AmountOfYourMen(FactionName1);
orgfaction1size = faction1size;

faction2size = AmountOfEnemyMen(FactionName2);
orgfaction2size = faction2size;

if(StratergyRoll(RandomGenerator) ==1){
    cout<<"the "<< FactionName2 << " are charging strait ahead using no apparent stratergy what will you do"<<endl;
    cout<<"(1)charge them head on"<<endl;
    cout<<"(2)attempt to surround them"<<endl;
    cin>> ArmyMove;
    if(ArmyMove ==1){
        cout<<"you charge foward meeting your enemy head on"<<endl;
        cout<<" "<<endl;
        cout<<"<battle sounds>"<<endl;
        cout<<" "<<endl;
        BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
    }else
    if(ArmyMove == 2){
        if(yourmove(RandomGenerator) >=0.4){
            cout<<"you have successufuly surrounded your enemy your men get stat boosts"<<endl;
            faction1hp += 40;
            faction1attack +=40;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
            BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
            }while(faction1size >= 1 && faction2size >=1);
        }else
        if(yourmove(RandomGenerator) < 0.4){
            cout<<"your attempt at surrounding your enemy have failed your men loose stats"<<endl;
            faction1hp -= 50;
            faction1attack -= 50;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
            BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
        }
    }else


if(StratergyRoll(RandomGenerator)==2){
    cout<<"the "<< FactionName2 << " your enemy is advancing with their cavelry positoned far out on each side and have their infantry in the middle what will you do"<<endl;
    cout<<"(1) ignore the cavlery and charge their infantry head on"<<endl;
    cout<<"(2)tell your cavelry to meet the enemy cavelry head on and tell your infantry to move foward to engage"<<endl;
    cout<<"(3)hold your ground put spearmen on your flanks and at the back of your army"<<endl;
    cin>> ArmyMove;
    if(ArmyMove ==1){
        cout<<"you charge foward meeting your enemy head on"<<endl;
        cout<<" "<<endl;
        cout<<"<battle sounds>"<<endl;
        cout<<" "<<endl;
        BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
    }else
    if(ArmyMove == 2){
        if(yourmove(RandomGenerator) >=0.5){
            cout<<"your cavelry have defeated the enemy cavelry and are now out flanking your enemy. your men get stat boosts"<<endl;
            faction1hp +=50;
            faction1attack +=50;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
            BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
        }else
        if(yourmove(RandomGenerator) < 0.5){
            cout<<"your cavelry was defeated and the enemy cavelry is now out flanking your men. stats lost "<<endl;
            faction1hp -= 60;
            faction1attack -= 60;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
            BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
        }
    }else
    if(ArmyMove == 3){
        if(yourmove(RandomGenerator) >= 0.1)
        cout<<"your men hold their ground and their cavelry crashed into your speers getting slaughtered"<<endl;
        cout<<" this was a good plan stopping the flanking and increases your stats"<<endl;
        faction2attack -=50;
        faction2hp -= 50;
        cout<<" "<<endl;
        cout<<"<battle sounds>"<<endl;
        cout<<" "<<endl;
        BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
    }else
    if(yourmove(RandomGenerator) <= 0.1){
        cout<<"your men hold and their cavelry crashed into your speers"<<endl;
        cout<<"this seemed like a good plan however the cavelry broke through and you are now surounded"<<endl;
        cout<<"your men loose stats"<<endl;
        faction1attack -=50;
        faction1hp -= 50;
        cout<<" "<<endl;
        cout<<"<battle sounds>"<<endl;
        cout<<" "<<endl;
        BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
    }
}else
if(StratergyRoll(RandomGenerator)==3){
    cout<<"the "<< FactionName2 << " are holding position what will you do"<<endl;
    cout<<"(1)chage foward. if your enemy wont come to you, you go to them"<<endl;
    cout<<"(2)tell your archers to hide on the flanks further up than your army and send in a platoon of men to attack and try to draw your enemy into a trap"<<endl;
    cout<<"(3)approach slowly keeping your gard up"<<endl;
    cin>> ArmyMove;
    if(ArmyMove ==1){
        cout<<"you charge foward meeting your enemy head on"<<endl;
        if(trapsuccess(RandomGenerator)<0.4){
            cout<<"the enemy were hoping you would do this and have a trap in place. You take archer fire from each side"<<endl;
            cout<<"your men loose stats"<<endl;
            faction1hp -= 60;
            faction1attack -= 60;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
           BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
        }else
        if(trapsuccess(RandomGenerator)>0.4){
            cout<<"you were lucky the enemy had no plan in place"<<endl;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
            BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
        }
    }else
    if(ArmyMove == 2){
        if(yourmove(RandomGenerator) >=0.41){
            cout<<"your trap was a success your men get stat boosts"<<endl;
            faction1hp += 50;
            faction1attack +=50;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
            BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
        }else
        if(yourmove(RandomGenerator) <= 0.4){
            cout<<"your trap failed the enemy realised what you where doing and countered. stats lost "<<endl;
            faction2hp += 20;
            faction2attack += 40;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
            BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
        }
    }else
    if(ArmyMove == 3){
        if(yourmove(RandomGenerator) >= 0.25)
        cout<<"your men approach causiosly and spot a trap being set so you counter. stat boost"<<endl;
        faction1attack +=40;
        faction1hp += 40;
        cout<<" "<<endl;
        cout<<"<battle sounds>"<<endl;
        cout<<" "<<endl;
        BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
    }else
    if(yourmove(RandomGenerator) < 0.25){
        cout<<"your men are causious but dont detect the trap. stats lost"<<endl;
        faction2attack +=40;
        faction2hp += 40;
        cout<<" "<<endl;
        cout<<"<battle sounds>"<<endl;
        cout<<" "<<endl;
        BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
    }
}else
if(faction2 == 1){
    if(StratergyRoll(RandomGenerator) == 3){
        cout<<"the Romans are forming the Testudo formation"<<endl;
        cout<<"what will you do"<<endl;
        cout<<"(1) barrage them with arrows they dont stand a chance"<<endl;
        cout<<"(2) charge tell all your men to charge them"<<endl;
        cout<<"(3) fire arrows and do a cavelry charge"<<endl;
        cin>>ArmyMove;
        if(ArmyMove = 1){
            if(yourmove(RandomGenerator) >= 0.95){
                cout<<"you got lucky the Testudo formation was not set properly"<<endl;
                cout<<"you cut them down with your arrows. stat boost"<<endl;
                faction1attack += 60;
                faction1hp +=80;
                cout<<" "<<endl;
                cout<<"<battle sounds>"<<endl;
                cout<<" "<<endl;
                BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
            }
        }else
        if(ArmyMove == 2){
            cout<<"you charge your enemy head on"<<endl;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
            BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
        }else
        if(ArmyMove == 3){
            cout<<"good job the legions not at fighting cavelry and skirmishers seperatly"<<endl;
            cout<<"but not together. stat boost"<<endl;
            faction1attack += 50;
            faction1hp += 50;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
            BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
        }
    }else
    if(StratergyRoll(RandomGenerator) == 4){
        cout<<"your enemy has chosen the battle field carefully"<<endl;
        cout<<"the ground is flat and perfect for the enemy chariots"<<endl;
        cout<<"what will you do"<<endl;
        cout<<"(1) who cares they dont stand a chance against me"<<endl;
        cout<<"(2) shift your cavelry to more ruff ground and hope they follow"<<endl;
        cout<<"(3) bring spearmen to the front so they can take on the chariots"<<endl;
        cin>>ArmyMove;
        if(ArmyMove == 1){
            cout<<"the battle ground sutes the enemy they get stat boost"<<endl;
            faction2attack +=60;
            faction2hp +=60;
            cout<<" "<<endl;
            cout<<"<battle sounds>"<<endl;
            cout<<" "<<endl;
            BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
        }else
        if(ArmyMove == 2){
            if(yourmove(RandomGenerator)>= 0.4){
                cout<<"your tactics work and your enemy follow you off to ruffer terrain"<<endl;
                cout<<"losing their battle advantage and gaining advantage for yourself"<<endl;
                faction1hp += 60;
                faction1attack += 60;
                cout<<" "<<endl;
                cout<<"<battle sounds>"<<endl;
                cout<<" "<<endl;
                BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
            }else
            if(yourmove(RandomGenerator) < 0.4){
                cout<<"your plan fails and the enemy sees what you are doing"<<endl;
                cout<<"he drives your army back to their chosen battlefield"<<endl;
                cout<<"stats lost"<<endl;
                faction1hp -=30;
                faction1attack -=30;
                cout<<" "<<endl;
                cout<<"<battle sounds>"<<endl;
                cout<<" "<<endl;
                BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
            }
        }else
        if(ArmyMove == 3){
            if(yourmove(RandomGenerator) >= 90){
                cout<<"you got lucky the enemy chariots were untrained and your spearmen provail"<<endl;
                cout<<"stats increase"<<endl;
                faction1attack += 30;
                faction1hp += 30;
                cout<<" "<<endl;
                cout<<"<battle sounds>"<<endl;
                cout<<" "<<endl;
                BattleSim(faction2hp, faction1hp, faction1attack, faction2attack, faction1size, faction2size, orghpfaction1, orghpfaction2);
            }
        }
    }
}


if(faction1size <= 0){
    cout<<FactionName2 << " are victorious"<<endl;
    cout<<" "<<endl;

}else
if(faction2size <=0){
    cout<<FactionName1 << " are victorious"<<endl;
    cout<<" "<<endl;
}


EndStatment(GeneralName, FactionName1, FactionName2, orgfaction1size, faction1size, orgfaction2size, faction2size);


return 0;
}


int AmountOfYourMen(string FactionName1)
{
 //amount of your men
 int faction1size;

cout<<"how many "<< FactionName1 <<":";
cin>>faction1size;

return faction1size;

}

int AmountOfEnemyMen(string FactionName2)
{
  //amount of enemy men
 int faction2size;

cout<<"how many "<< FactionName2 <<":";
cin>>faction2size;

return faction2size;

}

int EndStatment(string GeneralName, string FactionName1, string FactionName2, int orgfaction1size, int faction1size, int orgfaction2size, int faction2size)
{
cout<<" "<<endl;
cout<<FactionName1<< " casulties:"<< orgfaction1size - faction1size<<endl;
cout<<FactionName1<<" men remaining:"<< faction1size<<endl;
cout<<" "<<endl;
cout<<FactionName2<< " casulties:"<< orgfaction2size - faction2size<<endl;
cout<<FactionName2<<" men remaining:"<< faction2size<<endl;
cout<<" "<<endl;

if(faction1size <= 0){
    cout<<"General "<< GeneralName <<" you have been defeated and discraced"<<endl;
    cout<<"you should must regain your honor by playing again and wining"<<endl;
}else
if(faction2size<=0){
    cout<<"General "<< GeneralName << " you were VICTORIOUS"<<endl;
    cout<<"continue your military superiority by playing again"<<endl;
 }
}

void BattleSim(int &faction2hp, int &faction1hp, int &faction1attack, int &faction2attack, int &faction1size, int &faction2size, int &orghpfaction1, int &orghpfaction2)
{
uniform_real_distribution<float> AttackRoll(0.0,1);
mt19937 RandomBattle(time(NULL));


do {
    if(AttackRoll(RandomBattle) >= 0.5){
        faction2hp -= faction1attack;
        if(faction2hp <= 0){
            faction2size -=1;
            faction2hp = orghpfaction2;
        }
    }
    if(AttackRoll(RandomBattle) >= 0.5){
        faction1hp -= faction2attack;
        if(faction1hp <= 0){
            faction1size -=1;
            faction1hp = orghpfaction1;
        }
    }
  }while(faction1size >= 1 && faction2size >=1);
}