Search Results

Search found 491 results on 20 pages for 'rand'.

Page 1/20 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • MySQL: LIMIT then RAND rather than RAND then LIMIT

    - by Larry
    I'm using full text search to pull rows. I order the rows based on score (ORDER BY SCORE) , then of the top 20 rows (LIMIT 20), I want to rand (RAND) the result set. So for any specific search term, I want to randomly show 5 of the top 20 results. My workaround is code based- where I put the top 20 into an array then randomly select 5. Is there sql way to do this?

    Read the article

  • LIMIT then RAND rather than RAND then LIMIT

    - by Larry
    I'm using full text search to pull rows. I order the rows based on score (ORDER BY SCORE) , then of the top 20 rows (LIMIT 20), I want to rand (RAND) the result set. So for any specific search term, I want to randomly show 5 of the top 20 results. My workaround is code based- where I put the top 20 into an array then randomly select 5. Is there sql way to do this?

    Read the article

  • PHP rand function (or not so rand)

    - by Badr Hari
    I was testing PHP rand function to write on a image. Of course the output shows that it's not so random. The code I used: <?php header('Content-Type: image/png'); $lenght = 512; $im = imagecreatetruecolor($lenght, $lenght); $blue = imagecolorallocate($im, 0, 255, 255); for ($y = 0; $y < $lenght; $y++) { for ($x = 0; $x < $lenght; $x++) { if (rand(0,1) == 0) { imagesetpixel($im, $x, $y, $blue); } } } imagepng($im); imagedestroy($im); ?> My question is, if I use image width/lenght (variable $lenght in this example) number like 512, 256 or 1024, it is very clear that it's not so random. When I change the variable to 513 for an example, it is so much harder for human eye to detect it. Why is that? What is so special about these numbers? 512: 513: Edit: I'm running xampp on Windows to test it.

    Read the article

  • SQL SERVER – Using RAND() in User Defined Functions (UDF)

    - by pinaldave
    Here is the question I received in email. “Pinal, I am writing a function where we need to generate random password. While writing T-SQL I faced following issue. Everytime I tried to use RAND() function in my User Defined Function I am getting following error: Msg 443, Level 16, State 1, Procedure RandFn, Line 7 Invalid use of a side-effecting operator ‘rand’ within a function. Here is the simplified T-SQL code of the function which I am using: CREATE FUNCTION RandFn() RETURNS INT AS BEGIN DECLARE @rndValue INT SET @rndValue = RAND() RETURN @rndValue END GO I must use UDF so is there any workaround to use RAND function in UDF.” Here is the workaround how RAND() can be used in UDF. The scope of the blog post is not to discuss the advantages or disadvantages of the function or random function here but just to show how RAND() function can be used in UDF. RAND() function is directly not allowed to use in the UDF so we have to find alternate way to use the same function. This can be achieved by creating a VIEW which is using RAND() function and use the same VIEW in the UDF. Here is the step by step instructions. Create a VIEW using RAND function. CREATE VIEW rndView AS SELECT RAND() rndResult GO Create a UDF using the same VIEW. CREATE FUNCTION RandFn() RETURNS DECIMAL(18,18) AS BEGIN DECLARE @rndValue DECIMAL(18,18) SELECT @rndValue = rndResult FROM rndView RETURN @rndValue END GO Now execute the UDF and it will just work fine and return random result. SELECT dbo.RandFn() GO In T-SQL world, I have noticed that there are more than one solution to every problem. Is there any better solution to this question? Please post that question as a comment and I will include it with due credit. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology Tagged: technology

    Read the article

  • rand () for c++ with variables...

    - by timothy
    int userHP = 100; int enemyHP = rand() % ((userHP - 50) - (userHP - 75)) + 1; okay, for some reason this doesnt seem to work right, im trying to get 50 -25 hp for enemys. also id rather it be a percentage... like int enemyHP = rand() % ((userHP / 50%) - (userHP / 75%)) + 1; but id like to stick with integers and not mess with floats or doubles... can someone help me?

    Read the article

  • rand() generating the same number – even with srand(time(NULL)) in my main!

    - by Nick Sweet
    So, I'm trying to create a random vector (think geometry, not an expandable array), and every time I call my random vector function I get the same x value, thought y and z are different. int main () { srand ( (unsigned)time(NULL)); Vector<double> a; a.randvec(); cout << a << endl; return 0; } using the function //random Vector template <class T> void Vector<T>::randvec() { const int min=-10, max=10; int randx, randy, randz; const int bucket_size = RAND_MAX/(max-min); do randx = (rand()/bucket_size)+min; while (randx <= min && randx >= max); x = randx; do randy = (rand()/bucket_size)+min; while (randy <= min && randy >= max); y = randy; do randz = (rand()/bucket_size)+min; while (randz <= min && randz >= max); z = randz; } For some reason, randx will consistently return 8, whereas the other numbers seem to be following the (pseudo) randomness perfectly. However, if I put the call to define, say, randy before randx, randy will always return 8. Why is my first random number always 8? Am I seeding incorrectly?

    Read the article

  • How does MySQL's ORDER BY RAND() work?

    - by Eugene
    Hi, I've been doing some research and testing on how to do fast random selection in MySQL. In the process I've faced some unexpected results and now I am not fully sure I know how ORDER BY RAND() really works. I always thought that when you do ORDER BY RAND() on the table, MySQL adds a new column to the table which is filled with random values, then it sorts data by that column and then e.g. you take the above value which got there randomly. I've done lots of googling and testing and finally found that the query Jay offers in his blog is indeed the fastest solution: SELECT * FROM Table T JOIN (SELECT CEIL(MAX(ID)*RAND()) AS ID FROM Table) AS x ON T.ID >= x.ID LIMIT 1; While common ORDER BY RAND() takes 30-40 seconds on my test table, his query does the work in 0.1 seconds. He explains how this functions in the blog so I'll just skip this and finally move to the odd thing. My table is a common table with a PRIMARY KEY id and other non-indexed stuff like username, age, etc. Here's the thing I am struggling to explain SELECT * FROM table ORDER BY RAND() LIMIT 1; /*30-40 seconds*/ SELECT id FROM table ORDER BY RAND() LIMIT 1; /*0.25 seconds*/ SELECT id, username FROM table ORDER BY RAND() LIMIT 1; /*90 seconds*/ I was sort of expecting to see approximately the same time for all three queries since I am always sorting on a single column. But for some reason this didn't happen. Please let me know if you any ideas about this. I have a project where I need to do fast ORDER BY RAND() and personally I would prefer to use SELECT id FROM table ORDER BY RAND() LIMIT 1; SELECT * FROM table WHERE id=ID_FROM_PREVIOUS_QUERY LIMIT 1; which, yes, is slower than Jay's method, however it is smaller and easier to understand. My queries are rather big ones with several JOINs and with WHERE clause and while Jay's method still works, the query grows really big and complex because I need to use all the JOINs and WHERE in the JOINed (called x in his query) sub request. Thanks for your time!

    Read the article

  • openssl/rand.h header file not found

    - by Arun Reddy Kandoor
    I have installed libssl-dev package but that did not install the include files. How do I get the openssl include files? Appreciate your help. Checking for program g++ or c++ : /usr/bin/g++ Checking for program cpp : /usr/bin/cpp Checking for program ar : /usr/bin/ar Checking for program ranlib : /usr/bin/ranlib Checking for g++ : ok Checking for node path : ok /usr/bin/node Checking for node prefix : ok /usr Checking for header openssl/rand.h : not found /home/arun/Documents/webserver/node_modules/bcrypt/wscript:30: error: the configuration failed (see '/home/arun/Documents/webserver/node_modules/bcrypt/build/config.log') npm ERR! error installing [email protected] npm ERR! [email protected] preinstall: `node-waf clean || (exit 0); node-waf configure build` npm ERR! `sh "-c" "node-waf clean || (exit 0); node-waf configure build"` failed with 1 npm ERR! npm ERR! Failed at the [email protected] preinstall script. npm ERR! This is most likely a problem with the bcrypt package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node-waf clean || (exit 0); node-waf configure build npm ERR! You can get their info via: npm ERR! npm owner ls bcrypt npm ERR! There is likely additional logging output above. npm ERR! npm ERR! System Linux 3.8.0-32-generic npm ERR! command "node" "/usr/bin/npm" "install" npm ERR! cwd /home/arun/Documents/webserver npm ERR! node -v v0.6.12 npm ERR! npm -v 1.1.4 npm ERR! code ELIFECYCLE npm ERR! message [email protected] preinstall: `node-waf clean || (exit 0); node-waf configure build` npm ERR! message `sh "-c" "node-waf clean || (exit 0); node-waf configure build"` failed with 1 npm ERR! errno {} npm ERR! npm ERR! Additional logging details can be found in: npm ERR! /home/arun/Documents/webserver/npm-debug.log npm not ok

    Read the article

  • Distinct rand() sequences yielding the same results in an expression

    - by suszterpatt
    Ok, this is a really weird one. I have an MPI program, where each process has to generate random numbers in a fixed range (the range is read from file). What happens is that even though I seed each process with a different value, and the numbers generated by rand() are different in each process, the expression to generate the random numbers still yields the same sequence between them. Here's all relevant code: // 'rank' will be unique for each process int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); // seed the RNG with a different value for each process srand(time(NULL) + rank); // print some random numbers to see if we get a unique sequence in each process // 'log' is a uniquely named file, each process has its own log << rand() << " " << rand() << " " << rand() << std::endl; // do boring deterministic stuff while (true) { // waitTimeMin and waitTimeMax are integers, Max is always greater than Min waitSecs = waitTimeMin + rand() % (waitTimeMax - waitTimeMin); log << "waiting " << waitSecs << " seconds" << std::endl; sleep(waitSecs); // do more boring deterministic stuff } Here's the output of each process, with 3 processes generating numbers in the range [1,9]. process 1: 15190 28284 3149 waiting 6 seconds waiting 8 seconds waiting 9 seconds waiting 4 seconds process 2: 286 6264 3153 waiting 6 seconds waiting 8 seconds waiting 9 seconds waiting 4 seconds process 3: 18151 17013 3156 waiting 6 seconds waiting 8 seconds waiting 9 seconds waiting 4 seconds So while rand() clearly generates different numbers, the expression to calculate waitSecs still evaluates to the same sequence on all processes. What's even weirder: if I run the program with the same parameteres again, only the first 3 random numbers will change, the rest of the "random" sequence will be exactly the same in each run! Changing the range of numbers will obviously produce a different result from this one, but the same parameters always yield the same sequence, between processes and between executions: except for the first 3 numbers. Just what the hell is going on here?

    Read the article

  • [MySQL/PHP] Avoid using RAND()

    - by Andrew Ellis
    So... I have never had a need to do a random SELECT on a MySQL DB until this project I'm working on. After researching it seems the general populous says that using RAND() is a bad idea. I found an article that explains how to do another type of random select. Basically, if I want to select 5 random elements, I should do the following (I'm using the Kohana framework here)? If not, what is a better solution? Thanks, Andrew <?php final class Offers extends Model { /** * Loads a random set of offers. * * @param integer $limit * @return array */ public function random_offers($limit = 5) { // Find the highest offer_id $sql = ' SELECT MAX(offer_id) AS max_offer_id FROM offers '; $max_offer_id = DB::query(Database::SELECT, $sql) ->execute($this->_db) ->get('max_offer_id'); // Check to make sure we're not trying to load more offers // than there really is... if ($max_offer_id < $limit) { $limit = $max_offer_id; } $used = array(); $ids = ''; for ($i = 0; $i < $limit; ) { $rand = mt_rand(1, $max_offer_id); if (!isset($used[$rand])) { // Flag the ID as used $used[$rand] = TRUE; // Set the ID if ($i > 0) $ids .= ','; $ids .= $rand; ++$i; } } $sql = ' SELECT offer_id, offer_name FROM offers WHERE offer_id IN(:ids) '; $offers = DB::query(Database::SELECT, $sql) ->param(':ids', $ids) ->as_object(); ->execute($this->_db); return $offers; } }

    Read the article

  • Fill a table from a RAND based formula in Excel 2010

    - by Greg Reynolds
    I am trying to do a Monte Carlo simulation using Excel, but a lot of the tutorials I have found are either for older versions of the product, or are not quite what I am after. A simple example of the kind of think I am after is: Cell A1 contains the formula to simulate (for example int(6*rand())+1 to simulate rolling a dice). I have 10 rows of "Trials". What I want is to somehow point each row at a different calculation of the formula in A1. So I would end up with something like Trial Value 1 2 2 5 3 6 4 2 5 1 6 3 7 2 8 4 9 2 10 1 I have tried playing with some of the "What-if Analysis" tools, but I am a bit lost.

    Read the article

  • Example about crypto/rand in Go

    - by nevalu
    Could put a little example about the use of crypto/rand [1]? The function Read has as parameter an array of bytes. Why? If it access to /dev/urandom to get the random data. func Read(b []byte) (n int, err os.Error) [1] http://golang.org/pkg/crypto/rand/

    Read the article

  • is rand() is perdicatable in C++

    - by singh
    Hi When i run below program i always get same values each time..Is rand is not a true random function. int main() { while(1) { getch(); cout<<rand()<<endl; } } In each run i am getting below values. 41 18467 6334 26500 19169 15724 ......

    Read the article

  • Is rand() predictable in C++

    - by singh
    When I run the below program I always get the same values each time. Is rand not a true random function? int main() { while(1) { getch(); cout<<rand()<<endl; } } In each run I am getting the below values. 41 18467 6334 26500 19169 15724 ......

    Read the article

  • MySQL ORDER BY rand(), name ASC

    - by Josh K
    I would like to take a database of say, 1000 users and select 20 random ones (ORDER BY rand(),LIMIT 20) then order the resulting set by the names. I came up with the following query which is not working like I hoped. SELECT * FROM users WHERE 1 ORDER BY rand(), name ASC LIMIT 20

    Read the article

  • Plotting points so that they do not overlap if they have the same co-ordinates

    - by betamax
    Hi everyone, I have a function that takes longitude and latitude and converts it to x and y to be plotted. The conversion to X and Y is working fine and that is not what I have the problem with. I want to ensure that two points are not plotted in the same place. In one set of results there are about 30 on top of each other (because they have the same latitude and longitude), this number could be a lot larger. At the moment I am trying to achieve this by moving points to the left, right, top or bottom of the point to make a square. Once a square made up of points has been drawn, then moving to the next row on and drawing another square of points around the previous square. The code is Javascript but it is very generic so I guess it's slightly irrelevant. My code is as follows: var prevLong, prevLat, rand = 1, line = 1, spread = 8, i = 0; function plot_points(long, lat){ // CODE HERE TO CONVERT long and lat into x and y // System to not overlap the points if((prevLat == lat) && (prevLong == long)) { if(rand==1) { x += spread*line; } else if(rand==2) { x -= spread*line; } else if(rand==3) { y += spread*line; } else if(rand==4) { y -= spread*line; } else if(rand==5) { x += spread*line; y += spread*line; } else if(rand==6) { x -= spread*line; y -= spread*line; } else if(rand==7) { x += spread*line; y -= spread*line; } else if(rand==8) { x -= spread*line; y += spread*line; // x = double } else if(rand==9) { x += spread*line; y += spread; } else if(rand==10) { x += spread; y += spread*line; } else if(rand==11) { x -= spread*line; y -= spread; } else if(rand==12) { x -= spread; y -= spread*line; } else if(rand==13) { x += spread*line; y -= spread; } else if(rand==14) { x += spread; y -= spread*line; } else if(rand==15) { x += spread*line; y -= spread; } else if(rand==16) { x += spread; y -= spread*line; } else if(rand==17) { x -= spread*line; y += spread; } else if(rand==18) { x -= spread; y += spread*line; } else if(rand==19) { x -= spread*line; y += spread; } else if(rand==20) { x -= spread; y += spread*line; } if(rand == 20) {rand = 1; line++; } else { rand++; } i++ } else { line = 1; i = 0; } prevLat = latitude; prevLong = longitude; return [x,y]; } This is the output: It isn't working correctly and I don't even know if I am approaching the problem in a correct way at all. Has anyone had to do this before? What method would you suggest?

    Read the article

  • migrate method Rand(int) Visual Fox Pro to C#.net

    - by ch2o
    I'm migrating a Visual Fox Pro code to C #. NET What makes the Visual Fox Pro: generates a string of 5 digits ("48963") based on a text string (captured in a textbox), if you always enter the same text string will get that string always 5 digits (no reverse), my code in C #. NET should generate the same string. I want to migrate the following code (Visual Fox Pro 6 to C#) gnLower = 1000 gnUpper = 100000 vcad = 1 For y=gnLower to gnUpper step 52 genClave = **Rand(vcad)** * y vRound = allt(str(int(genclave))) IF Len(vRound) = 3 vDec = Right(allt(str(genClave,10,2)), 2) finClave = vRound+vDec Thisform.txtPass.value = Rand(971); Exit Endif Next y outputs: vcad = 1 return: 99905 vcad = 2 return: 10077 vcad = thanks return: 17200 thks!

    Read the article

  • Order By Rand by Time (HQL)

    - by Felipe
    Hi all, I'm developing a web application using asp.net Mvc 2 and NHibernate, and I'm paging data (products in a category) in my page, but this data are random, so, I'm using a HQL statement link this: string hql = "from Product p where p.Category.Id=:IdCategory order by rand()"; It's working fine, but when I page, sometimes the same product appears in the first, second, etc... pages because it's order by rand(). Is there any way to make a random order by fixed by period (time internal) ? Or any solution ? thanks Cheers

    Read the article

  • Error trying to use rand from std library cstdlib with g++

    - by Matt
    I was trying to use the random function in Ubuntu compiling with g++ on a larger program and for some reason rand just gave weird compile errors. For testing purposes I made the simplest program I could and it still gives errors. Program: #include <iostream> using std::cout; using std::endl; #include <cstdlib> int main() { cout << "Random number " << rand(); return 0; } Error when compiling with the terminal sudo g++ chapter_3/tester.cpp ./test ./test: In function _start': /build/buildd/eglibc-2.10.1/csu/../sysdeps/i386/elf/start.S:65: multiple definition of_start' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:/build/buildd/eglibc-2.10.1/csu/../sysdeps/i386/elf/start.S:65: first defined here ./test:(.rodata+0x0): multiple definition of _fp_hw' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:(.rodata+0x0): first defined here ./test: In function_fini': (.fini+0x0): multiple definition of _fini' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crti.o:(.fini+0x0): first defined here ./test:(.rodata+0x4): multiple definition of_IO_stdin_used' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:(.rodata.cst4+0x0): first defined here ./test: In function __data_start': (.data+0x0): multiple definition ofdata_start' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:(.data+0x0): first defined here ./test: In function __data_start': (.data+0x4): multiple definition of__dso_handle' /usr/lib/gcc/i486-linux-gnu/4.4.1/crtbegin.o:(.data+0x0): first defined here ./test: In function main': (.text+0xb4): multiple definition ofmain' /tmp/cceF0x0p.o:tester.cpp:(.text+0x0): first defined here ./test: In function _init': (.init+0x0): multiple definition ofinit' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crti.o:(.init+0x0): first defined here /usr/lib/gcc/i486-linux-gnu/4.4.1/crtend.o:(.dtors+0x0): multiple definition of `_DTOR_END' ./test:(.dtors+0x4): first defined here /usr/bin/ld: error in ./test(.eh_frame); no .eh_frame_hdr table will be created. collect2: ld returned 1 exit status

    Read the article

  • struct and rand()

    - by teoz
    I have a struct with an array of 100 int (b) and a variable of type int (a) I have a function that checks if the value of "a" is in the array and i have generated the array elements and the variable with random values. but it doesn't work can someone help me fix it? #include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct { int a; int b[100]; } h; int func(h v){ int i; for (i=0;i<100;i++){ if(v.b[i]==v.a) return 1; else return 0; } } int main(int argc, char** argv) { h str; srand(time(0)); int i; for(i=0;0<100;i++){ str.b[i]=(rand() % 10) + 1; } str.a=(rand() % 10) + 1; str.a=1; printf("%d\n",func(str)); return 0; }

    Read the article

  • Rand(); with exclusion to and already randomly generated number..?

    - by Stefan
    Hey, I have a function which calls a users associated users from a table. The function then uses the rand(); function to chose from the array 5 randomly selected userID's however!... In the case where a user doesnt have many associated users but above the min (if below the 5 it just returns the array as it is) then it gives bad results due to repeat rand numbers... How can overcome this or exclude a previously selected rand number from the next rand(); function call. Here is the section of code doing the work. Bare in mind this must be highly efficient as this script is used everywhere. $size = sizeof($users)-1; $nusers[0] = $users[rand(0,$size)]; $nusers[1] = $users[rand(0,$size)]; $nusers[2] = $users[rand(0,$size)]; $nusers[3] = $users[rand(0,$size)]; $nusers[4] = $users[rand(0,$size)]; return $nusers; Thanks in advance! Stefan

    Read the article

  • Cheap and cheerful rand() replacement.

    - by Mick
    After profiling a large game playing program, I have found that the library function rand() is consuming a considerable fraction of the total processing time. My requirements for the random number generator are not very onerous - its not important that it pass a great battery of statistical tests of pure randomness. I just want something cheap and cheerful that is very fast. Any suggestions?

    Read the article

  • =rand(100,60) - MSOffice Problem

    - by sagar
    Oho ! Have you tried this one ?? Very simple office utility question. The question is something like this. Open Microsoft word ( 2003 or 2007 ) whatever you use. ( Let me clarify that - I am not here for any kind of advertisement of Micro soft - I want to solution to my Query ) After opening the word. Let's have a new empty blank document. ( It's up to you to have it or not ) Press enter to go to a new line. now type "=rand(100,60)" in new line Now press enter After writing this - it will create 81 pages long story The question is Why ?? How ?? What exactly microsoft word is doing?? Thanks in advance for sharing your great knowledge. Sagar

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >