Search Results

Search found 4955 results on 199 pages for 'range'.

Page 22/199 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • Sum variable range of cells using "today's" date as starting point.

    - by Jason
    How do you sum a variable range of cells based upon today's date in MS Excel 2003. Spreadsheet format: Variable range = # of days to sum Date range = listed in row 1, 1 day per cell (example A1=1/1/10, B1=1/2/10, C1=1/3/10....) Numbers to be summed - listed in row 2, X number per cell (example A2=8, B2=6, C2=1.....) example problem: IF variable range = 2 & Current Date = 1/2/10 then...Sum(b2:c2)=7 I am able to sum the entire row based upon current date using the following formula but am not able to add the variable range to the sum function. =SUMIF(A1:C1,"="&TODAY(),A2:C2)

    Read the article

  • Configurable tables in sql database

    - by dot
    I have the following tables in my database: Config Table: ====================================== Start_Range | End Range | Config_id 10 | 15 | 1 ====================================== Available_UserIDs ========================== ID | UserID | Used_YN | 1 | 10 | t | 1 | 11 | f | 1 | 12 | f | 1 | 13 | f | 1 | 14 | f | 1 | 15 | f | ========================== Users ========================== UserId | FName | LName | 10 |John | Doe | ========================== This is used in a reservation system of sorts... which lets an administrator specify a range of numbers that will be assigned to users in the config table. Once the range has been defined, the system then populates the Available_userIDs table with all the numbers in between the range, and sets the Used_YN flag to false As users sign up, they grab the next user_id number that's not in use... and reserve it. Then the system adds a record to the Users table. Once the admin has specified a range, it is possible that they can change it. For example, they can start with 10-15... and then when the range is used up, they should be able to specify another range like 16 - 99. I've put a unique constraint on the Available_UserIDs table, as well as on the Users table - to ensure that UserIds can't be duplicated. My questions are as follows: What's the best way to prevent the admins from using a range that's already in use? I thought of the following options: -- check either the Users table to see if the start range or ending range numbers are being used. If they are, assume that all the numbers in between are in use too, and reject the range. -- let them specify whatever they want, try to populate the Available_UserIDs table. If there are duplicates, just ignore that specific error message from the database and continue on. How do I find gaps in the number ranges? For example, if they specify 10-15, and then 20-25, it'd be nice to be able to somehow suggest on my web page that 16-19 is currently available. I found this article: http://stackoverflow.com/questions/1312101/how-to-find-a-gap-in-running-counter-with-sql But it only seems to return the first available number... so in my example above, it would only return the number 16. I'm sure there's a simpler way to do things that I'm overlooking!

    Read the article

  • How to fetch only the sprites in the player's range of motion for collision testing? (2D, axis aligned sprites)

    - by Twodordan
    I am working on a 2D sprite game for educational purposes. (In case you want to know, it uses WebGl and Javascript) I've implemented movement using the Euler method (and delta time) to keep things simple. Now I'm trying to tackle collisions. The way I wrote things, my game only has rectangular sprites (axis aligned, never rotated) of various/variable sizes. So I need to figure out what I hit and which side of the target sprite I hit (and I'm probably going to use these intersection tests). The old fashioned method seems to be to use tile based grids, to target only a few tiles at a time, but that sounds silly and impractical for my game. (Splitting the whole level into blocks, having each sprite's bounding box fit multiple blocks I might abide. But if the sprites change size and move around, you have to keep changing which tiles they belong to, every frame, it doesn't sound right.) In Flash you can test collision under one point, but it's not efficient to iterate through all the elements on stage each frame. (hence why people use the tile method). Bottom line is, I'm trying to figure out how to test only the elements within the player's range of motion. (I know how to get the range of motion, I have a good idea of how to write a collisionCheck(playerSprite, targetSprite) function. But how do I know which sprites are currently in the player's vicinity to fetch only them?) Please discuss. Cheers!

    Read the article

  • Laser range finder, what language to use? Beginner advice

    - by DrOnline
    I hope this is the right place. I am a programming beginner, and I want to make a laser range finder, and I need advice about how to proceed etc. In a few weeks I will get a lot of dirt cheap 3-5V lasers and some cheap usb webcams. I will point the laser and webcam in parallel, and somehow use trigonometry and programming to determined distance. I have seen online that others made done it this way, I have purposefully not looked at the details too much because I want to develop it on my own, and learn, but I know the general outline. I have a general idea of how to proceed. The program loads in a picture from the webcam, and I dunno how images work really, but I imagine there is a format that is basically an array of RGB values.. is this right? I will load in the red values, and find the most red one. I know the height difference between the laser and the cam. I know the center dot in the image, I know the redmost dot. I'm sure there's some way to figure out some range there. TO THE POINT: 1) Is my reasoning sound thus far, especially in terms of image analysis? I don't need complete solutions, just general points 2) What I need to figure out, is what platform to use. I have an arduino... apparently, I've read it's too weak to process images. Read that online. I know some C I know some Python I have Matlab. Which is the best option? I do not need high sampling rates, I have not decided on whether it should be automated or whether I should make a GUI with a button to press for samples. I will keep it simple and expand I think. I also do not need it to be super accurate, I'm just having fun here. Advice!

    Read the article

  • Intersecting boundaries with lucene

    - by Silvio Donnini
    I'm using Lucene, and I'm trying to find a way to index and retrieve documents that have a ranged property. For example I have: Document 1: Price:[30 TO 50] Document 2: Price:[45 TO 60] Document 3: Price:[60 TO 70] And I would like to search for all the documents whose ranges intersect a specific interval, in the above example, if I search for Price in [55 TO 65] I should get Document 2 and Document 3 as results. I don't think NumericRangeQueries alone would do the trick, I need to work on the index with something similar to R-trees, but are they implemented in Lucene? Also, I suppose that what I need should be a subclass of MultiTermQuery, because the query Price in [55 TO 65] has two boundaries, but I don't see anything suitable among MultiTermQuery's subclasses. Any help is appreciated, thanks, Silvio P.S. I'm using Lucene 2.9.0, but I can update to the latest release if needed.

    Read the article

  • SQL CHECK constraint to prevent date overlap

    - by Michael
    I have a table that describes which software versions were installed on a machine at various times: machine_id::integer, version::text, datefrom::timestamp, dateto::timestamp I'd like to do a constraint to ensure that no date ranges overlap, i.e. it is not possible to have multiple software versions installed on a machine at the same time. How can this be achieved in SQL? I am using PostgreSQL v8.4.

    Read the article

  • Set textarea selection in Internet Explorer

    - by Tatu Ulmanen
    I'm looking for a way to set a selection in a textarea in Internet Explorer. In other browsers, this works just fine: textarea.selectionStart = start; textarea.selectionEnd = end; In IE, I assume I have to use createRange and adjust the selection somehow, but I cannot figure out how. Extra bonus points for a link to a proper documentation about createRange and associated methods, MSDN isn't helping out much.

    Read the article

  • ASP.NET RangeValidator can't do even the most basic math !?!?!?

    - by marc_s
    I'm having an issue with my ASP.NET RangeValidator controls. I want to allow users to enter a discount amount, and this amount must be negative (< $0.00). I want to verify that the amount entered in a textbox is a negative value, so I have this in my page markup: <asp:TextBox ID="tbxDiscount" runat="server" /> <asp:RangeValidator ID="rvDiscount" runat="server" ControlToValidate="tbxDiscount" MinimumValue="0.0" MaximumValue="0.0" EnableClientScript="true" ErrorMessage="Please enter a negative value for a discount" /> and I attempt to set the MinimumValue dynamically in my code before the page gets rendered - to the negative equivalent of my item price. So if the item is $69, I want to set the minimum value to - $69: rvDiscount.MinimumValue = (-1.0m * Price).ToString(); Trouble is: I keep getting this error message: The maximum value 0.0 cannot be less than the minimum value -69.00 for rvDiscount WTF?!?!??! Where I come from, -69 $ IS less than $0 ...... so what's the problem? And more importantly: what is the solution to the problem??

    Read the article

  • Get `n` random values between 2 numbers having average `x`

    - by Somnath Muluk
    I want to get n random numbers(e.g n=16)(whole numbers) between 1 to 5(including both) so that average is x. x can be any value between (1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5). I am using PHP. e.g. Suppose I have average x= 3. Then required 16 whole numbers between 1 to 5(including both). like (1,5,3,3,3,3,2,4,2,4,1,5,1,5,3,3) Update: if x=3.5 means average of 16 numbers should be between 3.5 to 4. and if x=4 means average of 16 numbers should be between 4 to 4.5 and if x=5 means all numbers are 5

    Read the article

  • PHP - BUG with filter_var and FILTER_VALIDATE_FLOAT

    - by Samuele
    I think there is a bug in this filter_var or maybe I'm doing something wrong: Try this: $options = array( 'options' => array( 'default' => 3, 'min_range' => 1000.0, 'max_range' => 5000.6, ) ); $VariableValue2 = 5698; $VariableValue4 = 5698.2; $chicco3 = filter_var($VariableValue2, FILTER_VALIDATE_INT, $options); $chicco4 = filter_var($VariableValue4, FILTER_VALIDATE_FLOAT, $options); It suppose to don't validate it... Infact the value: 5698 is greater than 5000.6!!!! But with FILTER_VALIDATE_INT it work FINE!! It return 3 that is the default value in case it don't validate it... PERFECT... Instead, with FILTER_VALIDATE_FLOAT it validate it... It return 5698.2!!! I'm doing something wrong??? Thank you to everybody... Samuele

    Read the article

  • Determining if an offset is in between line numbers?

    - by Sophomore
    hi I need to determine if a given selection is in between a start line and an end line. I have an ILineRange and a given offset within the viewport of eclipse. (I need to know, if the selection (from a remote party) was made within the current viewport of the local user. Unfortunately, I cannot get an LineRange from the selection. I must rely on getOffset() and getLength()... Anyone has an idea? I think there is not a clean solution for this, as the offset (or the characters per line vary (new line lines or a big block of comment).

    Read the article

  • Recursive algorithm for coalescing / collapsing list of dates into ranges.

    - by Dycey
    Given a list of dates 12/07/2010 13/07/2010 14/07/2010 15/07/2010 12/08/2010 13/08/2010 14/08/2010 15/08/2010 19/08/2010 20/08/2010 21/08/2010 I'm looking for pointers towards a recursive pseudocode algorithm (which I can translate into a FileMaker custom function) for producing a list of ranges, i.e. 12/07/2010 to 15/07/2010, 12/08/2010 to 15/08/2010, 19/08/2010 to 20/08/2010 The list is presorted and de-deuplicated. I've tried starting from both the first value and working forwards, and the last value and working backwards but I just can't seem to get it to work. Having one of those frustrating days... It would be nice if the signature was something like CollapseDateList( dateList, separator, ellipsis ) :-)

    Read the article

  • C# IndexOutOfRange issue, probably simple.

    - by MWC
    Banging my head off the wall due to this. I'm getting the error at cell[rcell] = repack[counter] even though I have 190 items in the repack array. private string csvtogrid(string input) { input = input.Replace("\r", ",").Substring(2).TrimEnd(',').Trim().Replace("\n", ",").Replace(",,,", ",").Replace(",,",","); string[] repack = input.Split(','); string[] cell = { }; int rcell = 1; for (int counter = 1; counter < repack.Length; counter++) { if (rcell < 4) { cell[rcell] = repack[counter]; rcell++; } procgrid.Rows.Add(cell[1], cell[2], cell[3]); rcell = 1; } richTextBox1.Text = input; return null; }

    Read the article

  • What to do when product range evolves and site name does not reflect this?

    - by nitbuntu
    Suppose, just as an example, I have a website with domain www.gifts-for-dogs.com.....but after a few years I start selling stuff for Cats and Fish. I may not keep enough of a range of products for these other type of pets yet, so can't justify changing the domain name and logo (to something like gifts-for-pets.com) just yet....but envisage that I eventually may have to in the not too distant future. What would be a good strategy here and what are the steps I would have to consider before making these changes?

    Read the article

  • How do I print out objects in an array in python?

    - by Jonathan
    I'm writing a code which performs a k-means clustering on a set of data. I'm actually using the code from a book called collective intelligence by O'Reilly. Everything works, but in his code he uses the command line and i want to write everything in notepad++. As a reference his line is >>>kclust=clusters.kcluster(data,k=10) >>>[rownames[r] for r in k[0]] Here is my code: from PIL import Image,ImageDraw def readfile(filename): lines=[line for line in file(filename)] # First line is the column titles colnames=lines[0].strip( ).split('\t')[1:] rownames=[] data=[] for line in lines[1:]: p=line.strip( ).split('\t') # First column in each row is the rowname rownames.append(p[0]) # The data for this row is the remainder of the row data.append([float(x) for x in p[1:]]) return rownames,colnames,data from math import sqrt def pearson(v1,v2): # Simple sums sum1=sum(v1) sum2=sum(v2) # Sums of the squares sum1Sq=sum([pow(v,2) for v in v1]) sum2Sq=sum([pow(v,2) for v in v2]) # Sum of the products pSum=sum([v1[i]*v2[i] for i in range(len(v1))]) # Calculate r (Pearson score) num=pSum-(sum1*sum2/len(v1)) den=sqrt((sum1Sq-pow(sum1,2)/len(v1))*(sum2Sq-pow(sum2,2)/len(v1))) if den==0: return 0 return 1.0-num/den class bicluster: def __init__(self,vec,left=None,right=None,distance=0.0,id=None): self.left=left self.right=right self.vec=vec self.id=id self.distance=distance def hcluster(rows,distance=pearson): distances={} currentclustid=-1 # Clusters are initially just the rows clust=[bicluster(rows[i],id=i) for i in range(len(rows))] while len(clust)>1: lowestpair=(0,1) closest=distance(clust[0].vec,clust[1].vec) # loop through every pair looking for the smallest distance for i in range(len(clust)): for j in range(i+1,len(clust)): # distances is the cache of distance calculations if (clust[i].id,clust[j].id) not in distances: distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec) #print 'i' #print i #print #print 'j' #print j #print d=distances[(clust[i].id,clust[j].id)] if d<closest: closest=d lowestpair=(i,j) # calculate the average of the two clusters mergevec=[ (clust[lowestpair[0]].vec[i]+clust[lowestpair[1]].vec[i])/2.0 for i in range(len(clust[0].vec))] # create the new cluster newcluster=bicluster(mergevec,left=clust[lowestpair[0]], right=clust[lowestpair[1]], distance=closest,id=currentclustid) # cluster ids that weren't in the original set are negative currentclustid-=1 del clust[lowestpair[1]] del clust[lowestpair[0]] clust.append(newcluster) return clust[0] def kcluster(rows,distance=pearson,k=4): # Determine the minimum and maximum values for each point ranges=[(min([row[i] for row in rows]),max([row[i] for row in rows])) for i in range(len(rows[0]))] # Create k randomly placed centroids clusters=[[random.random( )*(ranges[i][1]-ranges[i][0])+ranges[i][0] for i in range(len(rows[0]))] for j in range(k)] lastmatches=None for t in range(100): print 'Iteration %d' % t bestmatches=[[] for i in range(k)] # Find which centroid is the closest for each row for j in range(len(rows)): row=rows[j] bestmatch=0 for i in range(k): d=distance(clusters[i],row) if d<distance(clusters[bestmatch],row): bestmatch=i bestmatches[bestmatch].append(j) # If the results are the same as last time, this is complete if bestmatches==lastmatches: break lastmatches=bestmatches # Move the centroids to the average of their members for i in range(k): avgs=[0.0]*len(rows[0]) if len(bestmatches[i])>0: for rowid in bestmatches[i]: for m in range(len(rows[rowid])): avgs[m]+=rows[rowid][m] for j in range(len(avgs)): avgs[j]/=len(bestmatches[i]) clusters[i]=avgs return bestmatches

    Read the article

  • Extract data from specific range of cells in multiple worksheet in multiple files.

    - by Michele
    Extract data from specific range of cells(always the same cells) in multiple worksheet in multiple files. 1 file=1 day. I have 6 technicians each day of the week, Monday thru Friday. So, 5 files with 6 worksheets. I have entered specific info in specific cells of every work sheet. The range is constant(the same address in EVERY worksheet in every file.) So, I need a formula to extract and calculate the data in the given range and dump it into another spreadsheet. I can forward an example a file if it will help anyone to answer my question. Or more explanation if necessary is available upon request. JUST PLEASE SOMEBODY HELP ME!!!!! Thank you all in advance. Regards, Michele

    Read the article

  • Is there a way of disabled byte-range requests in Apache?

    - by Sam Minnée
    I have a web page with a link to a PDF file (target="_blank"). If I click the link, the PDF reader just shows a grey screen within the Firefox browser. If I copy that link and manually open it in a new tab, the PDF will display correctly, and subsequent requests made by clicking the original link now work, suggesting that the problem occurs when loading the file into the cache. It appears as though the Adobe PDF reader plugin is making byte-range requests (I see lots of 206 responses) and I suspect that this may be the cause of the issue. I am running an Apache webserver. Has anyone had problems with Apache and Adobe's byte-range requests? Are there any workarounds? Perhaps a way of configuring Apache to ignore byte-range requests on PDFs?

    Read the article

  • Can I connect an external antenna to a range extender?

    - by ercan
    I live in a kind of dormitory and the next access point is 60 meters away from my room. So I bought a range extender (TP-Link WA730RE) and installed it into my room in the same height as the access point. But my problem is still not solved. The reception is slightly better but my connection still gets broken every two minutes. The antenna that comes with this range extender was 4dB. My question is, can I buy an 8dB external antenna (like this one: http://www.amazon.com/TP-Link-TL-ANT2408C-Desktop-Omni-Directional-Antenna/dp/B0034CQSKW/ref=sr_1_14?ie=UTF8&qid=1332074993&sr=8-14) and replace it with the antenna that comes with the range extender? Or is this external antenna only suitable for the "receiver" end of the connection, i.e. the computer?

    Read the article

  • How to increase signal/range of your Wi-Fi antenna-less repeater/booster over the network?

    - by kenorb
    I've BT Home Hub in the upper flat (2-3 walls behind) and I'm using WPS Wireless-N Wifi Range Router Repeater Extender in my flat where I'm using my laptop. These are antenna-less devices. Are there any life-hack tricks to increase signal/range of my repeater without buying the new more powerful repeater? I've tried already to move my repeater closer to the ceiling or putting the aluminium foil underneath, but it didn't help. Are there any methods, specific plates or materials which can boost the signal? Specification: Model: WN518W2 Frequency range: 2.4-2.4835GHz Wireless transmit power: 14 ~17 dBm (Typical) Wireless Signal Rates With Automatic Fallback: 11n: Up to 300Mbps(dynamic), 11g: Up to 54Mbps(dynamic), 11b: Up to 11Mbps(dynamic) Modulation Technology: DBPSK, DQPSK, CCK, OFDM, 16-QAM, 64-QAM Receiver Sensitivity: 300M: -68dBm@10% PER / 150M: -68dBm@10% PER / 108M: -68dBm@10% PER / 54M: -68dBm@10% PER / 11M: -85dBm@8% PER / 6M: -88dBm@10% PER / 1M: -90dBm@8% PER Product dimensions: 11 * 6 * 7cm

    Read the article

  • Suggestion of device WiFi range in it's spec. Possible?

    - by SeeR
    I have router Draytek Vigor 2100VG at home almost in the center of it. The farthest point at my home is my balcony, ~12m from it. I have constant wifi signal range problems with some of my devices, but not with others. Notebook Lenovo W510 - no problems Nokia Home Music - always on 10m - no problems Sony PS3 - always on 7m - no problems Sony tablet S - problems around 6m Sony PSP - problems around 8m Sony PS Vita - problems around 8m Nokia E63 - problems around 8m I'm curious why my Notebook don't have any problems even on the balcony? I guess it has better hardware or uses more power for transmission. This information is really important when you want to buy new device/computer, so my real question is: Can device wifi range can somehow be found/suggested from official hardware technical specification? If not Is there some web page with wifi range reviews?

    Read the article

  • Is there a way of disabled byte-range requests in Apache?

    - by Sam Minnée
    I have a web page with a link to a PDF file (target="_blank"). If I click the link, the PDF reader just shows a grey screen within the Firefox browser. If I copy that link and manually open it in a new tab, the PDF will display correctly, and subsequent requests made by clicking the original link now work, suggesting that the problem occurs when loading the file into the cache. It appears as though the Adobe PDF reader plugin is making byte-range requests (I see lots of 206 responses) and I suspect that this may be the cause of the issue. I am running an Apache webserver. Has anyone had problems with Apache and Adobe's byte-range requests? Are there any workarounds? Perhaps a way of configuring Apache to ignore byte-range requests on PDFs?

    Read the article

  • How do you reset the range of available ports that libvirt autoport can use?

    - by bcmcfc
    Libvirt is using its autoport setting to automatically allocate ports within a range starting at 5900. Example excerpt from an XML configuration for a VM: <graphics type='spice' port='6000' autoport='yes' listen='127.0.0.1' keymap='en-gb'> <listen type='address' address='127.0.0.1'/> </graphics> Currently, there are free ports at various points within the range 5900 to 5999. However, newly booted VMs are picking up ports from 6000 on. I need for it to reuse the available ports in the 59xx range. Is this possible? If so, how do I do this? The problem arose because VMs are being accessed via websockets, and it tried to use 6000 which is a reserved port for X11. A solution that explains how to blacklist ports from being picked up by autport would also be sufficient.

    Read the article

  • How to count each digit in a range of integers?

    - by Carlos Gutiérrez
    Imagine you sell those metallic digits used to number houses, locker doors, hotel rooms, etc. You need to find how many of each digit to ship when your customer needs to number doors/houses: 1 to 100 51 to 300 1 to 2,000 with zeros to the left The obvious solution is to do a loop from the first to the last number, convert the counter to a string with or without zeros to the left, extract each digit and use it as an index to increment an array of 10 integers. I wonder if there is a better way to solve this, without having to loop through the entire integers range. Solutions in any language or pseudocode are welcome. Edit: Answers review John at CashCommons and Wayne Conrad comment that my current approach is good and fast enough. Let me use a silly analogy: If you were given the task of counting the squares in a chess board in less than 1 minute, you could finish the task by counting the squares one by one, but a better solution is to count the sides and do a multiplication, because you later may be asked to count the tiles in a building. Alex Reisner points to a very interesting mathematical law that, unfortunately, doesn’t seem to be relevant to this problem. Andres suggests the same algorithm I’m using, but extracting digits with %10 operations instead of substrings. John at CashCommons and phord propose pre-calculating the digits required and storing them in a lookup table or, for raw speed, an array. This could be a good solution if we had an absolute, unmovable, set in stone, maximum integer value. I’ve never seen one of those. High-Performance Mark and strainer computed the needed digits for various ranges. The result for one millon seems to indicate there is a proportion, but the results for other number show different proportions. strainer found some formulas that may be used to count digit for number which are a power of ten. Robert Harvey had a very interesting experience posting the question at MathOverflow. One of the math guys wrote a solution using mathematical notation. Aaronaught developed and tested a solution using mathematics. After posting it he reviewed the formulas originated from Math Overflow and found a flaw in it (point to Stackoverflow :). noahlavine developed an algorithm and presented it in pseudocode. A new solution After reading all the answers, and doing some experiments, I found that for a range of integer from 1 to 10n-1: For digits 1 to 9, n*10(n-1) pieces are needed For digit 0, if not using leading zeros, n*10n-1 - ((10n-1) / 9) are needed For digit 0, if using leading zeros, n*10n-1 - n are needed The first formula was found by strainer (and probably by others), and I found the other two by trial and error (but they may be included in other answers). For example, if n = 6, range is 1 to 999,999: For digits 1 to 9 we need 6*105 = 600,000 of each one For digit 0, without leading zeros, we need 6*105 – (106-1)/9 = 600,000 - 111,111 = 488,889 For digit 0, with leading zeros, we need 6*105 – 6 = 599,994 These numbers can be checked using High-Performance Mark results. Using these formulas, I improved the original algorithm. It still loops from the first to the last number in the range of integers, but, if it finds a number which is a power of ten, it uses the formulas to add to the digits count the quantity for a full range of 1 to 9 or 1 to 99 or 1 to 999 etc. Here's the algorithm in pseudocode: integer First,Last //First and last number in the range integer Number //Current number in the loop integer Power //Power is the n in 10^n in the formulas integer Nines //Nines is the resut of 10^n - 1, 10^5 - 1 = 99999 integer Prefix //First digits in a number. For 14,200, prefix is 142 array 0..9 Digits //Will hold the count for all the digits FOR Number = First TO Last CALL TallyDigitsForOneNumber WITH Number,1 //Tally the count of each digit //in the number, increment by 1 //Start of optimization. Comments are for Number = 1,000 and Last = 8,000. Power = Zeros at the end of number //For 1,000, Power = 3 IF Power 0 //The number ends in 0 00 000 etc Nines = 10^Power-1 //Nines = 10^3 - 1 = 1000 - 1 = 999 IF Number+Nines <= Last //If 1,000+999 < 8,000, add a full set Digits[0-9] += Power*10^(Power-1) //Add 3*10^(3-1) = 300 to digits 0 to 9 Digits[0] -= -Power //Adjust digit 0 (leading zeros formula) Prefix = First digits of Number //For 1000, prefix is 1 CALL TallyDigitsForOneNumber WITH Prefix,Nines //Tally the count of each //digit in prefix, //increment by 999 Number += Nines //Increment the loop counter 999 cycles ENDIF ENDIF //End of optimization ENDFOR SUBROUTINE TallyDigitsForOneNumber PARAMS Number,Count REPEAT Digits [ Number % 10 ] += Count Number = Number / 10 UNTIL Number = 0 For example, for range 786 to 3,021, the counter will be incremented: By 1 from 786 to 790 (5 cycles) By 9 from 790 to 799 (1 cycle) By 1 from 799 to 800 By 99 from 800 to 899 By 1 from 899 to 900 By 99 from 900 to 999 By 1 from 999 to 1000 By 999 from 1000 to 1999 By 1 from 1999 to 2000 By 999 from 2000 to 2999 By 1 from 2999 to 3000 By 1 from 3000 to 3010 (10 cycles) By 9 from 3010 to 3019 (1 cycle) By 1 from 3019 to 3021 (2 cycles) Total: 28 cycles Without optimization: 2,235 cycles Note that this algorithm solves the problem without leading zeros. To use it with leading zeros, I used a hack: If range 700 to 1,000 with leading zeros is needed, use the algorithm for 10,700 to 11,000 and then substract 1,000 - 700 = 300 from the count of digit 1. Benchmark and Source code I tested the original approach, the same approach using %10 and the new solution for some large ranges, with these results: Original 104.78 seconds With %10 83.66 With Powers of Ten 0.07 A screenshot of the benchmark application: If you would like to see the full source code or run the benchmark, use these links: Complete Source code (in Clarion): http://sca.mx/ftp/countdigits.txt Compilable project and win32 exe: http://sca.mx/ftp/countdigits.zip Accepted answer noahlavine solution may be correct, but l just couldn’t follow the pseudo code, I think there are some details missing or not completely explained. Aaronaught solution seems to be correct, but the code is just too complex for my taste. I accepted strainer’s answer, because his line of thought guided me to develop this new solution.

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >