• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 05:12
CEST 11:12
KST 18:12
  • 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
[ASL22] Ro24 Preview: Summer's End9Serral wins HomeStory Cup 2915Serral wins Maestros of the Game 244ByuL, and the Limitations of Standard Play3Team Liquid Map Contest #22: Results and Winners7
Community News
Weekly Cups (August 10-16): SHIN doubles2GSTL Returns in 2026!45Weekly Cups (Aug 3-9): Protoss get shut out7RSL goes to London! 2026 Offline Finals Nov 21-2212Weekly Cups (July 27-Aug 2): SHIN's big week0
StarCraft 2
General
Geoff 'iNcontroL' Robinson has passed away SC4ALL II: SC2 Player Announcement 6/8 - Maru GSTL Returns in 2026! Balance hotfix patch 5.0.16b (July 16) Serral wins Maestros of the Game 2
Tourneys
PIG STY FESTIVAL 8.0! (13 - 23 August) WORTEX 2026 - Hungarian SC2 Finals Budapest Sparkling Tuna Cup - Weekly Open Tournament SC2 AI Tournament 2026 Fall 2026 GSTL Announcement
Strategy
[G] Having the right mentality to improve
Custom Maps
Nexus Wars 2021 GUIDE [M] (2) Industrial Park
External Content
The PondCast: SC2 News & Results Mutation # 539 Thunder Dome Mutation # 538 Media Blackout Mutation # 537 Hostile Territory
Brood War
General
Replay Review Process - What do you do? Pros React To: First 'Fastest' Map in ASL History BW General Discussion [Personal Project Share] Terran Defense v0.60 ASL22 General Discussion
Tourneys
[ASL22] Ro24 Group C Small VOD Thread 2.0 Toronto invitational lan 22 august [ASL22] Ro24 Group A
Strategy
Odyssey Mineral Stack Saturation Fighting Spirit mining rates Any training maps people recommend? Simple Questions, Simple Answers
Other Games
General Games
Nintendo Switch Thread General RTS Discussion Thread Anyone here play Quakeworld back in the day? Stormgate/Frost Giant Megathread EVE Corporation
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
[TL LoL EUW IHs] Teemo shall perish TSM pausing esports and CLG Dead
Heroes of the Storm
Heroes of the Storm 2.0
Hearthstone
Deck construction bug
TL Mafia
TL Mafia Power Rank TL Mafia Community Thread NeO.D_StephenKing vs This Guy From 1 Million Dance
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread Canadian Politics Mega-thread Dating: How's your luck? Artificial Intelligence Thread
Fan Clubs
The Creator Fan Club MarineLorD Fan Club The ShoWTimE Fan Club
Media & Entertainment
Movie Discussion! Anime Discussion Thread
Sports
Football (Soccer) Thread MLB/Baseball 2023 TeamLiquid Health and Fitness Initiative For 2023 NBA General Discussion
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread Simple Questions Simple Answers FPS when play League Of Legend on laptop
TL Community
The Automated Ban List Northern Ireland Global Starcraft
Blogs
Young Players Exit Esports E…
TrAiDoS
LOCKPICKING NOOB
LUCKY_NOOB
Cathedral Of CS And NY pizza a…
FuDDx
Please support my new stand…
Peanutsc
Customize Sidebar...

Website Feedback

Closed Threads



Active: 5663 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 48m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
BRAT_OK 36
ProTech19
MindelVK 13
StarCraft: Brood War
Shuttle 3052
Bisu 664
Leta 631
BeSt 423
Killer 129
Sharp 126
EffOrt 98
PianO 50
Mind 47
Bale 28
[ Show more ]
Aegong 16
Noble 15
ZergMaN 9
Hm[arnc] 9
Dota 2
The International147434
Gorgc9979
singsing3550
Counter-Strike
shoxiejesuss702
Super Smash Bros
Mew2King75
Other Games
Sick159
amsayoshi36
Organizations
Other Games
gamesdonequick443
[ Show 11 non-featured ]
StarCraft 2
• LUISG 13
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• Migwel
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• WagamamaTV201
League of Legends
• Jankos1435
Upcoming Events
Sparkling Tuna Cup
48m
PiG Sty Festival
2h 48m
Solar vs Reynor
Serral vs Maru
OSC
6h 48m
Afreeca Starleague
1d
hero vs ggaemo
Larva vs Mong
The Patches Monday
1d 6h
Afreeca Starleague
2 days
Soulkey vs PianO
JyJ vs sSak
GSL
2 days
PiGosaur Cup
2 days
Replay Cast
2 days
Afreeca Starleague
3 days
Mini vs Calm
Queen vs EffOrt
[ Show More ]
Replay Cast
3 days
The PondCast
4 days
IntoTheTV X SOOP
5 days
GSL
6 days
Replay Cast
6 days
Liquipedia Results

Completed

Escore Tournament S3: W8
CranK Gathers Season 4: BW vs SC2 Team League
Eternal Conflict S2 Finale

Ongoing

KCM Race Survival 2026 Season 3
K-JUNGMAN
ASL Season 22
Super Anchor Qualifying S3
CSL Season 22: Qualifier 1
RSL Revival: Season 6
PiG Sty Festival 8.0
META DYMY #4
Esports World Cup 2026
Esports World Cup 2026: LCQ
BLAST Bounty Summer 2026
BLAST Bounty Summer Qual
Stake Ranked Episode 3
XSE Pro League 2026
IEM Cologne Major 2026

Upcoming

CSL Season 22: Qualifier 2
CSL 2026 AUTUMN (S22)
Acropolis #5
Acropolis #5 - TRS
Blizzard Classic Cup 2026
Acropolis #5 - GSA
Acropolis #5 - GSB
HSC XXX
SC4ALL II: StarCraft II
Kung Fu Cup 2026 Grand Finals
RSL Offline Finals
Calamity Invitational
Big Dog Cup 2026 Div 1
IEM Beijing 2026
Stake Ranked Episode 5
PGL Masters Bucharest 2026
Thunderpick World Champ. '26
ESL Pro League Season 24
Stake Ranked Episode 4
1win Private Club #1
Logitech G Play Connect 2026
SL StarSeries Fall 2026
FISSURE Playground #3
BLAST Open Fall 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.