samedi 31 janvier 2015

Deck of cards using a 3 dimensional array in Java

I'm making a deck of cards with a 3 dimensional array. But when I call the random card method, it says the card array has a null value even the I should be filling it with a double for loop?


I've looked up other posts on cards, but they are usually a 2 D or two different arrays, not 3D. Thanks for any of you time. If I'm way off in my coding/thoughts/post, please let me know, I'm pretty new to Java and stack.



import java.util.Random;
import java.util.Arrays;
public class Deck {

String Hearts, Diamonds, Spades, Clubs;
private String Suit;
private int Deck [][][];
private int card [][];


public void FreshDeck()
{
Deck = new int [][][]
{{{1,1},{2,1},{3,1},{4,1},{5,1},{6,1},{7,1},{8,1},{9,1},{10,1},{11,1},{12,1}}, //Hearts
{{1,2},{2,2},{3,2},{4,2},{5,2},{6,2},{7,2},{8,2},{9,2},{10,2},{11,2},{12,2}}, //Diamonds
{{1,3},{2,3},{3,3},{4,3},{5,3},{6,3},{7,3},{8,3},{9,3},{10,3},{11,3},{12,3}}, //Spades
{{1,4},{2,4},{3,4},{4,4},{5,4},{6,4},{7,4},{8,4},{9,4},{10,4},{11,4},{12,4}} //Clubs
};
}

private void setValue(int index, int value)
{
card[index][0] = value;
}
private void setSuit(int index, int suit)
{
card[index][1] = suit;
}
public int Value(int index)
{
return card[index][0];
}
public int Suit(int index)
{
return card[index][1];
}

public void setRandomCard()
{
Random randomCard = new Random();
int randomInt = randomCard.nextInt(51);
for (int i=0; i<12; i++)
{
for (int j=0; j<4; ++j)
{
card[i][j] = Deck[randomInt][i][j];
}
}

}
}




Random number generator in C not accepting input for play again?

it works until it asks the user to play again. It will prompt the user but automatically quit and go back to the command line. can somebody tell me what's going on? it doesn't give me any warnings and i can't think of a reason why, i've tried a few things. I'm new to C.



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

int main() {

char goAgain='y';
int theNum=0;
int guess=0;
int max=0;
do{
do{
printf("Enter a number over 99: ");
scanf("%d", &max);
if(max <= 99) {
printf("Please enter a number over 99");
}
}while(max <= 99);
srand(time(NULL));
theNum = (rand() % max) + 1;
do{
printf("Please enter a guess:\n ");
scanf("%d", &guess);
if(guess > theNum) {
printf("Too high\n");
}
else if(guess < theNum) {
printf("Too high\n");
}
else {
printf("That's correct!\n");
}
}while(theNum != guess);

printf("Would you like to play again? (y/n): ");
scanf("%c", &goAgain);
}while(goAgain == 'y');
return(0);
}




How to generate random numbers that re generate...?

I am making a game in java in which a disc is thrown through a hoop. The hoop's Y position is a random number and i would like to make this number change every time another hoop is generated.


Here is my code:





import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.util.Random;

@
SuppressWarnings("serial")
public class DiscHoopToss extends JPanel {

int x = 40;
int y = 150;
int xm = 0;
int ym = 0;
Random rng = new Random();
int r = rng.nextInt((220 - 20) + 1) + 20;

public DiscHoopToss() {
addKeyListener(new KeyListener() {

@
Override
public void keyTyped(KeyEvent e) {}

@
Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
ym = -4;
xm = 3;
}
}

@
Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
ym = 2;
xm = 3;
}
}
});
setFocusable(true);
}




private void moveDisc() {
x = x + xm;
y = y + ym;

if (y == 0) {
JOptionPane.showMessageDialog(this, "Don't let the disc go off the screen!", "Game Over", JOptionPane.ERROR_MESSAGE);
y = 150;
x = 40;
xm = 0;
ym = 0;
}

if (y == getHeight() - 20) {
JOptionPane.showMessageDialog(this, "Don't let the disc go off the screen!", "Game Over", JOptionPane.ERROR_MESSAGE);
y = 150;
x = 40;
ym = 0;
xm = 0;
}

}


@
Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

g2d.drawOval(x, r, 25, 55);

g2d.fillOval(650, y, 50, 20);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Toss the disc into the hoop!");
DiscHoopToss game = new DiscHoopToss();
frame.add(game);
frame.setSize(750, 350);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

while (true) {
game.moveDisc();
game.repaint();
Thread.sleep(10);
}
}
}






Generate random value at compiler time and forever

So, i don't know if i was completely clear in my question but what I'm trying to do is a simple concept: i want to while compiling a c# windows forms application a variable X assume a value i wont know. But EVERY time i execute the application without compiling it again, this value is the same (but you don't know). So what I'm asking is if exist the possibility to compile something that you don't know which value will be. The application will use this same variable with the same value each time, but every time you compile the application again, this variable would change.


I'm trying to implement a security algorithm that will be different for each distribution of my application, but i want to do this in a automatic way without changing manual paramters for each release of my application.


A simple example of what i mean:



  • (while compiling) i = rand().

  • (when executed the app) i = ? (some value you will never know, but will be the same every time you execute the application)





How to make a roulette?

I want to know how to make a basic roulette for android, with colors, and when you touch it, it will spin and a random space in the roulette will be selected. It is for a question game, the roulette will have categories in the roulette and then you will select a difficulty by buttons. But the thing i dont know how to do is the roulette.





How can I implement complex normal Gaussian noise?

I want to implement complex normal Gaussian noise in python or C.


Fig.1 shows what I want to implement. Fig.1


And first I implement it in python, like this.



import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pylab as pl

size = 100000
BIN = 70

x = np.random.normal(0.0,1.0,size)
y = np.random.normal(0.0,1.0,size)

xhist = pl.hist(x,bins = BIN,range=(-3.5,3.5),normed = True)
yhist = pl.hist(y,bins = BIN,range=(-3.5,3.5),normed = True)
xmesh = np.arange(-3.5,3.5,0.1)
ymesh = np.arange(-3.5,3.5,0.1)
Z = np.zeros((BIN,BIN))
for i in range(BIN):
for j in range(BIN):
Z[i][j] = xhist[0][i] + yhist[0][j]
X,Y = np.meshgrid(xmesh,ymesh)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_wireframe(X,Y,Z)
plt.show()


However, it is not complex Gaussian noise.


The output figure become Fig.2.Fig.2


I think Gaussian noises are addictive, however, why it become so different?


I already tried to change the parts of code



x = np.random.normal(0.0,1.0,size)
y = np.random.normal(0.0,1.0,size)


to



r = np.random.normal(0.0,1.0,size)
theta = np.random.uniform(0.0,2*np.pi,size)
x = r * np.cos(theta)
y = r * np.sin(theta)


however, the result was same.


Please tell me the correct implementation or equation of complex normal Gaussian noise.





6 different random unique numbers php [duplicate]


This question already has an answer here:




I have generated in an array 6 random numbers using the rand () function. I would like to ensure that none of these numbers are duplicates. I have written:



$lucky_numbers = array (rand (1,50), rand (1,50),rand (1,50),rand (1,50),rand (1,50),rand (1,50));
if ($lucky_numbers[0] == $lucky_numbers[1]) {
print "same"; $lucky_numbers[1]++;
}
if ($lucky_numbers[1] > 50) {
$lucky_numbers[1]= $lucky_numbers[1]- 6;
}


and then checked each consecutive number with a similar code. But something doesn´t work. Any ideas ? Thanks in advance.





Predictable Javascript array shuffle

I'm trying to predictably shuffle javascript arrays the same way each time the webpage is loaded.


I can shuffle the arrays randomly, but every time i reload the page it's a different sequence.


I'd like it to shuffle the arrays the same way every time the page loads. There are many arrays and they are part of a procedurally generated world.





C# Select random, unique, images from folder on button click

I'm working on a C# card game where I want images to be randomly selected on a button click. Once a card has been chosen, it has to be displayed to the user, and something has to happen so it can't be selected again. I got the first part down, a random image is selected and is shown to the user, but I can't make it so it can't be selected again. Sometimes a card is picked multiple times, sometimes no image is selected at all and I get the error image. This is the code so far.



public partial class Form1 : Form
{
private List<int> useableNumbers;

public Form1()
{
InitializeComponent();
// Creates a list of numbers (card names) that can be chosen from
useableNumbers = new List<int>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54};
settings = new Settings();
}

private void btnDrawCard_Click(object sender, EventArgs e)
{
this.setImage();
}

private void setImage()
{
// Checks if there are still numbers left in the List
if (useableNumbers.Count() == 0)
{
MessageBox.Show("The game has ended");
Application.Exit();
}
else
{
Random r = new Random();
int i = r.Next(useableNumbers.Count());
// Looks for the path the executable is in
string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + @"\images\";
// Looks up the image in the images folder, with the name picked by the Random class and with the extension .png
string image = path + i + ".png";
// Sets the image in the pictureBox as the image looked up
pictureBox1.ImageLocation = image;
// Removes the selected image from the List so it can't be used again
useableNumbers.RemoveAt(i);
}
}

private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}

private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
{
settings.Show();
}


To clarify it a little bit; I have a folder called 'images' in the same folder as the executable. Inside that folder, there are 54 images named '1' to '54' (52 normal cards and two jokers). The numbers in the useableNumbers List represent the imagenames inside that folder. When an image is selected, I want to remove that image's name from the List with useableNumbers.RemoveAt(i);. Although I do get the message 'The game has ended', I also get the aforementioned problems.


I feel like the useableNumbers.RemoveAt(i); doesn't change the indexes of the List, so when, say, '10' gets deleted, it keeps an index of 11 in stead of moving all values down by one, if you know what I mean.


I've also tried storing the images in a List, but couldn't get that to work either so that's why I did it like this. Still new to C#, so maybe there are better ways of doing it.


How can I fix the removing from the list, so I don't get the same image twice or more, or no image at all?





Randomize a generator

I want to check elements of an extremely long (over a billion elements) generator for a property. Obviously it is infeasible to check all the elements (that would take roughly 400 years). Currently, they are produced in an ordered fashion. In order for the small sample that I will have time to check to be more representative of the whole thing, I would like to access the generator randomly.


Is there any way to do this (as changing it to a list and doing random.shuffle is not possible)?





Random() efficiency in C++

I am writing function where I need to find the random number between 1 - 10. One of the easiest way is to use random() libc call. I am going to use this function a lot. But I don't know how efficient it will be. If any one has idea about efficiency of random() that will be a help ?


Also I notice that random() give the same pattern in 2 runs.



int main()
{
for(int i=0;i<10;i++)
{
cout << random() % 10 << endl;
}
}


Output 1st time :- 3 6 7 5 3 5 6 2 9 1


Second time also I got same output.


Then how come it's random ?





First call of rand() without seed() --> same number?

I am looking through a c program that is available for several OSs and produces inconsistent results among platforms for the exact same data. Looking because I lack some libraries to compile and debug it on my system.


I noticed that it calls rand() during initialization without calling srand(), probably because it needs only 1 random value. Now, I was wondering how does rand() behave in this case? Does it takes the operating system initial value of the random library ? I am currently hoping that this might explain the different results per platform, but I lack background knowledge to rand() and what happens if it is called without srand().


If it always returns an default-init value of the OS, it would explain why different platforms produces different results.


Thx for any input and sorry for the theoretic question - no code ^^.





How to get a random color in my create.js shape?

I want to have a random color where "Crimson" is defined



var stage = new createjs.Stage("demoCanvas");

var circle = new createjs.Shape();
circle.graphics.beginFill("Crimson").drawCircle(0, 0, 50);
circle.x = 100;
circle.y = 100;
stage.addChild(circle);
stage.update();




using random numbers in several states in UPPAAL

There is explained how to use generate random numbers in UPPAAL in the select statement of an edge. But it seems I can't use the value generated on other edges (say, I want to model a loop that will decrement a counter starting from a random integral value b , if I choose the starting point in the edge arriving to the looping state, I can't use update statements such as " b := b -1 "


Any idea how to overcome this issue?





poisson distribution always produces same instances at each run

I am trying to generate random arrivals via poisson distribution for my project. The code part:



#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <random>
#include <ctime>
int nextTime(double lambda,int timeslots,int PU_number);

int main()
{
srand(time(0));
//some code
nextTime(4,time_slots,PU_number);
}
int nextTime(double lambda,int timeslots,int PU_number)
{
int mat[PU_number][timeslots];
srand(time(0));
std::default_random_engine generator;
std::poisson_distribution<int> distribution(lambda);
int number;
int total=0;
for(int i=0; i< PU_number;i++)
{
total=0;
for(int j=0;j<timeslots;j++)
{
number = distribution(generator);
total+=number;
mat[i][j]=total;//another matrix, not relevant here
cout<<number<<" ";
}
cout<<endl;
}
return 0;
}


Above code always produces same numbers. what is wrong here?





Why does scala return a value out of range in this modulo operation?

This is a piece of code to generate random Long values within a given range, simplified for clarity:



def getLong(min: Long, max: Long): Long = {
if(min > max) {
throw new IncorrectBoundsException
}
val rangeSize = (max - min + 1L)
val randValue = math.abs(Random.nextLong())
val result = (randValue % (rangeSize)) + min
result
}


I know the results of this aren't uniform and this wouldn't work correctly for some values of min and max, but that's beside the point.


In the tests it turned out, that the following assertion isn't always true:



getLong(-1L, 1L) >= -1L


More specifically the returned value is -3. How is that even possible?





vendredi 30 janvier 2015

Android: Get random record in SQLite

I fetch records in my SQLite database like this.



spellId = extra.getString("spellId");
DBase db = new DBase(this);
db.open();
String[] data = db.getRecord(Integer.parseInt(spellId));
db.close();


And I'm wondering if I can get random data like this without using raw queries and cursor? Help, anyone? Thanks in advance! :)





How to explain this profilng data of Haskell random generator for huge memory usage and low speed?

I want to profile the speed of Haskell random generator, and my test case is to generate 1000000 double precision random numbers range from zero to one and calculate their sum. here is my code:



import System.Random
import System.Environment
import Control.Monad.State
import Data.Time.Clock
type Seed = Int
intDayTime :: IO Int
intDayTime = getCurrentTime >>= return.(floor.utctDayTime :: UTCTime->Int)
n = 1000000 :: Int
main :: IO ()
main = do
calc <- getArgs >>= return . (read ::(String->Int)).head
seed <- intDayTime
let calcit :: Int->Double
calcit 1 = calc1 n seed
calcit 2 = calc2 n (mkStdGen seed)
calcit _ = error "error calculating"
in print $ calcit calc
calc1 ::Int->Seed->Double
calc1 n initSeed =
let next :: Seed->(Double,Seed) -- my simple random number generator, just for test
myRandGen :: State Seed Double
calc :: Int->Int->Seed->Double->Double
next seed = let x = (1103515245 * seed + 12345) `mod` 1073741824 in (((fromIntegral x)/1073741824),x)
myRandGen = state next
calc _ 0 _ r = r
calc n c s r = calc n (c-1) ns (r + nv)
where (nv,ns) = runState myRandGen s
in calc n n initSeed 0
calc2 ::Int->StdGen->Double
calc2 n initSeed =
let myRandGen :: State StdGen Double
calc :: Int->Int->StdGen->Double->Double
next :: StdGen->(Double,StdGen)
next gen = randomR (0,1) gen
myRandGen = state next
calc _ 0 _ r = r
calc n c s r = calc n (c-1) ns (r + nv)
where (nv,ns) = runState myRandGen s
in calc n n initSeed 0


and I compile the code with



ghc profRandGen.hs -O3 -prof -fprof-auto -rtsopts


run with



./profRandGen.exe 1 +RTS -o # for calc1
./profRandGen.exe 2 +RTS -o # for calc2


and the profiling data for calc1 is



total time = 0.10 secs (105 ticks @ 1000 us, 1 processor)
total alloc = 128,121,344 bytes (excludes profiling overheads)


profiling data for calc1 is



total time = 1.48 secs (1479 ticks @ 1000 us, 1 processor)
total alloc = 2,008,077,560 bytes (excludes profiling overheads)


I can understand that the random generator in System.Randomwould be slower, but why would it be slower so much and why would it allocating much more memory?


I used tail recursion in my code and compiled wit -O3 option, why didn't I get constant memory usage?


is there anything wrong in my code? for example, is it because there being lazy evaluation that tail recursion is not optimized and a lot of memory is allocated? If so,How could this program be further optimized?





rand() giving same number each time [duplicate]


This question already has an answer here:




I'm using the rand() function to set up my game board, however every time I run my program it gives me the exact same values. I want the row/col positions to be random each time the program is run. Here's my code:



for (int x = 0; x < 30; x++)
{
int rowPos = (rand()%(21))+1;
int colPos = (rand()%(21))+1;
if(GetCellState(b, rowPos, colPos) != 7)
SetCellState(b, rowPos, colPos, 7);
else
--x;
}




C# need to add random response with switch statement


namespace _7._39
{
class Program
{
static void Main(string[] args)
{
string response1;
string response2;
string response3;
string response4;

Random resp = new Random();

bool correct = Question();// Create a value to call the question method

if (correct== true)// when the answer is true it return very good
{
Console.WriteLine("Very Good!");
}
else// when the answer is false it returns to try again
{
Console.WriteLine("No please try again");
}
}
public static bool Question()
{
Random rand = new Random();// we create a random number
int num = rand.Next(1, 9);// first random number between 1 and 9
int num1 = rand.Next(1, 9);// second random number between 1 and 9

int ans = num * num1;// the value of multiplication between 1 and 2

// asking what the two values are multiplied
Console.WriteLine("What is"+ num.ToString()+ "*" +num1.ToString());
// reads the users attempt
int attempt = int.Parse(Console.ReadLine());


if (attempt == ans)// when the attempt is equal to the answer
{
return true;// its returns true bool
}

else// if it is false it says no please try again
{
Console.WriteLine("No please try again");
return Question();// and creates a new question for the user
}
}
}
}


I need my correct== true and false to respond with a random response among 4 possible choices. I need to do this by doing a switch statement to issue each response. Also by using random to select which response comes up.


Very good!


Excellent!


Nice work!


Keep up the good work!


and 4 options for a false response as well





Random ">" sign appearing above a table in HTML

I wouldn't say I'm new to webdev (and coding in general), but I'm certainly not professional. I've been making a website for my flight school and on one of my pages, I've run into a problem: A random ">" appears above a table whenever the "" tag is included. I've been looking on Stack Exchange, Stack Overflow, and Google in general for about three hours now, and I've come up with nothing. This only happens on one page, and only with this table. Take out just the "" and it goes away; add it back in and it appears again. It will even show up in Chrome's Inspect Element (but not in the source code, obviously). I've rewritten this page so many times that I felt this was the last option. I'll attach the HTML source and the CSS so that you guys can take a look... Any help at all is much appreciated!!!



Rochester Air Center




<link rel="stylesheet" href="style1.css" type="text/css" />
<link rel="shortcut icon" href="/photos/favicon.ico" type="image/x-icon" />
<!-- InstanceEndEditable -->
<link rel="stylesheet" href="style1.css" type="text/css" />
<link rel="shortcut icon" href="photos/favicon.ico" type="image/x-icon" />
</head>
<body>
<div id="headerWrapper">
<div id="banner">
<img src="photos/banner.png" width="796px" height="44px"></img>
</div>
<div id="timeDiv">
<a href="conditions.html" id="time">Greenwich Mean Time:&nbsp;<iframe src="http://ift.tt/167inL2" frameborder="0" width="360" height="30" allowTransparency="true"></iframe></a>
</div>
</div>
<div id="navWrapper">
<nav class="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="parts.html">Parts and Licenses</a>
<ul>
<li><a href="part61.html">Part 61</a></li>
<li><a href="part141.html">Part 141</a></li>
<li><a style="cursor : pointer">Licenses</a>
<ul>
<li><a href="privateLicense.html">Private Pilots License</a></li>
<li><a href="ifr.html">Instrument Flight Rating (IFR)</a></li>
<li><a href="cpl.html">Commercial Pilots License (CPL)</a></li>
<li><a href="cfi.html">Certified Flight Instructor (CFI)</a></li>
</ul>
</li>
</ul>
<li><a href="pilotShopAndFacility">Pilot Shop and Facility</a></li>
<li><!--<a href="fleet.html">Fleet</a>--><a href="fleet-place-holder.html">Fleet</a>
<ul>
<li><!--<a href="150.html">Cessna 150</a>--><a href="plane-place-holder.html">Cessna 150</a></li>
<li><!--<a href="152.html">Cessna 152</a>--><a href="plane-place-holder.html">Cessna 152</a></li>
<li><!--<a href="172.html">Cessna 172</a>--><a href="plane-place-holder.html">Cessna 172</a></li>
<li><!--<a href="172sp.html">Cessna 172SP</a>--><a href="plane-place-holder.html">Cessna 172SP</a></li>
<li><!--<a href="182.html">Cessna 182</a>--><a href="plane-place-holder.html">Cessna 182</a></li>
<li><!--<a href="citabria.html">Citabria</a>--><a href="plane-place-holder.html">Citabria</a></li>
<li><!--<a href="pa28.html">Piper 28</a>--><a href="plane-place-holder.html">Piper 28</a></li>
<li><!--<a href="seneca.html">Piper Seneca</a>--><a href="plane-place-holder.html">Piper Seneca</a></li>
<li><a href="photos/redbird.pdf" target="_blank">Flight Simulator - Redbird</a></li>
</ul>
</li>
<li><a href="rates.html">Rates</a></li>
<li><a href="instructors.html">Instructors</a>
<ul>
<li><a href="alecMetildi.html">Alec Metildi</a></li>
<li><a href="christopherCaschette.html">Christopher Caschette</a></li>
<li><a href="edVorbach.html">Ed Vorbach</a></li>
<li><a href="josephSongin.html">Joseph Songin</a></li>
<li><a href="shawnFlickner.html">Shawn Flickner</a></li>
<li><a href="toddCameron.html">Todd Cameron</a></li>
<li><a href="royCzernikoski.html">Roy Czernikoski</a></li>
<li><a href="johnDougherty.html">John Dougherty</a></li>
<li><a href="danKindred.html">Dan Kindred</a></li>
<li><a href="robertMcNamara.html">Robert McNamara</a></li>
<li><a href="geraldFrumusa.html">Gerald Frumusa</a></li>
</ul>
</li>
<li><a href="http://ift.tt/164JWE0" id="schedule" target="_blank">Online Schedule</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
</div>
<div id="contentWrapper">
<div id="content">
<!-- InstanceBeginEditable name="content" -->
<table width="90%" cellspacing="1" cellpadding="1" class="rates" align="center">
<tbody>
<tr style="background-color : yellow; color : black">
<td>
<h3 class="ratesTable">Model</h3>
</td>
<td>
<h3 class="ratesTable">Callsign</h3>
</td>
<td>
<h3 class="ratesTable">Equipment</h3>
</td>
<td>
<h3 class="ratesTable">Aircraft Price per Hour</h3>
</td>
<td>
<h3 class="ratesTable">Instructor Price per Hour</h3>
</td>
<td>
<h3 class="ratesTable">Total Price per Hour</h3>
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Cessna 150
</td>
<td>
N225RA
</td>
<td>
VFR; VOR
</td>
<td>
$90.00
</td>
<td>
$55.00
</td>
<td>
$145.00
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Cessna 152
</td>
<td>
N714WS
</td>
<td>
VFR; VOR
</td>
<td>
$95.00
</td>
<td>
$55.00
</td>
<td>
$150.00
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Cessna 172M
</td>
<td>
N1126U
</td>
<td>
IFR; Dual VOR
</td>
<td>
$125.00
</td>
<td>
$55.00
</td>
<td>
$180.00
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Cessna 172M
</td>
<td>
N998RA
</td>
<td>
IFR; Dual VOR; Garmin 400 GPS
</td>
<td>
$125.00
</td>
<td>
$55.00
</td>
<td>
$180.00
</td>
</tr>>
<tr style="background-color : white; color : black; font-family : times">
<td>
Cessna 172M
</td>
<td>
N5270H
</td>
<td>
IFR; Dual VOR
</td>
<td>
$125.00
</td>
<td>
$55.00
</td>
<td>
$180.00
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Cessna 172SP
</td>
<td>
N225RA
</td>
<td>
IFR; Dual VOR; GPS; Autopilot
</td>
<td>
$140.00
</td>
<td>
$55.00
</td>
<td>
$195.00
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Cessna 182
</td>
<td>
N992RA
</td>
<td>
IFR; Dual VOR; GPS
</td>
<td>
$145.00
</td>
<td>
$55.00
</td>
<td>
$200.00
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Citabria
</td>
<td>
N197
</td>
<td>
VFR
</td>
<td>
$130.00
</td>
<td>
$55.00
</td>
<td>
$185.00
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Piper 28-200R
</td>
<td>
N827RA
</td>
<td>
IFR; VOR; GPS; Complex (Retractable Gear, Flaps, Constant Speed Propeller)
</td>
<td>
$140.00
</td>
<td>
$55.00
</td>
<td>
$195.00
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Piper Seneca II
</td>
<td>
N78SF
</td>
<td>
IFR; GPS; VOR
</td>
<td>
$275.00
</td>
<td>
$60.00
</td>
<td>
$335.00
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Full Motion Flight Simulator
</td>
<td>
Redbird
</td>
<td>
-
</td>
<td>
$65.00
</td>
<td>
$55.00
</td>
<td>
$120.00
</td>
</tr>
<tr style="background-color : white; color : black; font-family : times">
<td>
Ground Instruction
</td>
<td>
-
</td>
<td>
-
</td>
<td>
-
</td>
<td>
$55.00
</td>
<td>
$55.00
</td>
</tr>
</tbody>
</table>
<br />
<br />
</div>
</div>
<!-- InstanceEndEditable -->
</div>
</div>
<div id="foot">
<a href="faq.html" class="footer">Frequently Asked Questions</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
<a href="map.html" class="footer">Site Map</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
<a href="aboutUs.html" class="footer">About Us</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
<a href="contact.html" class="footer">Contact Us</a>
</div>
</body>


And here's my (related) CSS:



body { background-color : #000000; background-image : url('photos/background.jpg'); background-repeat : no-repeat; font-size: 13pt; background-attachment : fixed; color : #000000; font-family : arial }




table { font-size : 13pt; color : #000000; font-family : arial; text-align : center }
table.rates { font-family : times }
table.holder { background-color : #FFFFFF; color : #000000; text-align : center }
tr { font-size : 13pt; color : #000000; font-family : times; text-align : center }
td { font-size : 13pt; color : #000000; font-family : times; text-align : center }


I apologize for all of the overriding and such, I was having some problems, and once it worked, I left it... and yes, I am using Dreamweaver, and yes, I know it's not great for webdev anymore. Anyway... Thanks for any help!





Is a random number generator faster on Java than on C++? [on hold]

So I have been playing around with random numbers in both java and C++ and have noticed that when having a for loop repeating thousands of times, generating random numbers, the ones in java get generated some seconds after launch whilst in C++ it propably takes 30 seconds to generate the same amount of numbers. Is there any way to speed up this process in C++ or are the two languages using a total different way to create them?





How do I get a JS function resut to a HTML form?

I'm trying to build an app in js that would get a random question from an array that would combine with a random object from another array. So my app looks like this:



Array.prototype.random = function (length) {
return this[Math.floor(Math.random()*length)];
};



var country = [
{name:"Romania", capital: "Bucuresti"},
{name: "Bulgariei", capital: "Sofia"}
];
chosen_country = country.random(country.length);


var questions = [
"Which is the capital of ",
" is the capital of which country?"
];

var chosen_question = questions.random(questions.length);


function q() {
chosen_country;
chosen_question;
if(chosen_question == questions[0]){
return chosen_question + chosen_country.name + "?";
} else if(chosen_question == questions[1]){
return chosen_country.capital + chosen_question;
}

}
q();


So my app will generate a random question from the questions array and combine it with a random object from the country array:



  1. "Which is the capital of 'country x' ?"

  2. "'Capital x' is the capital of which country?"


I would like to know how get the random question generated with a button form in HTML. Afterwords I would like to answer the question within an input form and send the answer to be use in another function to check if the answer is corector not. Anyone having any idea? I have tried to use document.getElementById("que").innerHTML = q(); but I realy don't know how to use it properly. Is ther any other solutin or i could use some explenations how to use .innerHTLM





How to random generate objects on the X axis?

I am busy with a project of my own and I am having trouble at a certain part. I want to have a random that generates my pictureboxes on a random X axis location. I'll send you a pic of the looks of my application and below that, some code.


I am very new to programming so "high class" and very smart solutions are still unknown for me. If awnsering this question. Be kind please :)


enter image description here


As you can see. All the Black bars are alligned to eachother and the Y and foremost the X axis stays the same. So the game is predictable.. it only has one opening that the black picturebox on the bottom need to go trough..


Here is the method that I made for the position of my "enemys/black bars" Btw I added a field on top that has "int position on 0"



public int VijandPositie() // methode om de positie van de vijand te bepalen
{
positie += 1;
return positie;
}


I implemented this method into this timer_tick event.



private void timer1_Tick(object sender, EventArgs e) // timer voor het te laten bewegen van de vijanden
{
Vijand1.Top = VijandPositie();
Vijand2.Top = VijandPositie();
Vijand3.Top = VijandPositie();
Vijand4.Top = VijandPositie();
Vijand5.Top = VijandPositie();
Vijand6.Top = VijandPositie();
Vijand7.Top = VijandPositie();
Vijand8.Top = VijandPositie();

if (Vijand1.Top >= gbSpeelVeld.Height || Vijand2.Top >= gbSpeelVeld.Height || Vijand3.Top >= gbSpeelVeld.Height || Vijand4.Top >= gbSpeelVeld.Height || Vijand5.Top >= gbSpeelVeld.Height || Vijand6.Top >= gbSpeelVeld.Height || Vijand7.Top >= gbSpeelVeld.Height || Vijand8.Top >= gbSpeelVeld.Height)
{
positie = 0; // zorgt ervoor dat de positie gereset wordt op 0 en dan begint de pijl weer van boven af aan
score = Convert.ToInt32(lblScore.Text); // score wordt geconverteerd naar de label
score = score + 1;
lblScore.Text = score.ToString();
}


after the black bars reach the end of the screen they will get back on top again but the X axis location stays the same. I know that I have not putted a random inside yet.. so I know that this will not work. But I don't know where or how to implement the random to get the blackbars randomly on the X axis (Y axis is less important IMO).


Thanks in advance guys!





Improve random character output from string

I have a simple for loop that takes a string of characters and spits out 4 random ones, I use this to create game Id that is used in order to synchronize several users together. I feel like my method is not "random enough" and in some case can produce repetitive result even when character sting is that big. There is no need to store created game id's to compare against in order to see if they exist, I would, however, want to figure out a way to perform better random selection of characters from the string.



var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for( var i=0; i < 4; i++ )
{
gameId += characters.charAt(Math.floor(Math.random() * characters.length));
}


Edit: perhaps shuffling string before for loop could be a way?





first program in c, random number generator and have them guess it

i took java for a while and i'm switching over to C, this is my first program and i have to get a number over 99 from the user, create a random number from 1 to that number, and try to have them guess it. i'm having some troubles trying to get it to compile. can i get general tips and help as to what i'm doing wrong(why it won't compile)?



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

int main() {

char goAgain = "y";
int theNum = 1;
int guess;

do{
do{
printf("Enter a number over 99");
scan f("%d", &theNum);
if(theNum <= 99) {
printf("Please enter a number over 99");
}
}while(theNum <= 99);
do{

srand(time(NULL));
theNum = rand() % theNum+1;
printf("Please enter a guess");
scanf("%d", &guess);
if(guess > theNum) {
printf("Too high");
}
if(guess < theNum) {
printf("Too high");
}
else {
printf("That's correct!");
}
}while(theNum != guess);

printf("Would you like to play again? (y/n)");
goAgain = getchar();
while(getchar == "\n"){
}
}while(goAgain == "y");
return(0);
}




how to associate user to a nearest base station

This is the code in MATLAB to generate base station locations in a Voronoi tesselation but I need to generate users and to associate each user to a nearest base station.


Please help me and thanks in advance.



function [X Y init_n] = generate_ppp_square(params, lambda, r_total)

%%% generate a PPP in a square of dimensions 2r*2r centered at (0,0)
%assignparams;

lambda =0.1;
r_total =10;
cell_area = (2*r_total)^2;
init_n = poissrnd(lambda*cell_area);

%init_n = ceil(lambda*cell_area);
%UserPoints = sqrt(cell_area)*rand(init_n,2);
X = -r_total + 2*r_total*rand(init_n,1)
Y = -r_total + 2*r_total*rand(init_n,1)
voronoi(X,Y,'o');hold on




Add images to array, pick one at random and delete from array

So I just started programming in C# (I do know the basics though). With friends I sometimes play a card game where you have to pick a card and according to what's on it, we have to do a challenge and the loser has to take a drink. Just for fun, I want to make this game as a Windows Form Application. I'm having issues with the images though. I want to get them from a folder that's in the directory of the program executable and add them to an array. Then I want to randomly select one (with the Random class) when a button is clicked. Once a card has been picked, I want it to be deleted from the array so it can't be chosen again.


I've been looking through quite a bit of tutorials on SO and other places, but I can't find something that fully works. This one came closest, as it did select a random picture when a button was clicked and displayed it, but I didn't find a way to remove that picture from the array. How can I add the functionality to delete the image from the array?


Edit: I should've added that I've already tried some stuff that didn't work. I deleted that code though ('cause it didn't work), but I'll try some stuff again and post back when I can't make it work.





how to separate two variables

I have this codes,and my problem is that the image and the text appears in one div. How can I separate the text and display it to another div while the image appears also on another div. but still when i reload the page, image 1 will correspond to text 1.same with image 2 it should also appear with text 2.



<html>
<head>
<meta charset=utf-8 />
<title>Random Text Plus Image</title>
</head>
<body>
<div id="quote"></div>
<script>
(function() {
var quotes = [
{
text: "text1",
img: "image1.jpg"
},
{
text: "text2",
img: "image2.jpg",
}
];
var quote = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById("quote").innerHTML =
'<p>' + quote.text + '</p>' +
'<img src="' + quote.img + '">';
})();
</script>
</body>
</html>




Mathcad to Matlab - random processes and NPS

I'm trying to convert a simple Mathcad file into MATLAB script but results I get are just weird. Is there some kind of difference in rand functions? Am I forgetting something essential that differs those two environments?


This is how the Mathcad file looks like:


enter image description here


enter image description here


And this is code I'm currently using:



clear all
clc

N=100;
data=poissrnd(1000,N,N);
data2=zeros(N);
for l=1:N
for k=1:N
drozp=zeros(1,3);
eta_fot=data(l,k);
for m=1:eta_fot
ran=rand(1);
if ran<0.25
drozp(1)=drozp(1)+1;
elseif ran>=0.75
drozp(3)=drozp(3)+1;
else
drozp(2)=drozp(2)+1;
end
end
if (k>1) && (k<N)
data2(l,k)=data2(l,k)+drozp(2);
data2(l,k-1)=data2(l,k-1)+drozp(1);
data2(l,k+1)=data2(l,k+1)+drozp(3);
elseif k==1
data2(l,k)=data2(l,k)+drozp(2);
data2(l,N)=data2(l,N)+drozp(1);
data2(l,k+1)=data2(l,k+1)+drozp(3);
else
data2(l,k)=data2(l,k)+drozp(2);
data2(l,1)=data2(l,1)+drozp(3);
data2(l,k-1)=data2(l,k-1)+drozp(1);
end

end
end

data2 = data2 - mean(data2(:));
data_w = (1/sqrt(N))*fftshift(fft(data2, [], 2));

NPS1=(abs(data_w)).^2;
NPS2=sum(NPS1);
NPS=(1/N)*NPS2;

plot(NPS)


Now, I know it can run faster, originally this block:



for m=1:eta_fot
ran=rand(1);
if ran<0.25
drozp(1)=drozp(1)+1;
elseif ran>=0.75
drozp(3)=drozp(3)+1;
else
drozp(2)=drozp(2)+1;
end
end


looked like this:



[~,R] = histc(rand(1,eta_fot),cumsum([0;w(:)./sum(w)]));
R=a(R);
drozp=histc(R,a)


where:



a=1:3;
w=[0.25,0.5,0.25];


However I tried to get closer to the Mathcad file. Then again results I'm getting (no matter which way I do it) look just bad.


Is there something I'm missing? Something I've failed to understand? I'm at a loss.





Assigning data frame column values probabilistically

I am trying to create a data frame named "students" with four variables: Gender, Year (Freshman, Sophomore, Junior, Senior), Age, and GPA. The idea is to have a data frame that illustrates the four levels of measurement: nominal, ordinal, interval, and ratio.


At this point it looks something like this:



ID Gender Year Age GPA
1 Male Sophomore 0 3.9
2 Male Junior 0 3.3
3 Female Junior 0 3.6
4 Male Freshman 0 3.1
5 Female Senior 0 2.9


I'm having a problem with Age. I would like Age to be assigned based on a probability. For example, if a student is a Freshman, I'd like Age to be assigned along something like the following lines:



Age Probability
14 .47
15 .48
16 .05


I have a function to do that set up like this:



1: Age <- function(df) {
2: for (i in 1:nrow(df) {
3: if (df[i, 2] == "Freshman") {
4: df[i, 3] = 15
5: } else if {
6: continue through the years
7: }
8: }
9: }


My thinking is that I want to change the right side of the assignment in Line 4 to something that will assign the age probabilistically. That's what I cannot figure out how to do.


On a related note, if there's a better way to do it than what I'm considering, I'd be appreciative of hearing that.


And on a final note, I've Googled the web at large, queried the R forums on Reddit and Talk Stats, and searched the R tags on this site, all to no avail. I can't believe I'm the first person who's ever wanted to do something like this, so it occurs to me that maybe I'm phrasing the query wrong. If that's the case, any guidance there would also be appreciated.





How to count how many duplicates an array has in Php

I'm new to Php and today I came across the rand()-function. I'd like to fill an array with numbers created with this function and then count the number of its duplicates. I already tried it a first time, but somehow I seem to be on the woodway.



<?php

$numbers = array();


for ($i=0; $i < 100; $i++) {
$numbers[$i] = rand(0, 100);
}

//$numbers = array(12,12,12,12);
echo "random numbers generated.<br>";

$arrLength = count($numbers);
$arrWithDoubles = array();

for ($i=0; $i < $arrLength; $i++) {
//echo "start looping for i: ".$i."! numbers['i'] has the content".$numbers[$i].".<br>";
for ($x=$i; $x < $arrLength; $x++) {
//echo "looped for x: ".$x."! numbers['x'] has the content".$numbers[$x].".<br>";
if($numbers[$i] == $numbers[$x]) {
if($i != $x) {
//echo "pushed to 'arrWithDoubles'.<br>";
array_push($arrWithDoubles, $numbers[$x]);
}
}
}
}

echo "numbers of doubles: ".count($arrWithDoubles)."<br>";
echo "list of numbers which were double:<br>";
for ($i=0; $i < count($arrWithDoubles); $i++) {
echo $arrWithDoubles[$i];
echo "<br>";
}

?>




Create different type string in C# [on hold]

I need to create string with this model: a string example entered by user: 12345


My program should create combinations like:



21345
54321
32145
25413


and ...


Possibility of 12345


Change all char locations


Please help





jeudi 29 janvier 2015

Random Numbers, Column and Row. PHP

Please excuse me as this is my first post and I am fairly new to any type of programming. I hope my question is clear, I am using Excel references as I think this explains what I am trying to do best.


I am trying to generate random numbers for a pool. I have 8 rows of numbers and each row contains 10 spots, 0 to 9. I want to have a random number in each row and make sure the the number does not repeat in each row.


Example Grid - 8 columns wide x 10 rows long.


I am repeating this scrip for each column, but I am getting the same number is rows and I want make sure that does not happen.



for ($i=1; $i<=10; $i++) {
while (1) {
$duplicate = 0;
$num=rand(0,9);
for ($x=1; $x<$i; $x++) {
if ($NFC1[$x]==$num) { $duplicate = 1; }
}

if ($duplicate==0) {
$NFC1[$i]=$num;
break;
}
}
}


This is the results, as you can see I have random numbers is each column but not in each row.



"4";"8";"5";"5";"0";"4";"2";"7"
"5";"9";"4";"3";"9";"9";"9";"0"
"9";"5";"1";"1";"5";"8";"6";"1"
"7";"4";"6";"2";"6";"7";"3";"3"
"2";"6";"8";"4";"7";"2";"7";"5"
"0";"1";"0";"7";"2";"1";"4";"6"
"1";"7";"9";"9";"4";"3";"0";"4"
"3";"0";"3";"0";"3";"5";"5";"9"
"8";"2";"7";"8";"1";"6";"8";"2"
"6";"3";"2";"6";"8";"0";"1";"8"




How to generate random levels on this balance game

I'm trying to make a game with this mechanics: http://ift.tt/IBUwPr


I've been stuck for a couple of days on the generation of the levels. Probably some of you can guide me on how to approach this problem.


The game consists in placing objects of different weights on the sides of one or more balances, and the user has to determine which object is the heaviest using its logic.


The problem is that i'm not beeing able to place all the objects on the balances in a way that there is a 100% determinable solution. With this i mean that there may be some cases that regardless how much logic you have, you will never be able to determine which object is the heaviest.


One thing that i've been trying is to place randomly the objects on the balances but with some "rules". This rules are not currently enough to always have determinable levels.


Examples of the rules that i've tried are:


1) the heaviest object is always alone 2) the heaviest object cannot be less heavy than the sum of the weights of the objects on the other side of its balance, it can only have less or equal weight. etc


After trying a lot, i'm realizing that i must take into account the configuration of the other balances in order to know how to place the objects. The rules mentioned before only sees the objects on the current balance and not the others.


Can you please help me with this problem? Thank you!


Regards.





Generating random arrivals via Poisson process c++

There is something I didn't understand. I use the sample given from the cpp reference to generate numbers:



const int nrolls = 10; // number of experiments

std::default_random_engine generator;
std::poisson_distribution<int> distribution(4.1);

for (int i=0; i<nrolls; ++i){
int number = distribution(generator);
cout<<number<<" "<<endl;
}


(original code: http://ift.tt/15YoFeV )


This outputs: 2 3 1 4 3 4 4 3 2 3 and so on... First of all what those numbers mean? I mean do I have to sum them to create timing? For example: 2, (2+3)=5, (5+1)=6, (6+4)=10,..., and so on..


Secondly, my real question is, I need to produce both random arrivals for network packets and the size of packets. I mean, when the packets come and if packets come, what are the size of packets? How can I do that? I need something like that: http://ift.tt/1tALJLW





VS 2013- ASSIGN RANDOM NUMBERS WITHIN TEXTBOXES FROM LEAST TO GREATEST

Hello everyone I am having trouble with creating a number generator. Yes, another one. I’m using visual studio ultimate 2013, and I’m fairly new to it. I am trying to create a generator that gives the user the ability to change what numbers they want to be randomized. For instance randomizing odds only or evens only and displaying each result in its own separate textbox. I have figured that out even if it’s a rugged code, however I’m having a difficult time displaying the numbers in order from least to greatest without changing the numbers location relative to its assigned textbox. Essentially I want textbox2 to recognize whether or not it’s greater than textbox1, and if it’s not, then re-randomize a new number and continue to do so until that condition is met. I have tried using do, while, until, for loops and even tried using a delay, or sleep but I think this is beyond my scope because the program freezes on me. I have an example of my code below. Any help would be appreciated.



Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Randomize()
numbers = Int(9 * Rnd())
If numbers = "0" Then
TextBox1.Text = 2
End If
If numbers = "1" Then
TextBox1.Text = 4
End If
If numbers = "2" Then
TextBox1.Text = 6
End If
If numbers = "3" Then
TextBox1.Text = 8
End If
If numbers = "4" Then
TextBox1.Text = 10
End If
If numbers = "5" Then
TextBox1.Text = 12
End If
If numbers = "6" Then
TextBox1.Text = 14
End If
If numbers = "7" Then
TextBox1.Text = 16
End If
End Sub




How can I create simple random mathematical questions? [on hold]

I have to create a program that generates 10 simple mathematical questions at random using the mathematical operations of +, -, * and /. The numbers within the question also have to be between 0 and 12, so the program should take any 2 random numbers between 0 and 12 and select a random mathematical operation also at random. The user must also input their answer to the question correctly; their score will then be kept and shown on screen and at the end of the 10 questions the scoreboard will then display how many questions the user got correct.


Any ideas or solutions?


(I have already created a simple way to generate numbers and operations at random using .Next().)


Thanks for the help!





Transformation of distorted random sequences produces random sequences?

My program generates what might be called switch(x) sequences.


Here's a description the algorithm that produces them:



# define a switch(x) sequence of length n^2
def switch(x):
s = [] # define a bit string s:
s.append(random.choice([True, False])) # set its first bit randomly,
for i in range(1, n * n): # but for every subsequent bit i,
prior = s[i-1] # find its prior bit i-1,
shouldSwitch = x > random.random() # and with probability 1-x,
if shouldSwitch: s.append(not prior) # set i to opposite of its prior;
else: s.append(prior) # otherwise, have i = its prior.
return s


At x = .5, the sequence is thought to be a perfectly random sequence of bits. Deviating x distorts this randomness by producing sequences that either alternate or repeat bits too often.


I produced a program that computed the average alternation rate of a produced switch(x) sequence.



r = 0.0
for i in range(len(s)-1):
if s[i] != s[i+1]:
r = r + 1
rate = r/(len(s)-1)


Of course, I always obtain a rate relatively close to x when I put a switch(x) sequence through it, whatever x is. Like, within 1/100ths.


But suppose I transform my produced switch(x) sequence like so (where len(s) = n*n):



s1 = switch(x)
s2 = []
for i in range(n):
for j in range(n):
s2.append(s1[i + j*n])


Whenever I calculate the alternation rate for sequences transformed in this way, I always obtain a value really close to .5! The consistency is scary.


That doesn't make much sense to me, especially for values of x that are very close to 0 or 1. So I was hoping you could help me figure out what's going wrong.


Sorry if something's terrible about my style/efficiency.





turbo c coordinates to pixel conversion and random number gereration

I am making a simple game on Turbo C using graphic mode.I want to generate random numbers in my way. I found the technique to generate random number as:



*i=random(10000)%40;
*j=random(10000)%40;


& there is created a rectangle as:



*rectangle(0,0,400,400);


The aim is to randomize the above numbers i&j over the rectangular area but I don't understand how this is done and I can't understand when is pixel technique used in c graphic and when coordinates?


For example: If I want to write my name in coordinate point(50,2) then the co-ordinate technique seems to be used.


I tried to find out but I couldn't figure out about text mode and graphic mode yet.





python generate random strings of specific length, and a list of characters

I need a little program (inside another bigger one) that generates "random" strings. These strings have to be of a specific length, and the characters inside them, can't be just anything, but they have to be str(of any number from 1 to 9), Does any of you have any idea on how to do it? Thank you!





How do I create a method to grab a random value from another class?

I am trying to randomly grab integers from another class and cannot figure out how to get those values. The first class is my initial random number generator. The second class is the class I am trying to retrieve these numbers to. I have created a grab method but cannot figure out how to retrieve these random integers from class ArrayBag. Any help would be appreciated!



import java.util.Random;

public final class ArrayBag<T> implements BagInterface<T>
{
private final T[] bag;
private int numberOfEntries;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 6;
private static final int MAX_CAPACITY = 10000;

/** Creates an empty bag whose initial capacity is 6. */
public ArrayBag()
{
this(DEFAULT_CAPACITY);
System.out.print("Generating 6 random integers 1 - 6 in ArrayBag\n");

//Random loop to generate random numbers 1 to 6
Random rand = new Random();
for(int start=1; start <=6; start++)
{
int randInt = rand.nextInt(6);
System.out.println("Generated : " + randInt);
}
System.out.println("Finished\n");

} // end default constructor

This is my second class and method...

import java.util.Random;

public class PopulationBag
{
public PopulationBag()
{
ArrayBag ab = new ArrayBag();
LinkedBag lb = new LinkedBag();

}

/**
* Grab Method
*/

public int grab()
{
ArrayBag ab = new ArrayBag();
Random grab = new Random();
for(int start = 1; start <= 6; start++)
{
int randGrab = grab.nextInt(ab);
System.out.println("Randomly grabbed values : " + randGrab);
}
}

}




Can't find infinite loop in this while loop in Python

The code below produces an infinite loop that I can't quite place. Would you please help me find the infinite loop?



while count <= 25:
randnum = random.randint(1,25)
int(randnum)
rindex = randnum - 1
if randnum not in seats:
if seats[rindex - 1] and seats[rindex + 1] != 0:
seats[rindex] = randnum
count += 1
else:
count += 0
else:
count += 0




Unity script not doing anything, but dont get any errors either

Hey guys im pretty new to unity and coding in genereal but ive really tried to figure out why this script does not apply. The idea of the script is that is is supposed to spawn an object on a random location on the X-axis within the range +9 to -9 repeatedly, but it just spawn once at the start location of the object.Hope someone can point me in the right direction :) Here is the script, cheers!


using UnityEngine; using System.Collections;



public class SpawnOnXaxis : MonoBehaviour {

public GameObject Goodfood;
public int numToSpawn;
public Vector3 position;

void Awake()
{
Vector3 position = new Vector3(Random.Range(-9.0F, 9.0F), 10.5f, -1); // -9 på Xaxis - +9 ----- Y = 10.5 z = -1
}

void Start()
{
int spawned = 0;

while (spawned < numToSpawn)
{

position = new Vector3(Random.Range(-9.0F, 9.0F), 10.5f, Random.Range(-9.0F, 9.0F));

GameObject tmp = Instantiate(Goodfood, position, Quaternion.identity) as GameObject; // Quaternion.identity betyder "ingen rotation"

spawned++;
System.Threading.Thread.Sleep(500);
}
}


}





mercredi 28 janvier 2015

numpy random numpers in specified shape of any complexity

def shaperand(s): r = [] for i in s: if type(i) in [list,tuple]: r.append(shaperand(i)) else: r.append(np.random.rand()) return r


So,


shaperand([[1,2],[3,4,5],[6,7]])


results in:


[[0.27611814857329864, 0.6271028191307862], [0.6245245446787084, 0.743259931401167, 0.9061663248784034], [0.7236900927531255, 0.540622773908648]]


I didn't see a function to do this. If there's one it'd be faster. Is there a better, more nifty way to write this?





Parallel Computing using MPI in C

How to implement MPI-based parallel program to approximate π using monte carlo simulation in which instead of considering the entire circle, each process should only pick random points from within its own “patch”. For instance, if p = 9 processes, then domain will be partitioned into a 3 × 3 grid. And so each process will be responsible for one patch.


How to use rand function to choose points within the patch for the process? Also, how to allocate patches to processes?





How to properly use if else and else if

I am using codecademy courses and I'm learning how to make a rock paper scissors game out of randomizing numbers. It says I've done a "good job" but every time I try to properly get each one to properly show up to their respective conditions it messes up.


Please leave a comment pinpointing the error and tips on avoiding it in the future.


Conditions - 0 to .33 = Rock -.34 to .66 = Paper -.67 to 1 = Scissors


JS Code



var userChoice = prompt("Rock, Paper, or Scissors?");

var computerChoice = Math.random();

console.log(computerChoice);

if (computerChoice <= 0.33) {
console.log("Rock");
}

else if (0.34 < computerChoice < 0.66) {
console.log("Paper");
}

else {
console.log("Scissors");
}




Algorithm to generate random number of length 8 from the input of number length 16 without using any predefined function

I want to generate random number of length 8 from the input of 16 digit number without using any built in function . To achieve this can we use hash algorithm ? If yes then how ? Thanks in advance for any reply.





Fast, independent random draws / sample from a list in python - fixed probability, not total number

I'd like to draw a sample of items from a list, but I want to set the probability each item is included, not the total number of items to draw (so random.sample() does not work). I get the effect I want with the following code (where p is probability of inclusion, and items is the list of things):



[item for item in items if random.random() < p]


But it is very slow. Any suggestions for speeding it up?


Thanks!


Nick





Consecutive object creation using it's predecessors data

I currently have a school assignment, mainly focusing on Object Oriented Programming & using Collections.


I know how most of this is done, however I seem to have hit a snag: I coded my program so it makes 10 objects, puts them in a List<T> & then outputs them to a ListBox.


Which works fine, but for some reason, every single object is receiving the same exact values, even though they should be (pseudo)random.


Here's the object's class (named Boom), including it's constructor:



public class Boom
{
public static int aantalBomen = 0;
public enum boomType { Naald, Loof }

public boomType BoomType { get; set; }
public int VolgNr { get; set; }

private int aantalVogels;
public int AantalVogels
{
get { return aantalVogels; }
set
{
if (value >= 0 && value <= 10)
aantalVogels = value;
}
}

public Eekhoorn Eekhoorn { get; set; }

private int hoogte;
public int Hoogte
{
get { return hoogte; }
set
{
if (value >= 5 && value <= 10)
hoogte = value;
}
}

public bool eekHoorn = false;

public Boom()
{
aantalBomen++;
VolgNr = aantalBomen;
Random rnd = new Random();
Hoogte = rnd.Next(5, 11);
AantalVogels = rnd.Next(0, 11);
BoomType = (boomType)Enum.GetValues(typeof(boomType)).GetValue(rnd.Next(0, Enum.GetValues(typeof(boomType)).Length));
}

public void MaakEekhoorn()
{
Eekhoorn = new Eekhoorn();
eekHoorn = true;
aantalVogels = (int)Math.Round((double)(aantalVogels / 2), 0);
}
}


& Here's the loop which creates the 10 objects:



public List<Boom> Bomen = new List<Boom>();
for (int i = 1; i <= 10;i++ )
{
Bomen.Add(new Boom());
}


Finally, the code I'm using to test the creation of the objects:



for (int i = 0;i<10;i++)
{
lstBomen.Items.Add("VolgNr: " + bos.Bomen[i].VolgNr.ToString() + " AantalVogels: " + bos.Bomen[i].AantalVogels.ToString() + " BoomType: " +
bos.Bomen[i].BoomType.ToString() + " Hoogte: " + bos.Bomen[i].Hoogte.ToString());
}


I can't seem to figure out why my code keeps generating the exact same values for all 10 objects, resulting in output like this:


Output


If you need any more info, pertaining to code or anything connected to the program's execution, feel free to ask.





Error in sample.int(length(x), size, replace, prob) : invalid first argument

I am running the following lines of code and facing the above-mentioned error. Any ideas how to fix this?



install.packages("operator.tools")
X <- NULL
S <- NULL
remove.valuex <- NULL
N <- seq.int(1,25)

library(operator.tools)

repeat {

S<-sample(N ,1, replace = FALSE, prob = NULL)
S
if (S==1) {
remove.value<-c(S,S+1)
} else if (S==25) {
remove.value<-c(S,S-1)
}else {remove.value<-c(S-1,S,S+1)
}
remove.value

N <- N [which(N %!in% remove.value)]
N


if (is.null(N)) break }





Math.Random() giving properties to objects based on chance

I'm making an rpg, I want weapons in-game to have mods sort of Diablo 2 style. So far I want mods to be randomly generated based on percent chance, but I also want them to be selectable (when crafting). So I need 2 overloaded methods, one that doesnt require input and another that should take input to access the desired mod. Example:



Public class CopperSword extends Weapon{
private int coldDamage = 0;
private int physicalDamage = 2;

//- Available Mods only for this type of weapon
private String[] mods = {"Fiery" , "ColdSteel", "Raging"}
//Fiery has 10% chance to be given to a weapon, Coldsteel 10%, Raging 80%
//A weapon cannot have more than one mod added.

private int modLevel;
private String modSelected;
private String itemName;
private String baseItemName = " Copper Sword";

//In here the mod should be selected randomly and then set the String
//modSelected to one of the array of mods so it shows in the name.

private void modRandomSelection(){
//Stuff goes in here that selects the mod
modSelected = mods[i];
itemName = modSelected + baseItemName;
}

private void modCraftSelection(int mod){
//mod Int input is to select the mod from the array
}

}


I know I'm asking a lot here, but I would appreciate it a lot, I've spent most of the day figuring out how to draw items from my inventory to the screen and now Im a bit tired to figure out this one, but I would love if you guys gimme a hand D: I'm a total noob but trying my best. I'll give a big choco-cookie and a super-sized glass of milk to whoever helps me n.n


EDIT: Why is people downvoting? come on at least type in a comment what is wrong with the question I made. If not it just seems like griefing.





Probability of getting the same value using Math.random

The requirement is to send a unique id to database when user click on submit button. So I am using Javascript Math.random method. I just want to know what are the chances or possibility to get same number and what bit size of using Math.random.





Adding Rows in Google Fusion Tables

Just a quick question, everytime I hit "edit" "add row" it adds the row but not at the bottom of the table, it usually places it like 5-10 rows from the bottom and while it's not a huge deal it's just time consuming to move it and confusing at times because they're random rows all over now. Is their a setting or a certain way to add rows so they just get added to the bottom of the fusion table instead of randomly throughout?





Create variable $pathinfo and $random to get block 15 random lines of html file

I am working on a php website and would like to echo 15 random line from a html file. So far I just got 15 lines but the problem is I get the code from the html file and not 15 block lines from the text. How could I define 2 variables $pathinfo and $random to write my code in a way that gets me the correct solution?


My code:



<?php

$selected_file = $_POST['radio1'];
// get the filename of the file
$fileinfo = pathinfo($selected_file);
$filename = $fileinfo['dirname'] . DIRECTORY_SEPARATOR . $fileinfo['filename'];
$password = 'code';




if (isset($_POST['submitradio']))
{
echo '<div class="imageselected">';
echo '<img src="'.$selected_file.'" /></br>'.PHP_EOL;
echo '</div>';
// check to see if a html file named the same also exists
if(file_exists("$filename.html"))
{

echo "<form action='test_result.php' method='post'>";
echo '<div class="Password">';
echo 'Type in password to view full Script';

echo "<label><div class=\"Input\"><input type='password' name='passIT' value='passit'/></div>";
echo "<input type='submit' name='submitPasswordIT' value='Submit Password'/></div>";
echo '</div>';
echo '</form>';
echo "$filename.html shares the same name as $selected_file";



$lines = file("$filename.html");

for($x = 1;$x<=15;$x++) {

echo $lines [rand(0, count($lines)-1)]."<br>";
}
// end of forloop

}
// end of check
// start Sorrytext

else
{
echo '<div class="NoScript">';

echo "We apologize. No Script available for this movie.";
echo '</div>';
}

// end Sorrytext
}
// End of submitradio
if($_POST['submitPasswordIT']){
if ($_POST['passIT']== $password ){
echo "You entered correct password";
$dirs = glob("*", GLOB_ONLYDIR);
$pathinfo = ($dirs.'/'.$lines.'/html');
include($pathinfo);
}
else{
echo "You entered wrong password";
}
}

?>


Help would be very much appreciated:)





Randomize Image and Color Pair on Webpage

I'm looking to randomize a image and color pair on my webpage upon refresh. For example, when you refresh, it will show "img A" and "#999;", and next it might show "img B" and "#fff;"; basically, one image is paired with exactly one color, and that color never goes with a different image.


The tricky part is that I need the color to randomize under the css/div "a:hover{", and the image to randomize under a different id (i named it #scanner, if it helps)


So far I have this, but it isn't working. I'm not very experienced with javascript so I'm totally stuck (even though i probably just missed something very simple).



<script>

var colors = [["#CCCCCC", "http://ift.tt/1BxWP4E"], ["#7b9fb9", "http://ift.tt/1CMUzZf"], ["#3df756", "http://ift.tt/1BxWM9b"]];

var r = Math.floor(Math.random() * 4);
document.getElementById("scanner").innerHTML = "<font color=\"" + pairs[r][0] + "\"<img src=\"" + pairs[r][1] + "\">"

text.css('color', colors[col][0]);
</script>



<div id="scanner">
<script>
document.getElementById("scanner").innerHTML = "<img src = \"" + colors[col][1] + "\">"
</script>
</div>




Random Insult Generator (Randomizing Results)

I've written a random insult generator. It is fine, and works well to what I need. The problem is that when I run the program more than once, the insult is the same every time, unless I copy all the vars again. Here is my code:



var bodyPart = ["face", "foot", "nose", "hand", "head"];
var adjective = ["hairy and", "extremely", "insultingly", "astonishingly"];
var adjectiveTwo = ["stupid", "gigantic", "fat", "horrid", "scary"];
var animal = ["baboon", "sasquatch", "sloth", "naked cat", "warthog"];

var bodyPart = bodyPart[Math.floor(Math.random() * 5)];
var adjective = adjective[Math.floor(Math.random() * 4)];
var adjectiveTwo = adjectiveTwo[Math.floor(Math.random() * 5)];
var animal = animal[Math.floor(Math.random() * 5)];

var randomInsult = "Your" + " " + bodyPart + " " + "is more" + " " + adjective + " " + adjectiveTwo + " " + "than a" + " " + animal + "'s" + " " + bodyPart + ".";

randomInsult;
"Your nose is more insultingly stupid than a warthog's nose."
randomInsult;
"Your nose is more insultingly stupid than a warthog's nose."


What I'm trying to do is when I run randomInsult; again, I want a different result.





How to display array data in a grid?

I 've been stuck on this for ages and it's for classwork. Basically I'm trying to display array data into a text box, which will then be updated randomly. Please bear in mind I started coding recently and I barely get what I'm even doing.



import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.Scanner;
import java.io.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.util.Collections;
import java.util.*;

/**
* Write a description of class myWorld here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class myWorld extends World

{
/**
* Constructor for objects of class myWorld.
*
*/
public myWorld()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(600, 400, 1);


String[] list = new String[10];



int count = 0;
try{
Scanner s = new Scanner(new BufferedReader(new FileReader("words.txt")));
while(s.hasNext()) {
String item = s.next();
item.trim();
list[count] = item;
count++;

}

s.close();

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




}




}
catch(IOException ex)
{
System.out.println("Cannot read file");
System.exit(0);

}
grid grid1 = new grid();
addObject(grid1, 200, 200);

Random rgen = new Random();
for(int i=0; i<1; i++){
int randomPosition = rgen.nextInt(list.length);
String temp = list[i];
list[i] = list[randomPosition];
list[randomPosition] = temp;
System.out.println(list[0] + " " + list[1] + " " + list[2]);
System.out.println(list[3] + " " + list[4] + " " + list[5]);
System.out.println(list[6] + " " + list[7] + " " + list[8]);
}


}


}


That is my myWorld code. Below is the code for the grid.



import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
/**
* Write a description of class grid here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class grid extends Actor
{
/**
* Act - do whatever the grid wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()

{

{


GreenfootImage imgGrid = new GreenfootImage(355, 355);

imgGrid.setColor(new Color (0, 0, 255));
imgGrid.drawRect(0, 0, 350, 350);
imgGrid.drawLine(0, 350/3, 350, 350/3);
imgGrid.drawLine(0, (350/3)*2, 350, (350/3)*2);
imgGrid.drawLine(350/3, 0, 350/3, 350);
imgGrid.drawLine((350/3*2), 0, (350/3*2), 350);
Font font = new Font("Wide Latin", Font.BOLD, 25);
imgGrid.setFont(font);
imgGrid.drawString("night", 10, 30);
imgGrid.drawString("cell2", 125, 30);
imgGrid.drawString("cell3", 250, 30);
imgGrid.drawString("cell4", 10, 150);
imgGrid.drawString("cell5", 125, 150);
imgGrid.drawString("cell6", 250, 150);
imgGrid.drawString("cell7", 10, 275);
imgGrid.drawString("cell8", 125, 275);
imgGrid.drawString("cell9", 250, 275);
setImage(imgGrid);
}
}


}




Math.Random() Setting Limits

So I want a random number from 3-10 or 4-6, but that the lower the numbe the more chances it has to be selected, meanwhile the higher is the rarest, how do I do that?



private int bonusPoints;
private double randomBonusPoints = Math.Random() * 100;

bonusPoints = (int)randomBonusPoints;


What else could I add to limit the numbers it gives me?





Highchart x-axis shows label shows randomly

i'm dealing with a strange Highcharts error that's kind of random.




facts:



  • i'm making a weather chart with highcharts

  • the chain is: javascript highcharts -> converts to svg -> converts to png -> use mpdf to generate multiple page pdf with different charts

  • the data comes from an external xml, and its parsed with php




problem:




  • sometimes x-axis label shows date (day number + day label, ex: "10-Feb")




  • example of random error in label: http://ift.tt/1Bxuwn1






Anyone knows why this may happen?


Thanks!


(if you'd like i can post the code)