• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 02:25
CEST 08:25
KST 15:25
  • 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
RSL Season 1 - Final Week6[ASL19] Finals Recap: Standing Tall12HomeStory Cup 27 - Info & Preview18Classic wins Code S Season 2 (2025)16Code S RO4 & Finals Preview: herO, Rogue, Classic, GuMiho0
Community News
Esports World Cup 2025 - Brackets Revealed9Weekly Cups (July 7-13): Classic continues to roll2Team TLMC #5 - Submission extension2Firefly given lifetime ban by ESIC following match-fixing investigation17$25,000 Streamerzone StarCraft Pro Series announced7
StarCraft 2
General
Who will win EWC 2025? RSL Revival patreon money discussion thread Esports World Cup 2025 - Brackets Revealed Team TLMC #5 - Submission extension The GOAT ranking of GOAT rankings
Tourneys
RSL: Revival, a new crowdfunded tournament series FEL Cracov 2025 (July 27) - $8000 live event $5,100+ SEL Season 2 Championship (SC: Evo) WardiTV Mondays Sparkling Tuna Cup - Weekly Open Tournament
Strategy
How did i lose this ZvP, whats the proper response Simple Questions Simple Answers
Custom Maps
External Content
Mutation # 482 Wheel of Misfortune Mutation # 481 Fear and Lava Mutation # 480 Moths to the Flame Mutation # 479 Worn Out Welcome
Brood War
General
BW General Discussion Flash Announces (and Retracts) Hiatus From ASL Starcraft in widescreen BGH Auto Balance -> http://bghmmr.eu/ A cwal.gg Extension - Easily keep track of anyone
Tourneys
Cosmonarchy Pro Showmatches [Megathread] Daily Proleagues CSL Xiamen International Invitational [BSL20] Non-Korean Championship 4x BSL + 4x China
Strategy
Simple Questions, Simple Answers I am doing this better than progamers do.
Other Games
General Games
Nintendo Switch Thread Stormgate/Frost Giant Megathread Path of Exile CCLP - Command & Conquer League Project The PlayStation 5
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
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Stop Killing Games - European Citizens Initiative Russo-Ukrainian War Thread Summer Games Done Quick 2025! Things Aren’t Peaceful in Palestine
Fan Clubs
SKT1 Classic Fan Club! Maru Fan Club
Media & Entertainment
Movie Discussion! [Manga] One Piece Anime Discussion Thread [\m/] Heavy Metal Thread
Sports
Formula 1 Discussion TeamLiquid Health and Fitness Initiative For 2023 2024 - 2025 Football Thread NBA General Discussion NHL Playoffs 2024
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
Men Take Risks, Women Win Ga…
TrAiDoS
momentary artworks from des…
tankgirl
from making sc maps to makin…
Husyelt
StarCraft improvement
iopq
Trip to the Zoo
micronesia
Customize Sidebar...

Website Feedback

Closed Threads



Active: 550 users

The Big Programming Thread - Page 86

Forum Index > General Forum
Post a Reply
Prev 1 84 85 86 87 88 1031 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 1031 Next
Please log in or register to reply.
Live Events Refresh
Next event in 3h 36m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Nina 238
mcanning 42
StarCraft: Brood War
Zeus 1144
Noble 33
Bale 7
PianO 0
Dota 2
ODPixel398
NeuroSwarm111
canceldota0
League of Legends
JimRising 779
Counter-Strike
Stewie2K1137
Super Smash Bros
Mew2King114
Other Games
summit1g13069
WinterStarcraft337
Trikslyr39
SortOf18
Organizations
Other Games
gamesdonequick3179
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 14 non-featured ]
StarCraft 2
• Berry_CruncH391
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• lizZardDota213
League of Legends
• Rush2208
• Lourlo1592
Upcoming Events
Replay Cast
3h 36m
WardiTV European League
9h 36m
ShoWTimE vs sebesdes
Percival vs NightPhoenix
Shameless vs Nicoract
Krystianer vs Scarlett
ByuN vs uThermal
Harstem vs HeRoMaRinE
PiGosaur Monday
17h 36m
uThermal 2v2 Circuit
1d 9h
Replay Cast
1d 17h
The PondCast
2 days
WardiTV European League
2 days
Replay Cast
2 days
Epic.LAN
3 days
CranKy Ducklings
4 days
[ Show More ]
Epic.LAN
4 days
CSO Contender
4 days
BSL20 Non-Korean Champi…
4 days
Bonyth vs Sziky
Dewalt vs Hawk
Hawk vs QiaoGege
Sziky vs Dewalt
Mihu vs Bonyth
Zhanhun vs QiaoGege
QiaoGege vs Fengzi
Sparkling Tuna Cup
5 days
Online Event
5 days
BSL20 Non-Korean Champi…
5 days
Bonyth vs Zhanhun
Dewalt vs Mihu
Hawk vs Sziky
Sziky vs QiaoGege
Mihu vs Hawk
Zhanhun vs Dewalt
Fengzi vs Bonyth
Liquipedia Results

Completed

2025 ACS Season 2: Qualifier
RSL Revival: Season 1
Murky Cup #2

Ongoing

JPL Season 2
BSL 2v2 Season 3
CSL 17: 2025 SUMMER
Copa Latinoamericana 4
Jiahua Invitational
BSL20 Non-Korean Championship
Championship of Russia 2025
FISSURE Playground #1
BLAST.tv Austin Major 2025
ESL Impact League Season 7
IEM Dallas 2025
PGL Astana 2025
Asian Champions League '25
BLAST Rivals Spring 2025
MESA Nomadic Masters

Upcoming

CSL Xiamen Invitational
CSL Xiamen Invitational: ShowMatche
2025 ACS Season 2
CSLPRO Last Chance 2025
CSLPRO Chat StarLAN 3
BSL Season 21
K-Championship
RSL Revival: Season 2
SEL Season 2 Championship
uThermal 2v2 Main Event
FEL Cracov 2025
Esports World Cup 2025
Underdog Cup #2
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 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.