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

Website Feedback

Closed Threads



Active: 1871 users

The Big Programming Thread - Page 175

Forum Index > General Forum
Post a Reply
Prev 1 173 174 175 176 177 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.
phar
Profile Joined August 2011
United States1080 Posts
October 13 2012 23:43 GMT
#3481
On October 14 2012 08:14 NeMeSiS3 wrote:
So I just got my lineup for the midterm
+ Show Spoiler +

1. Write a "standard" java class.

//Instance variables
//Constructors
//Methods
--Accessor (getters)
--Mutator (setters)

2. "Has a" relationships

3. If Statements (easy pzy)

4. Understanding object reference variables
EX:
CP pt1 = new CP(1,2);
CP pt2 = new CP(3,4);
pt1 = pt2;
pt1.setX(5);
pt2.getX();

What is going to be presented? (ASSUME*** all previous code is in place to make such functions able to process)



My question is how should I study for this? It seems like a silly question but we never really got any questions all year, we just ran examples and did assignments and as this is my first year in CS I just dunno what it'll look like. Any advice or help on these, anyone got a simple way to remember "class" creation/use. I always have a bitch of a time writing multiple classes.

thanks!
For things like 1&2, the only way to properly "study" is to just write a lot of code. You've either written enough code to remember the basic constructs in a language, or you haven't. #3 is logic. Things like #4 are testing stuff that's not really java-specific. That type of question is really asking "Do you understand C-style pointers?"

#4 is very easy if you've learned C, lisp, or something else. If you understand stack variables vs. heap variables, it's easy. Pointers are kinda hidden from you in Java, but it's still best to think about variables and the actual objects as separate things. If can understand that the variable (thing1) is DIFFERENT from the actual object in memory, you'll be fine.

#4 is a lot easier to explain with drawings. I'm not good at explaining this in words.
Who after all is today speaking about the destruction of the Armenians?
Craton
Profile Blog Joined December 2009
United States17264 Posts
Last Edited: 2012-10-14 02:00:33
October 14 2012 01:56 GMT
#3482
C-style pointers? You're going way overboard with that.

It's just the basic difference between value and reference types and how setting one object equal to another works out.

Anyway, you study by actually writing code the hits all the points that are going to be on the test. If you don't know how to do it, you go look up how until you do.

Once you can write it all without referencing anything, you are good to go.
twitch.tv/cratonz
phar
Profile Joined August 2011
United States1080 Posts
Last Edited: 2012-10-14 02:18:00
October 14 2012 02:13 GMT
#3483
On October 14 2012 10:56 Craton wrote:
C-style pointers? You're going way overboard with that.
Not sure what you mean by "overboard." On the off chance that the previous poster has already done some C, it's worth pointing out. Every variable you deal with is essentially a pointer. If he's already had to go through a class with C, it could be very useful to draw this comparison.

On October 14 2012 10:56 Craton wrote:It's just the basic difference between value and reference types and how setting one object equal to another works out.
Agreed, it is important to know the difference between the java primitive types, and all other types with respect to what happens when you assign one variable to another.

In this case, you aren't setting objects equal to each other though, that's the whole point. The other object is still there** and completely unchanged, it's not set equal to anything. You are creating two objects (on heap). You also have two pointers (variable names, whatever), and are setting them both to point to the same object.

** There, until the GC feels like coming along and cleaning up your shit for you.

On October 14 2012 10:56 Craton wrote:Anyway, you study by actually writing code the hits all the points that are going to be on the test. If you don't know how to do it, you go look up how until you do.

Once you can write it all without referencing anything, you are good to go.
Definitely agree with this. Code more, you'll be fine.
Who after all is today speaking about the destruction of the Armenians?
CptCutter
Profile Joined September 2010
United Kingdom370 Posts
Last Edited: 2012-10-14 02:34:14
October 14 2012 02:28 GMT
#3484
On October 14 2012 11:13 phar wrote:
Show nested quote +
On October 14 2012 10:56 Craton wrote:
C-style pointers? You're going way overboard with that.
Not sure what you mean by "overboard." On the off chance that the previous poster has already done some C, it's worth pointing out. Every variable you deal with is essentially a pointer. If he's already had to go through a class with C, it could be very useful to draw this comparison.

Show nested quote +
On October 14 2012 10:56 Craton wrote:It's just the basic difference between value and reference types and how setting one object equal to another works out.
Agreed, it is important to know the difference between the java primitive types, and all other types with respect to what happens when you assign one variable to another.

In this case, you aren't setting objects equal to each other though, that's the whole point. The other object is still there** and completely unchanged, it's not set equal to anything. You are creating two objects (on heap). You also have two pointers (variable names, whatever), and are setting them both to point to the same object.

** There, until the GC feels like coming along and cleaning up your shit for you.

Show nested quote +
On October 14 2012 10:56 Craton wrote:Anyway, you study by actually writing code the hits all the points that are going to be on the test. If you don't know how to do it, you go look up how until you do.

Once you can write it all without referencing anything, you are good to go.
Definitely agree with this. Code more, you'll be fine.


as far as i knew, passing by reference all the time does not make you a good programmer, nor does it make your program memory efficient. its far more memory efficient to store pointers in c (integer variables that require 4 bytes) than creating another variable with the exact same values.

what im trying to say is that different situations should require either pass by reference or pass by value.
phar
Profile Joined August 2011
United States1080 Posts
October 14 2012 03:45 GMT
#3485
Java is like C. You cannot pass by reference. You can only pass by value. That value is either a java primitive (what craton is calling 'value type'), or a pointer (everything else). It's just like C.

And yes, different situations require different solutions.


I think we may be all meaning the same thing but saying different things here. Proper "pass by reference" in the C++ sense doesn't exist in C or Java. You can pass a pointer, which is common in C, and required in Java (except for primitives).



In any case, Nemesis, sorry for the derailing here. For #4 just make sure you understand that variables are pointers, and objects are separate things, living in the heap (the exception is primitive types). Multiple variables can be pointing to the same object. If you mutate the object, it is the actual object on the heap that is mutated.
Who after all is today speaking about the destruction of the Armenians?
Ian Ian Ian
Profile Blog Joined August 2009
915 Posts
October 14 2012 03:58 GMT
#3486
I'm taking an intro to python course. This is my first experience with computer programming at all. The course is annoying in the fact that the professor doesn't really explain how things works. He gives us a function and says "solve this physics problem with it". So very often I find myself getting stuck on really stupid things.

Regardless, the problem I'm having is that I have written a couple functions that plot and find the best fit line a set of data that holds Temperature averages for each month for 100 years or so. Afterwards we find the average temperature for each year, plot and find the best fit of that as well. Afterwrads, extrapolate that line and find what year the earth should "freeze" and "boil over".

I've done everything except find a way to code the last part. After I find the slope and intercept of the mean temperature I should just be able use those values to solve a simple y = mx + b equation. But I found and defined the slope and intercept in a function called plotAverage. I run plotAverage and then try to use the slope defined in that function, but it gives me a name error saying slope is not defined. I realize this is because I defined it in the other function and not the one I am currently writing, but how do I use that value without changing my plotAverage function?

The code is as follows, alot of it was written by our professor and we fixed it to do what we want.

+ Show Spoiler +


def getData( url ) :
"""
Retrieves a CSV file from the Interwebs and returns the
columns as a series of vectors.
"""
from urllib import urlretrieve # get a file from a URL
urlretrieve( url , 'tempfile.csv')
from numpy import loadtxt # load a CSV file
return loadtxt( 'tempfile.csv', skiprows=1, unpack=True, delimiter=',' )

def getRow( data, row ) :
"""
Accepts data, a 2D array, and row, a list of one or more row numbers.

Returns the requested row(s) of the data set, omitting the first column
which contains the year rather than a temperature.
"""
# the first column, offset zero, containing the year, is
# *purposefully* excluded
return data[ 1:13 , row ] # colon operator means columns with
# offsets 1-12 inclusive

def getCol( data, column ) :
"""
Accepts data, a 2D array, and column, a list of one or more column numbers.

Returns the requested column(s) of the data set.
"""
return data[ column, : ] # colon operator means 'all' rows

def annualAverage( data ) :
"""
Accepts data, a 2D array.

Returns the average temperature for each row (excluding the year
column, column zero, from the calculation).
"""
from numpy import mean

months = range( 1, 13 ) # month values, 1-12 inclusive
newData = getCol( data, months ) # get the subset of data
return mean( newData, axis=0 ) # average over each rows => axis=0

def plotHotCold( data ) :
from matplotlib.pyplot import plot
from scipy.stats import linregress

url ='http://gnh.uwaterloo.ca/toronto.csv'
Year, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec = getData(url)

plot(Year,Jan, 'b-')
plot(Year,Jul, 'r-')

a = linregress(Year,Jan) # set slope/intercept to the stats of linregress
slopeJan = a[0]
interceptJan = a[1] # rename them to values for a specific month
b = linregress(Year,Jul)
slopeJul = b[0]
interceptJul = b[1]

plot( Year , slopeJan*Year + interceptJan , 'k-')
plot( Year , slopeJul*Year + interceptJul , 'k-')

report = """
(a) The average annual January temperature increase is %5.3f C / year.
The average annual July temperature increase is %5.3f C / year.
""" % ( slopeJan, slopeJul )
print report

def plotAverage( data ) :
from matplotlib.pyplot import plot
from scipy.stats import linregress

url = 'http://gnh.uwaterloo.ca/toronto.csv'
Year, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec = getData(url)
y1 = annualAverage(toronto) #find the average over each row

plot( Year , y1 )
a = linregress(Year,y1)
slope = a[0]
intercept = a[1]
plot( Year , slope*Year + intercept)

report = """
(b) The average annual temperature increase is %5.3f C / year.
""" % ( slope )
print report

#=========================================================================
from matplotlib.pyplot import clf, savefig, xlabel, ylabel, grid
# Get the data from the supplied url.
toronto = getData( 'http://gnh.uwaterloo.ca/toronto.csv' )

# (a) Plot the January and July temperatures as a function of year.
clf()
plotHotCold( toronto )
xlabel( 'Year', fontsize=16 )
ylabel( 'Temperature', fontsize=16 )
grid( 'on' )

savefig( 'JanJul.png' )

# (b) Plot the mean annual temperature as a function of year.
clf()
plotAverage( toronto )
xlabel( 'Year', fontsize=16 )
ylabel( 'Average Temperature', fontsize=16 )
grid( 'on' )
savefig( 'AnnualAverage.png' )

# (c) Report the boiling and freezing years.

print slope

print """
(c) Extrapolating, Toronto was frozen in the year %-4.0f and will
boil in year %-6.0f.
""" % ( -6000, 2011 ) # not the right answer
mmp
Profile Blog Joined April 2009
United States2130 Posts
Last Edited: 2012-10-14 04:18:58
October 14 2012 04:18 GMT
#3487
Be careful with C/Java comparisons. There are subtle differences. For example:

C:

const MyClass bob = ...;


Java:

final MyClass bob = ...;





What happens when you try the following?

C:

bob = robert;


Java:

bob = robert;





What happens when you try the following?

C:

bob.field = value;


Java:

bob.field = value;





Regarding variable binding, keep in mind that Java has the notion of "clone" that in C is given when you assign by value.


typedef struct {
...
} MyClass;

MyClass a = {...};
MyClass b = a;
a.field = ...;
b.field = ...;


One Java pattern is to work with immutable objects wherever it is reasonable. You can sometimes improve performance with interning. Contrast this with languages like Haskell and Clojure where you're working with side-effect-free functions / immutable data structures ... and these sorts of performance hacks come for free in the compiler.
I (λ (foo) (and (<3 foo) ( T_T foo) (RAGE foo) )) Starcraft
mmp
Profile Blog Joined April 2009
United States2130 Posts
Last Edited: 2012-10-14 04:32:43
October 14 2012 04:25 GMT
#3488
On October 14 2012 12:58 Ian Ian Ian wrote:
I'm taking an intro to python course. This is my first experience with computer programming at all. The course is annoying in the fact that the professor doesn't really explain how things works. He gives us a function and says "solve this physics problem with it". So very often I find myself getting stuck on really stupid things.

Regardless, the problem I'm having is that I have written a couple functions that plot and find the best fit line a set of data that holds Temperature averages for each month for 100 years or so. Afterwards we find the average temperature for each year, plot and find the best fit of that as well. Afterwrads, extrapolate that line and find what year the earth should "freeze" and "boil over".

I've done everything except find a way to code the last part. After I find the slope and intercept of the mean temperature I should just be able use those values to solve a simple y = mx + b equation. But I found and defined the slope and intercept in a function called plotAverage. I run plotAverage and then try to use the slope defined in that function, but it gives me a name error saying slope is not defined. I realize this is because I defined it in the other function and not the one I am currently writing, but how do I use that value without changing my plotAverage function?

The code is as follows, alot of it was written by our professor and we fixed it to do what we want.

+ Show Spoiler +



def getData( url ) :
"""
Retrieves a CSV file from the Interwebs and returns the
columns as a series of vectors.
"""
from urllib import urlretrieve # get a file from a URL
urlretrieve( url , 'tempfile.csv')
from numpy import loadtxt # load a CSV file
return loadtxt( 'tempfile.csv', skiprows=1, unpack=True, delimiter=',' )

def getRow( data, row ) :
"""
Accepts data, a 2D array, and row, a list of one or more row numbers.

Returns the requested row(s) of the data set, omitting the first column
which contains the year rather than a temperature.
"""
# the first column, offset zero, containing the year, is
# *purposefully* excluded
return data[ 1:13 , row ] # colon operator means columns with
# offsets 1-12 inclusive

def getCol( data, column ) :
"""
Accepts data, a 2D array, and column, a list of one or more column numbers.

Returns the requested column(s) of the data set.
"""
return data[ column, : ] # colon operator means 'all' rows

def annualAverage( data ) :
"""
Accepts data, a 2D array.

Returns the average temperature for each row (excluding the year
column, column zero, from the calculation).
"""
from numpy import mean

months = range( 1, 13 ) # month values, 1-12 inclusive
newData = getCol( data, months ) # get the subset of data
return mean( newData, axis=0 ) # average over each rows => axis=0

def plotHotCold( data ) :
from matplotlib.pyplot import plot
from scipy.stats import linregress

url ='http://gnh.uwaterloo.ca/toronto.csv'
Year, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec = getData(url)

plot(Year,Jan, 'b-')
plot(Year,Jul, 'r-')

a = linregress(Year,Jan) # set slope/intercept to the stats of linregress
slopeJan = a[0]
interceptJan = a[1] # rename them to values for a specific month
b = linregress(Year,Jul)
slopeJul = b[0]
interceptJul = b[1]

plot( Year , slopeJan*Year + interceptJan , 'k-')
plot( Year , slopeJul*Year + interceptJul , 'k-')

report = """
(a) The average annual January temperature increase is %5.3f C / year.
The average annual July temperature increase is %5.3f C / year.
""" % ( slopeJan, slopeJul )
print report

def plotAverage( data ) :
from matplotlib.pyplot import plot
from scipy.stats import linregress

url = 'http://gnh.uwaterloo.ca/toronto.csv'
Year, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec = getData(url)
y1 = annualAverage(toronto) #find the average over each row

plot( Year , y1 )
a = linregress(Year,y1)
slope = a[0]
intercept = a[1]
plot( Year , slope*Year + intercept)

report = """
(b) The average annual temperature increase is %5.3f C / year.
""" % ( slope )
print report

#=========================================================================
from matplotlib.pyplot import clf, savefig, xlabel, ylabel, grid
# Get the data from the supplied url.
toronto = getData( 'http://gnh.uwaterloo.ca/toronto.csv' )

# (a) Plot the January and July temperatures as a function of year.
clf()
plotHotCold( toronto )
xlabel( 'Year', fontsize=16 )
ylabel( 'Temperature', fontsize=16 )
grid( 'on' )

savefig( 'JanJul.png' )

# (b) Plot the mean annual temperature as a function of year.
clf()
plotAverage( toronto )
xlabel( 'Year', fontsize=16 )
ylabel( 'Average Temperature', fontsize=16 )
grid( 'on' )
savefig( 'AnnualAverage.png' )

# (c) Report the boiling and freezing years.

print slope

print """
(c) Extrapolating, Toronto was frozen in the year %-4.0f and will
boil in year %-6.0f.
""" % ( -6000, 2011 ) # not the right answer



You define slope in the scope of plotAverage.
You evaluate slope globally, near the end.

Did you mean for slope to be global? If so, use 'global slope' in plot Average to lift the scope of 'slope', but this is sketchy Python practice.
I (λ (foo) (and (<3 foo) ( T_T foo) (RAGE foo) )) Starcraft
mmp
Profile Blog Joined April 2009
United States2130 Posts
Last Edited: 2012-10-14 04:59:42
October 14 2012 04:38 GMT
#3489
Ian Ian Ian,

Why don't you just make your life easier? Decouple the plotting and solving parts of plotAverage.


def solve_linear(data):
reg = linregress(...)
return {'slope': reg[0], 'intercept': reg[1]}


Now, wherever you need the slope or intercept, you can just run solve_linear(data)['slope']. You can also pass this solution into a plot function, so the plot function doesn't have to compute the data series -- you just pass it in by argument.

Similarly, you could probably reduce your various plot functions into a single plot function, where the details are provided as arguments. Then you wouldn't have redundant imports, redundant years, redundant linear plots, redundant printouts.
I (λ (foo) (and (<3 foo) ( T_T foo) (RAGE foo) )) Starcraft
Ian Ian Ian
Profile Blog Joined August 2009
915 Posts
October 14 2012 04:58 GMT
#3490
Again, very beginner programmer. I understand the danger of making it global though. I've never even heard of terms like scope, call, globally before though Ugh I hate this professor.

mmp: Our prof structured most of the stuff for us. If I had to write it all from scratch I probably would do it something more like that.

Thanks to both of you!
mmp
Profile Blog Joined April 2009
United States2130 Posts
October 14 2012 05:04 GMT
#3491
On October 14 2012 13:58 Ian Ian Ian wrote:
Again, very beginner programmer. I understand the danger of making it global though. I've never even heard of terms like scope, call, globally before though Ugh I hate this professor.

mmp: Our prof structured most of the stuff for us. If I had to write it all from scratch I probably would do it something more like that.

Thanks to both of you!

No worries. Python is a very friendly language once you get to know it, but my experience has been that physical scientists don't understand how to write concise, logical code the way software engineers do. As long as it works...

Don't Repeat Yourself. Try to define a function anytime you find yourself rewriting code. I've seen monstrously long Python programs (thousands of repetitious lines!) by very smart researchers who had no clue what they were doing.
I (λ (foo) (and (<3 foo) ( T_T foo) (RAGE foo) )) Starcraft
mmp
Profile Blog Joined April 2009
United States2130 Posts
October 14 2012 05:06 GMT
#3492
Google, StackOverflow can probably answer your queries where your professor cannot.
I (λ (foo) (and (<3 foo) ( T_T foo) (RAGE foo) )) Starcraft
mmp
Profile Blog Joined April 2009
United States2130 Posts
Last Edited: 2012-10-14 05:08:14
October 14 2012 05:07 GMT
#3493
And don't forget to visit docs.python.org.
I (λ (foo) (and (<3 foo) ( T_T foo) (RAGE foo) )) Starcraft
Ian Ian Ian
Profile Blog Joined August 2009
915 Posts
October 14 2012 14:53 GMT
#3494
Yeah the problem with google is that very often I get back an answer that is very very over my head
sluggaslamoo
Profile Blog Joined November 2009
Australia4494 Posts
October 14 2012 19:07 GMT
#3495
On October 14 2012 14:04 mmp wrote:
Show nested quote +
On October 14 2012 13:58 Ian Ian Ian wrote:
Again, very beginner programmer. I understand the danger of making it global though. I've never even heard of terms like scope, call, globally before though Ugh I hate this professor.

mmp: Our prof structured most of the stuff for us. If I had to write it all from scratch I probably would do it something more like that.

Thanks to both of you!

No worries. Python is a very friendly language once you get to know it, but my experience has been that physical scientists don't understand how to write concise, logical code the way software engineers do. As long as it works...

Don't Repeat Yourself. Try to define a function anytime you find yourself rewriting code. I've seen monstrously long Python programs (thousands of repetitious lines!) by very smart researchers who had no clue what they were doing.


Functional decomposition

DRY is something a lot broader and harder to explain.
Come play Android Netrunner - http://www.teamliquid.net/forum/viewmessage.php?topic_id=409008
Frigo
Profile Joined August 2009
Hungary1023 Posts
October 14 2012 20:30 GMT
#3496
Even if it's just a long function, take it apart to meaningfully named functions so it's easier to read. Also, don't reuse local variables, it's the worst possible mistake you can ever make, having the same name refer to two different things.

There are entire books written about the subject of clean code and refactoring. Take a look at Clean Code: A Handbook of Agile Software Craftsmanship to get an idea about why it's important, and how to write easily readable code.
http://www.fimfiction.net/user/Treasure_Chest
sluggaslamoo
Profile Blog Joined November 2009
Australia4494 Posts
Last Edited: 2012-10-14 23:26:31
October 14 2012 23:23 GMT
#3497
On October 15 2012 05:30 Frigo wrote:
Even if it's just a long function, take it apart to meaningfully named functions so it's easier to read. Also, don't reuse local variables, it's the worst possible mistake you can ever make, having the same name refer to two different things.

There are entire books written about the subject of clean code and refactoring. Take a look at Clean Code: A Handbook of Agile Software Craftsmanship to get an idea about why it's important, and how to write easily readable code.


Just to add onto this

Its more about making re-usable functions work together to work as one cohesive whole to fulfil an objective. Don't just break things down into functions that will only ever be used for one specific purpose, try to write functions that can be used for a lot of different things. This requires taking your hands off the keyboard for a bit and having a think about how things will piece together.

I trivial example, would be if you are creating a calculator. Instead of just coding straight away and writing all your logic in the input event handler, think, ok what does a calculator need to do? It can Add Subtract Divide Multiply. So theres 4 functions already.

Maybe after you have gotten your calculator working with the Add function, you create a Sum function that takes an Array for multiple numbers. It shouldn't stop there, we can make Sum more flexible, lets make it accept both an Array OR infinite arguments. (Overloading)

In this case Add becomes unnecessary now, and you can delete that function (deleting code is very important), and just use the Sum function for handling Add as well.

This is a trivial example of the thought process required so you can keep your code base nice and small and easy to maintain.
Come play Android Netrunner - http://www.teamliquid.net/forum/viewmessage.php?topic_id=409008
NeMeSiS3
Profile Blog Joined February 2012
Canada2972 Posts
Last Edited: 2012-10-15 01:56:29
October 15 2012 01:54 GMT
#3498
gah help!!!!

I have my midterm tmr and I've been stressing all night going over previous notes but I'm stuck, this is a previous midterm. (the other questions I got relatively easy)

+ Show Spoiler +
A company sells auto insurance has hired you to write a Java program to help with this.

You decide to begin by writing two java classes. First, you must write a class that can be used to represent the diriver of an automobile; you decide to call that class "Driver" (not to be confused with a "test" driver). For each Driver, you need to know their name and their age.
When a Driver object is first created you must always record their name and their current age.

Provide accessor methods for both Driver attributes. Also provide a mutator method to record the fact that the driver has just had a birthday ( i.e. they are now one year older).

You must also create and automobile class. This class will be used to represent and automobile that is insured by your client's company. For each automobile we need to record the model year (e.g. 2005), and name of the manufacturer(e.g. General Motors). We also need to know who will be the primary driver for the automobile. Include three (and only three) instance variables in the automobile class.

A constructor method should be provided for the automobile class; the constructor willl accept three parameters and use them to inialize the instance variables.

You do NOT need to write the accessor and mutator methods for each instance variable in the automobile class, and you do NOT need to include a toString() method.

However, you do need to provide one accessor method that will calculate and retrieve the insurance amount for the automobile. The base amount that your client's company charges for auto insurance is $900. However, for older automobiles the cost is higher; specifically, for an automobile with a model year prior to 2002 they charge an extra $50. Driver age is also a factor, if the primary driver is under 25 years of age, the company charges an additional $200.

You DO NOT need a test driver program.


I have no idea how to approach the automobile class. Here's what I got so far.

DRIVER
+ Show Spoiler +

public class driver
{      private String name;
      private int age;

      public driver(String nameIn, int ageIn)
       {       name = nameIn;
            age = ageIn;
       }

      public String getName()
      {       return name;
      }      

      public int getAge()
      {       return age;
      }

      public void setAGE(int age)
      { age = age++;
      }



}


AUTOMOBILE
+ Show Spoiler +

public class Automobile {
      private int model;
      private String manufacturer;

      public Automobile(int modelIn, String manufacturerIn)
      {       model = modelIn;
      manufacturer = manufacturerIn;
      }
}
FoTG fighting!
white_horse
Profile Joined July 2010
1019 Posts
Last Edited: 2012-10-15 01:56:45
October 15 2012 01:56 GMT
#3499
Ok guys I have this project where if I input two numbers anywhere between 4 and 1 million, the program outputs all the prime numbers between the two.

Well I got close to it but the program outputs but its really weird still....can you guys help me......

The professor talked about using square root function but I have no idea how.

Here is the computational part:



a is lower limit and b is upper limit.

for (int i = a; i <= b; i++)
{
for (int j = 2; j*j <= i; j++)
{
if (i%2 != 0)
{
cout << i << " is prime" << endl;
}
}
Translator
Abductedonut
Profile Blog Joined December 2010
United States324 Posts
October 15 2012 02:02 GMT
#3500
On October 15 2012 10:56 white_horse wrote:
Ok guys I have this project where if I input two numbers anywhere between 4 and 1 million, the program outputs all the prime numbers between the two.

Well I got close to it but the program outputs but its really weird still....can you guys help me......

The professor talked about using square root function but I have no idea how.

Here is the computational part:



a is lower limit and b is upper limit.

for (int i = a; i <= b; i++)
{
for (int j = 2; j*j <= i; j++)
{
if (i%2 != 0)
{
cout << i << " is prime" << endl;
}
}


What? I am so incredibly confused right now. How is checking if your loop counter is 0 or 1 relevant to whether or not a number is prime?

A prime number is a number that is divisible by only 1 and itself.

How does that code even come remotely close to working? Confused as hell.
Prev 1 173 174 175 176 177 1032 Next
Please log in or register to reply.
Live Events Refresh
WardiTV Korean Royale
12:00
Group Stage 1 - Group B
WardiTV682
TKL 279
Rex110
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
TKL 279
RotterdaM 234
Lowko207
SortOf 125
Rex 110
StarCraft: Brood War
Calm 6256
Hyuk 2587
Soma 508
Stork 414
ZerO 343
Pusan 227
Rush 130
Barracks 126
hero 118
Killer 95
[ Show more ]
sSak 84
Sharp 73
Sea.KH 49
ToSsGirL 42
Noble 42
Aegong 40
Backho 39
zelot 37
Free 33
Icarus 26
Movie 21
Shine 18
Sexy 16
Terrorterran 14
sas.Sziky 1
Dota 2
Dendi583
XaKoH 452
XcaliburYe189
BananaSlamJamma2
Counter-Strike
olofmeister1886
byalli545
edward19
Other Games
B2W.Neo1129
crisheroes289
DeMusliM287
Pyrionflax216
Sick211
ZerO(Twitch)4
Organizations
StarCraft: Brood War
lovetv 13
StarCraft 2
IntoTheiNu 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 12 non-featured ]
StarCraft 2
• Adnapsc2 5
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• lizZardDota241
Upcoming Events
OSC
3h 18m
Replay Cast
10h 18m
Replay Cast
20h 18m
Kung Fu Cup
23h 18m
Classic vs Solar
herO vs Cure
Reynor vs GuMiho
ByuN vs ShoWTimE
Tenacious Turtle Tussle
1d 10h
The PondCast
1d 21h
RSL Revival
1d 21h
Solar vs Zoun
MaxPax vs Bunny
Kung Fu Cup
1d 23h
WardiTV Korean Royale
1d 23h
PiGosaur Monday
2 days
[ Show More ]
RSL Revival
2 days
Classic vs Creator
Cure vs TriGGeR
Kung Fu Cup
2 days
CranKy Ducklings
3 days
RSL Revival
3 days
herO vs Gerald
ByuN vs SHIN
Kung Fu Cup
3 days
BSL 21
4 days
Tarson vs Julia
Doodle vs OldBoy
eOnzErG vs WolFix
StRyKeR vs Aeternum
Sparkling Tuna Cup
4 days
RSL Revival
4 days
Reynor vs sOs
Maru vs Ryung
Kung Fu Cup
4 days
WardiTV Korean Royale
4 days
BSL 21
5 days
JDConan vs Semih
Dragon vs Dienmax
Tech vs NewOcean
TerrOr vs Artosis
Wardi Open
5 days
Monday Night Weeklies
6 days
WardiTV Korean Royale
6 days
Liquipedia Results

Completed

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

Ongoing

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

Upcoming

SLON Tour Season 2
BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
RSL Revival: Season 3
META Madness #9
BLAST Bounty Winter 2026
BLAST Bounty Winter 2026: Closed Qualifier
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
BLAST Rivals Fall 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.