jeudi 31 mars 2016

Best random number generator for Learning Vector Quantization (LVQ) first weight

I random first weight for LVQ using java.util.random like this :

//random generator
private double RandomNumberGenerator(){
    java.util.Random rnd = new java.util.Random();
    return rnd.nextDouble();
}

//random data for weight
private void InitializeWeigths(){
    weights = new double[numberofcluster][inputdimension];
    for(int i=0;i<numberofcluster;i++){
        for(int j=0;j<inputdimension;j++){
            weights[i][j] = RandomNumberGenerator();
        }
    }
}

The problem is the result is not good enough, and it depends on the random number for accuracy, can you guys suggest me best random double number generator method or algorithm for this case?




What is a way I can make this raffle system code provably fair?

The following code is for a type of raffle, in which users deposit items to receive tickets. There amount of tickets they received is recorded in a weighted table. This is how the winner selection looks as the table is filled. I am using http://ift.tt/1VW9CcC for simplicity.

var rwc = require('random-weighted-choice');
var table = [
    { weight: 100, id: "user1"}
  , { weight: 120, id: "user2"} 
  , { weight: 400, id: "user3"} 
  , { weight: 2220, id: "user4"} 
];
var winner = rwc(table);

I want to make it provably fair by assigning the specific ticket numbers to users. Then using some kind of true random number gen with sha 2 to select a ticket number. This way the user can check that the ticket chosen was the ticket number the server generated. However I am new to Nodejs and web apps in general so I do not know how to code this type of function. Any hints or examples would be greatly appreciated.




prolog - generate list with random values

I am trying to generate a list with random values between 1 and 10, but when I run the code, I'm receiving "false"...

geraL(0,_).
geraL(C,Y):-
  C is C-1,
  random(1,10,U),
  Y = [U|Y],
  geraL(C,Y).


?-geraL(13,X).




Method without repeat

I have class called QuestionsAll with constructor

(label question, Button b1, Button b2, Button b3, Button b4)

and method called

questions(string question, string answer1, string answer2, string answer3, string answer4, Button correctanswer)

How I use it in my form:

Random rd = new Random();
int qu = rd.Next(0,4)
QuestionsAll q = new QuestionsAll(label1,Button1,Button2,Button3,Button4) //my question will be in label1, answer1 in Button1......)

if(qu == 1) q.questions("1+1 =", "1", "2", "3", "4", Button2)
if(qu == 2) q.questions("1+2 =", "1", "2", "3", "4", Button3)

And when you click in right question, question changes, but questions and answers repeat. How can i do it with no repeat?




Coin Flipper not working

i was bored, so i made a coin flipper thing, but I can't get it to work! i think the javascript thing works perfect, there is something wrong with the css stuff but I do not have any clue!

why is it not working?

here it is:

// Buttons
var ButtonFlip = document.getElementById("btnFlip");
var ButtonReset = document.getElementById("btnreset");
var ButtonChange = document.getElementById("btnchange");

// Texts
var DisplayLastValue = document.getElementById("lastvalue");
var DisplayCounter = document.getElementById("countertext");

// Other Variables
var flipper = document.getElementById("flipper");
var Counter = 0;
var Degrees = 0;
var CoinValue = "Heads";

// Functions
ButtonFlip.onclick = function() {
        if (Counter >= 1) {
                Counter = Counter + 1;
                DisplayCounter.innerHTML = Counter;
                DisplayLastValue.innerHTML = CoinValue;
        } else {
                Counter = 1;
                DisplayCounter.innerHTML = Counter;
        }

        var Value = Math.random();

        console.log("Original value: " + Value);
                if (Value >= 0.5) {
                        if (CoinValue == "Heads") {
                                CoinValue = "Heads";
                          Degrees += 1800;
                          flipper.style.webkitTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.MozTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.msTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.OTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.transform = "rotateY(" + Degrees + "deg)";
                        } else {
                                CoinValue = "Tails";
                          Degrees += 1800;
                          flipper.style.webkitTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.MozTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.msTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.OTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.transform = "rotateY(" + Degrees + "deg)";
                        }
                } else { // < 0.5
                        if (CoinValue == "Heads") {
                                CoinValue = "Tails";
                          Degrees += 1620;
                          flipper.style.webkitTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.MozTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.msTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.OTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.transform = "rotateY(" + Degrees + "deg)";
                        } else if (CoinValue == "Tails")  {
                                CoinValue = "Heads";
                          Degrees += 1620;
                          flipper.style.webkitTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.MozTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.msTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.OTransform = "rotateY(" + Degrees + "deg)";
                          flipper.style.transform = "rotateY(" + Degrees + "deg)";
                        }
                }
                console.log(Degrees);
}

ButtonReset.onclick = function() {
        console.log("Reset!");
        Counter = 0;
        if (CoinValue == "Heads") {
        } else if (CoinValue == "Tails")  {
                Degrees += 180;
                flipper.style.webkitTransform = "rotateY(" + Degrees + "deg)";
                flipper.style.MozTransform = "rotateY(" + Degrees + "deg)";
                flipper.style.msTransform = "rotateY(" + Degrees + "deg)";
                flipper.style.OTransform = "rotateY(" + Degrees + "deg)";
                flipper.style.transform = "rotateY(" + Degrees + "deg)";
                CoinValue = "Heads";
        }
        DisplayCounter.innerHTML = "";
        DisplayLastValue.innerHTML = "";
        console.log(CoinValue);
        console.log(Degrees);
}
html, body {
        background: url("http://ift.tt/22Sq0QQ") no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  background-repeat: no-repeat;
        color: white;
        font-weight: bold;
  text-align: center;
}

.flip-container {
        width: 250px;
        height: 250px;
  margin-left: auto;
  margin-right: auto;
}

.flipper {
        transition: 2s;
  -webkit-transition: 1.5s linear;
  -webkit-transform-style: preserve-3d;
}

.coinfront, .coinback {
        width: 250px;
        height: 250px;
  background-size: 100% 100%;
        border-radius: 100%;
        backface-visibility: hidden;
        position: absolute;
}

.coinfront {
  background-image: url('http://ift.tt/235pEmz');
  background-size: 100%;
  @include rotateY(0deg);
  z-index: 99;
}

.coinback {
  background-image: url('http://ift.tt/22Sq2rX');
  background-size: 100%;
  @include rotateY(0deg);
  z-index: 99;
}

.buttons {
  border-radius: 20px; 
  height: 32px; 
  width: 64px;
}
<div style="margin: 10px 10px 50px 10px;">
  <p>Number of flips: <b id="countertext"></b></p>
  <p>Previous value: <b id="lastvalue"></b></p>
  <div class="flip-container">
    <div class="flipper" id="flipper">
      <div class="coinfront" id="front">
      </div>
      <div class="coinback" id="back">
      </div>
    </div>
  </div>
  <br>
  <button id="btnFlip" class="buttons">
    Flip!
  </button>
  <button id="btnreset" class="buttons">
    Reset!
  </button>
</div>



Random function in Modelica

Hello,I need a function as random in C language. Maybe you will say that i can call C function, but the effect is not the same in visual c++ tool. So, I need your help. thanks.




Get all solutions to a query, that has no alternatives when queried

This may seem like an odd question that could simply be answered by the findall/3 predicate. However my problem is a little deeper than that.

So I have a predicate called ran_num/1 that returns one of five random numbers (that is I do not know what the numbers could be but there are only 5 of them).

When I run the predicate it returns this output as an example:

?- ran_num(X).
X = 2
?-

Note that there are no alternative answers, pressing ; will do nothing. Prolog is awaiting another query command.

If I run findall on this the result is:

?- findall(X, ran_num(X), L).
L = [2]
?-

Is there an inbuilt predicate or method I can implement that will get me all the possible numbers that can be generated? So for example I can get a list which is [2,60,349,400,401].

Assume I cannot change the ran_num/1 predicate to give me alternatives.




Random(staticSeed).Next() alternative that will never change implementation and is guaranteed consistent through versions

I'm looking for something similar like:

new Random(staticSeed).Next() 

but where I'm assured that the implementation will always be consistent through different .NET framework versions.

I'm specifically looking for something that:

...produces a sequence of numbers that meet certain statistical requirements for randomness.

...to quote the comment at the System.Random class.

  • Is there something like that in .NET or do I have to roll my own?
  • is there any specific recommended algorithm nowadays?

It's not used for security.




Shuffle database id

I have a database with songs. Every song have an unique id. How I can generate a random unique value for every id in database?

Example:

id | song name    
1  | song1  
2  | song2  
3  | song3

After shuffle

id | song name    
45 | song1  
96 | song2  
10 | song3  

Any idea?




Randomized algorithm for string matching

Question:

Given a text t[1...n, 1...n] and p[1...m, 1...m], n = 2m, from alphabet [0, Sigma-1], we say p matches t at [i,j] if t[i+k-1, j+L-1] = p[k,L] for all k,L. Design a randomized algorithm to find all matches in O(n^2) time with high probability.

Image:

enter image description here

Can someone help me understand what this text means? I believe it is saying that 't' has two words in it and the pattern is also two words but the length of both patterns is half of 't'. However, from here I don't understand how the range of [i,j] comes into play. That if statement goes over my head.

This could also be saying that t and p are 2D arrays and you are trying to match a "box" from the pattern in the t 2D array.

Any help would be appreciated, thank you!




mercredi 30 mars 2016

Image is not displayed when onclick

Functionality:

User navigate to the menu page where it shows a list of image brands. When user clicks on an individual image brand, a image description of the brand chosen will be displayed as a popup.

Therefore, lastly, when user click "Accept" in the image description. A third image of the brand image frame will be displayed on the last page.

What has been done:

All 3 groups of images are a list of images. Hence, I have grouped all of them into 3 different arrays, as:

var ImageMainMenu=["","","",....];
var ImageDescription=["","","",....];
var ImageBrandframe=["","","",....];

Secondly, I have randomised ImageMainMenu whenever a user enters the menu page. Thirdly, I have append the ImageDescription to each individual image in imageMainMenu. Lastly, I am stuck at calling the ImageBrandframe to each Image description.

var BrandNameArray = ["A", "B", "C", "D"];
var OfferArray = ["Aa", "Bb", "Cc", "Dd"];
var FrameArray = ["Aaa", "Bbb", "Ccc", "Ddd"];


var random_BrandIndex;
var random_BrandIndexArray = [];


$(function() {
  //To Set random Brand
  random_BrandIndexArray = [];

  //Re-create a randomised list of brands
  var BrandNameArrayBackup = JSON.parse(JSON.stringify(BrandNameArray));
  for (i = 0; i < $('#list').find('img').length; i++) {
    //To Set random Brand
    var random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
    //Assign Variable to generate random Brands
    var Brand = BrandNameArray[random_BrandIndex];
    random_BrandIndexArray.push(Brand);
    BrandNameArray.splice(random_BrandIndex, 1);
    $('#Brand_' + (i + 1)).attr('src', Brand);
    $('#Brand_' + (i + 1)).show();
  }
  console.log(random_BrandIndexArray);
  BrandNameArray = BrandNameArrayBackup;
});
//Choose Brand with popUp
function selectBrand(index) {

  $('#BrandDescription').fadeIn({
    duration: slideDuration,
    queue: false
  });
  //To append offer array list to randomised Brand set

  var storedBrand = random_BrandIndexArray[index - 1];
  console.log("storedBrand: " + storedBrand);
  var selectedIndex = -1;
  for (i = 0; i < BrandNameArray.length; i++) {
    if (BrandNameArray[i] == storedBrand) {
      selectedIndex = i;
      break;
    }
  }

  var selectedOffer = OfferArray[selectedIndex];

  $("#Description").attr('src', selectedOffer);
  console.log("selectedOffer: " + selectedOffer);
  $("#Description").show();
}

function BrandDescription() {
  idleTime = 0;

  $("#border_page").fadeOut(function() {
    $("#BrandDescription").fadeIn();
  });
}

function LikeBrand() {
  $('#BrandDescription').fadeOut({
    duration: slideDuration,
    queue: false
  });

  $('#Active_Camera').fadeIn({
    duration: slideDuration,
    queue: false,
    complete: function() {
      //To append offer array list to randomised Brand set

      var storedBrand = random_BrandIndexArray[index - 1];
      console.log("storedBrand: " + storedBrand);
      var selectedIndex = -1;
      for (i = 0; i < BrandNameArray.length; i++) {
        if (BrandNameArray[i] == storedBrand) {
          selectedIndex = i;
          break;
        }
      }

      var selectedFrame = FrameArray[selectedIndex];
      $("#Chosen_Photoframe").attr('src', selectedFrame);
      console.log("selectedOffer: " + selectedFrame);
      $("#Chosen_Photoframe").show();
    }
  });
  $("#CameraFeed").fadeIn({
    duration: slideDuration,
    queue: false
  });
}
<div id="ChooseBrand" align="center" style="position:absolute; width:1920px; height:1080px; background-repeat: no-repeat; display:none; z-index=3; top:0px; left:0px;">

  <div class="Container">
    <div id="list" class="innerScroll">
      <!--1st Row-->
      <img id="Brand_1" style="width:284px; height:140px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
      <img id="Brand_2" style="width:284px; height:140px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
      <img id="Brand_3" style="width:284px; height:140px; top:0px; left:650px; border:0px;" onclick="selectBrand('3');">
      <img id="Brand_4" style="width:284px; height:140px; top:0px; left:965px; border:0px;" onclick="selectBrand('4');">
    </div>
  </div>
</div>

<div id="BrandDescription" class="menu" align="center" style="position:absolute; width:1920px; height:1080px; background-repeat: no-repeat; display:none; top:0px; left:0px; z-index=10;">

  <img id="Description" style="position:absolute; top:124px; left:4px; z-index=99;">

</div>


<div id="Active_Camera" align="center" style="position:absolute; width:1080px; height:1920px; background-repeat: no-repeat; display: none; z-index=14; top:0px; left:0px; ">

  <!--Photoframe that is selected from brand chosen-->
  <img id="Chosen_Photoframe" style=" position:absolute; width:1920px; height:1080px; top:0px; left:0px;">
</div>

Issue: I have managed to get the image Description to display when user clicks on the individual imageBrand. However, when I click on accept in imageDescription, the imageBrand frame is having an issue.

I have tried using the same method as of function selectBrand(index). However, when run, it kept returning the error msg of : "uncaught referenceError: index is not defined". I am aware that in general the method to get the imageBrandframe is the same as the method to get the imageDescription in function selectBrand(index). however at this point, I am stuck as it is not calling due to error in index is not defined.

Please help. thank you.




Shuffle: Why is a for loop switching arr[i] with arr[r] (r : random 0 - length - 1) not a uniformly random shuffle?

I am currently taking Sedgewick's algorithms course on Coursera (taught in java). He says to create a uniformly random shuffling algorithm, I must go through each index i in my array, swapping that element with a random element FROM ONLY THOSE ELEMENTS I'VE ALREADY LOOKED OVER. He says if I were to swap the element with a random element out of the entire array, it wouldn't be uniformly random. Please explain why not? If for every iteration element[i] is swapped at complete random with another element in the array, including itself, than 1/N is always the probability of where element[i] will end up; I don't see how bias is introduced.

in other words he advocates :

for (var i = 0; i < arr.length; i++){
  var r = Math.floor(Math.random() * i + 1)
  swap(r, i);
}

over

for (var i = 0; i < arr.length; i++){
  var r = Math.floor(Math.random() * arr.length)
  swap(r, i);
}

Excuse the JavaScript as I am a brand new programmer and am more comfortable with it. Also please let me know if I have any fundamental misunderstandings with regards to how random numbers work, thank you :)




Seeded Python RNG showing non-deterministic behavior with sets

I'm seeing non-deterministic behavior when trying to select a pseudo-random element from sets, even though the RNG is seeded (example code shown below). Why is this happening, and should I expect other Python data types to show similar behavior?

Notes: I've only tested this on Python 2.7, but it's been reproducible on two different Windows computers.

Similar Issue: The issue at Python random seed not working with Genetic Programming example code may be similar. Based on my testing, my hypothesis is that run-to-run memory allocation differences within the sets is leading to different elements getting picked up for the same RNG state.

So far I haven't found any mention of this kind of caveat/issue in the Python docs for set or random.

Example Code (randTest produces different output run-to-run):

import random

''' Class contains a large set of pseudo-random numbers. '''
class bigSet:
    def __init__(self):
        self.a = set()
        for n in range(2000):
            self.a.add(random.random())
        return


''' Main test function. '''
def randTest():
    ''' Seed the PRNG. '''
    random.seed(0)

    ''' Create sets of bigSet elements, presumably many memory allocations. ''' 
    b = set()
    for n in range (2000):
        b.add(bigSet())

    ''' Pick a random value from a random bigSet. Would have expected this to be deterministic. '''    
    c = random.sample(b,1)[0]
    print('randVal: ' + str(random.random()))           #This value is always the same
    print('setSample: ' + str(random.sample(c.a,1)[0])) #This value can change run-to-run
    return




Random value witout if?

Random rd = new Random();
int question;
question = rd.Next(1,2);
if(question ==1)
{
label1.Text = "What is your name?";
}
if(question ==2)
{
label1.Text = "How old are you?";
}

Is there a way how to make it shorter? I need to do it this way, but find the shorter option, preferably witout if.




Randomly add numbers to a N x M zero matrix

I wanted to know how I can go about randomly placing numbers (up to 10 numbers) in a matrix.

I am starting with A = zeros(5,8), then randomly place the 10 random numbers around the matrix.

Thanks.




128/256 or more Pseudo-Random number generator implementation in C

Is there any library in C that can help me generate streams of random numbers by controlling the state of the random number generator at each generation? Similar to this

=) Rand(Some_Initial_State) --> random number X

=) Rand(X + Some_Variable)  --> random number Y

=> Rand(Y + Some_Variable)  --> ............. etc

Matlab let me do this with rng function, but for maximum of 48-bit numbers, I want a larger scope.

I wasn't able to control the seeding in OpenSSL, if it is possible I prefer OpenSSL.

Any help??




Extract random values from list that fulfil criteria? Python

Is it possible to use the random module to extract strings from a list, but only if the string has a length greater than x?

For example:

list_of_strings = ['Hello', 'Hello1' 'Hello2']

If you set x = 5 and call random.choice() the code would be 'choosing' between only list_of_strings[1] and list_of_strings[2].

I realise you could make a second list which contains only values of len > x but i would like to know if it is possible without this step.




Is there a good way to share the seed of random between modules (in python)?

I have a project with different main files (for different simulations). When I run one of the mainfiles, it should set a seed to random (and numpy.random), and all the modules in the project should use that seed.

I don't find a good way to do this. I have a file globals.py with this:

import random

myRandom=None


def initSeed(seed):
    global myRandom
    myRandom =random.Random(seed)

then from a main I do:

if __name__ == "__main__":

    seed=10
    globals.initSeed(seed)
...

Then in the modules that main calls, I do:

from globals import myRandom

But myRandom has the value None in the module (even though I modified it in main!). Why, and how to fix it? Is there a nicer way?




Second image is not displayed correctly when first image is clicked

Functionality:

When user clicks on a first image, the second image will fade in and be displayed. The second image is a child of the first image. Therefore, the second image shown has to be connected with the first image.

For e.g: there are 4 images and they are grouped in an array. for first imagevar firstImage= ["image1", "image2", "image3", "image4"] for second imagevar secondImage= ["image1a", "image2a", "image3a", "image4a"]

therefore, when I click on "image1", the corresponding image that will fade in will be "image1a"

What I have done:

As stated above:

1.) I have grouped the 2 different images into an array 2.) I have randomised the first array of images and it is displayed in the list in a randomised manner. 3.) I have tried to append the second image to the first image when clicked.

This is my code:

 var slideDuration = 1200;
 var idleTime = 0;
 var BrandNameArray = ["http://ift.tt/1q0PSsB?", "http://ift.tt/1BE5xku", "http://ift.tt/1q0PSsB?", "http://ift.tt/1BE5xku"];

 var OfferArray = ["http://ift.tt/1BE5xku", "http://ift.tt/1q0PSsB?", "http://ift.tt/1BE5xku", "http://ift.tt/1q0PSsB?"];



 $(function() {

   //Auto populate into brand container once randomised for each Brand image
   var BrandNameArrayBackup = JSON.parse(JSON.stringify(BrandNameArray));
   for (i = 0; i < $('#list').find('img').length; i++) {
     //To Set random Brand
     var random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
     //Assign Variable to generate random Brands
     var Brand = BrandNameArray[random_BrandIndex];
     BrandNameArray.splice(random_BrandIndex, 1);
     $('#Brand_' + (i + 1)).attr('src', Brand);
     $('#Brand_' + (i + 1)).show();
     console.log(Brand);
   }
   BrandNameArray = BrandNameArrayBackup; //re-assigning values back to array
 });

 function selectBrand(index) {

   $('#Vivo_BrandDescription').fadeIn({
     duration: slideDuration,
     queue: false
   });

   var chosenBrandIndex = OfferArray[index];
   //Set option clicked to CSS change 
   $('#Description').attr('src', chosenBrandIndex);
   $('#Description').show();
 }

 function Vivo_BrandDescription() {
   idleTime = 0;

   $("#border_page").fadeOut(function() {
     $("#Vivo_BrandDescription").fadeIn();
   });
 }
<div id="ChooseBrand" align="center" style="position:absolute; width:1920px; height:1080px; background-repeat: no-repeat;z-index=3; top:0px; left:0px;">

  <div class="Container">
    <div id="list" class="innerScroll">
      <!--1st Row-->
      <img id="Brand_1" style="width:284px; height:140px; top:0px; left:0px; border:0px; outline:0px" data-brand="1">
      <img id="Brand_2" style="width:284px; height:140px; top:0px; left:330px; border:0px;" data-brand="2">
      <img id="Brand_3" style="width:284px; height:140px; top:0px; left:650px; border:0px;" data-brand="3">
      <img id="Brand_4" style="width:284px; height:140px; top:0px; left:965px; border:0px;" data-brand="4">

    </div>
  </div>
  <div id="BrandDescription" class="menu" align="center" style="position:absolute; width:1920px; height:1080px; background-repeat: no-repeat; display:none; top:0px; left:0px; z-index=10;">

    <img id="Description" style="position:absolute; top:124px; left:534px;z-index=11;">
  </div>

Issue:

At this point in time, is that when I click on a random image, the corresponding image is not correctly displayed.

For example, when I clicked on "image1", the resulting image that faded in is displaying "image4a" instead of "image1a". All first array images have been randomised.

Hence, what have I done incorrectly or not done. Please help, thanks.




PRNG for ARM Assembly?

I'm having issues implementing a PRNG for ARM Assembly. I've tried a few algorithms that while working, end up taking a long time after the first few random number iterations, probably because the division (modulo) step takes a long time on large numbers. I'm trying to get a random number between 0 and 31. I've given my rough work below, with letters substituting specific registers.

start:

mov t, x            // t = x

// t ^= t << 11
lsl temp, t, #11
eor t, temp

// t ^= t >> 8
lsr temp, t, #8
eor t, temp

// z = w
mov z, w

// x = y
mov x, y

// y = z
mov y, z

// w ^= w >> 19
lsr temp, w, #19
eor w, temp

// w ^= t
eor w, t

// r0 is the RETURNED RANDOM NUMBER
mov result, w

That's my algorithm that I tried to implement from the XORSHIFT page on wikipedia. I just need this to return a random number from 0 to 31, so implementing division on a 10-digit number takes a while and seems pretty overkill. If anyone can help me optimize or point out a mistake I'd appreciate it.

edit: The above subroutine returns the random number, and then I basically divide it by 31 (that code isn't given here) and take the remainder as my "random" number from 0 to 31.




mardi 29 mars 2016

How can I generate a random number between 0-5 in Swift? [duplicate]

This question already has an answer here:

I have only been coding in my off time for a couple of weeks now and am creating an app with a very basic "guess how many" concept. The user will enter a number between 0-5 and the app will tell the user whether they are right or wrong.

How would I generate a number between 0-5?




VBA/Macro to get or copy random rows based on keywords

enter image description here

I need help to be able to get/copy random rows from another workbook with specific conditions:

source: rawdata.xlsx "Sheet1"

destination: tool.xlsm "Random Sample"

"AU", "FJ", "NC", "NZ", "SG12" are located in the first column (Column A). Attached screenshot shows how my rawdata.xlsx looks like.

If i click a button/run a macro, I should get

  • 4 random rows for all rows that has "AU"
  • 1 random row for all rows that has "FJ"
  • 1 random row for all rows that has "NC"
  • 3 random rows for all rows that has "NZ"
  • 1 random row for all rows that has "SG12"

All FROM rawdata.xlsx "Sheet1" and paste it to tool.xlsm "Random Sample".

All should happen in one click. It has been almost a month and i still got no luck being able to get answer to this question. I hope someone could help me out. Thanks.

Here is my code to get/copy random sample but without condition. I hope anyone can modify this.

Sub CopyRandomRows()

'Delete current random sample

 Sheets("Random Sample").Select
    Cells.Select
    Range("C14").Activate
    Selection.Delete Shift:=xlUp


'Remove duplicates in raw data file

Windows("rawdata.xlsx").Activate
Sheets("Sheet1").Select
Cells.RemoveDuplicates Columns:=Array(2)


'copy the header before pasting random rows

    Windows("rawdata.xlsx").Activate
    Rows("1:1").Select
    Selection.Copy
    Application.CutCopyMode = False
    Selection.Copy
    Windows("tool.xlsm").Activate
    Sheets("Random Sample").Select
    Rows("1:1").Select
    ActiveSheet.Paste


Dim source As Range, target As Range, randCount&, data(), value, r&, rr&, c&


  ' this defines the source to take the data

  With Workbooks("rawdata.xlsx").Worksheets("Sheet1")
    Set source = .Range("A1:" & .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, .Cells(1, .Columns.Count).End(xlToLeft).Column).Address)
    End With

  ' this defines the target to paste the data

  Set target = Workbooks("tool.xlsm").Worksheets("Random Sample").Range("A2")

  ' this defines the number of rows to generate based on the input in textbox


  randCount = 4



  ' this load the data in an array

  data = source.value

  'this shuffle the rows

  For r = 1 To randCount
    rr = 1 + Math.Round(VBA.rnd * (UBound(data) - 1))
    For c = 1 To UBound(data, 2)
      value = data(r, c)
      data(r, c) = data(rr, c)
      data(rr, c) = value
    Next
  Next

  ' this writes the data to the target

  target.Resize(randCount, UBound(data, 2)) = data


End Sub




Random number generator, how to get random numbers that are not the same

I am making a random number generator but I do not want the numbers over again. so for example

[1,2,3,4] is perfect - [1,1,2,4] is not what I want because a number recurring.

I have looked on here and no one has the answer to the problem I am searching for, in my logic this should work but I do not know what I am doing wrong.

I am new to python and I saw a couple questions like mine but none with the same problem

import random, timeit
random_num = random.randint(1,10)
cont_randomized_num = random.randint(1,10)
tries = 0
start = timeit.default_timer()
num_guess = 0
stored_numbers = []

while cont_randomized_num != random_num:
    if cont_randomized_num == stored_numbers:
        cont_randomized_num = random.randint(1,10)
    elif cont_randomized_num != stored_numbers:
        print(num_guess)
        stored_numbers.append(cont_randomized_num)
        print(stored_numbers)
        cont_randomized_num = random.randint(1,10)
        tries +=1

print()
print()
stop = timeit.default_timer()
print(random_num)
print('Number of tries:',tries)
print('Time elapsed:',stop)
input('press ENTER to end')




random number in constructor c#

I am a student taking an introductory programming course in line with game development. One of my assignments calls for me to define a players attack damage inside of the constructor. I want the damage to be random, but no matter what I do I get back the same number. This is a test I made to see how I can get this number to be random.

class MainChar
{
    public static Random random = new Random();
    public int Atk;        

    public MainChar()
    {
        this.Atk = random.Next(11);
    }

    public void h()
    {
        while (Atk != 10)
        {
            Console.WriteLine(Atk);

        }
    }
}

I'm creating a new instance of MainChar in my main program, and running h(). I get a repeating list of the same number instead of random numbers between 1 and 10. Any ideas?

P.S. This was useful, but could not answer my question.




Generate some "random" start times for scripts to run based on a period of time in python

I'm trying to generate some random seeded times to tell my script when to fire each of the scripts from within a main script.

I want to set a time frame of:

START_TIME = "02:00"
END_TIME = "03:00"

When it reaches the start time, it needs to look at how many scripts we have to run:

script1.do_proc()
script2.alter()
script3.noneex()

In this case there are 3 to run, so it needs to generate 3 randomized times to start those scripts with a minimum separation of 5 mins between each script but the times must be within the time set in START_TIME and END_TIME

But, it also needs to know that script1.main is ALWAYS the first script to fire, other scripts can be shuffled around (random)

So we could potentially have script1 running at 01:43 and then script3 running at 01:55 and then script2 might run at 02:59

We could also potentially have script1 running at 01:35 and then script3 running at 01:45 and then script2 might run at 01:45 which is also fine.

My script so far can be found below:

import random
import pytz
from time import sleep
from datetime import datetime

import script1
import script2
import script3

START_TIME = "01:21"
END_TIME = "03:00"

while 1:
    try:

        # Set current time & dates for GMT, London
        CURRENT_GMTTIME = datetime.now(pytz.timezone('Europe/London')).strftime("%H%M")
        CURRENT_GMTDAY = datetime.now(pytz.timezone('Europe/London')).strftime("%d%m%Y")
        sleep(5)

        # Grab old day from file
        try:
            with open("DATECHECK.txt", 'rb') as DATECHECK:
                OLD_DAY = DATECHECK.read()
        except IOError:
             with open("DATECHECK.txt", 'wb') as DATECHECK:
                DATECHECK.write("0")
                OLD_DAY = 0

        # Check for new day, if it's a new day do more
        if int(CURRENT_GMTDAY) != int(OLD_DAY):
            print "New Day"

            # Check that we are in the correct period of time to start running
            if int(CURRENT_GMTTIME) <= int(START_TIME.replace(":", "")) and int(CURRENT_GMTTIME) >= int(END_TIME.replace(":", "")):
                print "Starting"

                # Unsure how to seed the start times for the scripts below

                script1.do_proc()
                script2.alter()
                script3.noneex()

                # Unsure how to seed the start times for above

                # Save the current day to prevent it from running again today.
                with open("DATECHECK.txt", 'wb') as DATECHECK:
                    DATECHECK.write(CURRENT_GMTDAY)

                print "Completed"

            else:
                pass
        else:
            pass

    except Exception:
        print "Error..."
        sleep(60)




Random decimal between 0 and 1 stored in an int, Java

Working on a project, trying to find a way to generate a random decimal between 0 and 1, inclusive. Making a multi-threaded project that will increase and decrease an (int) number.

So far I have declared a private int number, initialized to 0 and also a random generator.

The way I am hoping to get this to work is to get a random decimal between 0 and 1 (I.E. 0.564184) and add it to number.

The way the program is designed is to check if number is less than 1, if it is then add a random decimal to it, re run the check until it is above 1 or the next number will make it above 1

I saw an example on Java random number between 0 and 0.06 But when i attached it in and modified it to this :

 while(number < max)
          {         
            double increase = random.nextInt(2);
            increase = increase / 10.0;
            number = (int) (number + increase);
            System.out.println(number);
          }

The program continuously runs just printing out 0's. I do believe this is due to the cast to int when adding the number before printing.

I have the threads working when I just use
number = number - random.nextInt(1) + 1; System.out.println(number);

Now I am stuck, looking different guides, I thought while I am looking I should ask for assistance. Thanks ahead of time.




VBA/Macro to get/copy random rows based on keywords

enter image description here

I need help to be able to get/copy random rows from another workbook with specific conditions:

source: rawdata.xlsx "Sheet1"

destination: tool.xlsm "Random Sample"

"AU", "FJ", "NC", "NZ", "SG12" are located in the first column (Column A). Attached screenshot shows how my rawdata.xlsx looks like.

If i click a button/run a macro, I should get 4 random rows for all rows that has "AU", 1 random row for all rows that has "FJ", 1 random row for all rows that has "NC", 3 random rows for all rows that has "NZ", and 1 random row for all rows that has "SG12" FROM rawdata.xlsx "Sheet1" and paste it to tool.xlsm "Random Sample".

All should happen in one click. It has been almost a month and i still got no luck being able to get answer to this question. I hope someone could help me out. Thanks.




Generate a random number with the largest range in Node.js?

I want to generate uniform random numbers in Node.js with the largest range possible. What's the best way to go about doing this?

(By "largest possible" I mean something like 2^64 possibilities, not an infinite number of possibilities).




Random Color Generator (Python 3)

How would I generate random (R,G,B) colors with minimum components of .5 in a tuple? I'm new at this and fairly confused.




Java: Give random double numbers in array

My task is to make a program like this:

give size of array:
-5
size < 0.
Give size of array: 5
1.: 1.77379378756135961,77
2.: 4.7920617665887924,79
3.: 24.2215470529474524,22
4.: 27.29623562686216327,3
5.: 9.8175915340430049,82

Here's my code: (and below my run)

    Scanner keyb = new Scanner (System.in);
    int size;

    do {
        System.out.println("give size of array");
        size= keyb.nextInt();
        keyb.nextLine();
        if (size<= 0) {
            System.out.println("size < 0");
        }
    } while (size<= 0);    

    double[] array= new double[size];
    Random generator = new Random(); 

    for (int i = 0; i < array.length; i++) {
        array[i] = generator.nextDouble();
        System.out.println((i + 1) + ".: " + array[i]);
    }

But my problem is I keep getting numbers between 0 and 1, what am I doing wrong?

1.: 0.4189300484903713
2.: 0.7600502254378542
3.: 0.3307584239116951
4.: 0.2617296585600827
5.: 0.8422085114389094




Replace values in a vector with a probability R

I don't know how to replace values in a vector with a certain probability. For example:

set.seed(49)
sample(c(0,1), nb_id, prob = c(opposite_prob_sur,prob_survival), replace = TRUE)

Gives something like: [1] 1 1 1 0 1 1 1 1 0 0

Is it possible with this vector to change 1s with 0s with a certain probability, lets say 40% ?

To go a little in the details, I'm generating a dataset with a certain probability of getting 1s vertically. But, I want to control for a probability horizontally at the same time (organisms that are entering in the population)

ch = data.frame(id = 1:10)
for (yr in 1:nb_year) {
  recapture = sample(c(0,1), nb_id, prob = c(opposite_prob_sur,prob_survival), replace = TRUE)
  ch[,yr] = recapture
  colnames_vect[yr] = paste("year", yr, sep = "")
  }
colnames(ch) = colnames_vect
ch




boost::random::variate_generator - Change parameters after construction

Is it possible to change the parameters of the distribution after the variate generator has been constructed? Let's take for example this simple setup

typedef boost::mt19937 base_gen_type;
typedef boost::uniform_int<int> dist_type;
typedef boost::variate_generator<base_gen_type &, dist_type> var_gen_type;

unsigned seed = 1337;
int a = 0, b = 42;

base_gen_type base_gen(seed);
dist_type dist(a, b);
var_gen_type rng(base_gen, dist);

If I wanted to change a and b, would this need a new var_gen_type object? The state of the base_gen would of course be unaffected but I wonder if there is a less complicated way.

Using dist_type & as a template parameter did not work.




Generate Random Name and Save From Selecting Again X Times

So I found an example, which generates a random name loaded from a text files. Works just fine, as I want to load 1 name each time, however it's tied to a button click, so removing the name from the list each time is mute because the same name could appear again after X amount of clicks.

The text file has 10 names currently. I want to randomly select a name and mark it as being used. Rinse/repeat until all 10 names are used. Then I want to mark all the names as being un-used and rinse/repeat another 10 times.

I'm having a tough time determining how to mark and save each name. Suggestions?

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    If IO.File.Exists("c:\temp\test file.txt") Then
        Dim sr As New IO.StreamReader("c:\temp\test file.txt")
        Dim fileContents As String = sr.ReadToEnd
        Dim fileList As New List(Of String)

        'Stores the contents of fileContents as items 
        'where the delimiator is a new line
        'I use vbCrLf in this case instead of environment.newline
        'Because environment.newline adds a blank space
        For Each Str As String In fileContents.Split(CChar(vbCrLf))
            fileList.Add(Str)
        Next

        'X = to the amount of times you want to add a random name
        Dim x As Integer = 0
        For i As Integer = 0 To x
            'Gets a random number from 0 to the fileList's item count
            Dim randItem As Integer = rand.Next(0, fileList.Count)
            'Adds the item to the listbox
            ListBox1.Items.Add(fileList.Item(randItem))
            'Removes the item from the list
            fileList.RemoveAt(randItem)
        Next
    Else
        MessageBox.Show("File Not Found")
    End If
End Sub




Stop Stealing focus in Windows 10

Why is it that so many long running/background apps steal and demand focus at random times? This is a HORRIBLE HORRIBLE IDIOTIC programming practice, and programmers who do this should have their fingers broken. It leads to numerous errant clicks. Is there a way to turn this off? I've tried a number of posts, and nothing works.

Nothing more annoying than writing code, and Adobe/Anti Virus/ or a myriad of other apps jump up right in the middle of me typing code with an 'update finished click to reboot', and it steals the keystrokes of me writing code, and reboots my computer. Only a complete moron thinks this is a good idea.

Is there any way to stop apps from stealing focus when you put them in the background?




Javascript random numbers no duplicates not in specific list

I'm trying to get a list of 10 random numbers between 0-30 with Javascript.
So far so good, but i've another list with specific numbers (0,5,10,11,12,13,15,16,17,18,20,22,23).
Only max. 4 numbers of this list are allowed in the random array. This makes me crazy because i've no idea to combine this.

I'm grateful for any help. Thank you.

Here is my code:

<script language="JavaScript" type="text/javascript">
<!--    

function random(min, max, i, filter) {
  var array = {};
  var zufall = [];
  while( i ) {

    var rnd = Math.floor(Math.random() * (max - min + 1)) + min;
    if( !array[rnd] )  {
      array[rnd] = true;
      i--;
      zufall.push(rnd);
    }
  }
  return zufall;
}

var filter = new Array(0,5,10,11,12,13,15,16,17,18,20,22,23);

console.log("Random: " + random(0,30,10,filter) );

//-->
</script>




Display random images if they have a different attribute

I have an array of 5 dice images that when I click a button, five random dice images show.

var diceImages = [ "img/dice-one.png","img/dice-two.png","img/dice-three.png", "img/dice-four.png", "img/dice-five.png", "img/dice-six.png"];

When I select some of those dice, they should not re-shuffle when I click that button again, and the unselected dice (containing data-selection = false) should reshuffle randomly again. The unselected dice are shuffling, but the problem is they're changing to the same image each time, they are not getting randomized. Here is a chunk of my code that's causing the problem:

  var rolls = [];

  for (var i = 0; i < 5; i++) {
  var randomNumber = Math.floor(Math.random() * diceImages.length);
  rolls.push(randomNumber + 1);
  var rollTheDice = $("[data-selection=false]"); //naming the unselected dice
  rollTheDice.each(function() { //Trying to display new random dice if data-selection = false
    $(this).attr('src', '' + diceImages[randomNumber]);
  });
  rollTheDice.attr('data',(randomNumber+1));
};




Randomly generated 3D points distributed on a density map

This topic may look like this one but I'd like some more details for this specific case.

Here is the thing.
I generate x 3D points on a surface whith the following method:

  • With:
    • a given 3D surface only composed by triangles
    • a given number of samples
  • Pick a random triangle on the surface
  • Generate a random point belonging to this triangle (with this formula)
  • Repeat for each sample

First, I'd like to improve the "pick a random triangle" part by taking account of the area of each triangle of the mesh to have a more uniform distribution (like suggested here).

Now I want to paint a grayscale map on my surface which will work as a density map: 100% white areas will receive the maximum number of points, 100% black areas won't receive any point, and intermediates grayscales will receive a percentage of points corresponding to the percentage of white at the given position.

The thing is, even with the right formulas and mathematical concept, I have some hard time "translating" math into code... So I was wondering how would you do it, step by step, like in pseudo-code or something. I usually work with Maya and python but it is more like a general math-to-code-question.

Thanks by advance!




Picking from list randomly according to Pareto Principle

I have a List<T> and try to randomly pick items according to Pareto Principle, so first 20% items will be picked 80% times, and 80% remaining items will be picked 20% times. So far I have a simple implementation:

static <T> T pickPareto(List<T> list) {
    int n = list.size();
    int first = n * 0.2;
    return rnd.next() < 0.8            
           ? list.get(rnd.nextInt(first))                // pick one of first 20%
           : list.get(first + rnd.nextInt(n - first));   // pick one of remaining 80%
}

It works well, but results a step function of distribution.

Does anyone know how to select items according to smooth distribution (maybe not exactly Pareto, but holding 20/80 property)?




What code to prevent repeat items in random list MIT App Inventor

I'm trying to select a random item from a list but after several button taps and I get repeat items and sometimes the same item comes up two or three times in a row. What code can I use to stop repeating items in list unless the complete list has been run through?

Here's my code: Random item in list




Shuffle an array in php does not really shuffle array [duplicate]

This question already has an answer here:

i am getting results from my database into a JSON array. I want to randomise this array because now it goes category 1, 2, 3, 4 and takes data always in same row. How can i randomise it so it takes data from category 4, 2, 1, 3(not necessarily in this order). My code:

$query = $handler->query('SELECT DISTINCT c.cat_description, c.cat_name, c.cat_id, q.question, q.q_id FROM `categories` c
                                        INNER JOIN `questions` q ON c.cat_id = q.cat_id ');
$records = array();
$records = $query->fetchAll(PDO::FETCH_ASSOC);
$first = array();
$second = array();
$third = array();
$query->closeCursor();
foreach($records as $k => $v){
    $first[] = array("category_name" => $v['cat_name'], "category_id" => $v['cat_id'], "category_description" => $v['cat_description'], "question_name" => $v['question'], "question_id" => $v['q_id'],  "question_answers" => array());
    $second[] = $v['question'];
}

foreach ($second as $key => $value) {
    $ques = $value;
    $qu = $handler->query("SELECT a.quest_id, a.answer, a.iscorrect, a.anser_id FROM `answers` a INNER JOIN `questions` q ON a.quest_id = q.q_id WHERE q.question = '$ques' ");
    $third = $qu->fetchAll(PDO::FETCH_ASSOC);
    foreach($third as $tk => $tv){
        $third[$tk]['answer'.($tk+1)] = $tv['answer'];
        $third[$tk]['iscorrect'.($tk+1)] = $tv['iscorrect'];
    }
    foreach ($first as $k => $v) {
        $first[$key]['question_answers'] = $third;
    }
}
function shuffle_assoc($list) { 
  if (!is_array($list)) return $list; 

  $keys = array_keys($list); 
  shuffle($keys); 
  $random = array(); 
  foreach ($keys as $key) { 
    $random[$key] = $list[$key]; 
  }
  return $random; 
}

$first = shuffle($first);

$j['quiz'] = $first;

echo json_encode($j);

I have tried shuffle but it only returns true. I have tried array_rand but it returns the key. How can i do this?




lundi 28 mars 2016

How Would I Make A Random Seed/Hash To Make Rand Actually Random?

how would i generate a seed or hash that would make rand actually random? I need it to change every time it picks a number. New to c++ so i'm not exactly sure how to do this. Thanks! :D




(Python) Creating 'X' points of form p = [a,b,c] using a for loop and then randomizing a,b,c within p = [a,b,c] 'Y' times using a second for loop?

I think that this question could be answered by all, but to give more background I am using python to code for rhino. My goal is to create a number of curves made out of X points. The points also have to be randomly located within a 10 by 80 by 20 unit rectangular prism. I started with this:

import rhinoscriptsyntax as rs
import random

crvNumber = 300
numRandPts = 5
xLength = 10
yLength = 80
zLength = 20
crvArray = []
crvPtArray = []

for j in range(0,numRandPts):

    ptj = [xLength*random.random(),yLength*random.random(),zLength*random.random()]
    crvPtArray.append(ptj)

for i in range(0,crvNumber):

    curves = rs.AddCurve (crvPtArray, degree = numRandPts)
    crvArray.append(curves)

I'm sure you can spot immediately that this won't work because the generation of the random points occurs within the first for loop, and as a result, the second for loop simply outputs the same random curve 300 times. Does anyone have any idea how I could generate a specific number of points with the first loop and then actually assign their values in the second for loop such that I end up with 300 curves with j random points? I've been researching this for the past 2 hours to no avail. My first workaround idea was that maybe it would be simpler to just generate a set of say 1000 random points and then choose j of them in the second for loop. However, I ran into the issue of not being able to choose from a list ("list objects are unhashable" error) with this code (I basically copied the for k in random.sample bit from an example I found on here):

for j in range(0,randomLevel):

    ptj = [xLength*random.random(),yLength*random.random(),zLength*random.random()]
    crvPtArray.append(ptj)

for i in range(0,crvNumber):

    crvPtArray2 = (crvPtArray[k] for k in random.sample(xrange(0,len(crvPtArray)), numRandPts))
    curves = rs.AddCurve (crvPtArray2, degree = numRandPts)
    crvArray.append(curves)

From here, I somehow stumbled onto the topics of dictionaries in python and tested these out but couldn't find a way to just print the list of "definitions" stored in the dictionary and not the "words" attached by a colon to the "definitions". And then I realized that even if I could do that the randomization would still be occurring in the dictionary for loop, not the curve-generating for loop (unless I'm wrong and it would randomize in the second for loop). So then I tried to generate blank points with pt[j] = [] and tried to somehow get the randomization to happen in the curve-generating for loop. Unfortunately, I didn't really have any success as I was completely out of my depth by this point and just trying to make up code that seemed like it might work.

Is there some way to create X blank variables or points and then retroactively define/randomize them? Is there a way to get my set and random sample idea to work? Is there some kind of crazy nested coding or something that might work for this? Any insight y'all could offer would be much appreciated.

(I there are any really really really dumb errors in my code they are probably transcriptional, but if there are any really dumb errors those might be mine ;))




Image is not displayed when parent image is clicked

Functionality:

When user enters the first page, the primary images are randomised and displayed. Therefore, when user clicks on the primary image (1st image), a secondary image (a 2nd image) will be displayed.

The secondary image is an extension to the 1st image, therefore, for e.g, when a user clicks on the 1st image of an apple, the second image of a worm is displayed.

What I have done:

I have set both the 1st images and 2nd images into a set of an array. Secondly, the array of 1st image is randomised, hence, I have set the 2nd array of image to append to the 1st randomised image.

I have attached the following code for your perusal:

//Brand Array
var BrandNameArray = ["lib/img/PAGE03/Brands/anis.png", "lib/img/PAGE03/Brands/aeo.png", "lib/img/PAGE03/Brands/alo.png", "lib/img/PAGE03/Brands/beauty.png", "lib/img/PAGE03/Brands/bbe.png", "lib/img/PAGE03/Brands/eds.png", "lib/img/PAGE03/Brands/coch.png", "lib/img/PAGE03/Brands/cotnon.png", "lib/img/PAGE03/Brands/dewel.png", "lib/img/PAGE03/Brands/esdoir.png", "lib/img/PAGE03/Brands/erit.png", "lib/img/PAGE03/Brands/ethouse.png"];
//Corresponding Image Array
var OfferArray = ["lib/img/PAGE04/adonis.png", "lib/img/PAGE04/aeo.png", "lib/img/PAGE04/aldo.png", "lib/img/PAGE04/beauty.png", "lib/img/PAGE04/bebe.png", "lib/img/PAGE04/ceds.png", "lib/img/PAGE04/coach.png", "lib/img/PAGE04/cottonon.png", "lib/img/PAGE04/dejewel.png", "lib/img/PAGE04/esboudoir.png", "lib/img/PAGE04/esprit.png", "lib/img/PAGE04/etudehouse.png"];

$(function() {

  //Auto populate into brand container once randomised for each Brand image
  var BrandNameArrayBackup = JSON.parse(JSON.stringify(BrandNameArray));
  for (i = 0; i < $('#list').find('img').length; i++) {
    //To Set random Brand
    var random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
    //Assign Variable to generate random Brands
    var Brand = BrandNameArray[random_BrandIndex];
    BrandNameArray.splice(random_BrandIndex, 1);
    $('#Brand_' + (i + 1)).attr('src', Brand);
    $('#Brand_' + (i + 1)).show();
    console.log(Brand);
  }
  BrandNameArray = BrandNameArrayBackup; //re-assigning values back to array
});

//Choose Brand with popUp
function selectBrand(index) {

  $('#Vivo_BrandDescription').fadeIn({
    duration: slideDuration,
    queue: false
  });
  $("#All").hide();
  $("#Back").hide();
  $("#Beauty").hide();
  $("#Choose").hide();
  $("#Fashion").hide();

  var chosenBrandIndex = OfferArray[BrandNameArray];
  //Set option clicked to CSS change 
  $('#Description').attr('src', chosenBrandIndex);
  $('#Description').show();
}

function Vivo_BrandDescription() {
  idleTime = 0;

  $("#border_page").fadeOut(function() {
    $("#Vivo_BrandDescription").fadeIn();
  });
}
<div id="ChooseBrand" align="center" style="position:absolute; width:1920px; height:1080px; background-repeat: no-repeat; z-index=3; top:0px; left:0px;">
  <img id="Main" src="lib/img/PAGE03/Background.png" />
  <input type="text" id="SearchField" style="position:absolute; top:190px; left:660px; height:40px; width:600px; outline=0px; border: 0; font-size:25px; font-family:'CenturyGothic'; background: transparent; z-index=4;" autofocus src="lib/img/transparent.png">
  <div class="Container">
    <div id="list" class="innerScroll">
      <!--1st Row-->
      <img id="Brand_1" style="width:284px; height:140px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
      <img id="Brand_2" style="width:284px; height:140px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
      <img id="Brand_3" style="width:284px; height:140px; top:0px; left:650px; border:0px;" onclick="selectBrand('3');">
      <img id="Brand_4" style="width:284px; height:140px; top:0px; left:965px; border:0px;" onclick="selectBrand('4');">

      <!--2nd Row-->
      <img id="Brand_5" style="width:284px; height:140px; top:140px; left:0px; border:0px;" onclick="selectBrand('5');">
      <img id="Brand_6" style="width:284px; height:140px; top:140px; left:330px; border:0px;" onclick="selectBrand('6');">
      <img id="Brand_7" style="width:284px; height:140px; top:140px; left:650px; border:0px;" onclick="selectBrand('7');">
      <img id="Brand_8" style="width:284px; height:140px; top:140px; left:965px; border:0px;" onclick="selectBrand('8');">

      <!--3rd Row-->
      <img id="Brand_9" style="width:284px; height:140px; top:280px; left:0px; border:0px;" onclick="selectBrand('9');">
      <img id="Brand_10" style="width:284px; height:140px; top:280px; left:330px; border:0px;" onclick="selectBrand('10');">
      <img id="Brand_11" style="width:284px; height:140px; top:280px; left:650px; border:0px;" onclick="selectBrand('11');">
      <img id="Brand_12" style="width:284px; height:140px; top:280px; left:965px; border:0px;" onclick="selectBrand('12');">
    </div>
  </div>
</div>

<div id="BrandDescription" class="menu" align="center" style="position:absolute; width:1920px; height:1080px; background-repeat: no-repeat; display:none; top:0px; left:0px; z-index=10;">

  <img id="Description" style="position:absolute; top:124px; left:534px;z-index=11;">

</div>

Issue:

There is the main issue that I am currently facing at the moment

**When I clicked on the primary image, the secondary image is not being displayed at all. Therefore, none of the secondary array image is appended to the first randomised image. hence, the secondary image is not displayed.

I am lost at what could have possibly gone wrong or missing. Please help.

Your help is much much appreciated.




I am trying to write a function that generates a random number that will stay under my user input that i type in for php

I need to generate a random integer that doesnt exceed the integer that is entered in my user input. Im just very confused how to write it as a

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://ift.tt/mOIMeg">
    <html lang="EN" dir="ltr" xmlns="http://ift.tt/lH0Osb">
        <head>
            <title>Roll The Die</title>
        </head>
        <body>
    <center>
    <h1>Dice Game</h1>

//Php form im just confused on how to generate a random number that stays under my user input number and that is also attached to the form

     <?php

    if (filter_has_var(INPUT_POST, 'userDie')){
        $roll = rand();
        $userDie = filter_has_var(INPUT_POST, "userDie");
        echo"You rolled a $roll";
    }
    //there's no input. Create the form
     print <<< HERE
    <form action = "" method = "post">
    <fieldset>
    <label>Please Enter a number to Roll</label>
     <input type = "text" 
     name = "userDie" /> 
     <button type = "submit">
      submit 
     </button>
    </fieldset>
     </form> 
    HERE;

    // end 'value exists' if
     ?>
    </body>
    </html>




Random Numbers from preset list

I'm a student and in the middle of a midterm project. I am not looking for people to code this for me but I need help with part of it. I am trying to make a Blackjack game and to do that I want to set a list of 52 integers [1,1,1,1,2,2,2,2.....] one for each card in a deck. But how do take a random number from the list and cancel it out? Just like a normal deck once you take a card you can't redraw it. I know a can set a random parameter [n = rand () % 11 + 1] for the program but I want to go above and beyond to get an A




VBA/Macro to copy random rows based on multiple conditions

I need help to be able to get random data from another worksheet with specific conditions:

If i click a button/run a macro, I should get 4 random samples for all rows that has "AU", 1 random sample for all rows that has "FJ", 1 random sample for all rows that has "NC", 3 random samples for all rows that has "NZ", and 1 random sample for all rows that has "SG12" ...

... FROM rawdata.xlsx "Sheet1" sheet and paste it to tool.xlsm "Random Sample" sheet.

All should happen in one click.

I am getting Error 1004: No cells were found and being directed tho this line of code:

 Intersect(.SpecialCells(xlCellTypeConstants).EntireRow, dataRng).Copy Destination:=randomSampleWs.Range("B2").Offset(rOffset)

This is my whole code so far:

        Option Explicit

Sub MAIN()
Dim key As String
Dim nKeyCells As Long, nRndRows As Long, rOffset As Long
Dim nRowsArr As Variant, keyArr As Variant
Dim i As Integer
Dim dataRng As Range, helperRng1 As Range, helperRng2 As Range
Dim rawDataWs As Worksheet, randomSampleWs As Worksheet

Set rawDataWs = Workbooks("rawdata.xlsx").Worksheets("Sheet1")
Set randomSampleWs = Workbooks("tool.xlsm").Worksheets("Random Sample")

keyArr = Array("AU", "FJ", "NC", "NZ", "SG12") '<== set your keywords
nRowsArr = Array(4, 1, 1, 3, 1) '<== set the n° of random rows to be associated to its correspondant keyword

With rawDataWs
    Set dataRng = .Range("B2:" & .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, .Cells(1, .Columns.Count).End(xlToLeft).Column).Address) '<== adapt it to your needs. keywords are assumed to be in the firts column of this range
    Set dataRng = Intersect(.UsedRange, dataRng)
End With

Set helperRng1 = dataRng.Resize(, 1).Offset(, dataRng.Columns.Count + 1) '<== here will be placed "1"s to mark rows to be copied and pasted: they'll be cleared at the end
For i = 0 To UBound(keyArr)
    nRndRows = CInt(nRowsArr(i))
    key = CStr(keyArr(i))
    nKeyCells = WorksheetFunction.CountIf(dataRng.Resize(, 1), key)
    Set helperRng2 = helperRng1.Offset(, 1).Resize(nRndRows) '<== here will be pasted random numbers: they'll be cleared at the end
    Call Unique_Numbers(1, nKeyCells, nRndRows, helperRng2)
    With helperRng1
        .Formula = "=IF(AND(RC" & dataRng.Columns(2).Column & "=""" & key & """,countif(" & helperRng2.Address(ReferenceStyle:=xlR1C1) & ",countif(R" & dataRng.Rows(1).Row & "C" & dataRng.Columns(2).Column & ":RC" & dataRng.Columns(2).Column & ",""" & key & """))>0),1,"""")"
        .value = .value
        Intersect(.SpecialCells(xlCellTypeConstants).EntireRow, dataRng).Copy Destination:=randomSampleWs.Range("A2").Offset(rOffset)
        rOffset = rOffset + nRndRows
        .EntireColumn.Resize(, 2).Clear
    End With
Next i

End Sub


Sub Unique_Numbers(Mn As Long, Mx As Long, Sample As Long, refRange As Range)
Dim tempnum As Long
Dim i As Long
Dim foundCell As Range
' adapted from http://ift.tt/1RCOxAU

If Sample > Mx - Mn + 1 Then
    MsgBox "You specified more numbers to return than are possible in the range!"
    Exit Sub
End If

Set refRange = refRange.Resize(Sample, 1)

Randomize
refRange(1) = Int((Mx - Mn + 1) * rnd + Mn)
For i = 2 To Sample
    Set foundCell = Nothing
    Do
       Randomize
       tempnum = Int((Mx - Mn + 1) * rnd + Mn)
       Set foundCell = refRange.Find(tempnum)
    Loop While Not foundCell Is Nothing
    refRange(i) = tempnum
Next

End Sub




Create numbers with boundaries based on a probability per number

I would like to create some numbers each time based on a probability.

Example:

Numbers from : 1-5

Number 1 has probability to be created by 0.55,

Number 2 has probability to be craeted by 0.25,

Number 3 has probability to be craeted by 0.10,

Number 4 has probability to be craeted by 0.05,

Number 5 has probability to be craeted by 0.05

In this case, it has to usually create number 1, and often number 2, sometimes number 3 and rarely number 4 or 5

So, the "method": create_the_numbers(int ending_number) should be like this pseado-code:

public int create_the_numbers(int ending_number){
return probability(Random.getInt(ending_number))
}

There is an question for the C# here: Probability Random Number Generator




Random Number with NextDouble (C#)

I'm programming a perceptron and really need to get the range from the normal NextDouble (0, 1) to (-0.5, 0.5). Problem is, I'm using an array and I'm not sure whether it is possible. Hopefully that's enough information.

Random rdm = new Random();

double[] weights = {rdm.NextDouble(), rdm.NextDouble(), rdm.NextDouble()};




how is /dev/random data generated on unix systems?

I would like to know how this data is generated. Is the data pulled from processor registers, random memory locations, or signal noise?




In java how can i randomize and int in an array

Hi i am just learning java and want to write a sort of vocabulary trainer. It is working but i want to give the questions in a random order. The trainer pics a list from an external file and splits the file in two parts. It is asking as long the next line isn't null.

for (int i = 0; (zeile = br.readLine()) != null; i++) { 
        splitted = zeile.split(";");                     
        eng[i] = splitted[0];                          
        ger[i] = splitted[1];

then i am asking for the vocabulary. But as you can see its always in the same order. I don't know how i can correctly randomize the list before the asking part.

for (int j = 0; j < eng.length; j++) {

        correct = false;
        while (!correct) {

            System.out.print(eng[j] + " bedeutet: ");

            gerEingabe = vokabel.nextLine(); 

            if (gerEingabe.equals(ger[j])) {
                System.out.println("Das ist Korrekt. Auf zur nächsten Aufgabe.");
                correct = true;
            } else {
                System.out.println("Das war leider Falsch. Bitte versuche es noch ein mal.");

It would be nice if someone can help me with this.




Prioritizing first items in a list (Random & Probability Distribution)

I have a list of sorted elements. First elements are supposed to be prioritized in contrast to last elements. Currently, I am just using random.choice(foo) to select items from my list.

The algorithm I am writing would be a lot more efficient with a different probability distribution (described above). Unfortunately, I am not sure how to implement it




Massive Python random sharer

I tried to make a program to take a certain amount of elements and randomly generate them. For example, the user could enter twenty names and have the algorithm spit them out randomly. I built the program in such a way that you could enter up to twenty elements, and it would print out that number plus one random things. So you could enter twenty elements and it would randomly choose from them twenty-one times. The problem is I'm not all too experience with random, so I made it ridiculously large (just shy of 500 lines). It works, but I'd like: 1) For it to be shortened. 2) To take any number, rather than between 2 and 20 and 3) To be able to spit out a user-entered number of random items. I don't know if any of that made sense, but help if you can! The whole massive code:

import random
a = input('Enter a number of elements(maximum twenty).\n')
if a < 2 or a > 20:
    print('Restart program and enter a value between two and twenty.')
if(a == 2):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    list_one = [one,two]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    print(choice_one, choice_two, choice_three)
if(a == 3):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    list_one = [one,two,three]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four)
if(a == 4):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    list_one = [one,two,three,four]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five)
if(a == 5):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    list_one = [one,two,three,four,five]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six)
if(a == 6):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    list_one = [one,two,three,four,five,six]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven)
if(a == 7):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    list_one = [one,two,three,four,five,six,seven]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight)
if(a == 8):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine)
if(a == 9):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten)
if(a == 10):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven)
if(a == 11):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    eleven = raw_input('Enter the eleventh element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten,eleven]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    choice_twelve = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven, choice_twelve)
if(a == 12):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    eleven = raw_input('Enter the eleventh element.\n')
    twelve = raw_input('Enter the twelth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    choice_twelve = random.choice(list_one)
    choice_thirteen = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven, choice_twelve, choice_thirteen)
if(a == 13):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    eleven = raw_input('Enter the eleventh element.\n')
    twelve = raw_input('Enter the twelth element.\n')
    thirteen = raw_input('Enter the thirteenth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    choice_twelve = random.choice(list_one)
    choice_thirteen = random.choice(list_one)
    choice_fourteen = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven, choice_twelve, choice_thirteen, choice_fourteen)
if(a == 14):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    eleven = raw_input('Enter the eleventh element.\n')
    twelve = raw_input('Enter the twelth element.\n')
    thirteen = raw_input('Enter the thirteenth element.\n')
    fourteen = raw_input('Enter the fourteenth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    choice_twelve = random.choice(list_one)
    choice_thirteen = random.choice(list_one)
    choice_fourteen = random.choice(list_one)
    choice_fifteen = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven, choice_twelve, choice_thirteen, choice_fourteen, choice_fifteen)
if(a == 15):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    eleven = raw_input('Enter the eleventh element.\n')
    twelve = raw_input('Enter the twelth element.\n')
    thirteen = raw_input('Enter the thirteenth element.\n')
    fourteen = raw_input('Enter the fourteenth element.\n')
    fifteen = raw_input('Enter the fifteenth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    choice_twelve = random.choice(list_one)
    choice_thirteen = random.choice(list_one)
    choice_fourteen = random.choice(list_one)
    choice_fifteen = random.choice(list_one)
    choice_sixteen = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven, choice_twelve, choice_thirteen, choice_fourteen, choice_fifteen,choice_sixteen)
if(a == 16):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    eleven = raw_input('Enter the eleventh element.\n')
    twelve = raw_input('Enter the twelth element.\n')
    thirteen = raw_input('Enter the thirteenth element.\n')
    fourteen = raw_input('Enter the fourteenth element.\n')
    fifteen = raw_input('Enter the fifteenth element.\n')
    sixteen = raw_input('Enter the sixteenth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    choice_twelve = random.choice(list_one)
    choice_thirteen = random.choice(list_one)
    choice_fourteen = random.choice(list_one)
    choice_fifteen = random.choice(list_one)
    choice_sixteen = random.choice(list_one)
    choice_seventeen = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven, choice_twelve, choice_thirteen, choice_fourteen, choice_fifteen,choice_sixteen, choice_seventeen)
if(a == 17):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    eleven = raw_input('Enter the eleventh element.\n')
    twelve = raw_input('Enter the twelth element.\n')
    thirteen = raw_input('Enter the thirteenth element.\n')
    fourteen = raw_input('Enter the fourteenth element.\n')
    fifteen = raw_input('Enter the fifteenth element.\n')
    sixteen = raw_input('Enter the sixteenth element.\n')
    seventeen = raw_input('Enter the seventeenth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    choice_twelve = random.choice(list_one)
    choice_thirteen = random.choice(list_one)
    choice_fourteen = random.choice(list_one)
    choice_fifteen = random.choice(list_one)
    choice_sixteen = random.choice(list_one)
    choice_seventeen = random.choice(list_one)
    choice_eighteen = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven, choice_twelve, choice_thirteen, choice_fourteen, choice_fifteen,choice_sixteen, choice_seventeen, choice_eighteen)
if(a == 18):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    eleven = raw_input('Enter the eleventh element.\n')
    twelve = raw_input('Enter the twelth element.\n')
    thirteen = raw_input('Enter the thirteenth element.\n')
    fourteen = raw_input('Enter the fourteenth element.\n')
    fifteen = raw_input('Enter the fifteenth element.\n')
    sixteen = raw_input('Enter the sixteenth element.\n')
    seventeen = raw_input('Enter the seventeenth element.\n')
    eighteen = raw_input('Enter the eighteenth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    choice_twelve = random.choice(list_one)
    choice_thirteen = random.choice(list_one)
    choice_fourteen = random.choice(list_one)
    choice_fifteen = random.choice(list_one)
    choice_sixteen = random.choice(list_one)
    choice_seventeen = random.choice(list_one)
    choice_eighteen = random.choice(list_one)
    choice_nineteen = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven, choice_twelve, choice_thirteen, choice_fourteen, choice_fifteen,choice_sixteen, choice_seventeen, choice_eighteen, choice_nineteen)
if(a == 19):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    eleven = raw_input('Enter the eleventh element.\n')
    twelve = raw_input('Enter the twelth element.\n')
    thirteen = raw_input('Enter the thirteenth element.\n')
    fourteen = raw_input('Enter the fourteenth element.\n')
    fifteen = raw_input('Enter the fifteenth element.\n')
    sixteen = raw_input('Enter the sixteenth element.\n')
    seventeen = raw_input('Enter the seventeenth element.\n')
    eighteen = raw_input('Enter the eighteenth element.\n')
    nineteen = raw_input('Enter the ninteenth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    choice_twelve = random.choice(list_one)
    choice_thirteen = random.choice(list_one)
    choice_fourteen = random.choice(list_one)
    choice_fifteen = random.choice(list_one)
    choice_sixteen = random.choice(list_one)
    choice_seventeen = random.choice(list_one)
    choice_eighteen = random.choice(list_one)
    choice_nineteen = random.choice(list_one)
    choice_twenty = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven, choice_twelve, choice_thirteen, choice_fourteen, choice_fifteen,choice_sixteen, choice_seventeen, choice_eighteen, choice_nineteen, choice_twenty)
if(a == 20):
    one = raw_input('Enter the first element.\n')
    two = raw_input('Enter the second element.\n')
    three = raw_input('Enter the third element.\n')
    four = raw_input('Enter the fourth element.\n')
    five = raw_input('Enter the fifth element.\n')
    six = raw_input('Enter the sixth element.\n')
    seven = raw_input('Enter the seventh element.\n')
    eight = raw_input('Enter the eighth element.\n')
    nine = raw_input('Enter the ninth element.\n')
    ten = raw_input('Enter the tenth element.\n')
    eleven = raw_input('Enter the eleventh element.\n')
    twelve = raw_input('Enter the twelth element.\n')
    thirteen = raw_input('Enter the thirteenth element.\n')
    fourteen = raw_input('Enter the fourteenth element.\n')
    fifteen = raw_input('Enter the fifteenth element.\n')
    sixteen = raw_input('Enter the sixteenth element.\n')
    seventeen = raw_input('Enter the seventeenth element.\n')
    eighteen = raw_input('Enter the eighteenth element.\n')
    nineteen = raw_input('Enter the ninteenth element.\n')
    twenty = raw_input('Enter the twentieth element.\n')
    list_one = [one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,twenty]
    choice_one = random.choice(list_one)
    choice_two = random.choice(list_one)
    choice_three = random.choice(list_one)
    choice_four = random.choice(list_one)
    choice_five = random.choice(list_one)
    choice_six = random.choice(list_one)
    choice_seven = random.choice(list_one)
    choice_eight = random.choice(list_one)
    choice_nine = random.choice(list_one)
    choice_ten = random.choice(list_one)
    choice_eleven = random.choice(list_one)
    choice_twelve = random.choice(list_one)
    choice_thirteen = random.choice(list_one)
    choice_fourteen = random.choice(list_one)
    choice_fifteen = random.choice(list_one)
    choice_sixteen = random.choice(list_one)
    choice_seventeen = random.choice(list_one)
    choice_eighteen = random.choice(list_one)
    choice_nineteen = random.choice(list_one)
    choice_twenty = random.choice(list_one)
    choice_twenty_one = random.choice(list_one)
    print(choice_one, choice_two, choice_three, choice_four, choice_five, choice_six, choice_seven, choice_eight, choice_nine, choice_ten, choice_eleven, choice_twelve, choice_thirteen, choice_fourteen, choice_fifteen,choice_sixteen, choice_seventeen, choice_eighteen, choice_nineteen, choice_twenty, choice_twenty_one)
raw_input('Press enter to exit.')




Assignment problems with simple random number generation in Modelica

I am relatively new to Modelica (Dymola-environment) and I am getting very desperate/upset that I cannot solve such a simple problem as a random number generation in Modelica and I hope that you can help me out. The simple function random produces a random number between 0 and 1 with an input seed seedIn[3] and produces the output seed seedOut[3] for the next time step or event. The call (z,seedOut) = random(seedIn); works perfectly fine.

The problem is that I cannot find a way in Modelica to compute this assignment over time by using the seedOut[3] as the next seedIn[3], which is very frustrating.

My simple program looks like this: *model Randomgenerator Real z; Integer seedIn3, seedOut[3]; equation (z,seedOut) = random(seedIn); algorithm seedIn := seedOut;

end Randomgenerator;*

I have tried nearly all possibilities with algorithm assignements, initial conditions and equations but none of them works. I just simply want to use seedOut in the next time step. One problem seems to be that when entering into the algorithm section, neither the initial conditions nor the values from the equation section are used.

I hope that you can help me with this problem.

Thanks, Daniel




Unable to call randomised Images correctly to parent array

Functionality Corresponding image will fade in and display when user clicks on the parent image. Therefore, the secondary image will correspond to the parent image.

What I have done:

All images are set into arrays, where they are all randomised. Furthermore, I have append the array of the corresponding images to the array of randomised image and append it to the displaying div tag.

I have attached the code for your perusal

//Brand Array
  var BrandNameArray = ["lib/img/PAGE03/Brands/anis.png", "lib/img/PAGE03/Brands/aeo.png", "lib/img/PAGE03/Brands/alo.png", "lib/img/PAGE03/Brands/beauty.png", "lib/img/PAGE03/Brands/bbe.png", "lib/img/PAGE03/Brands/eds.png", "lib/img/PAGE03/Brands/coch.png", "lib/img/PAGE03/Brands/cotnon.png", "lib/img/PAGE03/Brands/dewel.png", "lib/img/PAGE03/Brands/esdoir.png", "lib/img/PAGE03/Brands/erit.png", "lib/img/PAGE03/Brands/ethouse.png", "lib/img/PAGE03/Brands/forr2.png"];
  //Corresponding Image Array
  var OfferArray = ["lib/img/PAGE04/adonis.png", "lib/img/PAGE04/aeo.png", "lib/img/PAGE04/aldo.png", "lib/img/PAGE04/beauty.png", "lib/img/PAGE04/bebe.png", "lib/img/PAGE04/ceds.png", "lib/img/PAGE04/coach.png", "lib/img/PAGE04/cottonon.png", "lib/img/PAGE04/dejewel.png", "lib/img/PAGE04/esboudoir.png", "lib/img/PAGE04/esprit.png", "lib/img/PAGE04/etudehouse.png", "lib/img/PAGE04/forever21.png", ];
  var CorrectOfferArray = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
  var OfferIndex = "";

  $(function() {

    //Auto populate into brand container once randomised for each Brand image
    var BrandNameArrayBackup = JSON.parse(JSON.stringify(BrandNameArray));
    for (i = 0; i < $('#list').find('img').length; i++) {
      //To Set random Brand
      var random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
      //Assign Variable to generate random Brands
      var Brand = BrandNameArray[random_BrandIndex];
      BrandNameArray.splice(random_BrandIndex, 1);
      $('#Brand_' + (i + 1)).attr('src', Brand);
      $('#Brand_' + (i + 1)).show();
      console.log(Brand);
    }
    BrandNameArray = BrandNameArrayBackup; //re-assigning values back to array
  });

  //Choose Brand with popUp
  function selectBrand(index) {

    $('#Vivo_BrandDescription').fadeIn({
      duration: slideDuration,
      queue: false
    });
    $("#All").hide();
    $("#Back").hide();
    $("#Beauty").hide();
    $("#Choose").hide();
    $("#Fashion").hide();

    var random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
    var chosenBrandIndex = OfferArray[random_BrandIndex];
    //Set option clicked to CSS change 
    $('#Description').attr('src', chosenBrandIndex);
    $('#Description').show();
    OfferIndex = index + "";
  }

  function Vivo_BrandDescription() {
    idleTime = 0;

    $("#border_page").fadeOut(function() {
      $("#Vivo_BrandDescription").fadeIn();
    });
  }
<div id="ChooseBrand" align="center" style="position:absolute; width:1920px; height:1080px; background-repeat: no-repeat; z-index=3; top:0px; left:0px;">
  <img id="Main" src="lib/img/PAGE03/Background.png" />
  <input type="text" id="SearchField" style="position:absolute; top:190px; left:660px; height:40px; width:600px; outline=0px; border: 0; font-size:25px; font-family:'CenturyGothic'; background: transparent; z-index=4;" autofocus src="lib/img/transparent.png">
  <div class="Container">
    <div id="list" class="innerScroll">
      <!--1st Row-->
      <img id="Brand_1" style="width:284px; height:140px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
      <img id="Brand_2" style="width:284px; height:140px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
      <img id="Brand_3" style="width:284px; height:140px; top:0px; left:650px; border:0px;" onclick="selectBrand('3');">
      <img id="Brand_4" style="width:284px; height:140px; top:0px; left:965px; border:0px;" onclick="selectBrand('4');">

      <!--2nd Row-->
      <img id="Brand_5" style="width:284px; height:140px; top:140px; left:0px; border:0px;" onclick="selectBrand('5');">
      <img id="Brand_6" style="width:284px; height:140px; top:140px; left:330px; border:0px;" onclick="selectBrand('6');">
      <img id="Brand_7" style="width:284px; height:140px; top:140px; left:650px; border:0px;" onclick="selectBrand('7');">
      <img id="Brand_8" style="width:284px; height:140px; top:140px; left:965px; border:0px;" onclick="selectBrand('8');">

      <!--3rd Row-->
      <img id="Brand_9" style="width:284px; height:140px; top:280px; left:0px; border:0px;" onclick="selectBrand('9');">
      <img id="Brand_10" style="width:284px; height:140px; top:280px; left:330px; border:0px;" onclick="selectBrand('10');">
      <img id="Brand_11" style="width:284px; height:140px; top:280px; left:650px; border:0px;" onclick="selectBrand('11');">
      <img id="Brand_12" style="width:284px; height:140px; top:280px; left:965px; border:0px;" onclick="selectBrand('12');">
    </div>

    <div id="BrandDescription" class="menu" align="center" style="position:absolute; width:1920px; height:1080px; background-repeat: no-repeat; display:none; top:0px; left:0px; z-index=10;">

      <img id="Description" style="position:absolute; top:124px; left:534px;z-index=11;">
      <button id="Close" onclick="Close()"></button>
      <button id="LikeBrand" onclick="LikeBrand()"></button>
      <button id="DislikeBrand" onclick="DislikeBrand()"></button>
      <button id="Reset" onclick="Reset()"></button>
    </div>

Issue:

The corresponding image when displayed does not tally with the parent image. Meaning: If the parent image is displaying an apple image, and when the user clicks on the apple image, the corresponding image that will be displayed is a worm. However, at this instance, when user clicks on the parent image of "apple", the corresponding image of a banana is shown. Therefore, the randomised corresponding image is showing the wrong image when the parent image is clicked.

What has caused an error in the function?? I am not getting it.