text
stringlengths 0
27.6k
| python
int64 0
1
| DeepLearning or NLP
int64 0
1
| Other
int64 0
1
| Machine Learning
int64 0
1
| Mathematics
int64 0
1
| Trash
int64 0
1
|
---|---|---|---|---|---|---|
I'm trying to accomplish this in LaTeX:
⎡a⎤ ⎡b … n⎤
⎢⁞⎢ ⎢⁞ ⋱ ⁞⎢
⎣x⎦ ⎣y … z⎦
[a … x]
I'm able to get a vector + a matrix on one line, but I'm not sure how to align the vector below so that it sits perfectly under the large matrix.
Here's a less-unicode text representation of the 'drawing' above:
[a] [ b c ]
[d] [ e f ]
[ g h ]
Note that the last line ([ g h ]) is a single-row matrix, separate from the 2x2 matrix above it.
| 0 | 0 | 0 | 0 | 1 | 0 |
In description logic, what is the difference between "someValuesFrom" and "allValuesFrom"?
In other words, the difference between (limited existential quantification) and (value restriction).
For example, consider this:
∆ = {a, b, c, d, e}
ext(B) = {<c,d>}
ext(R) = {<a,b>, <a,c>, <d,c>, <c,e>}
So what is the difference between the following?
ext(∃R. B) = ?
ext(∀R. B) = ?
Is there any way to simplify the concept of somevaluefrom and allvaluesfrom?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have implemented the A* algorithm in AS3 and it works great except for one thing.
Often the resulting path does not take the most “natural” or smooth route to the target.
In my environment the object can move diagonally as inexpensively as it can move horizontally or vertically.
Here is a very simple example; the start point is marked by the S, and the end (or finish) point by the F.
| | | | | | | | | |
|S| | | | | | | | |
x| | | | | | | | | |
x| | | | | | | | | |
x| | | | | | | | | |
x| | | | | | | | | |
x| | | | | | | | | |
|F| | | | | | | | |
| | | | | | | | | |
| | | | | | | | | |
As you can see, during the 1st round of finding, nodes [0,2], [1,2], [2,2] will all be added to the list of possible node as they all have a score of N.
The issue I’m having comes at the next point when I’m trying to decide which node to proceed with. In the example above I am using possibleNodes[0] to choose the next node. If I change this to possibleNodes[possibleNodes.length-1] I get the following path.
| | | | | | | | | |
|S| | | | | | | | |
| |x| | | | | | | |
| | |x| | | | | | |
| | | |x| | | | | |
| | |x| | | | | | |
| |x| | | | | | | |
|F| | | | | | | | |
| | | | | | | | | |
| | | | | | | | | |
And then with possibleNextNodes[Math.round(possibleNextNodes.length / 2)-1]
| | | | | | | | | |
|S| | | | | | | | |
|x| | | | | | | | |
x| | | | | | | | | |
x| | | | | | | | | |
x| | | | | | | | | |
x| | | | | | | | | |
|F| | | | | | | | |
| | | | | | | | | |
| | | | | | | | | |
All these paths have the same cost as they all contain the same number of steps but, in this situation, the most sensible path would be as follows...
| | | | | | | | | |
|S| | | | | | | | |
|x| | | | | | | | |
|x| | | | | | | | |
|x| | | | | | | | |
|x| | | | | | | | |
|x| | | | | | | | |
|F| | | | | | | | |
| | | | | | | | | |
| | | | | | | | | |
Is there a formally accepted method of making the path appear more sensible rather than just mathematically correct?
| 0 | 1 | 0 | 0 | 0 | 0 |
I'm onto problem 245 now but have hit some problems. I've done some work on it already but don't feel I've made any real steps towards solving it. Here's what I've got so far:
We need to find n=ab with a and b positive integers. We can also assume gcd(a, b) = 1 without loss of generality and thus phi(n) = phi(ab) = phi(a)phi(b).
We are trying to solve:
Hence:
At this point I figured it would be a good idea to actually see how these numbers were distributed. I hacked together a brute-force program that I used to find all (composite) solutions up to 104:
15, 85, 255, 259, 391, 589, 1111, 3193, 4171, 4369, 12361, 17473, 21845, 25429, 28243, 47989, 52537, 65535, 65641, 68377, 83767, 91759
Importantly it looks like there won't be too many less than the 1011 limit the problem asks. The most interesting/ useful bit I discovered was that k was quite small even for the large values of n. In fact the largest k was only 138. (Additionally, it seems k is always even.)
Considering this, I would guess it is possible to consider every value of k and find what value(s) n can be with that value of k.
Returning to the original equation, note that it can be rewritten as:
Since we know k:
And that's about as far as I have got; I'm still pursuing some of my routes but I wonder if I'm missing the point! With a brute force approach I have found the sum up to 108 which is 5699973227 (only 237 solutions for n).
I'm pretty much out of ideas; can anyone give away some hints?
Update: A lot of work has been done by many people and together we've been able to prove several things. Here's a list:
n is always odd and k is always even. k <= 105.5. n must be squarefree.
I have found every solution for when n=pq (2 prime factors) with p>q. I used the fact that for 2 primes q = k+factor(k^2-k+1) and p = k+[k^2-k+1]/factor(k^2-k+1). We also know for 2 primes k < q < 2k.
For n with 2 of more prime factors, all of n's primes are greater than k.
| 0 | 0 | 0 | 0 | 1 | 0 |
This is something related with Mathematics as well. But this is useful in computing as well.
Lets say you have 10 coordinates. (x1,y1)(x2,y2)..... in 2D Space. (i.e on a X-Y Plane). Can we find a single smooth curve going across the each coordinate.
While expanding the question, If the space is 3D, then can we find an equation of a smooth surface that going across a given set of spacial coordinates?
Are there any Libraries (Any language) \ tools to perform such calculations?
| 0 | 0 | 0 | 0 | 1 | 0 |
I've written a small function in C, which almost do the same work as standart function `fcvt'. As you may know, this function takes a float/double and make a string, representing this number in ANSI characters. Everything works ;-)
For example, for number 1.33334, my function gives me string: "133334" and set up special integer variable `decimal_part', in this example will be 1, which means in decimal part only 1 symbol, everything else is a fraction.
Now I'm curious about what to do standart C function `printf'. It can take %a or %e as format string. Let me cite for %e (link junked):
"double" argument is output in scientific notation
[-]m.nnnnnne+xx
... The exponent always contains two digits.
It said: "The exponent always contains two digits". But what is an Exponent? This is the main question. And also, how to get this 'exponent' from my function above or from `fcvt'.
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm trying to find/write a function that would perform the same operation as imlincomb(). However, I am having trouble finding such functions in C++ without using any Matlab API functions other than Intel Performance Primitiives library, and I don't really want to purchase a license for it unless my application really has to take advantage of it. What would be any easy method of implementing it, or perhaps if there are any standard functions that make the job a lot easier?
Thanks in advance.
| 0 | 0 | 0 | 0 | 1 | 0 |
I've been tasked with creating a simulation of people moving around. It could be a bunch of people walking through a restaurant or exiting a school. Searching around, I've found a bunch A* related stuff which is fine for one person but I will have a bunch. Is there a standard library people use for this stuff? Or a kind of algorithm I should look at? Or a book that will get me going?
| 0 | 1 | 0 | 0 | 0 | 0 |
I'm building a custom regression tree and want to use m-estimate for pruning.
Does anyone know how to calculate that.
http://www.ailab.si/blaz/predavanja/UISP/slides/uisp07-RegTrees.ppt might help (slide 12, how should Em look like?)
| 0 | 1 | 0 | 0 | 1 | 0 |
Suppose I have a column of heights -- how can I select all and only those height values that are neither in the top 30% of values nor the bottom 30% of values.
I'd like the answer for PostgreSQL (or, failing that, MySQL -- I'm using Rails).
| 0 | 0 | 0 | 0 | 1 | 0 |
how do i find out pixel value at certain degree on the circumference of a circle if I know the pixel co-ordinates of the center of the circle, radius of the circle ,and perpendicular angle.
Basically, I am trying to draw the hands of a clock at various times ( 1 o clock , 2 o clock etc )
| 0 | 0 | 0 | 0 | 1 | 0 |
we have a particle detector hard-wired to use 16-bit and 8-bit buffers. Every now and then, there are certain [predicted] peaks of particle fluxes passing through it; that's okay. What is not okay is that these fluxes usually reach magnitudes above the capacity of the buffers to store them; thus, overflows occur. On a chart, they look like the flux suddenly drops and begins growing again. Can you propose a [mostly] accurate method of detecting points of data suffering from an overflow?
P.S. The detector is physically inaccessible, so fixing it the 'right way' by replacing the buffers doesn't seem to be an option.
Update: Some clarifications as requested. We use python at the data processing facility; the technology used in the detector itself is pretty obscure (treat it as if it was developed by a completely unrelated third party), but it is definitely unsophisticated, i.e. not running a 'real' OS, just some low-level stuff to record the detector readings and to respond to remote commands like power cycle. Memory corruption and other problems are not an issue right now. The overflows occur simply because the designer of the detector used 16-bit buffers for counting the particle flux, and sometimes the flux exceeds 65535 particles per second.
Update 2: As several readers have pointed out, the intended solution would have something to do with analyzing the flux profile to detect sharp declines (e.g. by an order of magnitude) in an attempt to separate them from normal fluctuations. Another problem arises: can restorations (points where the original flux drops below the overflowing level) be detected by simply running the correction program against the reverted (by the x axis) flux profile?
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm looking for POD low dimension vectors (2,3 and 4D let say) with all the necessary arithmetic niceties (operator +, - and so on). POD low dimension matrices would be great as well.
boost::ublas vectors are not POD, there's a pointer indirection somewhere (vector are resizeable).
Can I find that anywhere in boost? Using boost::array along with boost.operator lib is an options but maybe I'm missing something easier elsewhere?
Apart boost, does anybody know any good library around?
PS: POD <=> plain old data
EDIT:
Otherwise, here are some other links I gathered from another thread:
http://www.cgal.org/
http://geometrylibrary.geodan.nl
http://www.cmldev.net
http://www.openexr.com/index.html
http://project-mathlibs.web.cern.ch/project-mathlibs/sw/html/SMatrix.html
| 0 | 0 | 0 | 0 | 1 | 0 |
Background:
I was recently playing around with GDI+ to draw a "Disc" displaying a sweeping color change through 360 degrees. (I dug up some HSL to RGB code to loop through HSL(1,1,1) -> HSL(360,1,1))
Regarding the disc, I first drew a full solid circle using the above, and then a second circle in Grey over the center to give the following
So this is all fine... but I realised that GDI+ is insulating us from a lot of the tricky match that's going on here by way of the FillPie method. Also, FillPie requires you to supply a bounding rectangle for the pie as opposed to a Radius Length. It also does a full segment fill and doesnt allow you to specify a part of that segment only.
Question:
Can anyone point me in the direction of some Math functions or give any explanation on what forumla I would need to calculate the area & plot points of the following "Green Filled Area" given:
Point `c` - an x,y co-ordinate
Angle `A` - an angle from horizontal
Angle `B - an angle from horizontal where `B` - `A` == the sweep angle
Length `r` - a distance from `c`
Length `r2` - a distance from `c` where `r2` - `r` == the `height` of the segment to be filled.
Links to Math sources are fine but I've had a quick google & look at Wolfram Math and could find what I was looking for. Also, if there was some way to generate a sequence of bounding (x,y) co-or's that could be passed as a Point[] to Graphics.FillPolygon, that'd be cool too.
| 0 | 0 | 0 | 0 | 1 | 0 |
I regrettably haven't studied mathematics since I was 16 (GCSE level), I'm now a 27 year old C# developer.
Would it be a fruitless exercise trying to work through Structure and Interpretation of Computer Programs (SICP)?
What kind of mathematics standard is expected of the reader?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a list of points. Each point being an x and y coordinate (both of which are integers). Now I'm trying to find known patterns, such as lines, arcs or circles, knowing that the points are not perfectly on the pattern.
What's the best way to do it? I don't have many clues to get started.
Edit: the points are ordered. The user is drawing something and the program should detect the best patterns. For instance, if a triangle is drawn, it should detect three lines.
| 0 | 1 | 0 | 0 | 0 | 0 |
I've got two rectangles represented by structures that contain the x1, y1, x2, y2 coordinates. One rectangle can be considered the parent, another the child.
I already know how to detect if the child rectangle is within the parent rectangle; what I'm trying to figure out now is the simplest, fastest way to determine the rectangular areas within the parent that are not being overlapped by the child rectangle.
For example, consider a 100x100 parent rectangle, and a 50x50 child rectangle located exactly in the center of the parent. This would mean there would be four rectangles representing the four areas in the parent rectangle that aren't being overlapped by the child.
Of course, the child could be in the top left, top right, bottom left, bottom right corner, or a little to the left, a little to the right, etc... there might be one, two, three, or four rectangles that represent the non-overlapped areas.
I've had some ideas for implementations to figure this out, but all seem overly complex. Is there a simple, fast way to figure this out?
| 0 | 0 | 0 | 0 | 1 | 0 |
In other answers at Stackoverflow it's been suggested that Weka is good, but there are others (Classifier4j, jBNC, Naiban).
Does anyone have actual experience with these?
| 0 | 0 | 0 | 1 | 0 | 0 |
This one seems quite stupid, but I'm struglling from an hour to do this,
How to Draw the Sine Wave in WPF??
Thanks
| 0 | 0 | 0 | 0 | 1 | 0 |
I am trying to implement a Point3.Slerp method, so was looking for some samples but the ones I found seems like it's a whole brand new class to host all the code.
Is there a simple, straightforward way to implement it? Basically the ones I have seen was using Matrix types. Can I implement Slerp without matrices, or would that be a disadvantage (performance, etc)?
Pseudo codes are fine too.
| 0 | 0 | 0 | 0 | 1 | 0 |
I've got a manually created NavGraph in a 3D environment. I understand (and have implemented previously) an A* routine to find my way through the graph once you've 'got on the graph'.
What I'm interested in, is the most optimal way to get onto and 'off' the Graph.
Ex:
So the routine go's something like this:
Shoot a ray from the source to the destination, if theres nothing in the way, go ahead and just walk it.
if theres something in the way, we need to use the graph, so to get onto the graph, we need to find the closest visible node on the graph. (to do this, I previously sorted the graph based on the distance from the source, then fired rays from closet to furthest till i found one that didn't have an obstacle. )
Then run the standard A*...
Then 'exit' the graph, through the same method as we got on the graph (used to calculate the endpoint for the above A*) so I take and fire rays from the endpoint to the closest navgraph node.
so by the time this is all said and done, unless my navgraph is very dense, I've spent more time getting on/off the graph than I have calculating the path...
There has to be a better/faster way? (is there some kind of spacial subdivision trick?)
| 0 | 1 | 0 | 0 | 0 | 0 |
Google has suggestion come up when you make a typo entry,how do they do it?
| 0 | 0 | 0 | 1 | 0 | 0 |
I am trying to solve a problem involving printing the product of all divisors of a given number. The number of test cases is a number 1 <= t <= 300000 , and the number itself can range from 1 <= n <= 500000
I wrote the following code, but it always exceeds the time limit of 2 seconds. Are there any ways to speed up the code ?
from math import sqrt
def divisorsProduct(n):
ProductOfDivisors=1
for i in range(2,int(round(sqrt(n)))+1):
if n%i==0:
ProductOfDivisors*=i
if n/i != i:
ProductOfDivisors*=(n/i)
if ProductOfDivisors <= 9999:
print ProductOfDivisors
else:
result = str(ProductOfDivisors)
print result[len(result)-4:]
T = int(raw_input())
for i in range(1,T+1):
num = int(raw_input())
divisorsProduct(num)
Thank You.
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm having problem regarding max and sqrt
If I include math.h it coudn't find sqrt.
So I view the cmath header file and inside it includes math.h, but when I try to open math.h it says that file is not found. SO ithink my math.h is missing in Linux.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have implemented a full text search in a discussion forum database and I want to display
the search results in a way Google does. Even for a very long html page only a two or three
lines of the texts displayed in a search result list. Usually these are the lines
which contain a search terms.
What would be the good algorithm of how to extract a few lines of the text based on the text itself and a search terms. I could think of something as easy as just using one line of text before the search term occurrence in a text and a line after - but that seems to be too simple to work.
Would like to get a few directions, ideas and insights.
Thank you.
| 0 | 1 | 0 | 0 | 0 | 0 |
I have some code:
int CalculateAckermann(int x, int y)
{
if(!x)
{
return y++;
}
if(!y)
{
return CalculateAckermann(x--,1);
}
else
{
return CalculateAckermann(x--, CalculateAckermann(x, y--));
}
}
Designed to calculate the ackermann function. Above a fairly low number of x and y the application causes a stack overflow because it recurses too deeply and results in pretty big numbers. How would I go about slowly calculating a solution?
| 0 | 0 | 0 | 0 | 1 | 0 |
My math is bad, real bad. So bad I'm struggling to even phrase this question, but here goes.
The situation is train travel and you have four arrays to work with.
Leaving_Stations
Arriving_Stations
Leaving_Dates
Returning_Dates
So let's say you're only interested in one way routes and you need to figure out how many combinations of route there are. That would be (i think)
possible_routes = (leaving_stations x arriving_stations) x leaving_dates
But how would I go about figuring out how many combinations there are if I want a return trip?
UPDATE::
or would this work?
possible_routes = ((leaving_stations x arriving_stations) x leaving_dates) x (leaving_dates x returning_dates)
| 0 | 0 | 0 | 0 | 1 | 0 |
Is there any JavaScript library that can be used for calculations involving 700+ Digits?
Also, how about the same thing in C++?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am trying to map a trajectory path between two point. All I know is the two points in question and the distance between them. What I would like to be able to calculate is the velocity and angle necessary to hit the end point.
I would also like to be able to factor in some gravity and wind so that the path/trajectory is a little less 'perfect.' Its for a computer game.
Thanks F.
| 0 | 0 | 0 | 0 | 1 | 0 |
Say you've got a toy grammar, like: (updated so the output looks more natural)
S -> ${NP} ${VP} | ${S} and ${S} | ${S}, after which ${S}
NP -> the ${N} | the ${A} ${N} | the ${A} ${A} ${N}
VP -> ${V} ${NP}
N -> dog | fish | bird | wizard
V -> kicks | meets | marries
A -> red | striped | spotted
e.g., "the dog kicks the red wizard", "the bird meets the spotted fish or the wizard marries the striped dog"
How can you produce a sentence from this grammar according to the constraint that it must contain a total of n Vs + As + Ns. Given an integer the sentence must contain that many terminals. (note of course in this grammar the minimum possible n is 3).
| 0 | 1 | 0 | 0 | 0 | 0 |
I have been developing (for the last 3 hours) a small project I'm doing in C# to help me choose a home.
Specifically, I am putting crime statistics in an overlay on Google maps, to find a nice neighborhood.
Here is an example:
http://otac0n.com/Demos/prospects.html
Now, I manually found the Lat and Lng to match the corners of the map displated in the example, but I have a few more maps to overlay.
My new application allows me to choose a landmark and point at the image to tie the Pixel to a LatLng. Something like:
locations.Add(new LocationPoint(37.6790f, -97.3125f, "Kellogg and I-135"));
// and later...
targetPoint.Pixel = FindPixel(mouseEvent.Location);
So, I've gathered a list of pixel/latlng combinations, and now would like to transform the image (using affine or non-affine transformations).
The goal here is to make every street line up. Given a good map, the only necessary transformation would be a rotation to line the map up north-to-south (and for now I would be happy with that). But I'm not sure where to start.
Does anybody have any experience doing image transformations in C#? How would I find the proper rotation to make the map level?
After the case of well-made maps is resolved, I would eventually like to be able to overlay hand drawn maps. This would obviously entail heavy distortion of the final image, and may be beyond the scope of this first iteration. However, I would not like to develop a system that would be un-expandable to this system in the future.
| 0 | 0 | 0 | 0 | 1 | 0 |
I was hoping someone that is good with math and loops could help me out. I'm writing a program in Objective C where I need to come up with a way to do a cycle. If you don't know Objective C I would appreciate any help in pseudo code just to help me figure this out.
What I need is a scale that is based on two dates. I know this will be some sort of loop but not sure how to figure it out.
For instance, lets say that the first date is 5/25/1976 and the second date is 9/25/2009. Every 25 days there will be a "peak" so it's value will be 100. If I divide 23 in half I get 12 (rounded) so it would be the opposite or "valley" so it's numerical value would be 0. In other words on the 23rd day it would be at 100 but then on the 24th day it would start going back down and then bottom out 12 days later and then start the cycle back up and top out again at 23 days.
What I need to be able to do is find the numerical value for any given date in between any two given dates.
Thanks for any help you can offer!
| 0 | 0 | 0 | 0 | 1 | 0 |
This question is purely out of curiosity. I am off school for the summer, and was going to implement an algorithm to solve this just for fun. That led to the above question, how hard is this problem?
The problem: you are given a list of positive integers, a set of mathematical operators and the equal sign(=). can you create a valid mathematical expression using the integers (in the same order) and the operators (any number of times)?
An example will should clarify any questions:
given: {2, 3, 5, 25} , {+, -, *, /} , {=}
output: YES
the expression (only one i think) is (2 + 3) * 5 = 25. you only need to output YES/NO.
I believe the problem is in NP. I say this because it is a decision problem (YES/NO answer) and I can find a non-deterministic poly time algorithm that decides it.
a. non-deterministically select a sequence of operators to place between the integers.
b. verify you answer is a valid mathematical expression (this can be done in constant
time).
In this case, the big question is this: Is the problem in P? (i.e. Is there a deterministic poly time algorithm that decides it?) OR Is the problem NP complete? (i.e. Can a known NP Complete problem be reduced to this? or equivalently Is every NP language poly time reducable to this problem?) OR neither? (i.e. problem in NP but not NP Complete)
Note: This problem statement assumes P not equal to NP. Also, although I am new to Stack Overflow, I am familiar with the homework tag. This is indeed just curiosity, not homework :)
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm trying to add a fade effect to my form by manually changing the opacity of the form but I'm having some trouble calculating the correct value to increment by the Opacity value of the form.
I know I could use the AnimateWindow API but it's showing some unexpected behavior and I'd rather do it manually anyways as to avoid any p/invoke so I could use it in Mono later on.
My application supports speeds ranging from 1 to 10. And I've manually calculated that for a speed of 1 (slowest) I should increment the opacity by 0.005 and for a speed of 10 (fastest) I should increment by 0.1. As for the speeds between 1 and 10, I used the following expression to calculate the correct value:
double opSpeed = (((0.1 - 0.005) * (10 - X)) / (1 - 10)) + 0.1; // X = [1, 10]
I though this could give me a linear value and that that would be OK. However, for X equal 4 and above, it's already too fast. More than it should be. I mean, speeds between 7, and 10, I barely see a difference and the animation speed with these values should be a little more spaced
Note that I still want the fastest increment to be 0.1 and the slowest 0.005. But I need all the others to be linear between them.
What I'm doing wrong?
It actually makes sense why it works like this, for instance, for a fixed interval between increments, say a few milliseconds, and with the equation above, if X = 10, then opSpeed = 0.1 and if X = 5, then opSpeed = 0.47. If we think about this, a value of 0.1 will loop 10 times and a value of 0.47 will loop just the double. For such a small interval of just a few milliseconds, the difference between these values is not that much as to differentiate speeds from 5 to 10.
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm trying to estimate, for back-of-the-napkin calculation purposes, how many different device drivers are available for Windows. I'm trying to understand what it might take in terms of size of collected data and processing power what would be required to do some statistical analysis of drivers.
Anybody have any references? Ideas? At this point educated guesses would be much appreciated.
| 0 | 0 | 0 | 1 | 0 | 0 |
I'm trying to figure out a way to distribute a sum S over N different operands (b1, b2, .., bn), where b1, b2, ... bn are in a fixed ratio, which is determined by another set of operands (a1,a2, .. an)
Consider a situation where:
Candidate A gets a total of Ta votes from N constituencies, with distribution: {a1, a2, a3 .. aN}
Candidate B gets a total of Tb votes (Ta and Tb are unrelated, which means Ta < Tb, Ta = Tb & Ta > Tb are all possible) from M constituencies (IMP: M <= N), distribution unknown.
What is the best approach to allot the Tb votes to the constituencies b1, b2, b3.. bM such that, they are distributed in the same ratio as a1, a2, a3.. aN.
Some Cases:
1.Ideal
Ta = 20 (8,6,4,2) Tb = 10
Then we get: Tb (4,3,2,1)
2.Somewhat less ideal
Ta = 20(8 ,6, 4, 1 , 1) Tb = 10
Then we get (4, 3, 2, 1, 0) which actually means (4,3,2,1) (M < N), and is still tolerable.
| 0 | 0 | 0 | 0 | 1 | 0 |
How to move circle in a circular path like knob tune?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am afraid the question is a bit technical, but I hope someone might have stumbled into a similar subject, or give me a pointer of some kind.
If G is a group (in the sense of algebraic structure), and if g1, ..., gn are elements of G, is there an algorithm (or a function in some dedicated program, like GAP) to determine whether there is a subgroup of G such that those elements form a set of representatives for the cosets of the subgroup? (We may assume that G is a permutation group, and probably even the full symmetric group.)
(There are of course several algorithms to find the cosets of a given subgroups, like Todd-Coxeter algorithm; this is a kind of inverse question.)
Thanks,
Daniele
| 0 | 0 | 0 | 0 | 1 | 0 |
I am looking for a way to uniformly choose values in GF(2^M) between two bounds.
GF(2^M) is a Galois Field - See GF(4) as defined on this page - http://www.math.umbc.edu/~campbell/Math413Spr09/Notes/12-13_Finite_Fields.html
From a technical, non-math perspective, this is most similar to CRC operations.
For example:
ulong gf2step( ulong x, int bits, ulong p )
{
x = x << 1; // "multiply" by x
if ( x >= (1 << bits)) x = x ^ p;
return x;
}
Expanding the example from below:
12 is '1100
'1100 shifted left by 1 becomes `11000. Since bit 4 is set, xor with `10011 (p).
Next is `1011 or 11.
Similarly,
9 is '1001
'1001 shifted left by 1 becomes `10010. Since bit 4 is set, xor with `10011 (p).
Next is `0001.
My obvious method is to start with the integer exponents corresponding to the bounds, pick a random exponent between those and generate the value from that.
However, this has two problems --
1. Given arbitrary bounds, I can't find the corresponding integer exponent..
2. This will be repeated many, many times, so I am concerned about exponentiation speed.
Example:
int gf2random( ulong low, ulong high, ulong p);
gf2random( 12, 13, 19) should return evenly from the set {12, 11,5,10,7,14,15, 13}
gf2random( 9, 1, 19) should return either 9 or 1
I can step the values in GF(2^M) fairly easily - but I'm not sure how to avoid overshooting the upper bound.
Does it simplify the problem if the low bound was always '1' ?
| 0 | 0 | 0 | 0 | 1 | 0 |
My data structure is initialized as follows:
[[0,0,0,0,0,0,0,0] for x in range(8)]
8 characters, 8 rows, each row has 5 bits for columns, so each integer can be in the range between 0 and 31 inclusive.
I have to convert the number 177 (can be between 0 and 319) into char, row, and column.
Let me try again, this time with a better code example. No bits are set.
Ok, I added the reverse to the problem. Maybe that'll help.
chars = [[0,0,0,0,0,0,0,0] for x in range(8)]
# reverse solution
for char in range(8):
for row in range(8):
for col in range(5):
n = char * 40 + (row * 5 + col)
chars[char][row] = chars[char][row] ^ [0, 1<<4-col][row < col]
for data in range(320):
char = data / 40
col = (data - char * 40) % 5
row = ?
print "Char %g, Row %g, Col %g" % (char, row, col), chars[char][row] & 1<<4-col
| 0 | 0 | 0 | 0 | 1 | 0 |
Some Duplicates:
1.265 * 10000 = 126499.99999999999 ?????
How is floating point stored? When does it matter?
Strange floating-point behaviour in a Java program
Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?
Error in Flash addition
I divide 23 by 40 (23/40). In C this operation results in 0.5749999999999996. But actually it must be 0.575!
How can I fix this?
| 0 | 0 | 0 | 0 | 1 | 0 |
Kernel-based classifier usually requires O(n^3) training time because of the inner-product computation between two instances. To speed up the training, inner-product values can be pre-computed and stored in a two-dimensional array. However when the no. of instances is very large, say over 100,000, there will not be sufficient memory to do so.
So any better idea for this?
| 0 | 0 | 0 | 1 | 0 | 0 |
I intend to use a multi layer perceptron network trained with backpropagation (one hidden layer, inputs served as 8x8 bit matrices containing the B/W pixels from the image). The following questions arise:
which type of learning should I use: batch or on-line?
how could I estimate the right number of nodes in the hidden layer? I intend to process the 26 letter of english alphabet.
how could I stop the training process, to avoid overfitting?
(not quite related) is there another better NN prved to perform better than MLP? I know about MLP stucking in local minima, overfitting and so on, so is there a better (soft computing-based) approach?
Thanks
| 0 | 1 | 0 | 0 | 0 | 0 |
Is there an algorithm that can be used to determine whether a sample of data taken at fixed time intervals approximates a sine wave?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a table which indexes the locations of words in a bunch of documents.
I want to identify the most common bigrams in the set.
How would you do this in MSSQL 2008?
the table has the following structure:
LocationID -> DocID -> WordID -> Location
I have thought about trying to do some kind of complicated join... and i'm just doing my head in.
Is there a simple way of doing this?
I think I better edit this on monday inorder to bump it up in the questions
Sample Data
LocationID DocID WordID Location
21952 534 27 155
21953 534 109 156
21954 534 4 157
21955 534 45 158
21956 534 37 159
21957 534 110 160
21958 534 70 161
| 0 | 1 | 0 | 0 | 0 | 0 |
I'm currently working on building a game which is on a planet, the way in which I'm planning to store the data is in 6 2dimensional arrays, which are heightmaps around the sphere (on the faces of a cube).
The problem I have is this, given a normalised vector which points outwards from the centre of the sphere how can I determine these two things:
The plane which it intersects
The x/y coordinates I should look up in my 2d array to get the height.
My current solution is this (using XNA):
Construct a ray pointing out from [0,0] along the direction vector supplied. Loop through each surface and do a ray/plane intersection (which is a method supplied by the XNA framework) to get the distance to the intersection point. Select the closest plane (shortest distance to intersection)
Take the 3D point, and convert it to a 2D point which can be used as an array lookup to find the radius (this is the bit I cannot work out the maths for, or find any references to through google).
A helpful constraint is that the sphere/cube system is around the origin.
So, the problem which needs solving is this:
Given a direction vector, how do I determine where it intersects the surrounding cube. Using this result how do I then get the correct value in a 2D array which is "painted" on the face of this cube?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am trying to calculate an initial buffer size to use when decompressing data of an unknown size. I have a bunch of data points from existing compression streams but don't know the best way to analyze them.
Data points are the compressed size and the ratio to uncompressed size.
For example:
100425 (compressed size) x 1.3413 (compression ratio) = 134,700 (uncompressed size)
The compressed data stream doesn't store the uncompressed size so the decompressor has to alloc an initial buffer size and realloc if it overflows. I'll looking for the "best" initial size to alloc the buffer given the compressed size. I have over 293,000 data points.
| 0 | 0 | 0 | 0 | 1 | 0 |
Odd question here not really code but logic,hope its ok to post it here,here it is
I have a data structure that can be thought of as a graph.
Each node can support many links but is limited to a value for each node.
All links are bidirectional. and each link has a cost. the cost depends on euclidian difference between the nodes the minimum value of two parameters in each node. and a global modifier.
i wish to find the maximum cost for the graph.
wondering if there was a clever way to find such a matching, rather than going through in brute force ...which is ugly... and i'm not sure how i'd even do that without spending 7 million years running it.
To clarify:
Global variable = T
many nodes N each have E,X,Y,L
L is the max number of links each node can have.
cost of link A,B = Sqrt( min([a].e | [b].e) ) x
( 1 + Sqrt( sqrt(sqr([a].x-[b].x)+sqr([a].y-[b].y)))/75 + Sqrt(t)/10 )
total cost =sum all links.....and we wish to maximize this.
average values for nodes is 40-50 can range to (20..600)
average node linking factor is 3 range 0-10.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have some data, up to a between a million and a billion records, each which is represented by a bitfield, about 64 bits per key. The bits are independent, you can imagine them basically as random bits.
If I have a test key and I want to find all values in my data with the same key, a hash table will spit those out very easily, in O(1).
What algorithm/data structure would efficiently find all records most similar to the query key? Here similar means that most bits are identical, but a minimal number are allowed to be wrong. This is traditionally measured by Hamming distance., which just counts the number of mismatched bits.
There's two ways this query might be made, one might be by specifying a mismatch rate like "give me a list of all existing keys which have less than 6 bits that differ from my query" or by simply best matches, like "give me a list of the 10,000 keys which have the lowest number of differing bits from my query."
You might be temped to run to k-nearest-neighbor algorithms, but here we're talking about independent bits, so it doesn't seem likely that structures like quadtrees are useful.
The problem can be solved by simple brute force testing a hash table for low numbers of differing bits. If we want to find all keys that differ by one bit from our query, for example, we can enumerate all 64 possible keys and test them all. But this explodes quickly, if we wanted to allow two bits of difference, then we'd have to probe 64*63=4032 times. It gets exponentially worse for higher numbers of bits.
So is there another data structure or strategy that makes this kind of query more efficient?
The database/structure can be preprocessed as much as you like, it's the query speed that should be optimized.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a bit of a strange question. Can anyone tell me where to find information about, or give me a little bit of an introduction to using shortest path algorithms that use a hill climbing approach? I understand the basics of both, but I can't put the two together. Wikipedia has an interesting part about solving the Travelling Sales Person with hill climbing, but doesn't provide a more in-depth explanation of how to go about it exactly.
For example, hill climbing can be
applied to the traveling salesman
problem. It is easy to find a solution
that visits all the cities but will be
very poor compared to the optimal
solution. The algorithm starts with
such a solution and makes small
improvements to it, such as switching
the order in which two cities are
visited. Eventually, a much better
route is obtained.
As far as I understand it, you should pick any path and then iterate through it and make optimisations along the way. For instance going back and picking a different link from the starting node and checking whether that gives a shorter path.
I am sorry - I did not make myself very clear. I understand how to apply the idea to Travelling Salesperson. I would like to use it on a shortest distance algorithm.
| 0 | 1 | 0 | 0 | 0 | 0 |
I've coded a function that crops an image to a given aspect ratio and finally then resizes it and outputs it as JPG:
<?php
function Image($image, $crop = null, $size = null)
{
$image = ImageCreateFromString(file_get_contents($image));
if (is_resource($image) === true)
{
$x = 0;
$y = 0;
$width = imagesx($image);
$height = imagesy($image);
/*
CROP (Aspect Ratio) Section
*/
if (is_null($crop) === true)
{
$crop = array($width, $height);
}
else
{
$crop = array_filter(explode(':', $crop));
if (empty($crop) === true)
{
$crop = array($width, $height);
}
else
{
if ((empty($crop[0]) === true) || (is_numeric($crop[0]) === false))
{
$crop[0] = $crop[1];
}
else if ((empty($crop[1]) === true) || (is_numeric($crop[1]) === false))
{
$crop[1] = $crop[0];
}
}
$ratio = array
(
0 => $width / $height,
1 => $crop[0] / $crop[1],
);
if ($ratio[0] > $ratio[1])
{
$width = $height * $ratio[1];
$x = (imagesx($image) - $width) / 2;
}
else if ($ratio[0] < $ratio[1])
{
$height = $width / $ratio[1];
$y = (imagesy($image) - $height) / 2;
}
/*
How can I skip (join) this operation
with the one in the Resize Section?
*/
$result = ImageCreateTrueColor($width, $height);
if (is_resource($result) === true)
{
ImageSaveAlpha($result, true);
ImageAlphaBlending($result, false);
ImageFill($result, 0, 0, ImageColorAllocateAlpha($result, 255, 255, 255, 127));
ImageCopyResampled($result, $image, 0, 0, $x, $y, $width, $height, $width, $height);
$image = $result;
}
}
/*
Resize Section
*/
if (is_null($size) === true)
{
$size = array(imagesx($image), imagesy($image));
}
else
{
$size = array_filter(explode('x', $size));
if (empty($size) === true)
{
$size = array(imagesx($image), imagesy($image));
}
else
{
if ((empty($size[0]) === true) || (is_numeric($size[0]) === false))
{
$size[0] = round($size[1] * imagesx($image) / imagesy($image));
}
else if ((empty($size[1]) === true) || (is_numeric($size[1]) === false))
{
$size[1] = round($size[0] * imagesy($image) / imagesx($image));
}
}
}
$result = ImageCreateTrueColor($size[0], $size[1]);
if (is_resource($result) === true)
{
ImageSaveAlpha($result, true);
ImageAlphaBlending($result, true);
ImageFill($result, 0, 0, ImageColorAllocate($result, 255, 255, 255));
ImageCopyResampled($result, $image, 0, 0, 0, 0, $size[0], $size[1], imagesx($image), imagesy($image));
header('Content-Type: image/jpeg');
ImageInterlace($result, true);
ImageJPEG($result, null, 90);
}
}
return false;
}
?>
The function works as expected but I'm creating a non-required GD image resource, how can I fix it? I've tried joining both calls but I must be doing some miscalculations.
<?php
/*
Usage Examples
*/
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '1:1', '600x');
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '2:1', '600x');
Image('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png', '2:', '250x300');
?>
Any help is greatly appreciated, thanks.
| 0 | 0 | 0 | 0 | 1 | 0 |
This is probably a silly and easy question, but it seems sometimes the simplest things give me more problems!
This formula is suppose to give me a number between 0 and 100.
(200 / 23) * Abs(Mod(2987, 23) - 23 / 2)
In objective C I coded it like this:
(200 / 23) * abs(2987 % 23) - (23 / 2);
Is the formula flawed (and doesn't give an answer between 0 and 100) or is my code wrong? It seems that my modulus isn't giving me the right result. Shouldn't it give me a one number integer?
Thanks
| 0 | 0 | 0 | 0 | 1 | 0 |
Logic error problem with the Gaussian Elimination code...This code was from my Numerical Methods text in 1990's. The code is typed in from the book- not producing correct output...
Sample Run:
SOLUTION OF SIMULTANEOUS LINEAR EQUATIONS
USING GAUSSIAN ELIMINATION
This program uses Gaussian Elimination to solve the
system Ax = B, where A is the matrix of known
coefficients, B is the vector of known constants
and x is the column matrix of the unknowns.
Number of equations: 3
Enter elements of matrix [A]
A(1,1) = 0
A(1,2) = -6
A(1,3) = 9
A(2,1) = 7
A(2,2) = 0
A(2,3) = -5
A(3,1) = 5
A(3,2) = -8
A(3,3) = 6
Enter elements of [b] vector
B(1) = -3
B(2) = 3
B(3) = -4
SOLUTION OF SIMULTANEOUS LINEAR EQUATIONS
The solution is
x(1) = 0.000000
x(2) = -1.#IND00
x(3) = -1.#IND00
Determinant = -1.#IND00
Press any key to continue . . .
The code as copied from the text...
//Modified Code from C Numerical Methods Text- June 2009
#include <stdio.h>
#include <math.h>
#define MAXSIZE 20
//function prototype
int gauss (double a[][MAXSIZE], double b[], int n, double *det);
int main(void)
{
double a[MAXSIZE][MAXSIZE], b[MAXSIZE], det;
int i, j, n, retval;
printf("
\t SOLUTION OF SIMULTANEOUS LINEAR EQUATIONS");
printf("
\t USING GAUSSIAN ELIMINATION
");
printf("
This program uses Gaussian Elimination to solve the");
printf("
system Ax = B, where A is the matrix of known");
printf("
coefficients, B is the vector of known constants");
printf("
and x is the column matrix of the unknowns.");
//get number of equations
n = 0;
while(n <= 0 || n > MAXSIZE)
{
printf("
Number of equations: ");
scanf ("%d", &n);
}
//read matrix A
printf("
Enter elements of matrix [A]
");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
printf(" A(%d,%d) = ", i + 1, j + 1);
scanf("%lf", &a[i][j]);
}
//read {B} vector
printf("
Enter elements of [b] vector
");
for (i = 0; i < n; i++)
{
printf(" B(%d) = ", i + 1);
scanf("%lf", &b[i]);
}
//call Gauss elimination function
retval = gauss(a, b, n, &det);
//print results
if (retval == 0)
{
printf("
\t SOLUTION OF SIMULTANEOUS LINEAR EQUATIONS
");
printf("
\t The solution is");
for (i = 0; i < n; i++)
printf("
\t x(%d) = %lf", i + 1, b[i]);
printf("
\t Determinant = %lf
", det);
}
else
printf("
\t SINGULAR MATRIX
");
return 0;
}
/* Solves the system of equations [A]{x} = {B} using */
/* the Gaussian elimination method with partial pivoting. */
/* Parameters: */
/* n - number of equations */
/* a[n][n] - coefficient matrix */
/* b[n] - right-hand side vector */
/* *det - determinant of [A] */
int gauss (double a[][MAXSIZE], double b[], int n, double *det)
{
double tol, temp, mult;
int npivot, i, j, l, k, flag;
//initialization
*det = 1.0;
tol = 1e-30; //initial tolerance value
npivot = 0;
//mult = 0;
//forward elimination
for (k = 0; k < n; k++)
{
//search for max coefficient in pivot row- a[k][k] pivot element
for (i = k + 1; i < n; i++)
{
if (fabs(a[i][k]) > fabs(a[k][k]))
{
//interchange row with maxium element with pivot row
npivot++;
for (l = 0; l < n; l++)
{
temp = a[i][l];
a[i][l] = a[k][l];
a[k][l] = temp;
}
temp = b[i];
b[i] = b[k];
b[k] = temp;
}
}
//test for singularity
if (fabs(a[k][k]) < tol)
{
//matrix is singular- terminate
flag = 1;
return flag;
}
//compute determinant- the product of the pivot elements
*det = *det * a[k][k];
//eliminate the coefficients of X(I)
for (i = k; i < n; i++)
{
mult = a[i][k] / a[k][k];
b[i] = b[i] - b[k] * mult; //compute constants
for (j = k; j < n; j++) //compute coefficients
a[i][j] = a[i][j] - a[k][j] * mult;
}
}
//adjust the sign of the determinant
if(npivot % 2 == 1)
*det = *det * (-1.0);
//backsubstitution
b[n] = b[n] / a[n][n];
for(i = n - 1; i > 1; i--)
{
for(j = n; j > i + 1; j--)
b[i] = b[i] - a[i][j] * b[j];
b[i] = b[i] / a[i - 1][i];
}
flag = 0;
return flag;
}
The solution should be: 1.058824, 1.823529, 0.882353 with det as -102.000000
Any insight is appreciated...
| 0 | 0 | 0 | 0 | 1 | 0 |
On a PHP & CodeIgniter-based web site, users can earn reputation for various actions, not unlike Stack Overflow. Every time reputation is awarded, a new entry is created in a MySQL table with the user_id, action being rewarded, and value of that bunch of points (e.g. 10 reputation). At the same time, a field in a users table, reputation_total, is updated.
Since all this is sort of meaningless without a frame of reference, I want to show users their percentile rank among all users. For total reputation, that seems easy enough. Let's say my user_id is 1138. Just count the number of users in the users table with a reputation_total less than mine, count the total number of users, and divide to find the percentage of users with a lower reputation than mine. That'll be user 1138's percentile rank, right? Easy!
But I'm also displaying reputation totals over different time spans--e.g., earned in the past seven days, which involves querying the reputation table and summing all my points earned since a given date. I'd also like to show percentile rank for the different time spans--e.g., I may be 11th percentile overall, but 50th percentile this month and 97th percentile today.
It seems I would have to go through and find the reputation totals of all users for the given time span, and then see where I fall within that group, no? Is that not awfully cumbersome? What's the best way to do this?
Many thanks.
| 0 | 0 | 0 | 0 | 1 | 0 |
I know that you can split a power-of-two number in half like so:
halfintR = some32bitint & 0xFFFF
halfintL = some32bitint >> 16
can you do the same thing for an integer which is bounded by a non-power of two space?
(say that you want your range to be limited to the set of integers that will fit into 4 digit base 52 space unsigned)
| 0 | 0 | 0 | 0 | 1 | 0 |
Could you guys please tell me how I can make the following code more pythonic?
The code is correct. Full disclosure - it's problem 1b in Handout #4 of this machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab & I'm using scipy
Eg one question i have is the matrixes kept rounding to integers until I initialized one value to 0.0. Is there a better way?
Thanks
import os.path
import math
from numpy import matrix
from scipy.linalg import inv #, det, eig
x = matrix( '0.0;0;1' )
y = 11
grad = matrix( '0.0;0;0' )
hess = matrix('0.0,0,0;0,0,0;0,0,0')
theta = matrix( '0.0;0;0' )
# run until convergence=6or7
for i in range(1, 6):
#reset
grad = matrix( '0.0;0;0' )
hess = matrix('0.0,0,0;0,0,0;0,0,0')
xfile = open("q1x.dat", "r")
yfile = open("q1y.dat", "r")
#over whole set=99 items
for i in range(1, 100):
xline = xfile.readline()
s= xline.split(" ")
x[0] = float(s[1])
x[1] = float(s[2])
y = float(yfile.readline())
hypoth = 1/ (1+ math.exp(-(theta.transpose() * x)))
for j in range(0,3):
grad[j] = grad[j] + (y-hypoth)* x[j]
for k in range(0,3):
hess[j,k] = hess[j,k] - (hypoth *(1-hypoth)*x[j]*x[k])
theta = theta - inv(hess)*grad #update theta after construction
xfile.close()
yfile.close()
print "done"
print theta
| 0 | 0 | 0 | 1 | 0 | 0 |
I was looking for a numeric representation for a date and unix time for midnight (in UTC) seems to be reasonable choice for that. However, as I'm not sure in my math skills, so is
date = date - date % (24 * 60 * 60);
where date is unix timestamp, the way to do that? Is there any simpler method?
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm writing a vertex shader at the moment, and I need some random numbers. Vertex shader hardware doesn't have logical/bit operations, so I cannot implement any of the standard random number generators.
Is it possible to make a random number generator using only standard arithmetic? the randomness doesn't have to be particularly good!
| 0 | 0 | 0 | 0 | 1 | 0 |
I am wanting some expert guidance here on what the best approach is for me to solve a problem. I have investigated some machine learning, neural networks, and stuff like that. I've investigated weka, some sort of baesian solution.. R.. several different things. I'm not sure how to really proceed, though. Here's my problem.
I have, or will have, a large collection of events.. eventually around 100,000 or so. Each event consists of several (30-50) independent variables, and 1 dependent variable that I care about. Some independent variables are more important than others in determining the dependent variable's value. And, these events are time relevant. Things that occur today are more important than events that occurred 10 years ago.
I'd like to be able to feed some sort of learning engine an event, and have it predict the dependent variable. Then, knowing the real answer for the dependent variable for this event (and all the events that have come along before), I'd like for that to train subsequent guesses.
Once I have an idea of what programming direction to go, I can do the research and figure out how to turn my idea into code. But my background is in parallel programming and not stuff like this, so I'd love to have some suggestions and guidance on this.
Thanks!
Edit: Here's a bit more detail about the problem that I'm trying to solve: It's a pricing problem. Let's say that I'm wanting to predict prices for a random comic book. Price is the only thing I care about. But there are lots of independent variables one could come up with. Is it a Superman comic, or a Hello Kitty comic. How old is it? What's the condition? etc etc. After training for a while, I want to be able to give it information about a comic book I might be considering, and have it give me a reasonable expected value for the comic book. OK. So comic books might be a bogus example. But you get the general idea. So far, from the answers, I'm doing some research on Support vector machines and Naive Bayes. Thanks for all of your help so far.
| 0 | 0 | 0 | 1 | 0 | 0 |
Just trying to figure out the proper and safer way to execute mathematical operation passed as string. In my scenario it is values fetched from image EXIF data.
After little research I found two way of doing it.
first, using eval:
function calculator1($str){
eval("\$str = $str;");
return $str;
}
second, using create_function:
function calculator2($str){
$fn = create_function("", "return ({$str});" );
return $fn();
};
Both examples require string cleanup to avoid malicious code execution. Is there any other or shorter way of doing so?
| 0 | 0 | 0 | 0 | 1 | 0 |
In short:
Given that a is coprime to b if GCD(a,b) = 1 (where GCD stands for great common divisor), how many positive integers below N are coprime to N?
Is there a clever way?
Not necessary stuff
Here is the dumbest way:
def count_coprime(N):
counter = 0
for n in xrange(1,N):
if gcd(n,N) == 1:
counter += 1
return counter
It works, but it is slow, and dumb. I'd like to use a clever and faster algorithm.
I tried to use prime factors and divisors of N but I always get something that doesn't work with larger N.
I think the algorithm should be able to count them without calculating all of them like the dumbest algorithm does :P
Edit
It seems I've found a working one:
def a_bit_more_clever_counter(N):
result = N - 1
factors = []
for factor, multiplicity in factorGenerator(N):
result -= N/factor - 1
for pf in factors:
if lcm(pf, factor) < N:
result += N/lcm(pf, factor) - 1
factors += [factor]
return result
where lcm is least common multiple. Does anyone have a better one?
Note
I'm using python, I think code should be readable even to who doesn't know python, if you find anything that is not clear just ask in the comments. I'm interested in the algorithm and the math, the idea.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a task to draw a circle and then fill in with the most amount of circles without touching the sides. I can draw the circle, and I can make loops to pack the circle in a hexagonal/honeycomb format, but can't control whether they are inside or outside the circle.
I have used this: g.drawOval(50, 50, 300, 300); to specify my circle. Given I'm actually specifying a square as my boundaries I can't actually determine where the circle boundaries are. So I'm basically packing the square full of circles rather than the circle full of circles.
Can some please point me in the right direction? I'm new to java so not sure if I have done this the complete wrong way. My code is below. I have another class for the frame and another with the main in it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DrawCircle extends JPanel
{
private int width, height, diameter;
public DrawFrame d;
public DrawCircle()
{
width = 400;
height = 400;
diameter = 300;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.blue);
g.drawOval(50, 50, 300, 300);
for(int i=50; i<200; i=i+20)
{
for(int j=50; j<350; j=j+10)
{
g.drawOval(j, i, 10, 10);
}
}
for(int i=60; i<200; i=i+20)
{
for(int j=55; j<350; j=j+10)
{
g.drawOval(j, i, 10, 10);
}
}
for(int i=330; i>190; i=i-20)
{
for(int j=340; j>40; j=j-10)
{
g.drawOval(j, i, 10, 10);
}
}
for(int i=340; i>190; i=i-20)
{
for(int j=345; j>40; j=j-10)
{
g.drawOval(j, i, 10, 10);
}
}
}
}
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm writing an application draws in another application's window (this is under OS X with Cocoa, but the question is general enough that I hope it won't be bogged down by operating system / framework issues), and I'm running into a problem which seems like it should have a simple answer, but it's driving me absolutely insane. Here's the problem:
I draw a rectangle inside another application's window which has to be in a certain location relative to the top and left of the window (i.e. the margins between my rectangle and the top & left of the target window must remain fixed). I can calculate the relative x,y coordinates required as a percentage of the window's size, which works fine: the rectangle shows up correctly. However, the user then resizes the window, and I can resize the rectangle correctly by using a transformation based on the ratio of the new height and width to the old height and width, but I lose my relative positioning: the rectangle's coordinates are now incorrect (see image - this is a rough mockup of the problem).
image http://img30.imageshack.us/img30/5273/resizeexample.png
Now, I can't figure out how to calculate the new x,y coordinates relative to the top and left of the window. The window isn't square; its resize is constrained by the other application, but the aspect ratio width / height changes by some unknown function. When I measure the required y coordinates in relative terms, the percentage changes when the window resize. Numerically, it looks something like this:
Before resize:
window size: h=>760, w=>546
rectangle origin: x=>355, y=>84 (e.g. 84/546 = 15.3% of height)
After resize:
window size: h=>1009, w=>717
rectangle origin should be: ? (I can measure it as something like x=>474,y=>99, but I can't predict those values; 99/717 now = 13.8% of height).
I've tried every ratio of the two windows' measurements I can think of; I've also run across the idea of translating to the origin, scaling, and then translating back to avoid the problem of scaling moving the coordinates - but I don't know where to translate back to! This probably has some simple geometric / trigonometric solution, but nothing occurs to me no matter how many diagrams I draw. I'm willing to accept the inevitable embarrassment of someone pointing out some one-line solution to this problem if they can just point me in the right direction here!
| 0 | 0 | 0 | 0 | 1 | 0 |
Can you tell me any ways to generate non-uniform random numbers?
I am using Java but the code examples can be in whatever you want.
One way is to create a skewed distribution by adding two uniform random numbers together (i.e. rolling 2 dice).
| 0 | 1 | 0 | 0 | 0 | 0 |
Is there a natural language parser for date/times in ColdFusion?
| 0 | 1 | 0 | 0 | 0 | 0 |
I'd like to build a PokerBot (and a few other games) for the intellectual challenge. However, I only want to do this in an ethical and legal way.
So, I need a game server where all players and the game operator know that I'm running a pokerbot. Where that's not cheating but the norm. Perhaps even where being a human is against the rules.
(I'd also like to build PlayerBots for other games, not just poker.)
If one doesn't exist already, anyone up for doing a collaborative project to build such an environment?
UPDATE:
I would say that an open API is the ultimate sign of a server open to bots.
No API = Bots not welcome.
Also, I'm happy to play for points rather than real money.
| 0 | 1 | 0 | 0 | 0 | 0 |
I need to evaluate if two sets of 3d points are the same (ignoring translations and rotations) by finding and comparing a proper geometric hash. I did some paper research on geometric hashing techniques, and I found a couple of algorithms, that however tend to be complicated by "vision requirements" (eg. 2d to 3d, occlusions, shadows, etc).
Moreover, I would love that, if the two geometries are slightly different, the hashes are also not very different.
Does anybody know some algorithm that fits my need, and can provide some link for further study?
Thanks
| 0 | 0 | 0 | 0 | 1 | 0 |
Math escapes me today.
How do I find the X speed and the Y speed of an object if it is going at a defined speed (say, 5 pixels/second) at a 45 degree angle?
| 0 | 0 | 0 | 0 | 1 | 0 |
I know this is more a Math/Formal Language/Automata/Computer science question than an a programming one, but I hope I can get some advice on a comprehensible textbook (not an indecipherable monograph) on formal logic beyond Propositional and Predicate Calculus. I’m especially interested in monadic second order logic and Büchi Automata.
For now, I’ve only found Automata theory and its applications by Bakhadyr Khoussainov, Anil Nerode. Automata, logics, and infinite games By Erich Grädel, Thomas Wilke (eds). And Formal Models of Communicating Systems: Languages, Automata, and Monadic Second-Order Logic Benedikt Bollig....Way over my head.
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to implement some applications with n-grams (preferably in PHP).
Which type of n-grams is more adequate for most purposes? A word level or a character level n-gram? How could you implement an n-gram-tokenizer in PHP?
First, I would like to know what N-grams exactly are. Is this correct? It's how I understand n-grams:
Sentence: "I live in NY."
word level bigrams (2 for n): "# I', "I live", "live in", "in NY", 'NY #'
character level bigrams (2 for n): "#I", "I#", "#l", "li", "iv", "ve", "e#", "#i", "in", "n#", "#N", "NY", "Y#"
When you have this array of n-gram-parts, you drop the duplicate ones and add a counter for each part giving the frequency:
word level bigrams: [1, 1, 1, 1, 1]
character level bigrams: [2, 1, 1, ...]
Is this correct?
Furthermore, I would like to learn more about what you can do with n-grams:
How can I identify the language of a text using n-grams?
Is it possible to do machine translation using n-grams even if you don't have a bilingual corpus?
How can I build a spam filter (spam, ham)? Combine n-grams with a Bayesian filter?
How can I do topic spotting? For example: Is a text about basketball or dogs? My approach (do the following with a Wikipedia article for "dogs" and "basketball"): build the n-gram vectors for both documents, normalize them, calculate Manhattan/Euclidian distance, the closer the result is to 1 the higher is the similarity
What do you think about my application approaches, especially the last one?
I hope you can help me. Thanks in advance!
| 0 | 1 | 0 | 0 | 0 | 0 |
Is there any way to calculate the largest outcome from an Rijndael encryption with a fixed array length?
Encryption method: RijndaelManaged
Padding: PKCS7
CipherMode: CBC
BlockSize 128
KeySize: 128
I need this as im converting a database where all string are going to be encrypted so i need to change the size of all string fields.
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm writing a very basic parser(mostly just to better understand how they work) that takes a user's input of a select few words, detects whether the sentence structure is OK or Not OK, and outputs the result. The grammar is:
Sentence:
Noun Verb
Article Sentence
Sentence Conjunction Sentence
Conjunction:
"and"
"or"
"but"
Noun:
"birds"
"fish"
"C++"
Verb:
"rules"
"fly"
"swim"
Article:
"the"
Writing the grammar was simple. It's implementing the code that is giving me some trouble. My psuedocode for it is:
main()
get user input (string words;)
while loop (cin >> words)
call sentence()
end main()
sentence()
call noun()
if noun() call verb() (if verb is true return "OK" ???)(else "not ok"???)
else if not noun() call article()
if article() call sentence() (if sentence is true "OK"???)(else "not"?)
else if not noun() call conjunction()
if sentence() conjunction() sentence() - no idea how to implement
return "OK"
else "not ok"
So there is my extremely sloppy psuedo code. I have a few questions on implementing it.
For the word functions (noun, verb, etc.) how should I go about checking if they are true? (as in checking if the user's input has birds, fish, fly, swim, etc.)
How should I handle the conjunction call and the output?
Should I handle the output from the main function or the call functions?
None of the above questions matter if my psuedo code is completely wrong. Is there anything wrong with the basics?
As an added note, I'm on a Chapter 6 exercise of Programming: Practice and Principles Using C++ so I'd prefer to use language syntax that I've already learned, so anything that falls into the category of advanced programming probably isn't very helpful. (The exercise specifically says not to use tokens, so count those out.)
Thanks in advance
Last Edit: In the book's public group I asked the same question and Bjarne Stroustrup commented back saying he put the exercise solution online. He basically had the input read into the sentence function and used if statements to return true or false. However, he didn't use articles so mine was much more complex. I guess if I've learned anything from this exercise its that when dealing with a lot of user input, tokenization is key (from what I know so far.) Here is my code for now. I may go back to it later because it is still very buggy and basically only returns if the sentence is OK and can't handle things like (noun, conjunction, sentence), but for now I'm moving on.
#include "std_lib_facilities.h"
bool article(string words)
{
if (words == "the")
return true;
else return false;
}
bool verb(string words)
{
if (words == "rules" || words == "fly" || words == "swim")
return true;
else return false;
}
bool noun(string words)
{
if (words == "birds" || words == "fish" || words == "c++")
return true;
else return false;
}
bool conjunction(string words)
{
if (words == "and" || words == "but" || words == "or")
return true;
else return false;
}
bool sentence()
{
string w1;
string w2;
string w3;
string w4;
cin >> w1;
if (!noun(w1) && !article(w1)) return false; // grammar of IFS!
cin >> w2;
if (noun(w1) && !verb(w2)) return false;
if (article(w1) && !noun(w2)) return false;
cin >> w3;
if (noun(w1) && verb(w2) && (w3 == ".")) return true;
if (verb(w2) && !conjunction(w3)) return false;
if (noun(w2) && !verb(w3)) return false;
if (conjunction(w3)) return sentence();
cin >> w4;
if (article(w1) && noun(w2) && verb(w3) && (w4 == ".")) return true;
if (!conjunction(w4)) return false;
if (conjunction(w4)) return sentence();
}
int main()
{
cout << "Enter sentence. Use space then period to end.
";
bool test = sentence();
if (test)
cout << "OK
";
else
cout << "not OK
";
keep_window_open();
}
| 0 | 1 | 0 | 0 | 0 | 0 |
I would like to have something that looks something like this. Two different colors are not nessesary.
(source: sourceforge.net)
I already have the audio data (one sample/millisecond) from a stereo wav in two int arrays, one each for left and right channel. I have made a few attempts but they don't look anywhere near as clear as this, my attempts get to spikey or a compact lump.
Any good suggestions? I'm working in c# but psuedocode is ok.
Assume we have
a function DrawLine(color, x1, y1, x2, y2)
two int arrays with data right[] and left[] of lenght L
data values between 32767 and -32768
If you make any other assumptions just write them down in your answer.
for(i = 0; i < L - 1; i++) {
// What magic goes here?
}
This is how it turned out when I applied the solution Han provided. (only one channel)
alt text http://www.imagechicken.com/uploads/1245877759099921200.jpg
| 0 | 0 | 0 | 0 | 1 | 0 |
Possible Duplicate:
how to generate pseudo-random positive definite matrix with constraints on the off-diagonal elements?
The user wants to impose a unique, non-trivial, upper/lower bound on the correlation between every pair of variable in a var/covar matrix.
For example: I want a variance matrix in which all variables have 0.9 > |rho(x_i,x_j)| > 0.6, rho(x_i,x_j) being the correlation between variables x_i and x_j.
Thanks.
| 0 | 0 | 0 | 0 | 1 | 0 |
At present I have a control to which I need to add the facility to apply various acuteness (or sensitivity). The problem is best illustrated as an image:
Graph http://img87.imageshack.us/img87/7886/control.png
As you can see, I have X and Y axess that both have arbitrary limits of 100 - that should suffice for this explanation. At present, my control is the red line (linear behaviour), but I would like to add the ability for the other 3 curves (or more) i.e. if a control is more sensitive then a setting will ignore the linear setting and go for one of the three lines. The starting point will always be 0, and the end point will always be 100.
I know that an exponential is too steep, but can't seem to figure a way forward. Any suggestions please?
| 0 | 0 | 0 | 0 | 1 | 0 |
There are two sorts of TV: Traditional ones that have an aspect ratio of 4:3 and wide screen ones that are 16:9. I am trying to write a function that given the diagonal of a 16:9 TV gives the diagonal of a 4:3 TV with the equivalent height. I know that you can use Pythagoras' theorem to work this out if I know two of the sides, but I only know the diagonal and the ratio.
I have written a function that works by guessing, but I was wondering if there is a better way.
My attempt so far:
// C#
public static void Main()
{
/*
* h = height
* w = width
* d = diagonal
*/
const double maxGuess = 40.0;
const double accuracy = 0.0001;
const double target = 21.5;
double ratio4by3 = 4.0 / 3.0;
double ratio16by9 = 16.0 / 9.0;
for (double h = 1; h < maxGuess; h += accuracy)
{
double w = h * ratio16by9;
double d = Math.Sqrt(Math.Pow(h, 2.0) + Math.Pow(w, 2.0));
if (d >= target)
{
double h1 = h;
double w1 = h1 * ratio4by3;
double d1 = Math.Sqrt(Math.Pow(h1, 2.0) + Math.Pow(w1, 2.0));
Console.WriteLine(" 4:3 Width: {0:0.00} Height: {1:00} Diag: {2:0.00}", w, h, d);
Console.WriteLine("16:9 Width: {0:0.00} Height: {1:00} Diag: {2:0.00}", w1, h1, d1);
return;
}
}
}
| 0 | 0 | 0 | 0 | 1 | 0 |
Here's the background... in my free time I'm designing an artillery warfare game called Staker (inspired by the old BASIC games Tank Wars and Scorched Earth) and I'm programming it in MATLAB. Your first thought might be "Why MATLAB? There are plenty of other languages/software packages that are better for game design." And you would be right. However, I'm a dork and I'm interested in learning the nuts and bolts of how you would design a game from the ground up, so I don't necessarily want to use anything with prefab modules. Also, I've used MATLAB for years and I like the challenge of doing things with it that others haven't really tried to do.
Now to the problem at hand: I want to incorporate AI so that the player can go up against the computer. I've only just started thinking about how to design the algorithm to choose an azimuth angle, elevation angle, and projectile velocity to hit a target, and then adjust them each turn. I feel like maybe I've been overthinking the problem and trying to make the AI too complex at the outset, so I thought I'd pause and ask the community here for ideas about how they would design an algorithm.
Some specific questions:
Are there specific references for AI design that you would suggest I check out?
Would you design the AI players to vary in difficulty in a continuous manner (a difficulty of 0 (easy) to 1 (hard), all still using the same general algorithm) or would you design specific algorithms for a discrete number of AI players (like an easy enemy that fires in random directions or a hard enemy that is able to account for the effects of wind)?
What sorts of mathematical algorithms (pseudocode description) would you start with?
Some additional info: the model I use to simulate projectile motion incorporates fluid drag and the effect of wind. The "fluid" can be air or water. In air, the air density (and thus effect of drag) varies with height above the ground based on some simple atmospheric models. In water, the drag is so great that the projectile usually requires additional thrust. In other words, the projectile can be affected by forces other than just gravity.
| 0 | 1 | 0 | 0 | 0 | 0 |
What i am really looking for is a maths equation function that takes in a string representing and equation and calculates the answer as a return type
For Example
"(((4 * 5) + 6) * 2) / 8"
OutPut: 6.5
So in coding tearms something like
print calc("(((4 * 5) + 6) * 2) / 8");
Is there already a class or a function that some angel has built or do i gota do it my self
Thanks
| 0 | 0 | 0 | 0 | 1 | 0 |
I have this bit of VB6 sliced out of a project I'm working on:
Public Function C_Ln(c As ComplexNumber) As ComplexNumber
Set C_Ln = toComplex(Log(C_Abs(c)), Atan2(c.Imag, c.Real))
End Function
The VB6 Log() function is base-e. I'd like to cook up versions of this to do base-2, base-10 and base-n. Where do I start?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have three colors in an array, array('blue', 'red', 'green'), and in my loop, I want to be able to print blue, red, green, blue, red, green.
I know that I could just reset a counter every 3 loops, and use that to find the color I want - 1, 2, 3, reset, 1, 2, 3, reset, etc. But is there a simple way to pass it the current loop count, like, 5 or 7, and get 2? Or pass 6 or 9 and get 3? Am I missing some simple math solution to this?
| 0 | 0 | 0 | 0 | 1 | 0 |
How can I calculate a point (X,Y) a specified distance away, on a rotated axis? I know what angle I'd like the point "moving" along (in degrees).
| 0 | 0 | 0 | 0 | 1 | 0 |
I have followed an article on Speech Recognition with Delphi (SAPI 5.3).
http://edn.embarcadero.com/article/29583
I created a basic application. but the problem is that the application has got it all wrong !
it doesn't get what I am saying correctly. if i say for example : "word", it get "ward". and so on.
is there any better way to do speech recognition anyone can give me ?
| 0 | 1 | 0 | 0 | 0 | 0 |
I've been having fun rendering charts and graphs from co-ordinates lately, and I'm fascinated by using matrices to transform co-ordinate spaces.
I've been able to successfully scale and invert 2 dimensional co-ordinate spaces, but now my appetite is whetted. :)
Where can I go for clear, informative, (free), educational material on matrices, matrix math, especially as applies to 2 and 3 dimensional space?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have quite an interesting task at work - I need to find out how much time user spent doing something and all I have is timestamps of his savings. I know for a fact that user saves after each small portion of a work, so they is not far apart.
The obvious solution would be to find out how much time one small item could possibly take and then just go through sorted timestamps and if the difference between current one and previous one is more than that, it means user had a coffee break, and if it's less, we can just add up this difference into total sum. Simple example code to illustrate that:
var prev_timestamp = null;
var total_time = 0;
foreach (timestamp in timestamps) {
if (prev_timestamp != null) {
var diff = timestamp - prev_timestamp;
if (diff < threshold) {
total_time += diff;
}
}
prev_timestamp = timestamp;
}
The problem is, while I know about how much time is spent on one small portion, I don't want to depend on it. What if some user just that much slower than my predictions, I don't want him to be left without paycheck. So I was thinking, could there be some clever math solution to this problem, that could work without knowledge of what time interval is acceptable?
PS. Sorry for misunderstanding, of course no one would pay people based on this numbers and even if they would, they understand that it is just an approximation. But I'd like to find a solution that would emit numbers as close to real life as possible.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have an array of points. I want to know if this array of point represents a circle, a square or a triangle.
Where should i begin? (i use C#)
Thanks
Jon
| 0 | 0 | 0 | 0 | 1 | 0 |
Does such function exist? I created my own but would like to use an official one:
private function opposite(number:Number):Number
{
if (number < 0)
{
number = Math.abs(number);
}
else
{
number = -(number);
}
return number;
}
So, -5 becomes 5 and 3 becomes -3.
Edit:
Forgive me for being stupid. I'm human. :)
| 0 | 0 | 0 | 0 | 1 | 0 |
I am creating a game where I want to determine the intersection of a single line. For example if I create a circle on the screen I want to determine when I have closed the circle and figure out the points that exist within the area.
Edit: Ok to clarify I am attempting to create a lasso in a game and I am attempting to figure out how I can tell if the lasso's loop is closed. Is there any nice algorithm for doing this? I heard that there is one but I have not found any references searching on my own.
Edit: Adding more detail
I am working with an array of points. These points happen to wrap around and close. I am trying to figure out a good way of testing for this.
Thanks for the help.
Thoughts?
| 0 | 0 | 0 | 0 | 1 | 0 |
Forgive me if this is a naïve question, however I am at a loss today.
I have a simple division calculation such as follows:
double returnValue = (myObject.Value / 10);
Value is an int in the object.
I am getting a message that says Possible Loss of Fraction. However, when I change the double to an int, the message goes away.
Any thoughts on why this would happen?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am trying a couple of tutorials from http://nehe.gamedev.net, in order to learn openGL programming, I would like to position spheres along a Bezier curve such that they appear as a string of pearls. how can I position such spheres along the curve. I am drawing the curve using de Casteljau's algorithm and hence can get the XYZ points on the curve.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have an unordered tree.
Each node represents a task that can be done (1), not done (0) or have children tasks.
For example:
1
-1.1
-1.2
--1.2.1
--1.2.2
-1.3
2
3
-3.1
4
-4.1
--4.1.1
5
Suppose that the leaves 1.2.1, 3.1 and 5 are done
1
-1.1
-1.2
--1.2.1*
--1.2.2
-1.3
2
3
-3.1*
4
-4.1
--4.1.1
5*
I want to calculate the percentage of completeness of each node. The leaves are easily calculated with 0% or 100%, but how to compute all the others?
At the moment, I walk the tree from the leaves on and each node is calculated based on the percentage of completeness of the children. For example:
1 50%
-1.1* 100%
-1.2 0%
2 0%
3 33%
-3.1* 100%
-3.2 0%
-3.3 0%
Now, more children are added to 1.2 (that is no more a leaf but becomes a node). If the children are "not done", 1.2 is always 0% and so 1 is 50%, but I would like 1 to be less then 50%, as, descending into his children and grand-children the number of tasks to be completed in order for it to the done 100% is greater!
1 50%
-1.1* 100%
-1.2 0%
--1.2.1 0%
--1.2.2 0%
2 0%
3 33%
-3.1* 100%
-3.2 0%
-3.3 0%
What is the best way to calculate this? Thanks
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm writing a Mahjong Game in C# (the Chinese traditional game, not the solitaire kind). While writing the code for the bot player's AI, I'm wondering if a functional language like F# would be a more suitable language than what I currently use which is C# with a lot of Linq. I don't know much about F# which is why I ask here.
To illustrate what I try to solve, here's a quick summary of Mahjong:
Mahjong plays a bit like Gin Rummy. You have 13 tiles in your hand, and each turn, you draw a tile and discard another one, trying to improve your hand towards a winning Mahjong hand, which consists or 4 sets and a pair. Sets can be a 3 of a kind (pungs), 4 of a kind (kongs) or a sequence of 3 consecutive tiles (chows). You can also steal another player's discard, if it can complete one of your sets.
The code I had to write to detect if the bot can declare 3 consecutive tiles set (chow) is pretty tedious. I have to find all the unique tiles in the hand, and then start checking if there's a sequence of 3 tiles that contain that one in the hand. Detecting if the bot can go Mahjong is even more complicated since it's a combination of detecting if there's 4 sets and a pair in his hand. And that's just a standard Mahjong hand. There's also numerous "special" hands that break those rules but are still a Mahjong hand. For example, "13 unique wonders" consists of 13 specific tiles, "Jade Empire" consists of only tiles colored green, etc.
In a perfect world, I'd love to be able to just state the 'rules' of Mahjong, and have the language be able to match a set of 13 tiles against those rules to retrieve which rules it fulfills, for example, checking if it's a Mahjong hand or if it includes a 4 of a kind. Is this something F#'s pattern matching feature can help solve?
| 0 | 1 | 0 | 0 | 0 | 0 |
Say I want to display a graph of today's stock market. I gather all my data, and I go to display the graph...is there a well known formula to set the upper and lower bounds to?
Do I need to factor in all the data on the stock market from the last year to get some context?
In some ways this is a design/math question, but essentially, I want to know, is there a well known formula for making graphs for things like network traffic and visitor counts intuitive to read?
| 0 | 0 | 0 | 0 | 1 | 0 |
When Excel determines the axis values it will use to represent your data in a chart, the values are 'evenly distributed'.
For Example:
If you plot the following series in an Excel Line Chart.
[0.22,0.33,0.44,0.55,0.66,0.77,0.88,0.99,1.1,1.21,1.32,1.43,1.54,1.65,1.76,1.87,1.98,2.09,2.2]
Excel determines that the y-axis values should be [0,0.5,1,1.5,2,2.5].
What technique or formula is used to determine these values ?
| 0 | 0 | 0 | 0 | 1 | 0 |
Hmmm. Consider this program, whose goal is to figure out the best way to get the bottom 16 bits of an integer, as a signed integer.
public class SignExtend16 {
public static int get16Bits(int x)
{
return (x & 0xffff) - ((x & 0x8000) << 1);
}
public static int get16Bits0(int x)
{
return (int)(short)(x);
}
public static void main(String[] args)
{
for (String s : args)
{
int x = Integer.parseInt(s);
System.out.printf("%08x => %08x, %08x
",
x, get16Bits0(x), get16Bits(x));
}
}
}
I was going to use the code in get16Bits0, but I got the warning "Unnecessary cast from short to int" with Eclipse's compiler and it makes me suspicious, thinking the compiler could optimize out my "unnecessary cast". When I run it on my machine using Eclipse's compiler, I get identical results from both functions that behave the way I intended (test arguments: 1 1111 11111 33333 66666 99999 ). Does this mean I can use get16Bits0? (with suitable warnings to future code maintainers) I've always assumed that JRE and compiler behavior are both machine-independent for arithmetic, but this case is testing my faith somewhat.
| 0 | 0 | 0 | 0 | 1 | 0 |
Im looking to make my own implementation of these Identicons or Gravatars found here on StackOverflow. Most questions I could found was about utilizing existing 3rd party libraries, especially those hooked with Gravatar.
(source: levitated.net)
After some searching I stumbled upon this page. And from the looks of it, its not that hard. What needs to be randomly picked is:
One shape to be in middle
One shape for the corners
One shape for the edges
2 colors
A rotation for all shapes except for the middle one
Seed a randomizer with the md5 hash value and start retrieving random numbers. Then, add (pi/2)*i to each shape around the edge to create that cool radial symmetry effect.
You could say Im thinking in text here, but I want to know if Ive misunderstood anything. Also, if you have any thought one what more could be randomized to increase the diversity. Will the look or feel be "broken" if I start changing the:
Scale of the shape?
And then maybe also the offset in position of the shape within the block?
Picking more than two colors? Two colors per block with the same radial symmetry?
| 0 | 0 | 0 | 0 | 1 | 0 |
I need to initialize some three dimensional points, and I want them to be equally spaced throughout a cube. Are there any creative ways to do this?
I am using an iterative Expectation Maximization algorithm and I want my initial vectors to "span" the space evenly.
For example, suppose I have eight points that I want to space equally in a cube sized 1x1x1. I would want the points at the corners of a cube with a side length of 0.333, centered within the larger cube.
A 2D example is below. Notice that the red points are equidistant from eachother and the edges. I want the same for 3D.
In cases where the number of points does not have an integer cube root, I am fine with leaving some "gaps" in the arrangement.
Currently I am taking the cube root of the number of points and using that to calculate the number of points and the desired distance between them. Then I iterate through the points and increment the X, Y and Z coordinates (staggered so that Y doesn't increment until X loops back to 0, same for Z with regard for Y).
If there's an easy way to do this in MATLAB, I'd gladly use it.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have an object, that is facing a particular direction with (for instance) a 45 degree field of view, and a limit view range. I have done all the initial checks (Quadtree node, and distance), but now I need to check if a particular object is within that view cone, (In this case to decide only to follow that object if we can see it).
Apart from casting a ray for each degree from Direction - (FieldOfView / 2) to Direction + (FieldOfView / 2) (I am doing that at the moment and it is horrible), what is the best way to do this visibility check?
| 0 | 1 | 0 | 0 | 0 | 0 |
The code below projects the blue vector, AC, onto the red vector, AB, the resulting projected vector, AD, is drawn as purple. This is intended as my own implementation of this Wolfram demonstration.
Something is wrong however and I can really figure out what. Should be either that the projection formula itself is wrong or that I mistake some local coordinates with world coordinates. Any help is appreciated.
This code is trimmed but can still be executed without problems, assuming you have pygame:
import pygame
from pygame.locals import *
def vadd(a,b):
return (a[0]+b[0],a[1]+b[1])
def vsub(a,b):
return (a[0]-b[0],a[1]-b[1])
def project(a, b):
""" project a onto b
formula: b(dot(a,b)/(|b|^2))
"""
abdot = (a[0]*b[0])+(a[1]*b[1])
blensq = (b[0]*b[0])+(b[1]*b[1])
temp = float(abdot)/float(blensq)
c = (b[0]*temp,b[1]*temp)
print a,b,abdot,blensq,temp,c
return c
pygame.init()
screen = pygame.display.set_mode((150, 150))
running = True
A = (75.0,75.0)
B = (100.0,50.0)
C = (90,70)
AB = vsub(B,A)
AC = vsub(C,A)
D = project(AC,AB)
AD = vsub(D,A)
while running:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
running = False
pygame.draw.line(screen, (255,0,0), A, B)
pygame.draw.line(screen, (0,0,255), A, C)
pygame.draw.line(screen, (255,0,255), A, D)
pygame.display.flip()
| 0 | 0 | 0 | 0 | 1 | 0 |
In C++ we can rotate a point about an arbitrary axis:
void radRotateAxis( float a, float b, float c, float theta )
{
float newX = (
x*( a*a*(1-cos(theta)) + cos(theta) ) +
y*( a*b*(1-cos(theta)) - c*sin(theta) ) +
z*( a*c*(1-cos(theta)) + b*sin(theta) ) );
float newY = (
x*( a*b*(1-cos(theta)) + c*sin(theta) ) +
y*( b*b*(1-cos(theta)) + cos(theta) ) +
z*( b*c*(1-cos(theta)) - a*sin(theta) ) );
float newZ = (
x*( a*c*(1-cos(theta)) - b*sin(theta) ) +
y*( b*c*(1-cos(theta)) + a*sin(theta) ) +
z*( c*c*(1-cos(theta)) + cos(theta) ) );
x = newX ;
y = newY ;
z = newZ ;
}
But as we walk theta 0 -> 2PI this takes the point around a "unit circle" around the axis you're rotating about
How can we make it so as theta 0 -> 2PI the results are about an ellipse of width a, height b?
I do not want to apply transformation matrices to the points after rotating them about the axis - what I'm looking for is an "elliptical" rotation matrix, if anyone knows of such a thing!
| 0 | 0 | 0 | 0 | 1 | 0 |
Today I encountered this article about decimal expansion and I was instantaneously inspired to rework my solution on Project Euler Problem 26 to include this new knowledge of math for a more effecient solution (no brute forcing). In short the problem is to find the value of d ranging 1-1000 that would maximize the length of the repeating cycle in the expression "1/d".
Without making any further assumptions about the problem that could further improve the effecienty of solving the problem I decided to stick with
10^s=10^(s+t) (mod n)
which allows me for any value of D to find the longest repeating cycle (t) and the starting point for the cycle (s).
The problem is that eksponential part of the equation, since this will generate extremely large values before they're reduced by using modulus. No integral value can handle this large values, and the floating point data types seemes to be calculating wrong.
I'm using this code currently:
Private Function solveDiscreteLogarithm(ByVal D As Integer) As Integer
Dim NumberToIndex As New Dictionary(Of Long, Long)()
Dim maxCheck As Integer = 1000
For index As Integer = 1 To maxCheck
If (Not NumberToIndex.ContainsKey((10 ^ index) Mod D)) Then
NumberToIndex.Add((10 ^ index) Mod D, index)
Else
Return index - NumberToIndex((10 ^ index) Mod D)
End If
Next
Return -1
End Function
which at some point will compute "(10^47) mod 983" resulting in 783 which is not the correct result. The correct result should have been 732. I'm assuming it's because I'm using integral data types and it's causing overflow. I tried using double instead, but that gave even stranger results.
So what are my options?
| 0 | 0 | 0 | 0 | 1 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.