lundi 30 novembre 2015

Instance member cannot be used on type 'ViewController'

let fortuneArray = ["You will find true love in the summer.", "Outlook not good", "You may find great success in business soon.", "Watch out for grey cats."]
let randomIndex = Int(arc4random_uniform(fortuneArray.count))

I'm creating a very simple fortune telling app in Swift and I keep running into issues with arc4random_uniform. Currently I'm just trying to get the app to draw a string at random but I get an error saying:

Instance member 'fortuneArray' cannot be used on type 'ViewController'

on the line where I am declaring the variable randomIndex. I've been using google for awhile but haven't found a fix. Hopefully someone can help, thanks!




generating random numbers in verilog

I ran into this issue while writing a testbench for a project. I found how to use $random in verilog but for some reason it produces strange results for me. I have 2 16 bit wires called A and B, I tested it with random number btwn 0-10 every second output is a value which is the max value that you can have in 16 bits. I wonder if anyone else had had similar issue and can offer help. Thanks

reg[15:0]a;
reg[15:0]b;

 integer seed,i,j;
 initial begin 


   for (i=0; i<6; i=i+1)
    begin
      a=$random%10; 
      #100;
      b=$random%20;
    $display("A %d, B: %d",a,b);    
   end 
$finish;




New arc4random()%x; different from Previous number

I have this line of code to calculate a random number:

    myRand = arc4random()%24; //0:23

What's the most efficient way of adding to this in order for this not to generate the same number it previously generated.

I'm not trying to shuffle all 24, as I do want repeats, just preferably not 2 of the same number directly after each other...

I thought of storing the previous number separately, then comparing it and if matching, just do it again, but I couldn't figure out away if for example the same number came out 3 times in a row... Unlikely I know, but it's possible.

Thanks.




Codeigniter random and filtered

i want a result filtered by id and number of rcount.

this is my objectives table

enter image description here

objective_question table

enter image description here

i already have this query with codeigniter

$this->db->select("objectives.id, objectives.rcount, objective_questions.question, objective_questions.a, objective_questions.b, 
                 objective_questions.c, objective_questions.d, objective_questions.answer");

$this->db->from("objectives");

$this->db->join("objective_questions", "objectives.id = objective_questions.objective_id");

$this->db->where("sub_module_id", $sub_module_id);

$query = $this->db->get();

with this result of

enter image description here

what i want is to query the sub_module_id and pick a random question by the number of rcount where objectives.id is equal to objective_questions.objective_id, so total of question will i get based on my two tables is 9, 1 + 4 + 4 = 9.

the result i want is something like this, based on rcount and get random result where sub_module_id = 1 and where objectives.id is equal to objective_questions.objective_id

enter image description here

any idea how do i get the result? Thank you.!




Randomly Create Enemies In Android Studio

I'm making my first android game, and i want to create a random enemy every three seconds, i have six enemies but my code it's not working!!

I don't know what i'm missing or doing wrong, i have a red line under (rand == 0) and (rand == 1).

Please help!

The code i'm using:

if (EnemyElapsed > (2000-alien.getScore()/4)){
    switch ((int) (rand.nextDouble() * (2))) {
        if(rand == 0){
            enemy.add(new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.dog), WIDTH + 10,60, 250, 250, alien.getScore(), 2));
            enemyStartTime = System.nanoTime();
        }
        else if(rand == 1){
            enemy.add(new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.aalien), WIDTH + 10,60, 250, 250, alien.getScore(), 2));
            enemyStartTime = System.nanoTime();
        }
    }
}




Generate random between [0, 1)

I want to generate a random float value between 0 and 1 excluding 1, I.e. [0, 1). I've searched a lot but I couldn't find an answer of this. I've tried the following trick however it generates a negative values

(double)rand()/(double)RAND_MAX-1;




Prestashop module tab slider random product

This is Tab category slider module of Prestashop CMS, it shows last added productes, i need to show random products.

I will add more info if it will be needed

sry for my bad English.

Thanks for help guys.

class postabcateslider1 extends Module {
    private $spacer_size = '5'; 
    private $_postErrors  = array();
    private $_html= null;
    public function __construct() {
        $this->name         = 'postabcateslider1';
        $this->tab          = 'front_office_features';
        $this->version      = '1.5';
        $this->author       = 'posthemes';
        $this->displayName  = $this->l('Category Tabs Slider 1');
        $this->description  = $this->l('Category Tabs Slider 1');
        parent :: __construct();

    }

    public function install() {

    Configuration::updateValue($this->name . '_p_on_row', 4);
    Configuration::updateValue($this->name . '_p_limit', 30);
    Configuration::updateValue($this->name . '_tab_effect', 'wiggle');
    Configuration::updateValue($this->name . '_p_on_row', 4);
    Configuration::updateValue($this->name . '_p_width', 150);
    Configuration::updateValue($this->name . '_p_height', 200);
    Configuration::updateValue($this->name . '_min_item', 1);
    Configuration::updateValue($this->name . '_max_item', 5);
    Configuration::updateValue($this->name . '_speed_slide', 3000);
    Configuration::updateValue($this->name . '_a_speed', 500);
    Configuration::updateValue($this->name . '_show_arrow', 0);
    Configuration::updateValue($this->name . '_show_ctr', 0);

    $arrayDefault = array('CAT3','CAT4','CAT5');
    $cateDefault = implode(',',$arrayDefault);
    Configuration::updateGlobalValue($this->name . '_list_cate',$cateDefault);

        return parent :: install()

            && $this->registerHook('top')
        /*  && $this->registerHook('displayHome') */
            && $this->registerHook('blockPosition2')
            //&& $this->registerHook('displayHome')
            && $this->registerHook('header')
            && $this->registerHook('actionOrderStatusPostUpdate')
            && $this->registerHook('addproduct')
            && $this->registerHook('updateproduct')
            && $this->registerHook('deleteproduct');
    }

      public function uninstall() {
        Configuration::deleteByName($this->name . '_list_cate');
        $this->_clearCache('postabcateslider1.tpl');
        return parent::uninstall();
    }


    public function psversion() {
        $version=_PS_VERSION_;
        $exp=$explode=explode(".",$version);
        return $exp[1];
    }


    public function hookHeader($params){
        // if ($this->psversion()==5){
            // $this->context->controller->addCSS(($this->_path).'postabcateslider.css', 'all');
            // $this->context->controller->addCSS(($this->_path).'animate.delay.css', 'all');
            // $this->context->controller->addCSS(($this->_path).'animate.min.css', 'all');

        // } else {
            // Tools::addCSS(($this->_path).'postabcateslider.css');
            // Tools::addCSS(($this->_path).'animate.delay.css');
            // Tools::addCSS(($this->_path).'animate.min.css');

        // }
    }

    public function hookblockPosition2($params) {
            $nb = Configuration::get($this->name . '_p_limit');
            $product_on_row = Configuration::get($this->name . '_p_on_row');
            $arrayCategory = array();
            $catSelected = Configuration::get($this->name . '_list_cate');
            $cateArray = explode(',', $catSelected); 
            $id_lang =(int) Context::getContext()->language->id;
            $id_shop = (int) Context::getContext()->shop->id;
            $arrayProductCate = array();
            foreach($cateArray as $id_category) {
                $id_category = str_replace('CAT','',$id_category);
                $category = new Category((int) $id_category, (int) $id_lang, (int) $id_shop);
                $categoryProducts = $category->getProducts($this->context->language->id, 0, ($nb ? $nb : 5),'date_add','DESC');
                if($categoryProducts) {
                    $arrayProductCate[] = array('id' => $id_category, 'name'=> $category->name, 'product' => $categoryProducts);
                }
            }

            $options = array(
                'p_width' => Configuration::get($this->name . '_p_width'),
                'p_height' => Configuration::get($this->name . '_p_height'),

                'speed_slide' => Configuration::get($this->name . '_speed_slide'),
                'a_speed' => Configuration::get($this->name . '_a_speed'),
                 'show_des' => Configuration::get($this->name . '_show_des'),
                'show_arrow' => Configuration::get($this->name . '_show_arrow'),
                'show_ctr' => Configuration::get($this->name . '_show_ctr'),
                'min_item' => Configuration::get($this->name . '_min_item'),
                'max_item' => Configuration::get($this->name . '_max_item'),  'show_price' => Configuration::get($this->name . '_show_price'),

            );

            $this->context->smarty->assign('slideOptions', $options);
            $this->smarty->assign(array(
                'productCates' => $arrayProductCate,
                'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'),
                'homeSize' => Image::getSize(ImageType::getFormatedName('home')),
                'product_on_row' => $product_on_row,
                'tab_effect' => Configuration::get($this->name . '_tab_effect'),
                'title' => Configuration::get($this->name . '_title'),

            ));
        return $this->display(__FILE__, 'postabcateslider1.tpl');
    }

      public function getContent() {
        $output = '<h2>' . $this->displayName . '</h2>';
        if (Tools::isSubmit('submitPosTabCate')) {
            if (!sizeof($this->_postErrors))
                $this->_postProcess();
            else {
                foreach ($this->_postErrors AS $err) {
                    $this->_html .= '<div class="alert error">' . $err . '</div>';
                }
            }
        }
        return $output . $this->_displayForm();
    }

    public function getSelectOptionsHtml($options = NULL, $name = NULL, $selected = NULL) {
        $html = "";
        $html .='<select name =' . $name . ' style="width:130px">';
        if (count($options) > 0) {
            foreach ($options as $key => $val) {
                if (trim($key) == trim($selected)) {
                    $html .='<option value=' . $key . ' selected="selected">' . $val . '</option>';
                } else {
                    $html .='<option value=' . $key . '>' . $val . '</option>';
                }
            }
        }
        $html .= '</select>';
        return $html;
    }

    private function _postProcess() {

        Configuration::updateValue($this->name . '_list_cate', implode(',', Tools::getValue('list_cate')));
        Configuration::updateValue($this->name . '_p_on_row', Tools::getValue('p_on_row'));
        Configuration::updateValue($this->name . '_p_limit', Tools::getValue('p_limit'));
        Configuration::updateValue($this->name . '_tab_effect', Tools::getValue('tab_effect'));
        Configuration::updateValue($this->name . '_title', Tools::getValue('title'));
        Configuration::updateValue($this->name . '_p_height', Tools::getValue('p_height'));
        Configuration::updateValue($this->name . '_p_width', Tools::getValue('p_width'));
        Configuration::updateValue($this->name . '_p_limit', Tools::getValue('p_limit'));

        Configuration::updateValue($this->name . '_speed_slide', Tools::getValue('speed_slide'));
        Configuration::updateValue($this->name . '_a_speed', Tools::getValue('a_speed'));

        Configuration::updateValue($this->name . '_show_arrow', Tools::getValue('show_arrow'));
        Configuration::updateValue($this->name . '_show_ctr', Tools::getValue('show_ctr'));
        Configuration::updateValue($this->name . '_min_item', Tools::getValue('min_item'));
        Configuration::updateValue($this->name . '_max_item', Tools::getValue('max_item'));

        $this->_html .= '<div class="conf confirm">' . $this->l('Settings updated') . '</div>';
    }

    private function _displayForm(){ 
        $spacer = str_repeat('&nbsp;', $this->spacer_size);

     $tabEffect = array();
        $tabEffect = array(
            'none' => 'None', 
            'hinge' => 'Hinge', 
            'flash' => 'Flash', 
            'shake' => 'Shake',
            'bounce' => 'Bounce',
            'tada' => 'Tada' ,
            'swing' => 'Swing', 
            'wobble' => 'Wobble', 
            'pulse' => 'Pulse', 
            'flip' => 'Flip', 
            'flipInX' => 'FlipInX', 
            'flipInY' => 'FlipInY', 
            'fadeIn' => 'FadeIn', 
            'bounceInUp' => 'BounceInUp', 
            'fadeInLeft' => 'FadeInLeft', 
            'rollIn' => 'RollIn', 
            'lightSpeedIn' => 'LightSpeedIn', 
            'wiggle' => 'Wiggle', 
            'rotateIn' => 'RotateIn', 
            'rotateInUpLeft' => 'RotateInUpLeft', 
            'rotateInUpRight' => 'RotateInUpRight'

        );
         $this->_html .= '
        <form action="'.$_SERVER['REQUEST_URI'].'" method="post">
                  <fieldset>
                    <legend><img src="../img/admin/cog.gif" alt="" class="middle" />' . $this->l('Settings') . '</legend>
                    <label>'.$this->l('Title: ').'</label>
                    <div class="margin-form">
                            <input type = "text"  name="title" value ='.(Tools::getValue('title')?Tools::getValue('title'): Configuration::get($this->name.'_title')).' ></input>
                    </div>
                    <label>'.$this->l('Effect Tab: ').'</label>
                    <div class="margin-form">';
                       $this->_html .= $this->getSelectOptionsHtml($tabEffect,'tab_effect',   (Tools::getValue('tab_effect') ? Tools::getValue('tab_effect') : Configuration::get($this->name . '_tab_effect')));
                       $this->_html .='
                    </div>';

                    $this->_html .= '<label>' . $this->l('Show Link/Label Category: ') . '</label>';
                    $this->_html .= '<div class="margin-form">';
                    $this->_html .= '<select multiple="multiple" name ="list_cate[]" style="width: 200px; height: 160px;">';
                    // BEGIN Categories
                    $id_lang = (int) Context::getContext()->language->id;
                    $this->getCategoryOption(1, (int) $id_lang, (int) Shop::getContextShopID());
                    $this->_html .= '</select>
                    </div>';
                    $this->_html .='

                              <label>' . $this->l('Show Next/Back control: : ') . '</label>
                    <div class="margin-form">';
                    $this->_html .= $this->getSelectOptionsHtml(array(0 => 'No', 1 => 'Yes'), 'show_arrow', (Tools::getValue('title') ? Tools::getValue('show_arrow') : Configuration::get($this->name . '_show_arrow')));
                    $this->_html .='
                                </div>
                                <label>' . $this->l('Show navigation control: : ') . '</label>
                                 <div class="margin-form">';
                    $this->_html .= $this->getSelectOptionsHtml(array(0 => 'No', 1 => 'Yes'), 'show_ctr', (Tools::getValue('title') ? Tools::getValue('show_ctr') : Configuration::get($this->name . '_show_ctr')));
                    $this->_html .='
                                </div>
                     <label>'.$this->l('Products Limit: ').'</label>
                    <div class="margin-form">
                            <input type = "text"  name="p_limit" value ='.(Tools::getValue('p_limit')?Tools::getValue('p_limit'): Configuration::get($this->name.'_p_limit')).' ></input>
                    </div>
                    <input type="submit" name="submitPosTabCate" value="'.$this->l('Update').'" class="button" />
                     </fieldset>
        </form>';
        return $this->_html;
    }


     private function getCategoryOption($id_category = 1, $id_lang = false, $id_shop = false, $recursive = true) {
        $cateCurrent = Configuration::get($this->name . '_list_cate');  
        $cateCurrent = explode(',', $cateCurrent);
        $id_lang = $id_lang ? (int)$id_lang : (int)Context::getContext()->language->id;
        $category = new Category((int)$id_category, (int)$id_lang, (int)$id_shop);

        if (is_null($category->id))
            return;

        if ($recursive)
        {
            $children = Category::getChildren((int)$id_category, (int)$id_lang, true, (int)$id_shop);
            $spacer = str_repeat('&nbsp;', $this->spacer_size * (int)$category->level_depth);
        }

        $shop = (object) Shop::getShop((int)$category->getShopID());
                if (in_array('CAT'.(int)$category->id, $cateCurrent)) {
                    $this->_html .= '<option value="CAT'.(int)$category->id.'" selected ="selected" >'.(isset($spacer) ? $spacer : '').$category->name.' ('.$shop->name.')</option>';
                } else {
                    $this->_html .= '<option value="CAT'.(int)$category->id.'">'.(isset($spacer) ? $spacer : '').$category->name.' ('.$shop->name.')</option>';
                }

        if (isset($children) && count($children))
            foreach ($children as $child)
                $this->getCategoryOption((int)$child['id_category'], (int)$id_lang, (int)$child['id_shop']);
    }



}




random timer generator for swift in xcode [duplicate]

This question is an exact duplicate of:

I want a function to be called at random times while the user is playing. For example after 2 seconds passed a function is called and then after another 6 seconds it is called again. How do I do that?

This is not working

    func time() {
randomNumber = CGFloat((drand48())
timer = NSTimer.scheduledTimerWithTimeInterval(randomNumber, traget: self, selector: "startTimer", userInfo: nil, repeats: true)

Xcode is not liking it and I donot know why




How Does Java Produce a Random Number?

I know you can use Math.random() in Java to generate a random double from 0.0 to 1.0, but how does the computer pick a number? What code is the computer following to simulate randomness?




Random generator based off NStimer Xcode 7 swift 2 [on hold]

I want a function to be called at random times while the user is playing. For example after 2 seconds passed a function is called and then after another 6 seconds it is called again. How do I do that?

This is not working

    func time() {
randomNumber = CGFloat((drand48())
timer = NSTimer.scheduledTimerWithTimeInterval(randomNumber, traget: self, selector: "startTimer", userInfo: nil, repeats: true)

Xcode is not liking it and I donot know why




Seeding Random number generator not working

I have a c++ program that uses a random generator to create a cube. To create the cube I have this:

void generateSquare() {
  int num = 0;
  srand(time(NULL));

  for (int r = 0; r < MSQUARE; r++) {
    for (int c = 0; c < MSQUARE; c++) {
      do {
        num = (rand() % (MSQUARE * MSQUARE)) + 1;
      } while (!checkUnique(num));
      cube[r][c] = num;
    }
  }
}

It only allows a number to be generated one. This function is then wrapped in a do..while loop so that if the square doesn't meet a specific condition a new square will be generated until the one that does meet the condition is generated.

The problem is that it continually is generating the same square over and over again. I thought that the srand(time(NULL)) would seed the rand() function so that it would generate different random numbers each time to create a new unique square every time it is called but it looks like that is not happening.

void checkSquare() {
  do {
    generateSquare();
  } while (!perfect);
}

This is not the actual do...while loop but gives you an idea of how it's being called.

How do I make sure the seed is unique each time?




PHP Zip random files from directory

I am currently making a website and I am trying to collect a number of random files from a folder on my server (./uploads) and zip them so the user can download them. I think I am pretty close but cant seem to setup the loop right. I am trying to first get 20 random files with the line $files = $nfiles[array_rand($nfiles,20)]; then take these 20 files and use the loop to zip them all up but I can not figure out quite how to do it. :/

edit: discovered that i need to use $rand_indexes = array_rand($nfiles, 20); instead..now to figure out how to replace the glob function to just get a list of all objects.

<?php 
$rootPath = realpath('./uploads');
//make zip file
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$nfiles = glob($rootPath.'*.{aiff}', GLOB_BRACE);     
$files = $nfiles[array_rand($nfiles,20)]; 
//-------------------------------------------//
foreach ($files as $file)
 { 
 if (!$file->isDir())
{
    // Get path for current file
    $filePath = $file->getRealPath();
    $relativePath = substr($filePath, strlen($rootPath) + 1);  
    // Add file to zip
    $zip->addFile($filePath, $relativePath);
}
 }
 //-------------------------------------------//
 $zip->close();
 header('Content-Type: application/zip');
 header('Content-disposition: attachment; filename='.'generated            
 sounds.zip');
 header('Content-Length: ' . filesize('file.zip'));
 readfile('file.zip');
  if(file_exists('file.zip')){
  unlink('file.zip');
 }
?>




Randomly select from array then assign selection to a variable

I have a function that randomly selects a monster from an object. Here's the function:

var travel = function(direction) {
        var newRoom = rooms[currentRoom.paths[direction]];
        if (!newRoom) {
            $("<p>You can't go that way.</p>").properDisplay();
        }
        else {
            currentRoom = newRoom;
            $("<p>You are now in the " + currentRoom.name + " Room.</p>").properDisplay();
                if (currentRoom.hasMonsters) {
                    function pickRand() {
                        var monsterArray = Object.keys(monsters);   
                        var randomKey = Math.floor(Math.random() * monsterArray.length);
                        return $("<p>Holy Crap!  There's a " + monsterArray[randomKey] + " in here!</p>").properDisplay();  
                    }
                    pickRand();

                }
        }
    };

Here's the object:

var monsters = {
    zombie:  {
        hitPoints: 10,
        loot: "magic knife"
    },
    skeleton: {
        hitPoints: 15,
        loot: "magic shield"
    },
    ghoul:  {
        hitPoints: 12,
        loot: "magic helm"
    }
};  

It's set up to randomly select "Zombie", "Skeleton", or "Ghoul." Everything works fine. How do I take whatever was randomly selected and save it to a variable?

I've tried a couple things like:

var beast = pickRand();

and

var beast = monsterArray;

But no luck. What am I missing?




How would I randomize several string cell arrays? [on hold]

So I have certain trials:

ST1_lag2 = (['%', '&', ':]', '@', '!', '&', '&', '*', '(', 'A', '%', 'U', '#', '&', '@', '%', '%']);
ST2_lag2 = (['%', '&', '$', '@', '!', '&', '&', '*', '(', '&', 'I', ')', 'E', '&', '@', '%', '%']);
ST3_lag2 = (['*', '&', '$', '@', '!', '&', '&', 'T', '(', 'H', '%', '*', '#', '&', '@', '%', '%']);

Now I want a while loop that can go through all these variables, and randomize them so that the letters amongst the symbols always appear after one symbol in between. Can I do that? If so, Please help me as to how I can accomplish this.

THank You




+1/-1 randomly distributed in 2D array

I would like to create a 4x4 array which is filled randomly with +1 or -1 only in fortran95. I found a post that can generate numbers:

program rand_test
use,intrinsic :: ISO_Fortran_env
real  :: r(6)
integer       :: i(6)

! call init_random_seed() would go here

call random_number(r)

i = -1 + FLOOR(3*r)       ! n=-1 and m=1

print *, i
end program

However, this includes 0 which I don't want. Is it possile to remove the 0, if so, how?




How can I randomizing results on a lottery ticket

im trying to highlight specific areas on a lotto ticket and randomise them just as you were buying a ticket For e,g I have a ticket and I want to randomise the numbers and raffle on computer.

Another e,g my current numbers r 3 4 1 2 And my raffle is Aqua 2444 6554 I want to use the pc to randomise the results like Camelot lotto. Python language




Generate random number without srand

I need to generate a random number with srand. I used :

std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1,6);
int dice_roll = distribution(generator);  // generates number in the range 1..6 

but it keeps generating same number.




Zipping random files in PHP

Hi I am trying to collect a number of random files from a folder on my server (./uploads) and zip them so the user can download. I think I am pretty close but I could use some help. I am getting a "503 backend fetch" error everytime and i can not pinpoint my issue. Thank you!!!

<?php 
$rootPath = realpath('./uploads');
//make zip file
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$nfiles = glob($rootPath.'*.{aiff}', GLOB_BRACE);     
$files = $nfiles[array_rand($nfiles,20)]; 
//-------------------------------------------//
foreach ($files as $file)
 { 
 if (!$file->isDir())
{
    // Get path for current file
    $filePath = $file->getRealPath();
    $relativePath = substr($filePath, strlen($rootPath) + 1);  
    // Add file to zip
    $zip->addFile($filePath, $relativePath);
}
 }
 //-------------------------------------------//
 $zip->close();
 header('Content-Type: application/zip');
 header('Content-disposition: attachment; filename='.'generated            
 sounds.zip');
 header('Content-Length: ' . filesize('file.zip'));
 readfile('file.zip');
  if(file_exists('file.zip')){
  unlink('file.zip');
 }
?>




How to sort random number in bubble sort

I'm trying to put run a program that would print 1000 random number and sorted them in bubble sorting but when I run this code, it'll print my 1000 random numbers but wont sort it out. Please help me understand.

import java.util.Random;
import java.util.Arrays;
public class JavaApplication3 {
    public static void main(String [] args){
        Random g = new Random();

        int [] number = new int [1000];

        System.out.print("Random Numbers:");
        for (int d = 0 ; d<number.length ; d++){
            int RandomG = g.nextInt(1000)+1;
            System.out.print(" " +RandomG);
        }

        System.out.print("\nSorted Numbers:"+Arrays.toString(BubbleSortAsceMethod(number)));
    }
    public static int [] BubbleSortAsceMethod(int[] number){
        int temp;

        for(int i = 0 ; i < number.length-1 ; i++){
            for ( int j = 1 ; j < number.length-1 ; j++){
                if ( number[j-1] < number[j]){
                    temp = number[j-1];
                    number[j-1] = number[j];
                    number[j] = temp;
                }
            }
        }
        return number;   
    }
}




Generate unique random number- Logic error

I have the below logic to generate unique random numbers and further, load images referenced by these unique random numbers (from the images Array) at 9 positions:

1) Initially for position 0, generate a random number and load the image referenced by this random number in position 0. 2) Simultaneously load a new Array list with random number already loaded in the previous step. 3) Again for positions 1 to 8, 3.1) generate random number each time. 3.2) compare the random number with the already loaded Array list 3.3) if the newly generated random number already exists in the loaded Array list, Generate another random number; else populate the image corresponding to the unique random number in that position.

Here's the code:

But somehow I am missing out the logic somewhere and get same random numbers repeatedly. Please guide me on the same. Thanks.

    ImageView[] baseimages = {(ImageView) findViewById(R.id.image1), (ImageView) findViewById(R.id.image2), (ImageView) findViewById(R.id.image3), (ImageView) findViewById(R.id.image4), (ImageView) findViewById(R.id.image5), (ImageView) findViewById(R.id.image6), (ImageView) findViewById(R.id.image7), (ImageView) findViewById(R.id.image8), (ImageView) findViewById(R.id.image9)};
    ArrayList<String> Loadimgs = new ArrayList<String>();

    for (i = 0; i < 9; i++) {
        if (first = true)  //initially true
      {
       String alpha[] = {"r1", "r2", "r3", "g1", "g2", "g3", "b1", "b2", "b3", "p1", "p2", "p3", "b1", "br2", "br3"};

 int ran1 = new Random().nextInt(alpha.length);

            baseimages[i].setImageResource(getResources().getIdentifier(alpha[ran1], "drawable", getPackageName()));
            first = false;
            Loadimgs.add(i,alpha[ran1]);

        } else {
            String alpha[] = {"r1", "r2", "r3", "g1", "g2", "g3", "b1", "b2", "b3", "p1", "p2", "p3", "b1", "br2", "br3"};
            int ran1 = new Random().nextInt(alpha.length);
            genimg = alpha[ran1];

            for (j = 0; j < Loadimgs.size(); j++) {
                if (genimg == Loadimgs.get(j)) {
                    j = Loadimgs.size();
                    i--;
                    second = "No";
                } else {
                    continue;
                }
            }
            if (second == "yes")    //initially 'yes'
              {
         baseimages[i].setImageResource(getResources().getIdentifier(genimg,    "drawable", getPackageName()));
         Loadimgs.add(i,genimg);
              }
        }
    }  




NIST STS igamc: UNDERFLOW depending on bitstream size

I am attempting to use NIST's STS tool to determine if a hash function is statistically weak. I have a generated about 25 million hashes and output them into a file as ASCII 0's and 1's (per the STS guide). STS was successfully compiled on and works with the supplied samples. Each hash output is represented by a sequence 512 binary characters, this means the argument for assess is 512 (ie. we run using: ./assess 512). But here is the rub, the number of bitstreams (prompted during execution - I have full terminal output below) seems to toggle success / failure of the tool. For example, 50 bitstreams result in success, while anything over about 5,000 seems to fail with the igamc: underflow error. To my knowledge, bitstreams is pretty much the number of sample to read from the source file. Is this understanding correct? How do I narrow down this error / correct it?

I apologize for the long-form text but I am trying to be as complete as possible.


./assess 512
       G E N E R A T O R    S E L E C T I O N 
       ______________________________________

[0] Input File                 [1] Linear Congruential
[2] Quadratic Congruential I   [3] Quadratic Congruential II
[4] Cubic Congruential         [5] XOR
[6] Modular Exponentiation     [7] Blum-Blum-Shub
[8] Micali-Schnorr             [9] G Using SHA-1

Enter Choice: 0

    User Prescribed Input File: sha3mod.dat

            S T A T I S T I C A L   T E S T S
            _________________________________

[01] Frequency                       [02] Block Frequency
[03] Cumulative Sums                 [04] Runs
[05] Longest Run of Ones             [06] Rank
[07] Discrete Fourier Transform      [08] Nonperiodic Template Matchings
[09] Overlapping Template Matchings  [10] Universal Statistical
[11] Approximate Entropy             [12] Random Excursions
[13] Random Excursions Variant       [14] Serial
[15] Linear Complexity

     INSTRUCTIONS
        Enter 0 if you DO NOT want to apply all of the
        statistical tests to each sequence and 1 if you DO.

Enter Choice: 0

     INSTRUCTIONS
        Enter a 0 or 1 to indicate whether or not the numbered statistical
        test should be applied to each sequence.

  123456789111111
           012345
  111111110111111


    P a r a m e t e r   A d j u s t m e n t s
    -----------------------------------------
[1] Block Frequency Test - block length(M):         128
[2] NonOverlapping Template Test - block length(m): 9
[3] Approximate Entropy Test - block length(m):     10
[4] Serial Test - block length(m):                  16
[5] Linear Complexity Test - block length(M):       500

Select Test (0 to continue): 0

   How many bitstreams? 120000

   Input File Format:
    [0] ASCII - A sequence of ASCII 0's and 1's
    [1] Binary - Each byte in data file contains 8 bits of data

Select input mode: 0

 Statistical Testing In Progress.........

igamc: UNDERFLOW
igamc: UNDERFLOW

The underflow error seems to continue until I cancel execution.




C++11 discarding numbers in a PRNG sequence

I am trying to use the function discard to skip numbers in a sequence of random numbers. Here is my try:

#include <random>
#include <iostream>

using namespace std;

int main ()
{
  unsigned seed = 1;
  uniform_real_distribution<> dis(0,10);
  mt19937 gen (seed);
  cout << dis(gen) << endl;
  //gen.discard(1); // supposed to be the same of `dis(gen)`?
  cout << dis(gen) << endl;
  cout << dis(gen) << endl;
}

The output of this code is

9.97185
9.32557
1.28124

If I uncomment the line with gen.discard(1) I get

9.97185
0.00114381
3.02333

but I was expecting that the first two numbers are 9.97185 and 1.28124, since the number 9.32557 would be skipped.

Q: How to use discard properly or, is there an alternative solution with the same effect I want? I could simply use dis(gen), but maybe it i

Thanks.




MatLAB help: shuffling a predefined vector without consecutive numbers

I'm having troubles with randomly a shuffling vector but without consecutive numbers, given that each value is repeated equally.

More specifically, I would like to repeat the matrix [1:4] ten times (40 elements in total) so that 1, 2, 3 and 4 would all repeat 10 times without being consecutive.

If there is any clarification needed please let me know, I hope this question was clear.

This is what I have so far:

cond_order = repmat([1:4],10,1); %make matrix
cond_order = cond_order(:); %make sequence

I know randperm is quite relevant but I'm not sure how to use it with the one condition of non-consecutive numbers.




What did i do wrong with my downloader code? [PHP]

I am trying to randomly download some files and I apologize because I posted it earlier but can someone explain what I am doing wrong in detail? I can not seem to debug it as I know minimal php :/

<?php 
$rootPath = realpath('./uploads');
//make zip file
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$nfiles = glob($rootPath.'*.{aiff}', GLOB_BRACE);     
$files = array_rand($nfiles, 20);
foreach($files as $file)  {
    $pathtofile = $nfiles[$file];
 if (!$file->isDir())
{
    // Get path for current file
    $filePath = $pathtofile->getRealPath();
    $relativePath = str_replace($rootPath, "", $file);
    // Add file to zip
    $zip->addFile($filePath, $relativePath);
}
}
 //-------------------------------------------//
 $zip->close();
 header('Content-Type: application/zip');
 header('Content-disposition: attachment; filename='.'generatedsounds.zip');
 header('Content-Length: ' . filesize('file.zip'));
 readfile('file.zip');
  if(file_exists('file.zip'))
{
  unlink('file.zip');
}
?>




Adding code to random number generator to prevent duplicates [duplicate]

This question already has an answer here:

I need to get code that will allow me to remove duplicates of numbers as I have a random number generator which generates number associated to the counter of an array, the array being a 'pack' of cards, so I can't really afford to change the code but I really need to stop duplicates appearing!

    for (int v = 0; v < 30; v++)
    {
        Random rnd = new Random();
        rnd.nextInt(30);

        int i = rnd.nextInt(30);

        System.out.println(i + " " + aCards[i].getCard());
    }

This is what the code above produces, there are clearly duplicates within the list!




A query that creates a unique 10 digit number the leading digit must not be zero and the 2ndand 3rd wil represesnt a state

I need to write a query that creates a unique 10 digit number for my table named tbl_user_vital. The leading digit must not be zero and the 2nd & 3rd digit will represent a state.

Here is what I have so far:

DELIMITER @@
CREATE FUNCTION generate_unique_pin() RETURNS int(10)
BEGIN

DECLARE newpin INT;
DECLARE myloop BOOL;
SET myloop = 1;

WHILE myloop = 1 DO
   SET newpin = FLOOR(RAND() * 9999999();
   IF (SELECT COUNT(*) AS used db_younitive.tbl_user_vital.user_pin WHERE user_pin = newpin) = 0 THEN
      SET myloop = 0;
   END IF;
END WHILE;

RETURN newpin;
END@@
DELIMITER ;

And here is the error message I'm getting:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '();
   IF (SELECT COUNT(*) AS used db_younitive.tbl_user_vital.user_pin WHERE u' at line 9

It seems the problem is it is the newpin variable, it is not receiving any value. I cant figure out why..

Number Generated: 2140-1234-45

This will be entered in the mysql database using jquery.




Php shuffle trough database users

How can I shuffle through the users of my database, currently I have this:

$users = db->select($table, $columnUsers);

foreach($users as $user) {
    echo $user['firstname'];
}

This echo's me out all users of my database, but how can I shuffle those users at this point?




Php shuffle users equally to calender weeks

I am trying to print Calender Weeks from 1-52 in a table with their starting and ending date,

now I want to add some users of my database (database holds 15 users):

Code:

<tbody>
    <?php
    $currentYear = date('Y');
    $kw = CalenderWeekHelper::getCalenderWeek($currentYear);
    for ($i=1; $i <= 52; $i++) {
        foreach($resultRand as $result) {
    ?>
    <tr>
        <td>
            <?php echo $i; ?>
        </td>
        <td colspan="2">
            <?php echo $kw[$i]['start'].' - '.$kw[$i]['end']; ?>
        </td>
        <td>
            <?php echo $result['user']; ?>
        </td>
    </tr>
    <?php
        }
    }
    ?>
</tbody>

Helper Class looks like this (works):

<?php

class CalenderWeekHelper {

        public static function getCalenderWeek($year)
        {
            for ($i=1; $i <= 52; $i++)
            {
                $week = sprintf('%02s', $i); 
                $from = date("d.m.Y", strtotime("{$year}W{$week}"));
                $to   = date("d.m.Y", strtotime("{$year}W{$week} +6 days"));
                $weekArray[$i] = array('start' => $from, 'end' => $to);

            }
            return $weekArray;
        }
}

?>

This gives me something like this:

    Calender Weeks     |             date            |       user
_______________________________________________________________
    1                  |   29.12.2014 - 04.01.2015   |      Steven
    2                  |             ...             |      Steven
    3                  |             ...             |      Steven
    4                  |             ...             |      Steven
    5                  |             ...             |      Steven
    6                  |             ...             |      Steven
    7                  |             ...             |      Steven
    8                  |             ...             |      Steven
    9                  |             ...             |      Steven
   10                  |             ...             |      Steven
   11                  |             ...             |      Steven
   ...                 |             ...             |      Steven
   52                  |             ...             |      Steven
    1                  |   29.12.2014 - 04.01.2015   |      Glenn
   ...                 |             ...             |      Glenn
   52                  |             ...             |      Glenn

The dates do work, but as you can see I cannot handle those 2 loops. It should look something like this:

    Calender Weeks     |             date            |       user
_______________________________________________________________
    1                  |   29.12.2014 - 04.01.2015   |      Steven
    2                  |             ...             |      Glenn
    3                  |             ...             |      Lisa
    4                  |             ...             |      Jonn
    5                  |             ...             |      Alex
    6                  |             ...             |      Micheal
    7                  |             ...             |      Sucre
    8                  |             ...             |      T-Bag
    9                  |             ...             |      Han
   10                  |             ...             |      ...
   11                  |             ...             |      ...
   ...                 |             ...             |      ...
   52                  |             ...             |      ...

Since I have only 15 users in my database, the names have to repeat but should repeat equally if possible.

Can anyone help me out?




Pick a random value from a Go Slice

So in my quest to learn new languages,I have decided to learn Go and this is the very first day so please be gentle on me..I have a slice of values and i need to randomly pickup a value and then concatenate it with a fixed string..This is what i have till now..

func main() {
//create the reasons slice and append reasons to it
reasons := make([]string, 0)
reasons = append(reasons,
    "Locked out",
    "Pipes broke",
    "Food poisoning",
    "Not feeling well")

message := fmt.Sprint("Gonna work from home...", pick a random reason )
}

Is there an inbuilt function which can help me do that "pick a random reason" part..?




Generate random elements from array having hindi characters

I am trying to develop a program using c++ that generates a random element from an array that has Hindi characters stored in it. I had hardcoded the array while initiating it e.g

std::string hindi_array[] = {std::to_string('ठ')};

now to generate a random element from the array, I have written a function that generates a random index of the array(which works fine). After I get the random index, I pass it on to another function that uses this index to print the character. The following lines are the snippet for that:

   int key = generate_random();
   sprintf(str, "%s", Hindi_array[key].c_str());
   lbl->setCaption(Rand_array[key].c_str());

lbl is a defined label here. The output that I'm getting is a number like 14722230. Are hindi characters somehow represented in this way at some level? Is there a way to transform it to the actual character that I want to display?

I am a complete newbie to c++ programming so please pardon me if it is too basic or stupid a question. Any help would be great...Thanks!




dimanche 29 novembre 2015

Java: Using a for-loop to fill in an array with random integers within a specific range [duplicate]

This question already has an answer here:

Criticism is welcome! I'm learning and wish to be corrected so that I may learn!

How would I go about using a for-loop to generate a random values to fill an array within the range of something like 1 to 50.

I have it set up to fill an array with however many numbers the user wishes for it to fill. I'm currently just playing around with arrays trying to understand how to use them in different ways. I know I'll have a test coming up where I'll have to do something similar and would like to have mastered it.

This is what I have so far... but I'd like to fill it with random integers in a range (any range), but for the sake of giving a range for learning purposes lets just go with 1-50.

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

{public static void main(String [] args)
   {
     Scanner MyScan = new Scanner(System.in);
     int Number;
     System.out.println("How many integers do you want in your array?");
     Number = MyScan.nextInt();
     int[] MyArray = new int[Number];

    }//end main
}//end class




[C++]Finding error about the pointer of a distribution (function)

Could someone tell me what is wrong about my code (C++):

int main(){
unsigned seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::subtract_with_carry_engine<unsigned, 24, 10, 24> gen(seed);
std::tr1::normal_distribution<double> *imDensity;
imDensity = new std::tr1::normal_distribution<double>(0, 5);

double p = imDensity(gen) //here is the error
}

The error is "expression preceding parentheses of apparent call must have (pointer-to-) function type". I have to pass the random generator to the distribution function, but I don't know how to do it when using a pointer.




How do you randomize cell rows and lock certain elements in place?

lag2 = [{'walk', 'water', 'warm', 'cheer', 'word', 'happy', 'whim', 'womb', 'wear', 'well'};
{'hello', 'here', 'hat', 'that', 'happy', 'hide', 'awesome', 'there', 'howl', 'harry'};
{'look', 'listen', 'lyer', 'hateful', 'lost', 'hatred', 'plot', 'player', 'plow', 'lay'};
{'goat', 'meat', 'hope', 'house', 'love', 'wall', 'down', 'up', 'sky', 'mount'};
{'go', 'golf', 'loser', 'gyrus', 'terrible', 'gallore', 'tug', 'thor', 'gear', 'leg'}];

So I have this cell array with 5 rows. I want to randomize the order of the rows so they appear differently. I also want to lock certain targets like the words: cheer, happy happy, awesome hateful, hatred hope, love loser, terrible. SO that they always have one word in between. How do I do that?




How do I shuffle certain parts of an array in java?

In my program, I have an array that changes sizes (16 elements, 36 elements, and 64 elements) that I need to randomly shuffle. I want to have one block of code or method so that it will shuffle only those elements of the array but not include the "null" values. So is there a way to only shuffle specific parts of an array Ex. first 16, 36, or 64?




Codeigniter random and filtered

i want a result filtered by id and number of rcount.

this is my objectives table

http://ift.tt/1Iihi4F

objective_question table

http://ift.tt/1loqv0X

i already have this query with codeigniter

$this->db->select("objectives.id, objectives.rcount, objective_questions.question, objective_questions.a, objective_questions.b, 
                 objective_questions.c, objective_questions.d, objective_questions.answer");

$this->db->from("objectives");

$this->db->join("objective_questions", "objectives.id = objective_questions.objective_id");

$this->db->where("sub_module_id", $sub_module_id);

$query = $this->db->get();

with this result of

http://ift.tt/1Iihj8G

what i want is to query the sub_module_id and pick a random question by the number of rcount where objectives.id is equal to objective_questions.objective_id, so total of question will i get based on my two tables is 9. 1 + 4 + 4 = 9.

any idea how do i get the result? Thank you.!




Randomly Create Enemies In Android Studio

I'm making my first android game, and i want to create a random enemy every three seconds, i have six enemies but my code it's not working!! i don't know what i'm missing or doing wrong, i have a red line under (rand == 0) and (rand == 1) please help! The code i'm using:

if (EnemyElapsed > (2000-alien.getScore()/4)){ switch ((int) (rand.nextDouble() * (6))) { if(rand == 0){ enemy.add(new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.dog), WIDTH + 10,60, 250, 250, alien.getScore(), 2)); enemyStartTime = System.nanoTime();} else if(rand == 1){ enemy.add(new Enemy(BitmapFactory.decodeResource(getResources(), R.drawable.aalien), WIDTH + 10,60, 250, 250, alien.getScore(), 2)); enemyStartTime = System.nanoTime();} }




Generate random between [0, 1)

I want to generate a random float value between 0 and 1 excluding 1, I.e. [0, 1). I've searched a lot but I couldn't find an answer of this. I've tried the following trick however it generates a negative values

(double)rand()/(double)RAND_MAX-1;




youtube feeds random music based on location?

hi,
i am trying to get list of youtube random music each time i refresh the page using feed link
is there anyway to do that using similar link below?

https://www.youtube.com/feeds/videos.xml?xxxxxxxxxxxxxxx




word guessing game replacing guesses in python

import random

words = ["stack", "queue", "tree", "linked list", "software", "hardware", "operating systems",
"algorithm", "computer", "network"]

PLAYER_NAME=raw_input("What is your name? ")
print("Hey, "),PLAYER_NAME
print("You will guess this words.."),words

def random_choice(words):
    randomword=random.choice(words)
    return randomword
random_choice(words)

# Your second function is responsible of initializing the word with '' (dashes).
# The initialize word has to be a word that is represented with a list.
# Example: Word that will be guessed = COMPUTER


def initalizing_word(words):
    initalized_word=[]
    randomword=random_choice(words)
    for i in range(1,len(randomword)+1):
        initalized_word.append('-')
    print(initalized_word),"is the word that you will be guess."
    print(randomword)
    return initalized_word
randomword=random.choice(words)
initalizing_word(words)

# Your third and last function is responsible of replacing the correct letters to its
# corresponding indexes in the list and word.

def replace_word(randomword,initalized_word):
    while True:
        guess=raw_input("your guess pls..\n")
        if len(guess)>len(randomword) or len(guess)<1:
            print("This is impossible.")
        if len(guess)>1:
            print("You must enter just one string.")
        if len(guess)==1 and guess!=int: #having problem at this part. i can't replace correct guesses to the initilazed_word list.
            if guess in randomword:
                initilazed_word.replace("-",guess)
        print(initilazed_word)
initilazed_word=initalizing_word(words)
replace_word(randomword,initilazed_word)

Hey there! I am trying to code word guessing game.. However, i can't find a solution for replacing True guesses to the initilazed _word list. Furthermore i'm thinking that i overused function calls, so there is two different words to guess like

['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-',     '-', '-'] is the word that you will be guess.
operating systems

['-', '-', '-', '-', '-', '-', '-'] is the word that you will be guess.
network

i guess im using funtions wrong :| i need your help for these problems..

furthermore.. i expect an output if the randomword is stack and guess s

['s', '-', '-', '-', '-'] and on..




Prestashop module tab slider random product

This is Tab category slider module of Prestashop CMS, it shows last added productes, i need to show random products.

I will add more info if it will be needed sry for my bad English.

Hello guys, This is Tab category slider module of Prestashop CMS, it shows last added productes, i need to show random products.

Hello guys, This is Tab category slider module of Prestashop CMS, it shows last added productes, i need to show random products.

Hello guys, This is Tab category slider module of Prestashop CMS, it shows last added productes, i need to show random products.

I will copy text cause i cant post this thread.

class postabcateslider1 extends Module {
    private $spacer_size = '5'; 
    private $_postErrors  = array();
    private $_html= null;
    public function __construct() {
        $this->name         = 'postabcateslider1';
        $this->tab          = 'front_office_features';
        $this->version      = '1.5';
        $this->author       = 'posthemes';
        $this->displayName  = $this->l('Category Tabs Slider 1');
        $this->description  = $this->l('Category Tabs Slider 1');
        parent :: __construct();

    }

    public function install() {

    Configuration::updateValue($this->name . '_p_on_row', 4);
    Configuration::updateValue($this->name . '_p_limit', 30);
    Configuration::updateValue($this->name . '_tab_effect', 'wiggle');
    Configuration::updateValue($this->name . '_p_on_row', 4);
    Configuration::updateValue($this->name . '_p_width', 150);
    Configuration::updateValue($this->name . '_p_height', 200);
    Configuration::updateValue($this->name . '_min_item', 1);
    Configuration::updateValue($this->name . '_max_item', 5);
    Configuration::updateValue($this->name . '_speed_slide', 3000);
    Configuration::updateValue($this->name . '_a_speed', 500);
    Configuration::updateValue($this->name . '_show_arrow', 0);
    Configuration::updateValue($this->name . '_show_ctr', 0);

    $arrayDefault = array('CAT3','CAT4','CAT5');
    $cateDefault = implode(',',$arrayDefault);
    Configuration::updateGlobalValue($this->name . '_list_cate',$cateDefault);

        return parent :: install()

            && $this->registerHook('top')
        /*  && $this->registerHook('displayHome') */
            && $this->registerHook('blockPosition2')
            //&& $this->registerHook('displayHome')
            && $this->registerHook('header')
            && $this->registerHook('actionOrderStatusPostUpdate')
            && $this->registerHook('addproduct')
            && $this->registerHook('updateproduct')
            && $this->registerHook('deleteproduct');
    }

      public function uninstall() {
        Configuration::deleteByName($this->name . '_list_cate');
        $this->_clearCache('postabcateslider1.tpl');
        return parent::uninstall();
    }


    public function psversion() {
        $version=_PS_VERSION_;
        $exp=$explode=explode(".",$version);
        return $exp[1];
    }


    public function hookHeader($params){
        // if ($this->psversion()==5){
            // $this->context->controller->addCSS(($this->_path).'postabcateslider.css', 'all');
            // $this->context->controller->addCSS(($this->_path).'animate.delay.css', 'all');
            // $this->context->controller->addCSS(($this->_path).'animate.min.css', 'all');

        // } else {
            // Tools::addCSS(($this->_path).'postabcateslider.css');
            // Tools::addCSS(($this->_path).'animate.delay.css');
            // Tools::addCSS(($this->_path).'animate.min.css');

        // }
    }

    public function hookblockPosition2($params) {
            $nb = Configuration::get($this->name . '_p_limit');
            $product_on_row = Configuration::get($this->name . '_p_on_row');
            $arrayCategory = array();
            $catSelected = Configuration::get($this->name . '_list_cate');
            $cateArray = explode(',', $catSelected); 
            $id_lang =(int) Context::getContext()->language->id;
            $id_shop = (int) Context::getContext()->shop->id;
            $arrayProductCate = array();
            foreach($cateArray as $id_category) {
                $id_category = str_replace('CAT','',$id_category);
                $category = new Category((int) $id_category, (int) $id_lang, (int) $id_shop);
                $categoryProducts = $category->getProducts($this->context->language->id, 0, ($nb ? $nb : 5),'date_add','DESC');
                if($categoryProducts) {
                    $arrayProductCate[] = array('id' => $id_category, 'name'=> $category->name, 'product' => $categoryProducts);
                }
            }

            $options = array(
                'p_width' => Configuration::get($this->name . '_p_width'),
                'p_height' => Configuration::get($this->name . '_p_height'),

                'speed_slide' => Configuration::get($this->name . '_speed_slide'),
                'a_speed' => Configuration::get($this->name . '_a_speed'),
                 'show_des' => Configuration::get($this->name . '_show_des'),
                'show_arrow' => Configuration::get($this->name . '_show_arrow'),
                'show_ctr' => Configuration::get($this->name . '_show_ctr'),
                'min_item' => Configuration::get($this->name . '_min_item'),
                'max_item' => Configuration::get($this->name . '_max_item'),  'show_price' => Configuration::get($this->name . '_show_price'),

            );

            $this->context->smarty->assign('slideOptions', $options);
            $this->smarty->assign(array(
                'productCates' => $arrayProductCate,
                'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'),
                'homeSize' => Image::getSize(ImageType::getFormatedName('home')),
                'product_on_row' => $product_on_row,
                'tab_effect' => Configuration::get($this->name . '_tab_effect'),
                'title' => Configuration::get($this->name . '_title'),

            ));
        return $this->display(__FILE__, 'postabcateslider1.tpl');
    }

      public function getContent() {
        $output = '<h2>' . $this->displayName . '</h2>';
        if (Tools::isSubmit('submitPosTabCate')) {
            if (!sizeof($this->_postErrors))
                $this->_postProcess();
            else {
                foreach ($this->_postErrors AS $err) {
                    $this->_html .= '<div class="alert error">' . $err . '</div>';
                }
            }
        }
        return $output . $this->_displayForm();
    }

    public function getSelectOptionsHtml($options = NULL, $name = NULL, $selected = NULL) {
        $html = "";
        $html .='<select name =' . $name . ' style="width:130px">';
        if (count($options) > 0) {
            foreach ($options as $key => $val) {
                if (trim($key) == trim($selected)) {
                    $html .='<option value=' . $key . ' selected="selected">' . $val . '</option>';
                } else {
                    $html .='<option value=' . $key . '>' . $val . '</option>';
                }
            }
        }
        $html .= '</select>';
        return $html;
    }

    private function _postProcess() {

        Configuration::updateValue($this->name . '_list_cate', implode(',', Tools::getValue('list_cate')));
        Configuration::updateValue($this->name . '_p_on_row', Tools::getValue('p_on_row'));
        Configuration::updateValue($this->name . '_p_limit', Tools::getValue('p_limit'));
        Configuration::updateValue($this->name . '_tab_effect', Tools::getValue('tab_effect'));
        Configuration::updateValue($this->name . '_title', Tools::getValue('title'));
        Configuration::updateValue($this->name . '_p_height', Tools::getValue('p_height'));
        Configuration::updateValue($this->name . '_p_width', Tools::getValue('p_width'));
        Configuration::updateValue($this->name . '_p_limit', Tools::getValue('p_limit'));

        Configuration::updateValue($this->name . '_speed_slide', Tools::getValue('speed_slide'));
        Configuration::updateValue($this->name . '_a_speed', Tools::getValue('a_speed'));

        Configuration::updateValue($this->name . '_show_arrow', Tools::getValue('show_arrow'));
        Configuration::updateValue($this->name . '_show_ctr', Tools::getValue('show_ctr'));
        Configuration::updateValue($this->name . '_min_item', Tools::getValue('min_item'));
        Configuration::updateValue($this->name . '_max_item', Tools::getValue('max_item'));

        $this->_html .= '<div class="conf confirm">' . $this->l('Settings updated') . '</div>';
    }

    private function _displayForm(){ 
        $spacer = str_repeat('&nbsp;', $this->spacer_size);

     $tabEffect = array();
        $tabEffect = array(
            'none' => 'None', 
            'hinge' => 'Hinge', 
            'flash' => 'Flash', 
            'shake' => 'Shake',
            'bounce' => 'Bounce',
            'tada' => 'Tada' ,
            'swing' => 'Swing', 
            'wobble' => 'Wobble', 
            'pulse' => 'Pulse', 
            'flip' => 'Flip', 
            'flipInX' => 'FlipInX', 
            'flipInY' => 'FlipInY', 
            'fadeIn' => 'FadeIn', 
            'bounceInUp' => 'BounceInUp', 
            'fadeInLeft' => 'FadeInLeft', 
            'rollIn' => 'RollIn', 
            'lightSpeedIn' => 'LightSpeedIn', 
            'wiggle' => 'Wiggle', 
            'rotateIn' => 'RotateIn', 
            'rotateInUpLeft' => 'RotateInUpLeft', 
            'rotateInUpRight' => 'RotateInUpRight'

        );
         $this->_html .= '
        <form action="'.$_SERVER['REQUEST_URI'].'" method="post">
                  <fieldset>
                    <legend><img src="../img/admin/cog.gif" alt="" class="middle" />' . $this->l('Settings') . '</legend>
                    <label>'.$this->l('Title: ').'</label>
                    <div class="margin-form">
                            <input type = "text"  name="title" value ='.(Tools::getValue('title')?Tools::getValue('title'): Configuration::get($this->name.'_title')).' ></input>
                    </div>
                    <label>'.$this->l('Effect Tab: ').'</label>
                    <div class="margin-form">';
                       $this->_html .= $this->getSelectOptionsHtml($tabEffect,'tab_effect',   (Tools::getValue('tab_effect') ? Tools::getValue('tab_effect') : Configuration::get($this->name . '_tab_effect')));
                       $this->_html .='
                    </div>';

                    $this->_html .= '<label>' . $this->l('Show Link/Label Category: ') . '</label>';
                    $this->_html .= '<div class="margin-form">';
                    $this->_html .= '<select multiple="multiple" name ="list_cate[]" style="width: 200px; height: 160px;">';
                    // BEGIN Categories
                    $id_lang = (int) Context::getContext()->language->id;
                    $this->getCategoryOption(1, (int) $id_lang, (int) Shop::getContextShopID());
                    $this->_html .= '</select>
                    </div>';
                    $this->_html .='

                              <label>' . $this->l('Show Next/Back control: : ') . '</label>
                    <div class="margin-form">';
                    $this->_html .= $this->getSelectOptionsHtml(array(0 => 'No', 1 => 'Yes'), 'show_arrow', (Tools::getValue('title') ? Tools::getValue('show_arrow') : Configuration::get($this->name . '_show_arrow')));
                    $this->_html .='
                                </div>
                                <label>' . $this->l('Show navigation control: : ') . '</label>
                                 <div class="margin-form">';
                    $this->_html .= $this->getSelectOptionsHtml(array(0 => 'No', 1 => 'Yes'), 'show_ctr', (Tools::getValue('title') ? Tools::getValue('show_ctr') : Configuration::get($this->name . '_show_ctr')));
                    $this->_html .='
                                </div>
                     <label>'.$this->l('Products Limit: ').'</label>
                    <div class="margin-form">
                            <input type = "text"  name="p_limit" value ='.(Tools::getValue('p_limit')?Tools::getValue('p_limit'): Configuration::get($this->name.'_p_limit')).' ></input>
                    </div>
                    <input type="submit" name="submitPosTabCate" value="'.$this->l('Update').'" class="button" />
                     </fieldset>
        </form>';
        return $this->_html;
    }


     private function getCategoryOption($id_category = 1, $id_lang = false, $id_shop = false, $recursive = true) {
        $cateCurrent = Configuration::get($this->name . '_list_cate');  
        $cateCurrent = explode(',', $cateCurrent);
        $id_lang = $id_lang ? (int)$id_lang : (int)Context::getContext()->language->id;
        $category = new Category((int)$id_category, (int)$id_lang, (int)$id_shop);

        if (is_null($category->id))
            return;

        if ($recursive)
        {
            $children = Category::getChildren((int)$id_category, (int)$id_lang, true, (int)$id_shop);
            $spacer = str_repeat('&nbsp;', $this->spacer_size * (int)$category->level_depth);
        }

        $shop = (object) Shop::getShop((int)$category->getShopID());
                if (in_array('CAT'.(int)$category->id, $cateCurrent)) {
                    $this->_html .= '<option value="CAT'.(int)$category->id.'" selected ="selected" >'.(isset($spacer) ? $spacer : '').$category->name.' ('.$shop->name.')</option>';
                } else {
                    $this->_html .= '<option value="CAT'.(int)$category->id.'">'.(isset($spacer) ? $spacer : '').$category->name.' ('.$shop->name.')</option>';
                }

        if (isset($children) && count($children))
            foreach ($children as $child)
                $this->getCategoryOption((int)$child['id_category'], (int)$id_lang, (int)$child['id_shop']);
    }



}




samedi 28 novembre 2015

random timer generator for swift in xcode [duplicate]

This question is an exact duplicate of:

I want a function to be called at random times while the user is playing. For example after 2 seconds passed a function is called and then after another 6 seconds it is called again. How do I do that?

This is not working

    func time() {
randomNumber = CGFloat((drand48())
timer = NSTimer.scheduledTimerWithTimeInterval(randomNumber, traget: self, selector: "startTimer", userInfo: nil, repeats: true)

Xcode is not liking it and I donot know why




How Does Java Produce a Random Number?

I know you can use Math.random() in Java to generate a random double from 0.0 to 1.0, but how does the computer pick a number? What code is the computer following to simulate randomness?




Random generator based off NStimer Xcode 7 swift 2

I want a function to be called at random times while the user is playing. For example after 2 seconds passed a function is called and then after another 6 seconds it is called again. How do I do that?

This is not working

    func time() {
randomNumber = CGFloat((drand48())
timer = NSTimer.scheduledTimerWithTimeInterval(randomNumber, traget: self, selector: "startTimer", userInfo: nil, repeats: true)

Xcode is not liking it and I donot know why




Seeding Random number generator not working

I have a c++ program that uses a random generator to create a cube. To create the cube I have this:

void generateSquare() {
  int num = 0;
  srand(time(NULL));

  for (int r = 0; r < MSQUARE; r++) {
    for (int c = 0; c < MSQUARE; c++) {
      do {
        num = (rand() % (MSQUARE * MSQUARE)) + 1;
      } while (!checkUnique(num));
      cube[r][c] = num;
    }
  }
}

It only allows a number to be generated one. This function is then wrapped in a do..while loop so that if the square doesn't meet a specific condition a new square will be generated until the one that does meet the condition is generated.

The problem is that it continually is generating the same square over and over again. I thought that the srand(time(NULL)) would seed the rand() function so that it would generate different random numbers each time to create a new unique square every time it is called but it looks like that is not happening.

void checkSquare() {
  do {
    generateSquare();
  } while (!perfect);
}

This is not the actual do...while loop but gives you an idea of how it's being called.

How do I make sure the seed is unique each time?




PHP Zip random files from directory

I am currently making a website and I am trying to collect a number of random files from a folder on my server (./uploads) and zip them so the user can download them. I think I am pretty close but cant seem to setup the loop right. I am trying to first get 20 random files with the line $files = $nfiles[array_rand($nfiles,20)]; then take these 20 files and use the loop to zip them all up but I can not figure out quite how to do it. :/

edit: discovered that i need to use $rand_indexes = array_rand($nfiles, 20); instead..now to figure out how to replace the glob function to just get a list of all objects.

<?php 
$rootPath = realpath('./uploads');
//make zip file
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$nfiles = glob($rootPath.'*.{aiff}', GLOB_BRACE);     
$files = $nfiles[array_rand($nfiles,20)]; 
//-------------------------------------------//
foreach ($files as $file)
 { 
 if (!$file->isDir())
{
    // Get path for current file
    $filePath = $file->getRealPath();
    $relativePath = substr($filePath, strlen($rootPath) + 1);  
    // Add file to zip
    $zip->addFile($filePath, $relativePath);
}
 }
 //-------------------------------------------//
 $zip->close();
 header('Content-Type: application/zip');
 header('Content-disposition: attachment; filename='.'generated            
 sounds.zip');
 header('Content-Length: ' . filesize('file.zip'));
 readfile('file.zip');
  if(file_exists('file.zip')){
  unlink('file.zip');
 }
?>




Randomly select from array then assign selection to a variable

I have a function that randomly selects a monster from an object. Here's the function:

var travel = function(direction) {
        var newRoom = rooms[currentRoom.paths[direction]];
        if (!newRoom) {
            $("<p>You can't go that way.</p>").properDisplay();
        }
        else {
            currentRoom = newRoom;
            $("<p>You are now in the " + currentRoom.name + " Room.</p>").properDisplay();
                if (currentRoom.hasMonsters) {
                    function pickRand() {
                        var monsterArray = Object.keys(monsters);   
                        var randomKey = Math.floor(Math.random() * monsterArray.length);
                        return $("<p>Holy Crap!  There's a " + monsterArray[randomKey] + " in here!</p>").properDisplay();  
                    }
                    pickRand();

                }
        }
    };

Here's the object:

var monsters = {
    zombie:  {
        hitPoints: 10,
        loot: "magic knife"
    },
    skeleton: {
        hitPoints: 15,
        loot: "magic shield"
    },
    ghoul:  {
        hitPoints: 12,
        loot: "magic helm"
    }
};  

It's set up to randomly select "Zombie", "Skeleton", or "Ghoul." Everything works fine. How do I take whatever was randomly selected and save it to a variable?

I've tried a couple things like:

var beast = pickRand();

and

var beast = monsterArray;

But no luck. What am I missing?




How would I randomize several string cell arrays?

So I have certain trials:

ST1_lag2 = (['%', '&', ':]', '@', '!', '&', '&', '*', '(', 'A', '%', 'U', '#', '&', '@', '%', '%']);
ST2_lag2 = (['%', '&', '$', '@', '!', '&', '&', '*', '(', '&', 'I', ')', 'E', '&', '@', '%', '%']);
ST3_lag2 = (['*', '&', '$', '@', '!', '&', '&', 'T', '(', 'H', '%', '*', '#', '&', '@', '%', '%']);

Now I want a while loop that can go through all these variables, and randomize them so that the letters amongst the symbols always appear after one symbol in between. Can I do that? If so, Please help me as to how I can accomplish this.

THank You




+1/-1 randomly distributed in 2D array

I would like to create a 4x4 array which is filled randomly with +1 or -1 only in fortran95. I found a post that can generate numbers:

program rand_test
use,intrinsic :: ISO_Fortran_env
real  :: r(6)
integer       :: i(6)

! call init_random_seed() would go here

call random_number(r)

i = -1 + FLOOR(3*r)       ! n=-1 and m=1

print *, i
end program

However, this includes 0 which I don't want. Is it possile to remove the 0, if so, how?




How print a variable randomly in a list

In python

For Example:

import random
Bandit="B"
List=["","","",""]

What i want it to print out as:

print["B","","B",""] or ["","B","","B"]  




How can I randomizing results on a lottery ticket

im trying to highlight specific areas on a lotto ticket and randomise them just as you were buying a ticket For e,g I have a ticket and I want to randomise the numbers and raffle on computer.

Another e,g my current numbers r 3 4 1 2 And my raffle is Aqua 2444 6554 I want to use the pc to randomise the results like Camelot lotto. Python language




Generate random number without srand

I need to generate a random number with srand. I used :

std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1,6);
int dice_roll = distribution(generator);  // generates number in the range 1..6 

but it keeps generating same number.




Zipping random files in PHP

Hi I am trying to collect a number of random files from a folder on my server (./uploads) and zip them so the user can download. I think I am pretty close but I could use some help. I am getting a "503 backend fetch" error everytime and i can not pinpoint my issue. Thank you!!!

<?php 
$rootPath = realpath('./uploads');
//make zip file
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$nfiles = glob($rootPath.'*.{aiff}', GLOB_BRACE);     
$files = $nfiles[array_rand($nfiles,20)]; 
//-------------------------------------------//
foreach ($files as $file)
 { 
 if (!$file->isDir())
{
    // Get path for current file
    $filePath = $file->getRealPath();
    $relativePath = substr($filePath, strlen($rootPath) + 1);  
    // Add file to zip
    $zip->addFile($filePath, $relativePath);
}
 }
 //-------------------------------------------//
 $zip->close();
 header('Content-Type: application/zip');
 header('Content-disposition: attachment; filename='.'generated            
 sounds.zip');
 header('Content-Length: ' . filesize('file.zip'));
 readfile('file.zip');
  if(file_exists('file.zip')){
  unlink('file.zip');
 }
?>




vendredi 27 novembre 2015

How to sort random number in bubble sort

I'm trying to put run a program that would print 1000 random number and sorted them in bubble sorting but when I run this code, it'll print my 1000 random numbers but wont sort it out. Please help me understand.

import java.util.Random;
import java.util.Arrays;
public class JavaApplication3 {
    public static void main(String [] args){
    Random g = new Random();

    int [] number = new int [1000];

    System.out.print("Random Numbers:");
    for (int d = 0 ; d<number.length ; d++){
        int RandomG = g.nextInt(1000)+1;
        System.out.print(" " +RandomG);
        }

  System.out.print("\nSorted Numbers:"+Arrays.toString(BubbleSortAsceMethod(number)));

                     }
     public static int [] BubbleSortAsceMethod(int[] number){
    int temp;

    for(int i = 0 ; i < number.length-1 ; i++){
        for ( int j = 1 ; j < number.length-1 ; j++){
            if ( number[j-1] < number[j]){
                temp = number[j-1];
                number[j-1] = number[j];
                number[j] = temp;
            }
            }
                }
        return number;   
                }
}



Generate unique random number- Logic error

I have the below logic to generate unique random numbers and further, load images referenced by these unique random numbers (from the images Array) at 9 positions:

1) Initially for position 0, generate a random number and load the image referenced by this random number in position 0. 2) Simultaneously load a new Array list with random number already loaded in the previous step. 3) Again for positions 1 to 8, 3.1) generate random number each time. 3.2) compare the random number with the already loaded Array list 3.3) if the newly generated random number already exists in the loaded Array list, Generate another random number; else populate the image corresponding to the unique random number in that position.

Here's the code:

But somehow I am missing out the logic somewhere and get same random numbers repeatedly. Please guide me on the same. Thanks.

    ImageView[] baseimages = {(ImageView) findViewById(R.id.image1), (ImageView) findViewById(R.id.image2), (ImageView) findViewById(R.id.image3), (ImageView) findViewById(R.id.image4), (ImageView) findViewById(R.id.image5), (ImageView) findViewById(R.id.image6), (ImageView) findViewById(R.id.image7), (ImageView) findViewById(R.id.image8), (ImageView) findViewById(R.id.image9)};
    ArrayList<String> Loadimgs = new ArrayList<String>();

    for (i = 0; i < 9; i++) {
        if (first = true)  //initially true
      {
       String alpha[] = {"r1", "r2", "r3", "g1", "g2", "g3", "b1", "b2", "b3", "p1", "p2", "p3", "b1", "br2", "br3"};

 int ran1 = new Random().nextInt(alpha.length);

            baseimages[i].setImageResource(getResources().getIdentifier(alpha[ran1], "drawable", getPackageName()));
            first = false;
            Loadimgs.add(i,alpha[ran1]);

        } else {
            String alpha[] = {"r1", "r2", "r3", "g1", "g2", "g3", "b1", "b2", "b3", "p1", "p2", "p3", "b1", "br2", "br3"};
            int ran1 = new Random().nextInt(alpha.length);
            genimg = alpha[ran1];

            for (j = 0; j < Loadimgs.size(); j++) {
                if (genimg == Loadimgs.get(j)) {
                    j = Loadimgs.size();
                    i--;
                    second = "No";
                } else {
                    continue;
                }
            }
            if (second == "yes")    //initially 'yes'
              {
         baseimages[i].setImageResource(getResources().getIdentifier(genimg,    "drawable", getPackageName()));
         Loadimgs.add(i,genimg);
              }
        }
    }  




How do I add Additive Noise into a sequence of number,C#?

I am beginner in C#. How do i add Additive Noise into a sequence of number? For example, I want to add Noise(3,2,1) into this sequence:

1:1
2:1
3:1
4:1
5:2
6:1
6:2
6:60
7:1
8:1
9:2
10:1

The expected result are as follows, where the noise will be added randomly.

1:1
2:1
3:1
4:1**,3**
5:2
6:1
6:2
6:60**,2**
7:1
8:1
9:2**,1**
10:1




Java Math.Random() for series of numbers

Is it possible to use Math.Random() in Java to obtain numbers in a series such as 10, 20, 30, 40... or 100, 200, 300.... My current implementation is Math.Random()*3*100 as I thought that would bring me numbers up to 300 that are divisible by 100.




Alternative Gaussian random number generator in Java

It has beeen prohibited to me to use java.util.Random class because they think that's not so trustworthy. So, I should use some alternative implementation in Java about a Gaussian Random Number Generator. Are there some given implementations? Thanks.




Weird parameter in Numpy method [duplicate]

This question already has an answer here:

In some MachineLearning tutorial I discovered the following code:

trX = np.linspace(-1, 1, 101)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33
                                ^
                                |___ what does this do?

At first I thought this is a mistake but the code is working perfectly and if I delete the * in *trX.shape the code generates errors. However, I am unable to figure out what exactly this operator does to the parameter trX.shape. If I try *someArray.shape in IPython it always throws a syntax error.

Is it some special "trick operator" somehow unpacking the shape and converting it to an integer? (since random.randn awaits an integer)




How to read in a word from .txt using Java Jframe and choose a random word from file

In my program I need to read a word from a .txt file that contains lot of words (in different lines) and my program should be able to choose a random word from the .txt file. I did lot of research on this but somehow it doesnt worked for me not sure if because i'm Using Jframe. Greatly appreciate your help and guidance.

I am able to choose a random words from my program but have no luck with reading a random word from .txt file.

public class GuessForm extends javax.swing.JFrame {
 String[] FindWord1 = {"hello", "hey", "well", "story", "fight","punch"};
 int idx = new Random().nextInt(FindWord1.length);
 String FindWord = (FindWord1[idx]);
 int wordL = FindWord.length();

I have tried using several methods but nothing seems to worked.

import java.util.Random;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner; 

public class GuessForm extends javax.swing.JFrame {
   String filename = "H:\\lol.txt";
   File file = new File (filename);
   Scanner input = new Scanner new FileReader(file));
   while (input.hasNext()){
   String FindWord1 = input.next();}
   int idx = new Random().nextInt(FindWord1.length);
   String FindWord = (FindWord1[idx]);
   int wordL = FindWord.length(); }




Make directory from generated hash output

This bash command generates a short hash that I'd like to use to name a directory created with mkdir:

cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1

Which (I think):

  1. Creates a random-ish number
  2. Limits the character set with tr (translation)
  3. Folds/wraps each line of output at 32 characters
  4. Limits output to one line starting at the start with head

I can simply copy the output of this command and paste it into a mkdir command, but how would it be done in a single command?

I tried adding | mkdir and | mkdir -p to then end, thinking I could pipe the output to mkdir.




How to make a variable equate to another variable (Python)

I don't even know how to explain this one.

Question1 = "a" 
Question2 = "b" 
Question3 = "c" 
Question4 = "d"
Question5 = "e"

etc.

Answer1 = "a" 
Answer2 = "b" 
Answer3 = "c" 
Answer4 = "d" 
Answer5 = "e"

etc.

questioninteger = random.randint(1,20)
if(questioninteger == 1):
    Boolean1 = True
    Question == Question1
    Answer == Answer1
    FlashCard()
if(questioninteger == 2):
    Boolean2 = True
    Question == Question2
    Answer == Answer2
    FlashCard()
if(questioninteger == 3):
    Boolean3 = True
    Question == Question3
    Answer == Answer3
    FlashCard()

etc.

print("")
print(Question)
print("")
key = raw_input()
if(key == Answer):
    print("Correct!")
    time.sleep(1)
    QuestionPicker()

(all are within functions)

Problem is Python won't print the variable Question, and no error comes up, just when it should be printed it is blank. 'Answer is successfully changed, Question isn't or won't be printed.




Strange Errors. Using rand() and arrays within a loop

I really can not explain what is going on with my program. I really can't spot what may be causing the problems. It occurs within this function

void test()
{
    srand(time(NULL));

    questionNo = 1;

    for (testLoop = 0; testLoop < 10; ++testLoop)
    {
        const char opArray[3] = { 'x', '+', '-' };
        int pickValue = rand() % 3;
        char Operator = opArray[pickValue];

        int n1 = rand() % 20 + 1;
        int n2 = rand() % 20 + 1;

        if (Operator = '+')
            answer = n1 + n2;
        else if (Operator = '-')
            answer = n1 - n2;
        else
            answer = n1 * n2;

        cout << "Question " << questionNo << "\n";
        ++questionNo;
        cout << n1 + " " << Operator + " " << n2 << "?";
        userAnswer = cin.get();

        if (userAnswer = answer)
        {
            cout << "\n\n Correct!\n";
            system("cls");
            ++score;
        }
        else
        {
        cout << "\n\n Incorrect!\n";
        system("cls");
        }
        Sleep(500);
    }
    cout << "You scored " << score << " out of 10!";
    fileWrite(score);
}

An example of what occurs is the following. This outputs to console

Question 1
@Øÿ×╝׳×0ƒ11?

What even is that???
It also skips two questions every time. For example it goes

"Question 1"
"Question 3"
"Question 5"




How to make Random sound when button click?

So i have 4 sound here, i was use SoundPool

     sound1 = soundPool.load(this, R.raw.aww, 1);
     sound2 = soundPool.load(this, R.raw.arh, 1);
     sound3 = soundPool.load(this, R.raw.agg, 1);
     sound4 = soundPool.load(this, R.raw.uhh, 1);

so i wonder how to make button choose random sound :

    click= (Button)findViewById(R.id.bm);
    click.setOnClickListener(new View.OnClickListener() {

          public void onClick(View click){             
             //choose one of four sound to play   
            }
        });
}

Anyone have some Idea?




Python random list

I'm new to Python, and have some problems with creating random lists.

I'm using random.sample(range(x, x), y).

I want to get 4 lists with unique numbers, from 1-4, so I have been using this

a = random.sample(range(1, 5), 4)
b = random.sample(range(1, 5), 4)
c = random.sample(range(1, 5), 4)
d = random.sample(range(1, 5), 4)

So I get for example

a = 1, 3, 2, 4
b = 1, 4, 3, 2
c = 2, 3, 1, 4
d = 4, 2, 3, 1

How can I make it that the column are also unique?




Java - Generating A Set of Random Numbers Without Duplicates [duplicate]

This question already has an answer here:

With the following code I am attempting to generate 10 random numbers between 1 and 50 without any duplicates being printed out.

My current code is in the file RandomNum.java:

public class RandomNum
{
    public static void main(String[] args) 
    {
             int counter = 0;
             int num = 0;
             while(counter<=10)
             {
                    num=(int)(1+Math.random()*(50));
                    System.out.println("The number"+" "+num+" "+"was drawn.");
                    ++counter;
            }
    }
}

This code successfully generates and prints out the value of the numbers, but I want to make it so that the program prints out 10 unique numbers between 1 and 50 rather than including any duplicates.

How would I go about doing this?

Thanks!




Random ints in array C

I'm trying to create an array of random ints, but I get a segmentation fault error. I'm using rand() function, but if I replace the rand() with any number it works.

int *arreglo, cant_int = 1000; //cant_int can be any number.
srand(time(NULL); //also tried with srand(0)
arreglo = (int *) malloc(sizeof(int) * cant_int);

for (i = 0; i < cant_int; i++) {
        arreglo[i] = rand(); // arreglo[i] = 1111 or any number doesn't show error
};




Generate Random Numbers between 10 and 65

I want my program to generate 500 random numbers with the range of 10 and 65. How do I do that?
Currently, my program generates between 0 to 74 random numbers. And also, it seems that my highest and lowest value does not read the random generated number but the range of it. This is my code:

#include<iostream>
#include<exception>
#include<stdlib.h>   
using namespace std;

int main(){
    int year;
    int nextLine = 20;
    int highestValue = 0;
    int lowestValue = 0;
    int ages[500];
    int range = 65;

    cout << "Enter year today: ";
    cin >> year;
    srand(year);

    cout << "The ages are: \n";
    for (int i = 0; i < 500; i++){
        ages[i] = rand() % 65 + 10;
        cout << ages[i] << " ";

        if (i + 1 == nextLine){
            cout << "\n";
            nextLine += 20;
        }
    }

    for (int j = 0; j < 500; j++){
        if (ages[j] > highestValue)
            highestValue = ages[j];

        if (ages[j] < lowestValue)
            lowestValue = ages[j];
    }

    cout << "\nRange(HV-LV): " << highestValue << " - " << lowestValue << " = " << highestValue - lowestValue;

    system("pause>0");
    return 0;
}




jeudi 26 novembre 2015

Why the two implementations of random sort vary a lot in performance?

I need to implement a random sort, which is very bad at performance but just used to get used to random generating things:

I have two implementations:

public void sort(Integer[] a) {
    boolean sorted = false;
    boolean auxSorted = true;
    List<Integer> list = Arrays.asList(a);
    int n = a.length;

    while (sorted == false) {
        Collections.shuffle(list);

        int i = 0;
        while (i < n-1 && list.get(i) <= list.get(i + 1)) {
            i = i + 1;
        }
        if (i == n - 1) {
            sorted = true;
        }
    Integer[] sortedArray = new Integer[list.size()];
    a = list.toArray(sortedArray);
}

when I use an array of length 5 it gives correct answer very quickly, however I have another for loop version:

while (sorted == false) {
        Collections.shuffle(list);

        for(int i = 0; i < n-1; i++) {
            if(list.get(i) > list.get(i+1)) {
                auxSorted = false;
                break;
            }
        }

        if(auxSorted) {
            sorted = true;              
        }

    }

when I test with the same array it runs extremely slowly.

Are there any differences between the two implementations? To me I think the for loop version is actually more efficient in this context.




Using tkinter to create a grid using words from an external file

Okay, this code can display the grid fine, but the way it is programmed is extremely inefficient and I know there is a quicker way of doing this but I can't seem to get it. Also, in order for this grid to be random I need the words to be randomly allocated rather than always being in the same place and I'm trying to add it to a list and then use 'random.shuffle' but once I've done that I can't extract the words from the list and then put them into the grid. I've stripped the program down to only the parts which I can get working. Another part of the program is to make the grid switch to the same words but in different, random positions. I'm relatively new to Python so this probably sounds very basic so, apologies.

import random

from tkinter import *

root=Tk()

word_list=[]

with open("easy_words.txt", "r") as f:

word_1=f.read(6)
word_2=f.read(6)
word_3=f.read(6)
word_4=f.read(6)
word_5=f.read(6)
word_6=f.read(6)
word_7=f.read(6)
word_8=f.read(6)
word_9=f.read(6)

def easy_grid():

w=Label(root, text=(word_1), fg='black').grid(row=1, column=1)
w=Label(root, text=(word_2), fg='black').grid(row=1, column=2)
w=Label(root, text=(word_3), fg='black').grid(row=1, column=3)
w=Label(root, text=(word_4), fg='black').grid(row=2, column=1)
w=Label(root, text=(word_5), fg='black').grid(row=2, column=2)
w=Label(root, text=(word_6), fg='black').grid(row=2, column=3)
w=Label(root, text=(word_7), fg='black').grid(row=3, column=1)
w=Label(root, text=(word_8), fg='black').grid(row=3, column=2)
w=Label(root, text=(word_9), fg='black').grid(row=3, column=3)

def menu():

b=Button(root,text='Easy', command=easy_grid()).grid(row=4, column=1)
b=Button(root,text='Hard', command=print('Hard game')).grid(row=4, column=3)
b=Button(root, text='Close', command=root.destroy).grid(row=4, column=2)

menu()




Multi choice, easygui buttonbox menu

We trying to create a multi choice menu using easygui, buttonbox. We have tired if, else and elif statements but whenever selecting one of the math subject options, it always takes the player to addition/will ask the player addition questions. We are not sure whether it is a problem with the if/else/elif statment (we would've expected elif to work) or if it is another problem with the Figure1/Figure2 we can not seem to find.

Here is an example of our coding, we have only shown you the subject selection menu, addition, and subtraction problems. (to hopefully save you all time as all the subjects are the same, they are just be changed to DivisionAnswers and MultiplicationAnswers etc. ) But we are focusing on the problem within the subject selection

   Subject = easygui.buttonbox ("What maths subject would you like to test?", choices = ["Addition","Subtraction","Multiplication","Division"])
if "Addition":
    easygui.msgbox ("Please enter the correct answer to earn a point, there are 10 questions in this quiz")

for number in range(0,10):
    Figure1 = random.randrange(0,11)
    Figure2 = random.randrange(0,11)

    PlayerAnswer = easygui.enterbox ("What is " +str(Figure1)+ " + " +str(Figure2)+ "?")

    if int(PlayerAnswer) == Figure1 + Figure2:
        AdditionAnswers += 1
        easygui.msgbox ("Correct! Your score is "+str(AdditionAnswers))
        print(AdditionAnswers)#To see if game is keeping count of questions asked
    else:
        AdditionAnswers += 0
        IncorrectAnswers += 1
        easygui.msgbox ("Sorry, incorrect! Your score is still "+str(AdditionAnswers))
        print(AdditionAnswers)#To see if game is keeping count of questions asked

easygui.msgbox ("You scored " +str(AdditionAnswers)+ " out of 10")

print(AdditionAnswers) #To check if programme is calculating score correctly
print(IncorrectAnswers)

elif "Subtraction":
    easygui.msgbox ("Please enter the correct answer to earn a point, there are 10 questions in this quiz")

for number in range(0,10):
    Figure1 = random.randrange(0,11)
    Figure2 = random.randrange(0,11)

    PlayerAnswer = easygui.enterbox ("What is " +str(Figure1)+ " - " +str(Figure2)+ "?")

    if int(PlayerAnswer) == Figure1 - Figure2:
        SubtractionAnswers += 1
        easygui.msgbox ("Correct! Your score is "+str(SubtractionAnswers))
        print(SubtractionAnswers)#To see if game is keeping count of questions asked
    else:
        SubtractionAnswers+= 0
        IncorrectAnswers += 1
        easygui.msgbox ("Sorry, incorrect! Your score is still "+str(SubtractionAnswers))
        print(SubtractionAnswers)#To see if game is keeping count of questions asked

easygui.msgbox ("You scored " +str(SubtractionAnswers)+ " out of 10")

print(SubtractionAnswers) #To check if programme is calculating score correctly
print(IncorrectAnswers)

Thankyou for any help or suggestions you can give us, it is greatly appreciated as we are all just beginning to learn python programming.