Search Results

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

Page 10/20 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Find Shortest element in Array

    - by Ani
    I have a Array string[] names = { "Jim Rand", "Barry Williams", "Nicole Dyne", "Peter Levitt", "Jane Jones", "Cathy Hortings"}; Is there any way to find which is the shortest(Length wise) element in this array and then store rest of elements in a different array. Thanks, Ani

    Read the article

  • Floating point vs integer calculations on modern hardware

    - by maxpenguin
    I am doing some performance critical work in C++, and we are currently using integer calculations for problems that are inherently floating point because "its faster". This causes a whole lot of annoying problems and adds a lot of annoying code. Now, I remember reading about how floating point calculations were so slow approximately circa the 386 days, where I believe (IIRC) that there was an optional co-proccessor. But surely nowadays with exponentially more complex and powerful CPUs it makes no difference in "speed" if doing floating point or integer calculation? Especially since the actual calculation time is tiny compared to something like causing a pipeline stall or fetching something from main memory? I know the correct answer is to benchmark on the target hardware, what would be a good way to test this? I wrote two tiny C++ programs and compared their run time with "time" on Linux, but the actual run time is too variable (doesn't help I am running on a virtual server). Short of spending my entire day running hundreds of benchmarks, making graphs etc. is there something I can do to get a reasonable test of the relative speed? Any ideas or thoughts? Am I completely wrong? The programs I used as follows, they are not identical by any means: #include <iostream> #include <cmath> #include <cstdlib> #include <time.h> int main( int argc, char** argv ) { int accum = 0; srand( time( NULL ) ); for( unsigned int i = 0; i < 100000000; ++i ) { accum += rand( ) % 365; } std::cout << accum << std::endl; return 0; } Program 2: #include <iostream> #include <cmath> #include <cstdlib> #include <time.h> int main( int argc, char** argv ) { float accum = 0; srand( time( NULL ) ); for( unsigned int i = 0; i < 100000000; ++i ) { accum += (float)( rand( ) % 365 ); } std::cout << accum << std::endl; return 0; } Thanks in advance!

    Read the article

  • Grayscale in matlab

    - by ruthenium
    I'm trying to convert a 2D array to grayscale but using mat2gray doesn't do anything and imshow() appears to create a binary image that when I graph I cannot rotate it, e.g. the original array is 2d but maps in 3d. So, what is the best way to take a grayscale of 2d array in Matlab so if you have A=rand(5,10) or something and want to take a grayscale of that, what is the best way?

    Read the article

  • How to use ternary operator instead of if-else in PHP

    - by Mac Taylor
    hey guys i need to shorten or better to say ., harden my codes this is my original code : if ($type = "recent") { $OrderType = "sid DESC"; }elseif ($type = "pop"){ $OrderType = "counter DESC"; }else { $OrderType = "RAND()"; } now how can i use markers like this : $OrderType = ($type = "recent") ? "sid DESC" : "counter DESC" ; i tried but i didnt know how to write elseif in operators

    Read the article

  • Select random row from MySQL (with probability)

    - by James Simpson
    I have a MySQL table that has a row called cur_odds which is a percent number with the percent probability that that row will get selected. How do I make a query that will actually select the rows in approximately that frequency when you run through 100 queries for example? I tried the following, but a row that has a probability of 0.35 ends up getting selected around 60-70% of the time. SELECT * FROM table ORDER BY RAND()*cur_odds DESC

    Read the article

  • seperating interface and implemention with normal functions

    - by ace
    this seems like it should be pretty simple, im probably leaving something simple out. this is the code im trying to run. it is 3 files, 2*cpp and 1*header. -------------lab6.h ifndef LAB6_H_INCLUDED define LAB6_H_INCLUDED int const arraySize = 10; int array1[arraySize]; int array2[arraySize]; void generateArray(int[], int ); void displayArray(int[], int[], int ); void reverseOrder(int [],int [], int); endif // LAB6_H_INCLUDED -----------------lab6.cpp include using std::cout; using std::endl; include using std::rand; using std::srand; include using std::time; include using std::setw; include "lab6.h" void generateArray(int array1[], int arraySize) { srand(time(0)); for (int i=0; i<10; i++) { array1[i]=(rand()%10); } } void displayArray(int array1[], int array2[], int arraySize) { cout<<endl<<"Array 1"<<endl; for (int i=0; i<arraySize; i++) { cout<<array1[i]<<", "; } cout<<endl<<"Array 2"<<endl; for (int i=0; i<arraySize; i++) { cout<<array2[i]<<", "; } } void reverseOrder(int array1[],int array2[], int arraySize) { for (int i=0, j=arraySize-1; i<arraySize;j--, i++) { array2[j] = array1[i]; } } ------------and finally main.cpp include "lab6.h" int main() { generateArray(array1, arraySize); reverseOrder(array1, array2, arraySize); displayArray(array1, array2, arraySize); return 0; }

    Read the article

  • Can't read excel file after creating it using File.WriteAllText() function

    - by Srikanth Mattihalli
    public void ExportDataSetToExcel(DataTable dt) { HttpResponse response = HttpContext.Current.Response; response.Clear(); response.Charset = "utf-8"; response.ContentEncoding = Encoding.GetEncoding("utf-8"); response.ContentType = "application/vnd.ms-excel"; Random Rand = new Random(); int iNum = Rand.Next(10000, 99999); string extension = ".xls"; string filenamepath = AppDomain.CurrentDomain.BaseDirectory + "graphs\\" + iNum + ".xls"; string file_path = "graphs/" + iNum + extension; response.AddHeader("Content-Disposition", "attachment;filename=\"" + iNum + "\""); string query = "insert into graphtable(graphtitle,graphpath,creategraph,year) VALUES('" + iNum.ToString() + "','" + file_path + "','" + true + "','" + DateTime.Now.Year.ToString() + "')"; try { int n = connect.UpdateDb(query); if (n > 0) { resultLabel.Text = "Merge Successfull"; } else { resultLabel.Text = " Merge Failed"; } resultLabel.Visible = true; } catch { } using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // instantiate a datagrid DataGrid dg = new DataGrid(); dg.DataSource = dt; //ds.Tables[0]; dg.DataBind(); dg.RenderControl(htw); File.WriteAllText(filenamepath, sw.ToString()); // File.WriteAllText(filenamepath, sw.ToString(), Encoding.UTF8); response.Write(sw.ToString()); response.End(); } } } Hi all, I have created an excel sheet from datatable using above function. I want to read the excel sheet programatically using the below connectionstring. This string works fine for all other excel sheets but not for the one i created using the above function. I guess it is because of excel version problem. OleDbConnection conn= new OleDbConnection("Data Source='" + path +"';provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;";); Can anyone suggest a way by which i can create an excel sheet such that it is readable again using above query. I cannot use Microsoft InterOp library as it is not supported by my host.

    Read the article

  • How to build a function on the fly in java?

    - by stereos
    I'm parsing a text file that is being mapped to some java code like such: public void eval(Node arg) { if(arg.data.equals("rand")) { moveRandomly(); } else if(arg.data.equals("home")) { goHome(); }//snip.. This is going to need to be re-evaluated about a thousand times and I'd rather not have to traverse the whole thing every time. Is there any way to make this traversal once and then have it be a function that is called every other time?

    Read the article

  • Euclidian Distances between points

    - by R S
    I have an array of points in numpy: points = rand(dim, n_points) And I want to: Calculate all the l2 norm (euclidian distance) between a certain point and all other points Calculate all pairwise distances. and preferably all numpy and no for's.

    Read the article

  • C++ random number from a set

    - by user69514
    Is it possible to print a random number in C++ from a set of numbers with ONE SINGLE statement? let's say the set is 2, 5, 22, 55, 332 i looked up rand, but I double it's possible to do in a single statement

    Read the article

  • How to use iterator in nested arraylist

    - by Muhammad Abrar
    I am trying to build an NFA with a special purpose of searching, which is totally different from regex. The State has following format class State implements List{ //GLOBAL DATA static int depth; //STATE VALUES String stateName; ArrayList<String> label = new ArrayList<>(); //Label for states //LINKS TO OTHER STATES boolean finalState; ArrayList<State> nextState ; // Link with multiple next states State preState; // previous state public State() { stateName = ""; finalState = true; nextState = new ArrayList<>(); } public void addlabel(String lbl) { if(!this.label.contains(lbl)) this.label.add(lbl); } public State(String state, String lbl) { this.stateName = state; if(!this.label.contains(lbl)) this.label.add(lbl); depth++; } public State(String state, String lbl, boolean fstate) { this.stateName = state; this.label.add(lbl); this.finalState = fstate; this.nextState = new ArrayList<>(); } void displayState() { System.out.print(this.stateName+" --> "); for(Iterator<String> it = label.iterator(); it.hasNext();) { System.out.print(it.next()+" , "); } System.out.println("\nNo of States : "+State.depth); } Next, the NFA class is public class NFA { static final String[] STATES= {"A","B","C","D","E","F","G","H","I","J","K","L","M" ,"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; State startState; State currentState; static int level; public NFA() { startState = new State(); startState = null; currentState = new State(); currentState = null; startState = currentState; } /** * * @param st */ NFA(State startstate) { startState = new State(); startState = startstate; currentState = new State(); currentState = null; currentState = startState ; // To show that their is only one element in NFA } boolean insertState(State newState) { newState.nextState = new ArrayList<>(); if(currentState == null && startState == null ) //if empty NFA { newState.preState = null; startState = newState; currentState = newState; State.depth = 0; return true; } else { if(!Exist(newState.stateName))//Exist is used to check for duplicates { newState.preState = currentState ; currentState.nextState.add(newState); currentState = newState; State.depth++; return true; } } return false; } boolean insertState(State newState, String label) { newState.label.add(label); newState.nextState = null; newState.preState = null; if(currentState == null && startState == null) { startState = newState; currentState = newState; State.depth = 0; return true; } else { if(!Exist(newState.stateName)) { newState.preState = currentState; currentState.nextState.add(newState); currentState = newState; State.depth++; return true; } else { ///code goes here } } return false; } void markFinal(State s) { s.finalState = true; } void unmarkFinal(State s) { s.finalState = false; } boolean Exist(String s) { State temp = startState; if(startState.stateName.equals(s)) return true; Iterator<State> it = temp.nextState.iterator(); while(it.hasNext()) { Iterator<State> i = it ;//startState.nextState.iterator(); { while(i.hasNext()) { if(i.next().stateName.equals(s)) return true; } } //else // return false; } return false; } void displayNfa() { State st = startState; if(startState == null && currentState == null) { System.out.println("The NFA is empty"); } else { while(st != null) { if(!st.nextState.isEmpty()) { Iterator<State> it = st.nextState.iterator(); do { st.displayState(); st = it.next(); }while(it.hasNext()); } else { st = null; } } } System.out.println(); } /** * @param args the command line arguments */ /** * * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here NFA l = new NFA(); State s = new State("A11", "a",false); NFA ll = new NFA(s); s = new State("A111", "a",false); ll.insertState(s); ll.insertState(new State("A1","0")); ll.insertState(new State("A1111","0")); ll.displayNfa(); int j = 1; for(int i = 0 ; i < 2 ; i++) { int rand = (int) (Math.random()* 10); State st = new State(STATES[rand],String.valueOf(i), false); if(l.insertState(st)) { System.out.println(j+" : " + STATES[rand]+" and "+String.valueOf(i)+ " inserted"); j++; } } l.displayNfa(); System.out.println("No of states inserted : "+ j--); } I want to do the following This program always skip to display the last state i.e. if there are 10 states inserted, it will display only 9. In exist() method , i used two iterator but i do not know why it is working I have no idea how to perform searching for the existing class name, when dealing with iterators. How should i keep track of current State, properly iterate through the nextState List, Label List in a depth first order. How to insert unique States i.e. if State "A" is inserted once, it should not insert it again (The exist method is not working) Best Regards

    Read the article

  • Random record in ActiveRecord

    - by astrofoo
    I'm in need of getting a random record from a table via ActiveRecord. I've followed the example from Jamis Buck from 2006. However, I've also come across another way via a Google search (can't attribute with a link due to new user restrictions): rand_id = rand(Model.count) rand_record = Model.first(:conditions => [ "id >= ?", rand_id]) I'm curious how others on here have done it or if anyone knows what way would be more efficient.

    Read the article

  • Rails 2.3: How to create this SQL into a named_scope

    - by randombits
    Having a bit of difficulty figuring out how to create a named_scope from this SQL query: select * from foo where id NOT IN (select foo_id from bar) AND foo.category = ? ORDER BY RAND() LIMIT 1; Category should be variable to change. What's the most efficient way the named_scope can be written for the problem above?

    Read the article

  • Does MySQL short-circuit the ORDER BY clause?

    - by nickf
    Given this SQL: SELECT * FROM mytable ORDER BY mycolumn, RAND() Assuming that mycolumn happens to only contain unique values (and hence, contains enough information to perform the ORDER BY), does MySQL short-circuit the operation and skip evaluating the rest?

    Read the article

  • Naming member functions/methods with a single underscore, good style or bad?

    - by Extrakun
    In some languages where you cannot override the () operator, I have seen methods with a single underscore, usually for 'helper' classes. Something likes this: class D10 { public function _() { return rand(1,10); } } Is it better to have the function called Roll()? Is a underscore fine? After all, there is only one function, and it removes the need to look up the name of the class. Any thoughts?

    Read the article

  • Freebase; select a random record?

    - by user168083
    1) Is there any way to select a random record from Freebase? If I do a limit of 1, it consistently returns the same record. I could grab the larger data set and select a random rec from that but that seems like overkill. Analogous to MySQL's : select * from profiles order by rand() limit 1; 2) Is there any way to tell Freebase not to select certain items in a set? Analogous to MySQL's : select * from profiles where id NOT IN (SELECT profile_id from approved_profiles) Thanks in advance

    Read the article

  • Need help converting Ruby code to php code

    - by newprog
    Yesterday I posted this queston. Today I found the code which I need but written in Ruby. Some parts of code I have understood (I don't know Ruby) but there is one part that I can't. I think people who know ruby and php can help me understand this code. def do_create(image) # Clear any old info in case of a re-submit FIELDS_TO_CLEAR.each { |field| image.send(field+'=', nil) } image.save # Compose request vm_params = Hash.new # Submitting a file in ruby requires opening it and then reading the contents into the post body file = File.open(image.filename_in, "rb") # Populate the parameters and compute the signature # Normally you would do this in a subroutine - for maximum clarity all # parameters are explicitly spelled out here. vm_params["image"] = file # Contents will be read by the multipart object created below vm_params["image_checksum"] = image.image_checksum vm_params["start_job"] = 'vectorize' vm_params["image_type"] = image.image_type if image.image_type != 'none' vm_params["image_complexity"] = image.image_complexity if image.image_complexity != 'none' vm_params["image_num_colors"] = image.image_num_colors if image.image_num_colors != '' vm_params["image_colors"] = image.image_colors if image.image_colors != '' vm_params["expire_at"] = image.expire_at if image.expire_at != '' vm_params["licensee_id"] = DEVELOPER_ID #in php it's like this $vm_params["sequence_number"] = -rand(100000000);????? vm_params["sequence_number"] = Kernel.rand(1000000000) # Use a negative value to force an error when calling the test server vm_params["timestamp"] = Time.new.utc.httpdate string_to_sign = CREATE_URL + # Start out with the URL being called... #vm_params["image"].to_s + # ... don't include the file per se - use the checksum instead vm_params["image_checksum"].to_s + # ... then include all regular parameters vm_params["start_job"].to_s + vm_params["image_type"].to_s + vm_params["image_complexity"].to_s + # (nil.to_s => '', so this is fine for vm_params we don't use) vm_params["image_num_colors"].to_s + vm_params["image_colors"].to_s + vm_params["expire_at"].to_s + vm_params["licensee_id"].to_s + # ... then do all the security parameters vm_params["sequence_number"].to_s + vm_params["timestamp"].to_s vm_params["signature"] = sign(string_to_sign) #no problem # Workaround class for handling multipart posts mp = Multipart::MultipartPost.new query, headers = mp.prepare_query(vm_params) # Handles the file parameter in a special way (see /lib/multipart.rb) file.close # mp has read the contents, we can close the file now response = post_form(URI.parse(CREATE_URL), query, headers) logger.info(response.body) response_hash = ActiveSupport::JSON.decode(response.body) # Decode the JSON response string ##I have understood below def sign(string_to_sign) #logger.info("String to sign: '#{string_to_sign}'") Base64.encode64(HMAC::SHA1.digest(DEVELOPER_KEY, string_to_sign)) end # Within Multipart modul I have this: class MultipartPost BOUNDARY = 'tarsiers-rule0000' HEADER = {"Content-type" => "multipart/form-data, boundary=" + BOUNDARY + " "} def prepare_query (params) fp = [] params.each {|k,v| if v.respond_to?(:read) fp.push(FileParam.new(k, v.path, v.read)) else fp.push(Param.new(k,v)) end } query = fp.collect {|p| "--" + BOUNDARY + "\r\n" + p.to_multipart }.join("") + "--" + BOUNDARY + "--" return query, HEADER end end end Thanks for your help.

    Read the article

  • Java How to get exact tile location in random tile engine

    - by SYNYST3R1
    I am using the slick2d library. I want to know how to get the exact tile location so when I click on a tile it only changes that tile and not every tile on the screen. My tile generation class public Image[] tiles = new Image[3]; public int width, height; public int[][] index; public Image grass, dirt, selection; boolean selected; int mouseX, mouseY; public void init() throws SlickException { grass = new Image("assets/tiles/grass.png"); dirt = new Image("assets/tiles/dirt.png"); selection = new Image("assets/tiles/selection.png"); tiles[0] = grass; tiles[1] = dirt; width = 50; height = 50; index = new int[width][height]; Random rand = new Random(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { index[x][y] = rand.nextInt(2); } } } public void update(GameContainer gc) { Input input = gc.getInput(); mouseX = input.getMouseX(); mouseY = input.getMouseY(); if(input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) { selected = true; } else{ selected = false; } } public void render() { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { tiles[index[x][y]].draw(x * 64, y *64); if(IsMouseInsideTile(x, y)) selection.draw(x * 64, y * 64); } } } public boolean IsMouseInsideTile(int x, int y) { return (mouseX >= x * 64 && mouseX <= (x + 1) * 64 && mouseY >= y * 64 && mouseY <= (y + 1) * 64); } I have tried a couple different ways to change the tile I am clicking on, but I don't understand how to do it.

    Read the article

  • using markers instead of if and else statement in php

    - by Mac Taylor
    hey guys i need to shorten or better to say ., harden my codes this is my original code : if ($type = "recent") { $OrderType = "sid DESC"; }elseif ($type = "pop"){ $OrderType = "counter DESC"; }else { $OrderType = "RAND()"; } now how can i use markers like this : $OrderType = ($type = "recent") ? "sid DESC" : "counter DESC" ; i tried but i didnt know how to write elseif in marker way

    Read the article

  • MYSQL JOIN SELECT Statment - omit duplicated

    - by mouthpiec
    Hi, I am tying to join the following 2 queries but I am having duplicated .... it is possible to remove duplacted fro this: ( SELECT bar_id, bar_name, town_name, bar_telephone, (subscription_type_id *2) AS subscription_type_id FROM bar, sportactivitybar, towns, subscriptiontype WHERE sport_activity_id_fk =14 AND bar_id = bar_id_fk AND town_id = town_id_fk AND subscription_type_id = subscription_type_id_fk ) UNION ( SELECT bar_id, bar_name, town_name, bar_telephone, subscription_type_id FROM bar, towns, subscriptiontype WHERE town_id = town_id_fk AND subscription_type_id = subscription_type_id_fk ) ORDER BY subscription_type_id DESC , RAND( ) Please note that I need to omit those duplicates that will have a lower subscription_type_id

    Read the article

  • Any special assertion to test if the resulting integer lies within a range

    - by barerd
    I would like to test if an instance variable lies in a range of numbers. I solved the problem by using assert_in_delta but would like to know if there is a formal assertion for this. #part of the tested class def initialize(value = 70 + rand(30)) @value = value end #test_value.rb class ValueTestCase < Test::Unit::TestCase def test_if_value_in_range assert_in_delta(85, p.value, 15) end end

    Read the article

  • how to use summation in matlab???

    - by lucky
    i have a randomly generated vector say A of length M say A=rand(M,1) and also i have function X(k)=sin(2*pi*k) how would i find Y(k) which is summation of A(l)*X(k-l) as l goes from 0 to M ... assume any value of k... but answer should be summation of all M+1 terms

    Read the article

  • Where do you extend classes in your rails application?

    - by ro
    Just about to extend the Array class with the following extension: class Array def shuffle! size.downto(1) { |n| push delete_at(rand(n)) } self end end However, I was wondering where a good place to keep these sort of extensions. I was thinking environment.rb or putting in its own file in the initializers directory.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >