
Apologies for the shouting but this is important.
When answering a question please:
 Read the question carefully
 Understand that English isn't everyone's first language so be lenient of bad spelling and grammar
 If a question is poorly phrased then either ask for clarification, ignore it, or mark it down. Insults are not welcome
 If the question is inappropriate then click the 'vote to remove message' button
Insults, slapdowns and sarcasm aren't welcome. Let's work to help developers, not make them feel stupid.
cheers,
Chris Maunder
The Code Project Cofounder
Microsoft C++ MVP





For those new to message boards please try to follow a few simple rules when posting your question. Choose the correct forum for your message. Posting a VB.NET question in the C++ forum will end in tears.
 Be specific! Don't ask "can someone send me the code to create an application that does 'X'. Pinpoint exactly what it is you need help with.
 Keep the subject line brief, but descriptive. eg "File Serialization problem"
 Keep the question as brief as possible. If you have to include code, include the smallest snippet of code you can.
 Be careful when including code that you haven't made a typo. Typing mistakes can become the focal point instead of the actual question you asked.
 Do not remove or empty a message if others have replied. Keep the thread intact and available for others to search and read. If your problem was answered then edit your message and add "[Solved]" to the subject line of the original post, and cast an approval vote to the one or several answers that really helped you.
 If you are posting source code with your question, place it inside <pre></pre> tags. We advise you also check the "Encode "<" (and other HTML) characters when pasting" checkbox before pasting anything inside the PRE block, and make sure "Use HTML in this post" check box is checked.
 Be courteous and DON'T SHOUT. Everyone here helps because they enjoy helping others, not because it's their job.
 Please do not post links to your question into an unrelated forum such as the lounge. It will be deleted. Likewise, do not post the same question in more than one forum.
 Do not be abusive, offensive, inappropriate or harass anyone on the boards. Doing so will get you kicked off and banned. Play nice.
 If you have a school or university assignment, assume that your teacher or lecturer is also reading these forums.
 No advertising or soliciting.
 We reserve the right to move your posts to a more appropriate forum or to delete anything deemed inappropriate or illegal.
cheers,
Chris Maunder
The Code Project Cofounder
Microsoft C++ MVP





Hello everyone!
I've a follow question: is there any way to optimize this algorithm, which recursively computes the square root of an positive integer?.
int mySqrt(int x, int left, int right)
{
static int result = 0;
if (left <= right)
{
int middle = left + (right  left) / 2;
if ((middle != 0 && middle <= x / middle) 
(middle == 0 && middle <= x / (middle + 1)))
{
result = middle;
return mySqrt(x, middle + 1, right);
}
else
{
return mySqrt(x, left, middle  1);
}
}
return result;
}
Thank you!





Why recursion? Binary search can be expressed as iteration, or, since you actually have a constant bound on the number of iterations here, an unrolled iteration. That would IMO still count as the same algorithm, just a different realization of it.
lnikon wrote: left + (right  left) / 2 This trick is to avoid overflow. There cannot be any overflow here anyway, since both left and right will be well below MAXINT (at most they'll be the square root of MAXINT). So you can write it the simple/shorter/faster way.
lnikon wrote: middle == 0 && middle <= x / (middle + 1) Is this even correct? Note that the right operand of the && effectively checks whether 0 <= x which is not useful since x is known to be nonnegative (precondition).
The whole zero business can be avoided by checking whether middle * middle > x (this multiplication cannot overflow unless incorrect bounds were passed), which by avoiding division is both "zerosafe" and more efficient.





Your answer is very useful. Thank you!





Use Newton's method[^].
You'll also need to use floatingpoint numbers, since most square roots are not integers.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
 Homer





Hi,
I am interested on how to convert a point in 3D space (x,y,z) to 2D Space (x,y) using perspective accurate projection. I have found lots of things online showing how to do this, but they all use a bunch of stuff I don't understand like matrixes. I am only a grade 9 student so I don't know a lot of advanced math. If you guys could explain it to me in a simple way like:
x' = (something with x and z)
y' = (something with y and z)
That would be awesome
Thanks in advance everyone.
Sidenote, if you want to send me some example code please do it in python its the only language I'm any good at





I'm sorry ... but if you want to create a pseudo3DPoint inside a 2DView you need to know "a little bit" about Matrixes and vectorcalculation.
Normally your pseudo3dAxises are something like this :
Z
 Y
 /
/
X
.... but as a real 3DPoint the Yvector is not to be seen because it's in direction "into the screen".
So now, depending on your viewpoint (or camerapoint) you have to calculate it's new position inside the 2DView.
I hope I could explain what you need to do ...





I am going to agree with that answer.
There is quite a bit of basic math along with matrix math that one must master.
And one must also understand how to construct entities in a 3D space just so they can be rendered into 2D.
A conceptual understanding of the difficulties might be acquired by looking into the following,
Flatland  Wikipedia[^]





Thank you for your voting ...





I looked at this problem and assuming most node are behind a firewall that blocks port forwarding and the nodes are small machines then I just cannot come up with a plan that scales to millions of users that won't end up flooding the network with internal chatter.
My current thoughts are of specialized DNS type nodes working as a replicated cluster to provide the service and then dealing with subdomaining the address at a later date if needs be but this is not the way I like working and is made worse because the lookup's will be 100200 bytes in size.
As if things could not get any worse the data needs to be encrypted before being written to files but the values are 32 byte public keys that can be broken down and map 35 X 35 X 35 files which seems like the starting point.





I sometimes send an email to myself.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal





I have a problem with my homework.
Description:
1. In the group of people we define the relationship: A does not like B. This relation is not symmetrical.
If there is a series of relationships A1 does not like A2, A2 does not like A3 ... Ak does not like A1,
all people in this cycle belong to one group of "disliking".
For the given pair specifying the relations, determine the maximum division
groups of "disliking". Provide complexity and justify the correctness of your solution.
2. There are some animosities in the group of naughty children. The preschool teacher decided to
set the children in a row. If A does not like B, he can not stand in a row in front of B (not to throw papers in it).
a) Specify if a group of children can be set in one row.
b) If not, enter the minimum number of rows to set children in above configuration.
Provide complexity and justify the correctness of your solution.
c) Enter the minimum number of rows necessary to set the children, if:
Child A does not like child B, it must stand in a row with a lower number.
I know that in the first task I have to find strongly connected components. Actually I did it using Tarjan's algorithm in PHP implementations. I wonder that is it correct approach and how to provide complexity of my solution. Unfortunately I don't have any information how to solve second task. Maybe someone has an idea and could give a clue.
Thanks for advice
Code of first task:
const GROUPS_COUNTER = 10;
const MIN_ASCII = 65;
const MAX_ASCII = 69;
function generateGroups($n) {
$matrix = [];
$exist = [];
echo "************************\n";
for ($i = 0; $i < $n; $i++) {
$a = chr(rand(MIN_ASCII, MAX_ASCII));
$b = chr(rand(MIN_ASCII, MAX_ASCII));
if ($a == $b  isset($exist[$a][$b])  isset($exist[$b][$a])) {
$i;
continue;
}
$matrix[$i][0] = $a;
$matrix[$i][1] = $b;
$exist[$a][$b] = true;
echo $a . " " . $b . "\n";
}
echo "************************\n";
return $matrix;
}
function findGroups($groups) {
$dislikeList = [];
$checked = [];
foreach ($groups as $groupParent) {
if (isset($checked[$groupParent[0]])) {
continue;
}
$groupChildList = [];
foreach ($groups as $groupChild) {
if ($groupParent[0] == $groupChild[0]) {
array_push($groupChildList, $groupChild[1]);
}
}
echo $groupParent[0] . " => " . implode(", ", $groupChildList) . "\n";
$dislikeList[$groupParent[0]] = $groupChildList;
$checked[$groupParent[0]] = true;
}
echo "************************\n";
return $dislikeList;
}
function phpTarjanEntry($groups) {
global $cycles;
global $marked;
global $markedStack;
global $pointStack;
$cycles = array();
$marked = array();
$markedStack = array();
$pointStack = array();
$marked = array();
foreach ($groups as $key => $value) {
$marked[$key] = FALSE;
}
foreach ($groups as $key => $value) {
phpTarjan($key, $key);
while (!empty($markedStack)) {
$marked[array_pop($markedStack)] = FALSE;
}
}
$cycles = array_keys($cycles);
return $cycles;
}
function phpTarjan($s, $v) {
global $G;
global $cycles;
global $marked;
global $markedStack;
global $pointStack;
$f = FALSE;
$pointStack[] = $v;
$marked[$v] = TRUE;
$markedStack[] = $v;
foreach ($G[$v] as $w) {
if ($w < $s) {
$G[$w] = array();
} else if ($w == $s) {
$cycles[implode('', $pointStack)] = TRUE;
$f = TRUE;
} else if (isset($marked[$w]) && $marked[$w] === FALSE) {
$g = phpTarjan($s, $w);
if (!empty($f) OR ! empty($g)) {
$f = TRUE;
}
}
}
if ($f === TRUE) {
while (end($markedStack) != $v) {
$marked[array_pop($markedStack)] = FALSE;
}
array_pop($markedStack);
$marked[$v] = FALSE;
}
array_pop($pointStack);
return $f;
}
$mixGroups = generateGroups(GROUPS_COUNTER);
$res = findGroups($mixGroups);
$G = $res;
$cycles = phpTarjanEntry($res);
echo '<p>Cycles found: ' . count($cycles);
print_r($cycles);





Hi, everyone, I am not a software developer or coder, but I have a very interesting question for you!
I work for a cargo airline, our cargo area inside aircraft is a cylinder with Radius of 30 inches and length of 332 inches, with a flat floor on bottom of 44 inches.
Now, here is the question,
I have a customer have many boxes with dimension of x*y*z,
lets say the box dimension is 24*18*14 and I want to know the max amount of boxes I can put in the aircraft, and how?





Member 13644847 wrote: I am not a software developer or coder, but I have a very interesting question for you! No, of course not.
See knapsack problem  Google Search[^]





Member 13644847 wrote: I am not a software developer or coder,...I want to know the max amount of boxes I can put in the aircraft, and how?
Then hire a mathematician. Or even a consulting company.





Hi,
there is no straightforward way to solve this problem. Instead, you should try different schemes and calculate how many boxes you can store in each of them, then pick the optimum.
Assuming box dimension d3 * d2 * d1 with d3>=d2>=d1, boxes are allowed to be rotated in any way and can be stacked all the way to the top, and assuming the cargo room is much longer than its diameter, this is what I would do in a first attempt, and I expect it to get really close to the absolute optimum:
 work one layer at a time, i.e. the problem gets reduced from a 3D problem to a number of much easier 2D problems;
 the first layer would have thickness d1;
 now fit as many boxes as possible in that one layer; obvious choices would be: all in long direction, or all in cross direction (the former normally being better than the latter);
 first refinement: if length of cargo room isn't a multiple of d3, you might be slightly better of splitting it (per layer!) in two parts, a big part using long direction, the remainder using cross direction;
 once the maximum is found for that layer proceed to the next layer again using thickness d1; note that the second layer has the same length but a larger width than the first layer, hence the result could be a larger number of boxes;
 continue designing your layers with thickness d1 until you reach the 45 degree angle, then the layer height should equal d2 (instead of d1), everything else remains the same;
 and once you reach the 135 degree angle, switch back to the original scheme (thickness d1).
Second refinement, somewhat more difficult: as you will probably not reach exactly 45 degrees, you might consider one less layer with thickness d1; similarly you might consider one less layer with thickness d2. This yields four cases to consider, there is a possibility one of them gives you one more layer in total, and a better solution.
Final remark: it is not sure that orthogonal filling yields the optimum, the optimum could consist of arches and other schemes that might not be practical at all, I would guess you won't care for those...
modified 8Feb18 21:36pm.





i am not able to figure out why linspace not able to create equal intervals till the value of machine epsilon
here is the code....
from numpy import *
import sys
import numpy as np
x=1
epsilon=sys.float_info.epsilon/2.0
# machine epsilon
h = np.linspace(1,epsilon,1000)
e1= (((sin(x) sin(xh))/hcos(x))/cos(x)) #realtive error in first order
e2= (((sin(x2*h)4*sin(xh)+3*sin(x))/(2*h)cos(x))/cos(x)) #realtive error in second order
e3= (((2*sin(x+h)+3*sin(x)6*sin(xh)+sin(x2*h))/(6*h)cos(x))/cos(x))#realtive error in third order
e4 = (((sin(x3*h)+6*sin(x2*h)18*sin(xh)+10*sin(x)+3*sin(x+h))/(12*h)cos(x))/cos(x))#realtive error in fourth order
print(h)
import matplotlib.pyplot as plt
plt.plot(h,e1,'b',lw=3)
plt.plot(h,e2,'g',lw=3)
plt.plot(h,e3,'m',lw=3)
plt.plot(h,e4,'r',lw=3)
plt.xscale('log')
plt.yscale('log')
plt.xlabel('h')
plt.ylabel('Relative error')
plt.legend(['first order','second order','third order','fourth order'])
plt.title('Effect of order of accuracy on the numerical differentiation')
plt.show()





Works on my machine. However, since the samples are uniformly spaced, all but the last of them are extremely far from epsilon in a relative sense.





Hi, to be able to validate a cart I need to compare what is in the cart against the min and max limitations of one or more product categories.
In the example below, to be valid, my cart must have at least one product from Cat A and a maximum of 3 products in total from Cat A and Cat B.
Cat A > min=1 max=3
Cat B > min=0 max=2
What logic can I apply to tackle this (pref in C#) ?
Thanks for your inputs !





I think you need a litter box for all those cat products.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal





Very helpful thanks !





Member 13585107 wrote: What logic can I apply to tackle this How about comparing the values?





NOAA's National Centers for Environmental Information collects global climate data and aggregates this data to provide information on climate trends and variability. One product they offer is a monthly regional analysis. The following table gives "anomaly" data by continent for January 2017. "Anomaly" means the value is the temperature difference from the average temperature from years 1910–2000.
Continent Anomaly (C)
North America 3.18
South America 1.36
Europe 0.12
Africa 0.53
Asia 1.92
Oceania 0.98
Assignment task:
Your task is to develop an algorithm that would sort data such as these from least to greatest. Specifically, given an unsorted set of N decimal values, your algorithm should sort them to give an answer of the sorted data. For this set of N = 6, your algorithm should produce:
0.12
0.53
0.98
1.36
1.92
3.18
Execute your algorithm for a different set of data, such as a subset of the given data, data you make up, or another month's climate data, such as February 2017: https://www.ncdc.noaa.gov/sotc/globalregions/201702
Does your algorithm work for any N? Have you thought of corner cases it might need to handle, such as N = 0 or N = 1?





Do you know the difference between "help" and "I did nothing; someone do it for me"?
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal




