• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 04:14
CEST 10:14
KST 17:14
  • 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
ByuL, and the Limitations of Standard Play0Team Liquid Map Contest #22: Results and Winners7Code S Season 2 (2026): RO4 and Finals Preview12TL.net Map Contest #22 - Voting & Ladder Map Selection7Code S Season 2 (2026) - RO8 Preview8
Community News
[TLMC] Summer 2026 Ladder Map Rotation05.0.16 patch for SC2 goes live (8 worker start)50ZeroSpace at Steam NextFest - Last free demo25Weekly Cups (June 8-14): Clem and Solar double, PTR tested0RSL: S6 Finals played at BlizzCon 202611
StarCraft 2
General
5.0.16 patch for SC2 goes live (8 worker start) take on 5.0.16 ?Bug in new patch ByuL, and the Limitations of Standard Play Daily SC2 Player Grid - feedback wanted
Tourneys
INu's Battles#17 <BO.9> RSL Revival: Season 6 - Qualifiers and Main Event Sparkling Tuna Cup - Weekly Open Tournament GSL CK #4 20-21th June Douyu Cup 2026: $20,000 Legends Event (June 26-28)
Strategy
[G] Having the right mentality to improve
Custom Maps
New Map Maker - Looking for Advice - Love or Hate Work In Progress Melee Maps [D]RTS in all its shapes and glory <3
External Content
The PondCast: SC2 News & Results Mutation # 531 Experimental Artillery Mutation # 530 One For All Mutation # 529 Opportunities Unleashed
Brood War
General
ASL 22 Proposed Map Pool BW General Discussion STARCRAFT MOVIE - Last Night at the Command center Fact based Zerg Upgrade Tier List BGH Auto Balance -> http://bghmmr.eu/
Tourneys
[BSL22] GosuLeague Casts - Tue & Thu 22:00 CEST [Megathread] Daily Proleagues CSLAN 4 is Coming! Small VOD Thread 2.0
Strategy
Why doesn't anyone use restoration? Simple Questions, Simple Answers Relatively freeroll strategies Creating a full chart of Zerg builds
Other Games
General Games
The Perfect Game Rogue Command ZeroSpace at Steam NextFest - Last free demo Stormgate/Frost Giant Megathread Beyond All Reason
Dota 2
Looking for a Dota Mentor 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
TL Mafia
Vanilla Mini Mafia
Community
General
US Politics Mega-thread Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread [H]Internet/Gaming Cafe Tips and Tricks The Games Industry And ATVI
Fan Clubs
The HerO Fan Club! The herO Fan Club!
Media & Entertainment
Movie Discussion! Series you have seen recently... [Req][Books] Good Fantasy/SciFi books [TV/BOOK] *SPOILERS* Game of Thrones Discussion
Sports
2024 - 2026 Football Thread TeamLiquid Health and Fitness Initiative For 2023 McBoner: A hockey love story Formula 1 Discussion Cricket [SPORT]
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread Facing Challenges in Mobile App Development
TL Community
The Automated Ban List
Blogs
How To Predict Tilt in Espor…
TrAiDoS
An Exploration of th…
waywardstrategy
I'm an arrogant trash talke…
FlaShFTW
Gauntlet SC2: A Retrospectiv…
Ctone23
Why RTS gamers make better f…
gosubay
Customize Sidebar...

Website Feedback

Closed Threads



Active: 7165 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
Next event in 1h 46m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
StateSC2 267
SortOf 204
StarCraft: Brood War
Hyuk 648
Tasteless 264
Hm[arnc] 111
Dewaltoss 80
Leta 61
Aegong 48
NaDa 39
Larva 26
Super Smash Bros
Mew2King158
Other Games
summit1g7549
ceh9535
RuFF_SC228
Organizations
Dota 2
PGL Dota 2 - Main Stream1853
Other Games
gamesdonequick568
StarCraft: Brood War
UltimateBattle 118
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
[ Show 14 non-featured ]
StarCraft 2
• Berry_CruncH259
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Rush1020
• Jankos722
• Stunt702
Upcoming Events
The PondCast
1h 46m
OSC
8h 46m
Douyu Cup 2020
20h 46m
Oliveira vs Trap
Jieshi vs XY
soO vs FanTaSy
TY vs Coffee
OSC
1d 7h
Douyu Cup 2020
1d 20h
Neeb vs Impact
MacSed vs Cyan
Scarlett vs Kelazhur
INnoVation vs Dear
Douyu Cup 2020
2 days
Maestros of the Game
3 days
herO vs Classic
Maru vs Serral
BSL22 NKC (BSL vs China)
3 days
Douyu Cup 2020
3 days
BSL22 NKC (BSL vs China)
4 days
[ Show More ]
Online Event
4 days
RSL Revival
4 days
RSL Revival
5 days
WardiTV Weekly
5 days
RSL Revival
6 days
Liquipedia Results

Completed

Proleague 2026-06-19
WardiTV Spring 2026
Heroes Pulsing #2

Ongoing

IPSL Spring 2026
Acropolis #4
CSCL: Masked Kings S4
YSL S3
BSL 22 Non-Korean Championship
CSL Season 21: Qualifier 1
SCTL 2026 Spring
Maestros of the Game 2
Murky Cup 2026
IEM Cologne Major 2026
Stake Ranked Episode 2
CS Asia Championships 2026
Asian Champions League 2026
IEM Atlanta 2026
PGL Astana 2026
BLAST Rivals Spring 2026
IEM Rio 2026
PGL Bucharest 2026

Upcoming

CSL Season 21: Qualifier 2
CSL 2026 Summer (S21)
CSLAN 4
Blizzard Classic Cup 2026
Kung Fu Cup 2026 Grand Finals
RSL Revival: Season 6
CranK Gathers Season 4: BW vs SC2 Team League
HSC XXIX
Douyu Cup 2026
BCC 2026
Light Tournament 2026
Eternal Conflict S2 Finale
Eternal Conflict S2 E1
Heroes Pulsing #3
BLAST Open Fall 2026
Esports World Cup 2026
BLAST Bounty Summer 2026
BLAST Bounty Summer Qual
Stake Ranked Episode 3
XSE Pro League 2026
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 © 2026 TLnet. All Rights Reserved.