• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 10:29
CET 16:29
KST 00:29
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
TL.net Map Contest #21: Winners11Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10[ASL20] Finals Preview: Arrival13TL.net Map Contest #21: Voting12[ASL20] Ro4 Preview: Descent11
Community News
[TLMC] Fall/Winter 2025 Ladder Map Rotation6Weekly Cups (Nov 3-9): Clem Conquers in Canada4SC: Evo Complete - Ranked Ladder OPEN ALPHA8StarCraft, SC2, HotS, WC3, Returning to Blizzcon!45$5,000+ WardiTV 2025 Championship7
StarCraft 2
General
[TLMC] Fall/Winter 2025 Ladder Map Rotation Mech is the composition that needs teleportation t Weekly Cups (Nov 3-9): Clem Conquers in Canada Craziest Micro Moments Of All Time? SC: Evo Complete - Ranked Ladder OPEN ALPHA
Tourneys
Constellation Cup - Main Event - Stellar Fest Tenacious Turtle Tussle Sparkling Tuna Cup - Weekly Open Tournament $5,000+ WardiTV 2025 Championship Merivale 8 Open - LAN - Stellar Fest
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 499 Chilling Adaptation Mutation # 498 Wheel of Misfortune|Cradle of Death Mutation # 497 Battle Haredened Mutation # 496 Endless Infection
Brood War
General
BW General Discussion FlaSh on: Biggest Problem With SnOw's Playstyle Terran 1:35 12 Gas Optimization BGH Auto Balance -> http://bghmmr.eu/ [ASL20] Ask the mapmakers — Drop your questions
Tourneys
[BSL21] RO32 Group D - Sunday 21:00 CET [BSL21] RO32 Group C - Saturday 21:00 CET [ASL20] Grand Finals [Megathread] Daily Proleagues
Strategy
Current Meta PvZ map balance How to stay on top of macro? Soma's 9 hatch build from ASL Game 2
Other Games
General Games
EVE Corporation Nintendo Switch Thread Stormgate/Frost Giant Megathread Should offensive tower rushing be viable in RTS games? Path of Exile
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread SPIRED by.ASL Mafia {211640}
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine Canadian Politics Mega-thread The Games Industry And ATVI
Fan Clubs
White-Ra Fan Club The herO Fan Club!
Media & Entertainment
[Manga] One Piece Anime Discussion Thread Movie Discussion! Korean Music Discussion Series you have seen recently...
Sports
2024 - 2026 Football Thread Formula 1 Discussion NBA General Discussion MLB/Baseball 2023 TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
SC2 Client Relocalization [Change SC2 Language] Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
Dyadica Gospel – a Pulp No…
Hildegard
Coffee x Performance in Espo…
TrAiDoS
Saturation point
Uldridge
DnB/metal remix FFO Mick Go…
ImbaTosS
Reality "theory" prov…
perfectspheres
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1229 users

The Big Programming Thread - Page 86

Forum Index > General Forum
Post a Reply
Prev 1 84 85 86 87 88 1032 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
kingcoyote
Profile Blog Joined May 2010
United States546 Posts
Last Edited: 2011-10-13 16:54:09
October 13 2011 16:53 GMT
#1701
Sad news today: Dennis Ritchie has passed away.

http://www.zdnet.co.uk/news/business-of-it/2011/10/13/dennis-ritchie-father-of-unix-and-c-dies-40094176/

He was one of the most influential programmers out there, having created C and, along with Brian Kerninghan, wrote the deeply respected The C Programming Language.

Apparently, I was beaten to it by 4 hours, and yet didn't notice that post when I scanned through this thread to see if it was mentioned. My apologies.
Blisse
Profile Blog Joined July 2010
Canada3710 Posts
Last Edited: 2011-10-13 18:29:40
October 13 2011 18:12 GMT
#1702
On October 13 2011 17:38 Morfildur wrote:
Show nested quote +
On October 13 2011 17:16 Blisse wrote:
On October 13 2011 15:25 EvanED wrote:
Very simply. Never use floating point numbers (doubles count) for money. :-)

(I'm not really kidding either. That really is something that basically no one should ever do.)


What should I use for money then? The input has two decimal places... ?

I don't remember getting these kinds of errors in Python, but I'm using C now, and the lesson is supposed to be learning how to deal with the doubles I think...


Floating point numbers have problems with precision. On the first look they work, but then you end up having customers pay only 0.99 cent instead of 1 euro.

For money you have to use a fixed point type (or in C you usually calculate with cents instead of euros/dollars) as they have exact instead of approximate representations.


Not possible. My input has two decimal places. That's why I'm having trouble. Would it help if I only ever rounded down? Currently I'm using floor(), but I think that's why I'm having problems...

EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case.
There is no one like you in the universe.
EvanED
Profile Joined October 2009
United States111 Posts
Last Edited: 2011-10-14 04:33:19
October 14 2011 04:32 GMT
#1703
On October 14 2011 03:12 Blisse wrote:
EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case.

If you're using doubles, you've already lost.

Binary floating point numbers can't represent, say, 10 cents exactly. The proper way to store monetary values is in numbers of cents in an integer. (Or if you're interested in some fixed fraction of cents, the number of those fractions.) And if int isn't big enough for you (it will be on most systems and compilers nowadays, but isn't technically guaranteed), there is always long.
Sentient
Profile Joined April 2010
United States437 Posts
Last Edited: 2011-10-14 05:26:44
October 14 2011 05:26 GMT
#1704
On October 14 2011 03:12 Blisse wrote:
EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case.

As EvanED said, you should never touch floats or doubles when dealing with money. After verifying that the input is a valid number (and depending on how robust you want to be, keep in mind that other places in the world use a comma instead of a period), you should strip punctuation from the number and parse it into an integer of cents.
Blisse
Profile Blog Joined July 2010
Canada3710 Posts
Last Edited: 2011-10-14 05:54:47
October 14 2011 05:30 GMT
#1705
On October 14 2011 14:26 Sentient wrote:
Show nested quote +
On October 14 2011 03:12 Blisse wrote:
EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case.

As EvanED said, you should never touch floats or doubles when dealing with money. After verifying that the input is a valid number (and depending on how robust you want to be, keep in mind that other places in the world use a comma instead of a period), you should strip punctuation from the number and parse it into an integer of cents.


The input is an array of doubles. How would you strip the decimal?

For example, I'm given { 999.99, 999.99, 0.00} as an array input and I need to split this three ways and output the dollars and the cents.

Would I just go through the double array and put the values in an int array while multiply all the values by 100?

EDIT: Dies on tests called floatingpointprecision3 and 5. No idea why.
There is no one like you in the universe.
AzurewinD
Profile Joined November 2010
United States569 Posts
Last Edited: 2011-10-14 07:08:37
October 14 2011 07:08 GMT
#1706
First time posting here, hoping I can at least be of some use.

On October 14 2011 14:30 Blisse wrote:
Show nested quote +
On October 14 2011 14:26 Sentient wrote:
On October 14 2011 03:12 Blisse wrote:
EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case.

As EvanED said, you should never touch floats or doubles when dealing with money. After verifying that the input is a valid number (and depending on how robust you want to be, keep in mind that other places in the world use a comma instead of a period), you should strip punctuation from the number and parse it into an integer of cents.


The input is an array of doubles. How would you strip the decimal?

For example, I'm given { 999.99, 999.99, 0.00} as an array input and I need to split this three ways and output the dollars and the cents.

Would I just go through the double array and put the values in an int array while multiply all the values by 100?

EDIT: Dies on tests called floatingpointprecision3 and 5. No idea why.


Depends on what those tests are doing? Where do they come from?

You don't have to put them in a separate array if you're just looking for a grand total of dollars and a grand total of cents. Maybe I'm not understanding the exercise or what splitting it three ways entails.

I'm assuming this is opening coursework and that input validation/sanitation aren't critical? That is, it would seem that way, as the values are guaranteed to only have two decimal places. If not, then of course take steps to make sure the person feeding you the numbers isn't trying to break your program by messing with commas/decimal places/delimiters.

...But if I'm on the right track at all, you should be able to convert each double in the input array to an integer, then do some modulus and integer division to parse out the cents and dollar amounts respectively from that integer, and add them to a running total for each.

That at least seems like the overall approach if I understand it correctly. Maybe someone can verify/lambaste me for giving bad advice just to clarify.
"...I want more people to be in that state more often, to see things not through the limited and rigid mind or the fearful ego, but through a heart that loves to express and create" - Xiaonan "Glider" Sun
shinarit
Profile Joined May 2010
Hungary900 Posts
October 14 2011 07:17 GMT
#1707
Hey guys! I have a Python question. What is the nicest/shortest/wittiest code to create something iterable (order is not important) of tuples of integer coordinates with the format of ([0 - MaxX-1], [0 - MaxY-1])?
I tried some generators, but all have some issues, and now im working with a one liner, but not sure its the best.

What i tired:

>>> [((x, y) for x in range(n)) for y in range(n)]
[<generator object <genexpr> at 0x7f1318670f50>, <generator object <genexpr> at 0x7f13168c4050>]
>>> ([(x, y) for x in range(n)] for y in range(n))
<generator object <genexpr> at 0x7f13168c40a0>
>>> [[(x, y) for x in range(n)] for y in range(n)]
[[(0, 0), (1, 0)], [(0, 1), (1, 1)]]


And i went with the third one, connected with the itertools library.


itertools.chain.from_iterable([[(x, y) for x in range(sizex)] for y in range(sizey)])


But there must be some nicer, more effective way, i know it.
T for BoxeR, Z for IdrA, P because i have no self-respect
Blisse
Profile Blog Joined July 2010
Canada3710 Posts
Last Edited: 2011-10-14 07:38:32
October 14 2011 07:30 GMT
#1708
On October 14 2011 16:08 AzurewinD wrote:
First time posting here, hoping I can at least be of some use.

Show nested quote +
On October 14 2011 14:30 Blisse wrote:
On October 14 2011 14:26 Sentient wrote:
On October 14 2011 03:12 Blisse wrote:
EDIT: Conversion to int didn't fix the precision problems. I multiplied the double number by 10,000 then concerted it to int. It doesn't work. And since the max number I will get is less than 1,000,000.00, converting it to int breaks it as I'm out of bounds.... less than 10,000 messes up with the 999,999.99 case.

As EvanED said, you should never touch floats or doubles when dealing with money. After verifying that the input is a valid number (and depending on how robust you want to be, keep in mind that other places in the world use a comma instead of a period), you should strip punctuation from the number and parse it into an integer of cents.


The input is an array of doubles. How would you strip the decimal?

For example, I'm given { 999.99, 999.99, 0.00} as an array input and I need to split this three ways and output the dollars and the cents.

Would I just go through the double array and put the values in an int array while multiply all the values by 100?

EDIT: Dies on tests called floatingpointprecision3 and 5. No idea why.


Depends on what those tests are doing? Where do they come from?

You don't have to put them in a separate array if you're just looking for a grand total of dollars and a grand total of cents. Maybe I'm not understanding the exercise or what splitting it three ways entails.

I'm assuming this is opening coursework and that input validation/sanitation aren't critical? That is, it would seem that way, as the values are guaranteed to only have two decimal places. If not, then of course take steps to make sure the person feeding you the numbers isn't trying to break your program by messing with commas/decimal places/delimiters.

...But if I'm on the right track at all, you should be able to convert each double in the input array to an integer, then do some modulus and integer division to parse out the cents and dollar amounts respectively from that integer, and add them to a running total for each.

That at least seems like the overall approach if I understand it correctly. Maybe someone can verify/lambaste me for giving bad advice just to clarify.


Thanks. This is an assignment for school.

I don't put the inputs in an array. They're given to me in an array. Or more specifically, I submit my code electronically and they run it through test cases that I don't know, and tell me whether I passed them all or not. The test cases they run are supposed to try and break my function, not my code. I don't need to check for negatives or 0.000 numbers, or whether the total is greater than 1 million, those are the constraints on their end.

I did what was suggested and converted stuff to int, but it doesn't pass. Precision and sumerrors.

Anyways, I got it to pass by using doubles, multiplying by a 1,000,000 and then doing calculations, undoing the multiplication and converting to int at the end for output. I don't think I needed the second array as that was from when I was still using int, but I don't feel like changing it since it works fine.

Ints couldn't store enough digits for me to have a precision of 5 I think, which seems to mean a precision of 0.00001. I was going to choose like 1,000,000,000 instead of 1,000,000 if that didnt work... lol

+ Show Spoiler +

void printAverageAmount(double money[], int n)
{
int i;
double temp[n];
double sum = 0;
for (i = 0; i < n; i++)
{
temp[i] = money[i]*1000000;
}
for (i = 0; i < n; i++)
{
sum += temp[i];
}
double split = sum / n;
/*printf("%d", split);*/
double dollars, cents;

dollars = split / 1000000;
cents = (int)(split/10000) % 100;
printf("Everyone gets %d dollar(s) and %d cent(s).\n", (int)dollars, (int)cents);
}
There is no one like you in the universe.
MisterD
Profile Blog Joined June 2010
Germany1338 Posts
October 14 2011 07:53 GMT
#1709
if you are required to use a double[] as your input, you might want to ignore the most of this post. Just be informed that the multiplication by 1000000 in theory doesn't change anything. can you however chose to not use double in the first place, you should avoid it. Details below. but keep in mind, if you get your inputs as double[], there's no real point in converting them to int/float, because the precision is already lost and you can't regain it anyways.

------

multiplying a double by 1000000 doesn't really increase precision, it only makes the double store a "5 more zeroes at the end" since doubles are internally stored as 1.01010110 * 2^15, the decimal point is always moved such that there is only a 1 in front. so multiplying by 1000000 changes the bits a little bit (since there's a few 5 factors in there that can't be converted to 2^x), but in the end you end somewhere at 1.10010010*2^35 which has the same amount of bits to store the precision as before. So basically, if you use a float, and store a value of 5, it rounds at .00000001. But when storing a value of 5000000, it rounds at .01 already. So you actually don't gain any precision. (these are arbitrary values for demonstration purposes, to find the proper length of rounding you'd have to think in binary and use the correct bit lenghts for the fields, read up on IEEE floating point if you want details.)

also, you should not calculate money using floating point data types because they to weird rounding stuff and you might end up donating or disintegrating some value when handling large amounts (because, as i said, the decimal point is moved up to store as 1.xxx*2^y, so basically it can't store values consisting of more than 20 or so bits in "length" without rounding, and even values below that, like .02, must be expressed as some weird bit mask because it's basically stored as a sum of powers of 1/2, with which you just can't express .02 correctly because it has 5s in the factors).

so, have you tried using long? like float -> double for precision of floating point numbers, its int -> long for integer numbers. So basically, instead of capping at around 2 million (or 4 million for unsigned int), it caps at 8 million million (or 16 million million = 4 million squared for unsigned long). (values without guarantees, i *think* they are correct but i didn't look them up)

when calculating money, you should always calculate int or long, counting the cents. so $1.20 is actually "int money = 120; //cts", instead of doing the "human" thing and storing "float money = 1.2; //$".
Gold isn't everything in life... you need wood, too!
shinarit
Profile Joined May 2010
Hungary900 Posts
Last Edited: 2011-10-14 08:17:36
October 14 2011 08:01 GMT
#1710
On October 14 2011 16:53 MisterD wrote:when calculating money, you should always calculate int or long, counting the cents. so $1.20 is actually "int money = 120; //cts", instead of doing the "human" thing and storing "float money = 1.2; //$".


Or even better (and: safer): create a type for it

Edit: okay, read back, its a C course. But still, C can emulate the C++'s functionality very well in these basic levels, its not really a type, only a bunch of data with some helper functions
T for BoxeR, Z for IdrA, P because i have no self-respect
Blisse
Profile Blog Joined July 2010
Canada3710 Posts
Last Edited: 2011-10-14 08:11:41
October 14 2011 08:10 GMT
#1711
Yeah, sadly, this assignment was I think a lesson in handling floating point.

The input is double array[n] = { 0.00, 0.00, 0.00 } for example.

You're saying about the multiplication by a million that my code would pass without it as well?
There is no one like you in the universe.
Wamic
Profile Joined September 2010
Norway2 Posts
October 14 2011 08:30 GMT
#1712
Hello! I'm pretty new to programming, as i just started studying java as a part of my game design bachelor this year.

Anyway, i'm supposed to turn normal english statements into logical tests that could be used in an if/else statement.

The english statement is "y is a multiple of z" i couldn't figure it out so i checked the correct answer, and it is: y % z == 0

Any idea why this is? Thanks
bbm
Profile Joined April 2011
United Kingdom1320 Posts
October 14 2011 08:37 GMT
#1713
On October 14 2011 17:30 Wamic wrote:
Hello! I'm pretty new to programming, as i just started studying java as a part of my game design bachelor this year.

Anyway, i'm supposed to turn normal english statements into logical tests that could be used in an if/else statement.

The english statement is "y is a multiple of z" i couldn't figure it out so i checked the correct answer, and it is: y % z == 0

Any idea why this is? Thanks


The percentage sign is "modulo", which you'll be familiar from kiddie-maths as a "remainder" function.

The result is the remainder between z and the next highest number which is a factor of y. IE: The remainder

so
9%4 = 1 (4*2 = 8, 1 less than 9),
17%3 = 2 (3*5 = 15, 2 less than 17), etc, etc.

Good luck.
By.Sun or By.Rain, he always delivers
Denar
Profile Blog Joined March 2011
France1633 Posts
October 14 2011 08:38 GMT
#1714
On October 14 2011 17:30 Wamic wrote:
Hello! I'm pretty new to programming, as i just started studying java as a part of my game design bachelor this year.

Anyway, i'm supposed to turn normal english statements into logical tests that could be used in an if/else statement.

The english statement is "y is a multiple of z" i couldn't figure it out so i checked the correct answer, and it is: y % z == 0

Any idea why this is? Thanks


% is the modulo operation.

y % z = x means that x is the rest of the division y / z.

So, "y is a multiple of z" is equivalent to "0 is the rest of the division of y by z", which is : y % z = 0
Wamic
Profile Joined September 2010
Norway2 Posts
October 14 2011 09:21 GMT
#1715
Thanks guys

you may (or may not) enjoy this :p
Lady Java
BottleAbuser
Profile Blog Joined December 2007
Korea (South)1888 Posts
Last Edited: 2011-10-14 11:31:56
October 14 2011 11:29 GMT
#1716
When you deal with serious business (particularly money) that must be infinitely precise in base-10, you use binary encoded decimals. Use 4 bits to represent every digit. You'll lose storage space (4 bits can represent up to 16 numbers, but you're only using them to store 10), but you gain precision. Use a byte for every 2 digits you need, and you're golden.

Of course, you'll end up having to use specialized operators to do arithmetic. This stuff is usually implemented in hardware because whoever needs it also wants speed (like banks). For homework, which will probably not have a problem with performance, I'd suggest using strings. You could implement basic arithmetic operators with loops that emulate what you'd do by hand (O(n^2) for division and multiplication).

If your input is in a double format, I'd assume that the input itself is represented well enough not to worry (2.34 will print as "2.34" on the screen). So, you could convert it to a string, and convert it to 100*(input) by parsing the characters to ints one at a time and multiplying by 10. When you're done, you print your output 1 character at a time, inserting a decimal point as appropriate.
Compilers are like boyfriends, you miss a period and they go crazy on you.
MisterD
Profile Blog Joined June 2010
Germany1338 Posts
October 15 2011 01:03 GMT
#1717
On October 14 2011 17:10 Blisse wrote:
Yeah, sadly, this assignment was I think a lesson in handling floating point.

The input is double array[n] = { 0.00, 0.00, 0.00 } for example.

You're saying about the multiplication by a million that my code would pass without it as well?


it should, yes.
Gold isn't everything in life... you need wood, too!
Necosarius
Profile Blog Joined September 2009
Sweden4042 Posts
October 15 2011 19:27 GMT
#1718
On October 13 2011 02:14 Frigo wrote:
+ Show Spoiler +
On October 13 2011 01:58 Necosarius wrote:
I have a hard time understanding recursion. Could someone please explain what it is/what it does?

A recursive function might call itself with different parameters to compute its return value, that's all.

For example, factorial calculation:
public class Main
{

public static void main (String[] args)
{
System.out.println(factorial(5));
}

public static int factorial (int n)
{
if( n == 0 ){
return 1;
}
return n * factorial(n - 1);
}

}


Another common example, calculating the Fibonacci number:
public class Main
{

public static void main (final String[] args)
{
System.out.println(fibonacci(7));
}

public static int fibonacci (int n)
{
if( n == 0 ){
return 0;
}
if( n == 1 ){
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}

}


On October 13 2011 05:49 Millitron wrote:
+ Show Spoiler +
On October 13 2011 01:58 Necosarius wrote:
I have a hard time understanding recursion. Could someone please explain what it is/what it does?

Recursion is a general idea for creating methods. A recursive method has a simple answer for some base case, and calls itself for any other cases. The recursive calls generally try to whittle the problem down to a base case, then merge the returns of each call.

The Fibonacci and the factorial example, while being relatively easy to understand, are computationally very slow. There are much faster algorithms that don't use recursion.

On October 13 2011 07:00 killa_robot wrote:
+ Show Spoiler +
On October 13 2011 01:58 Necosarius wrote:
I have a hard time understanding recursion. Could someone please explain what it is/what it does?



Recursion just means a method calls itself until it reaches some sort predetermined value. In this case, the method calls itself until it reaches zero. Since it calls itself there's only ever one of it, so it's static.



public class Main
{

public static void main (final String[] args)
{
GetToZero(7);
}

public static void GetToZero (int n)
{
if(n == 0)
{
System.out.println("Reached Zero");
}
else if (n > 0)
{
System.out.println("Subtracting 1 - " + n);
n--;
GetToZero(n);
}
else if (n < 0)
{
System.out.println("Adding 1 - " + n);
n++;
GetToZero(n);
}
}
}

On October 13 2011 07:28 Kambing wrote:
+ Show Spoiler +
On October 13 2011 01:58 Necosarius wrote:
I have a hard time understanding recursion. Could someone please explain what it is/what it does?


First thing to recognize: programming is problem solving by decomposition. Given a problem, you decompose that problem repeatedly into smaller problems until the subproblems are manageable to solve on their own. For example, the problem of cooking spaghetti involves several subtasks such as buying the ingredients, preparing the sauce, preparing the meat, and the mixing it all together. In code, you typically use functions/methods to realize this decomposition, e.g.,


void cookSpaghetti() {
buyIngredients();
prepareSauce();
prepareMeat();
mixIngredients();
}


With that in mind, recursion is a problem solving technique in which you recognize that the subproblems that you create are actually smaller versions of the original problem that you are trying to solve.

To make this more concrete, imagine a line of folk waiting for the release of heart of swarm:


front <(^^)> <(^^)> <(^^)> back


Now imagine that the person in the back of line is trying to figure out what place they are in line. One thing they can do is step out of line and count the number of people in front of them directly. However, instead of risking losing their place in line, they can ask the person in front of them:


front <(^^)> <(^^)> <(^^)> back
|-- "What place are you in line?"


Now, the person in front of them is posed with a similar question, so they can ask the person in front of them the same question:


front <(^^)> <(^^)> <(^^)> back
| |-- "What place are you in line?"
|-- "What place are you in line?"



Finally the question is posed to the person in the front of the line. He's know he's #1, so he tells the person behind him.


front <(^^)> <(^^)> <(^^)> back
| | |-- "What place are you in line?"
1 |-- "What place are you in line?"


With that answer, the person behind the first in line now knows what place they are in line. They know they're second by adding one to the place of the person in front of them.


front <(^^)> <(^^)> <(^^)> back
| | |-- "What place are you in line?"
1 2


And finally the person in the back knows their place in line given the position of the person in front of them by adding one.


front <(^^)> <(^^)> <(^^)> back
| | |
1 2 3


This is the essence of simple recursion:

  • A base case that handles the situation when the problem we're trying to solve is directly solvable.
  • A recursive case that solves the current problem by solving an identical subproblem of a smaller size.


Let's extend this to a code example that people have mentioned already, factorial(n).


int factorial(int n) {
// Base case, i.e., front of the line: 0! = 1
if (n <= 0) {
return 1;
// Recursive case, i.e., the middle or the line: n! = n * (n-1)!
} else {
return n * factorial(n-1);
}
}


Wow thank all for the replies!
Frigo
Profile Joined August 2009
Hungary1023 Posts
October 15 2011 20:39 GMT
#1719
Managed to get Ant and JUnit working together. It was a bit tricky cause JUnit takes the package name from the relative path given by Ant, instead of y'know, the actual package declaration inside the java files. So instead of jfrigo.test.math.PolynomialTest, it tried to run test.math.PolynomialTest or even math.PolynomialTest, without any success of course.

The solution is trivial, but it took me a while to think outside the box and realize the trick. We simply run it from the parent directory and give a longer relative path

			<batchtest fork="yes" todir="report">
<formatter type="plain"/>
<fileset dir="..">
<include name="jfrigo/test/**/*.java"/>
</fileset>
</batchtest>


Wrote a simple unit test as practice. Managed to catch a few silent errors in a seemingly perfect Polynomial implementation: wrong result at integration of the zero polynomial, sign error at definite integration, empty toString for the zero polynomial, and an invariant violation due to some one-off error.

Moral of the story: automated unit tests are fukken awesome.
http://www.fimfiction.net/user/Treasure_Chest
Phrost
Profile Blog Joined May 2010
United States4008 Posts
October 16 2011 07:03 GMT
#1720
On October 14 2011 17:30 Wamic wrote:
Hello! I'm pretty new to programming, as i just started studying java as a part of my game design bachelor this year.

Anyway, i'm supposed to turn normal english statements into logical tests that could be used in an if/else statement.

The english statement is "y is a multiple of z" i couldn't figure it out so i checked the correct answer, and it is: y % z == 0

Any idea why this is? Thanks



% returns the remainer of the statement after division.

so 2%2 = 0
3%2 = 1
4%2 = 0

etc

if its evenly divisible then x%y would = 0
iamphrost.tumblr.com // http://howtobebettermagicplayer.tumblr.com // twitter @phrost_
Prev 1 84 85 86 87 88 1032 Next
Please log in or register to reply.
Live Events Refresh
OSC
11:30
Mid Season Playoffs
Krystianer vs PercivalLIVE!
WardiTV1063
TKL 199
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
TKL 199
SteadfastSC 109
Rex 91
StarCraft: Brood War
Calm 3367
Bisu 2918
Rain 2430
Hyuk 1473
Horang2 984
Flash 514
Soma 498
Stork 393
Rush 303
Soulkey 121
[ Show more ]
Backho 114
Barracks 58
sas.Sziky 46
hero 38
Aegong 27
zelot 22
sSak 21
Terrorterran 20
Rock 19
Killer 16
Dota 2
Gorgc3152
qojqva2018
Dendi1105
BananaSlamJamma123
XcaliburYe100
Other Games
hiko638
Sick526
DeMusliM442
Hui .346
Fuzer 199
Mew2King94
QueenE50
Organizations
StarCraft: Brood War
Kim Chul Min (afreeca) 9
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 16 non-featured ]
StarCraft 2
• poizon28 22
• intothetv
• AfreecaTV YouTube
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• HerbMon 10
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• C_a_k_e 3021
• WagamamaTV453
League of Legends
• Nemesis4037
• TFBlade977
Upcoming Events
Tenacious Turtle Tussle
7h 31m
The PondCast
18h 31m
RSL Revival
18h 31m
Solar vs Zoun
MaxPax vs Bunny
Kung Fu Cup
20h 31m
WardiTV Korean Royale
20h 31m
PiGosaur Monday
1d 9h
RSL Revival
1d 18h
Classic vs Creator
Cure vs TriGGeR
Kung Fu Cup
1d 20h
CranKy Ducklings
2 days
RSL Revival
2 days
herO vs Gerald
ByuN vs SHIN
[ Show More ]
Kung Fu Cup
2 days
IPSL
3 days
ZZZero vs rasowy
Napoleon vs KameZerg
BSL 21
3 days
Tarson vs Julia
Doodle vs OldBoy
eOnzErG vs WolFix
StRyKeR vs Aeternum
Sparkling Tuna Cup
3 days
RSL Revival
3 days
Reynor vs sOs
Maru vs Ryung
Kung Fu Cup
3 days
WardiTV Korean Royale
3 days
BSL 21
4 days
JDConan vs Semih
Dragon vs Dienmax
Tech vs NewOcean
TerrOr vs Artosis
IPSL
4 days
Dewalt vs WolFix
eOnzErG vs Bonyth
Wardi Open
4 days
Monday Night Weeklies
5 days
WardiTV Korean Royale
5 days
The PondCast
6 days
Liquipedia Results

Completed

Proleague 2025-11-07
Stellar Fest: Constellation Cup
Eternal Conflict S1

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
SOOP Univ League 2025
YSL S2
BSL Season 21
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual

Upcoming

SLON Tour Season 2
BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
RSL Revival: Season 3
META Madness #9
BLAST Bounty Winter 2026
BLAST Bounty Winter 2026: Closed Qualifier
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.