• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 19:57
CEST 01:57
KST 08:57
  • 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
Tournament Spotlight: FEL Cracow 20259Power Rank - Esports World Cup 202577RSL Season 1 - Final Week9[ASL19] Finals Recap: Standing Tall15HomeStory Cup 27 - Info & Preview18
Community News
[BSL 2025] H2 - Team Wars, Weeklies & SB Ladder0EWC 2025 - Replay Pack1Google Play ASL (Season 20) Announced26BSL Team Wars - Bonyth, Dewalt, Hawk & Sziky teams10Weekly Cups (July 14-20): Final Check-up0
StarCraft 2
General
#1: Maru - Greatest Players of All Time EWC 2025 - Replay Pack Tournament Spotlight: FEL Cracow 2025 Power Rank - Esports World Cup 2025 I offer completely free coaching services
Tourneys
FEL Cracov 2025 (July 27) - $10,000 live event Esports World Cup 2025 $25,000 Streamerzone StarCraft Pro Series announced $5,000 WardiTV Summer Championship 2025 WardiTV Mondays
Strategy
How did i lose this ZvP, whats the proper response
Custom Maps
External Content
Mutation # 484 Magnetic Pull Mutation #239 Bad Weather Mutation # 483 Kill Bot Wars Mutation # 482 Wheel of Misfortune
Brood War
General
BEST RECOVERY EXPERTS FOR BITCOIN,CRYPTO,USDT HIRE Google Play ASL (Season 20) Announced [BSL 2025] H2 - Team Wars, Weeklies & SB Ladder [Update] ShieldBattery: 2025 Redesign Dewalt's Show Matches in China
Tourneys
[Megathread] Daily Proleagues [BSL20] Non-Korean Championship 4x BSL + 4x China CSL Xiamen International Invitational [CSLPRO] It's CSLAN Season! - Last Chance
Strategy
Simple Questions, Simple Answers [G] Mineral Boosting Does 1 second matter in StarCraft?
Other Games
General Games
Stormgate/Frost Giant Megathread Nintendo Switch Thread Total Annihilation Server - TAForever [MMORPG] Tree of Savior (Successor of Ragnarok) Path of Exile
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
UK Politics Mega-thread US Politics Mega-thread Stop Killing Games - European Citizens Initiative Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread
Fan Clubs
INnoVation Fan Club SKT1 Classic Fan Club!
Media & Entertainment
Anime Discussion Thread [\m/] Heavy Metal Thread Movie Discussion! [Manga] One Piece Korean Music Discussion
Sports
2024 - 2025 Football Thread Formula 1 Discussion TeamLiquid Health and Fitness Initiative For 2023 NBA General Discussion
World Cup 2022
Tech Support
Installation of Windows 10 suck at "just a moment" Computer Build, Upgrade & Buying Resource Thread
TL Community
TeamLiquid Team Shirt On Sale The Automated Ban List
Blogs
Ping To Win? Pings And Their…
TrAiDoS
momentary artworks from des…
tankgirl
from making sc maps to makin…
Husyelt
StarCraft improvement
iopq
Socialism Anyone?
GreenHorizons
Eight Anniversary as a TL…
Mizenhauer
Customize Sidebar...

Website Feedback

Closed Threads



Active: 637 users

The Big Programming Thread - Page 564

Forum Index > General Forum
Post a Reply
Prev 1 562 563 564 565 566 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.
LaNague
Profile Blog Joined April 2010
Germany9118 Posts
Last Edited: 2015-01-11 22:32:59
January 11 2015 22:32 GMT
#11261
Yeah, essentially the game engine itself needs to be built for multi-threading from the ground up with all the associated overhead


maybe i wrote something wrong, but that was what i meant
Manit0u
Profile Blog Joined August 2004
Poland17255 Posts
January 11 2015 23:13 GMT
#11262
On January 12 2015 07:26 Nesserev wrote:
For the C++ guru's:

Does anyone know if there's a smart pointer design that uses a 'main pointer' that manages the existence of an object, and that can create 'reference pointers', that point to the object managed by the main pointer, and which are also made aware of when the 'main smart pointer' has been deleted (along with the object it managed), and throw exceptions (or some kind of reaction) if there's an attempt to still use them.

Basically, weak/shared pointers, but without the ability to "promote" weak pointers to shared pointers and co-manage the existence of the object, and all the surrounding bs. I guess this behaviour can be mimicked with weak/smart pointers, and that one of the reasons why one should use weak/shared pointers is so that an object isn't deleted while it's being used somewhere else? But, due to the shared ownership and stuff, shared_ptr's feel way too general

The reason why I ask all of this, is because I've been looking into some safe coding for the past two weeks, and more specifically, solutions to cases that lead to invalidated references or dangling pointers.

Sometimes, you just have no other sensible option but to return a reference or a pointer. Move semantics can unintentionally invalidate tons of references on the other side of the program, raw pointers have no way to check if the object that they're supposed to point to still exist, etc.

A lot of these problems are prevented by good code design, but every programmer can make a mistake when code bases tend to become large, and these kind of bugs are very annoying to track and deal with.

Does anyone know of any (active) searches/attempts to solve these problems in coding, or if there's something similar to the smart pointers that I described above? I wish I could stop worrying about invalidated references and dangling pointers.


I'm not very good with C++ but I need to ask out of curiosity: Are you looking to implement something like a singleton?
Time is precious. Waste it wisely.
nunez
Profile Blog Joined February 2011
Norway4003 Posts
Last Edited: 2015-01-11 23:55:53
January 11 2015 23:26 GMT
#11263
edit.

@nesserver
if you are planning on using the object through several references then you need shared ownership.
you promote the weak pointer and share ownership in the block you want to use the object,
then the shared_ptr goes out of scope and only have a weak reference again.

if you are just looking to communicate that an object is destroyed, and not actually
use it, then unique_ptr / raw pointer can do the job. i think this sounds a bit absurd, and i doubt
that this is what you are looking for.

or a bit more contrived:
write a noncopyable wrapper of a shared_ptr, and a wrapper that makes lock private for weak_ptr,
then you can use expired to investigate if it's gone (but you can't use the object, since that would
require shared ownership).

contrived example + bugs.
#include<iostream>
#include<memory>
#include<boost/utility.hpp>

using namespace std;
using boost::noncopyable;

template<class T>
class nesserev_shared_ptr:
public shared_ptr<T>,
noncopyable //no copies
{
using shared_ptr<T>::shared_ptr; //inherit ctor
};

template<class T>
class nesserev_weak_ptr:
public weak_ptr<T>
{
using weak_ptr<T>::weak_ptr; //inherit ctor
using weak_ptr<T>::lock; //disallow lock
};

int
main()
{
nesserev_shared_ptr<int> N(make_shared<int>(4));
// nesserev_shared_ptr<int> M(N); not allower
nesserev_weak_ptr<int> K(N);
// auto M=K.lock(); not allowed
if(!K.expired())
cout<<"good ptr\n";
N.reset();
if(K.expired())
cout<<"bad ptr\n";
}

but i think shared_ptr / weak_ptr is exactly what you are looking for.
conspired against by a confederacy of dunces.
Nesserev
Profile Blog Joined January 2011
Belgium2760 Posts
January 11 2015 23:38 GMT
#11264
--- Nuked ---
nunez
Profile Blog Joined February 2011
Norway4003 Posts
January 11 2015 23:55 GMT
#11265
pointers and references are the shit.
stop your complaining immediately.
conspired against by a confederacy of dunces.
delHospital
Profile Blog Joined December 2010
Poland261 Posts
January 12 2015 00:07 GMT
#11266
On January 10 2015 20:24 berated- wrote:
I've also seen what 15 years of duct tape solutions can do to a code base, especially when developers are coming and going. Some of them were probably good at the boy scout method (leaving it better than you found it ) type of approach that you mention. Others struggle... making changes is extremely difficult because being able to read the code and comprehend the effect of change you are introducing is either extremely time consuming or too difficult without giving up and pitching a rewrite.

What a great opportunity for some more language bashing. "Easy to reason about" is the #1 thing I like about languages like C and Haskell. C code does what it says on the cover and discourages too much abstraction. Haskell, on the other hand, is all about abstraction. However, the strong type system requires you to be very honest about it.

Let's say you encounter something that looks like a hand-written sort, and you're wondering if it can be replaced with a call to a library function. In a language like C++ you'd have to dig really deep to determine whether that's safe to do. How is the comparison operator of the template parameter implemented? Maybe the code will only work correctly when the operator is called a certain number of times? Or maybe something weird happens at assignment?

In C there's no templates. The function most likely works on a single type, and everything is in plain sight. In Haskell the comparison operator is a function in the mathematical sense -- it looks at two objects, and returns a boolean. No place for trickery. So you just look at the sorting code, say "yep, that's a sort", and replace it with a library function call.
nunez
Profile Blog Joined February 2011
Norway4003 Posts
Last Edited: 2015-01-12 00:49:14
January 12 2015 00:22 GMT
#11267
this confusion is unacceptable.

you can not equivocate a function with a function template in this context.
a function template is not a function: it's a set of functions.

with this confusion is out of the way, surely you will see how C++
is indeed way superior in this respect. if the function template describes
a set of cardinality 1, then C and C++ are equivalent.

however if the function template describes a set of larger cardinality,
then you are sitting pretty with C++ relative to the C equivalent,
as only in the worst case would you have to inspect all the functions,
unlike in C. and all this at no performance cost.

humble yourself.

edit:
finally i note that having to go to the trouble of reading the function definition
to assert the semantic of a function applies to functions and operators alike,
regardless of if it is a template specialization.
conspired against by a confederacy of dunces.
delHospital
Profile Blog Joined December 2010
Poland261 Posts
January 12 2015 00:52 GMT
#11268
On January 12 2015 09:22 nunez wrote:
this confusion is unacceptable.

you can not equivocate a function with a function template in this context.
a function template is not a function: it's a set of functions.

It is a function. A polymorphic one.

with this confusion is out of the way, surely you will see how C++
is indeed way superior in this respect. if the function template describes
a set of cardinality 1, then C and C++ are equivalent.

however if the function template describes a set of larger cardinality,
then you are sitting pretty with C++, as only in the worst case would you have
to inspect all the functions, unlike in C. and all this at no performance cost.

In C++ you usually have more abstractions than in C. It's a trade-off, and I side with C here.
nunez
Profile Blog Joined February 2011
Norway4003 Posts
Last Edited: 2015-01-12 02:02:39
January 12 2015 01:28 GMT
#11269
listen...

you made a point comparing a function template to a function.
for your comparison to make sense, by function template, you are either
referring to one element in the set it describes, where the template arguments
corresponds to the types of the arguments of the function, or, you
are talking about the function as a set of functions containing only that function.

in the first case we are talking about two functions, in the second case
we are talking about two sets of functions.

both implementations are viable in C++, only one is viable in C. you are siding
with the latter implementation... but for this to be a meaningful statement
we need more context.

however it doesn't say anything about C++ compared to C,
beyond that you have more tools to work with in C++.

edit:

'tis a great sin indeed, before any problem has presented itself,
to you restrict your toolbox, mistaking confusion about the nature of these tools
for a sense of superiority.

and 'tis a righteous humiliation then, that the problem you haughtily described to justify your folly
is solved more easily with the tools you threw away in all but one scenario, and here they are equivalent.

humble yourselves in the sight of the GCC, and he shall humiliate you nonetheless.

unto me, who am less than the least of all programmers,
is this grace given, that i should preach among the heretics
the unsearchable riches of C++ templates.
conspired against by a confederacy of dunces.
delHospital
Profile Blog Joined December 2010
Poland261 Posts
January 12 2015 02:02 GMT
#11270
I'm not talking about a syntactic translation of C++ code to C. In C you do with fewer abstractions, and more concrete stuff instead. The C function could've taken a void pointer, and a comparison function int (*)(void *, void *), but a concrete implementation is much more common. 8 classes and 3000 lines of generic C++ code translate to 4 structs and 5000 lines of more specialized code in C.

Code that's hacks on top of hacks until it works (90% of code out there) will break a lot of expectations. In the case of a template function in C++ you have to inspect a lot of code to be sure that two implementations of that function are "equivalent". There is no direct translation of that template function to C, because in C the entire program is structured differently. When you look at a piece of that hypothetical C code, it is comparatively easier to determine whether it is equivalent to something else.

This makes C easier to reason about than C++ (this is all assuming that you can't rely on a good test suite, well documented code base, etc.).
nunez
Profile Blog Joined February 2011
Norway4003 Posts
Last Edited: 2015-01-12 02:36:11
January 12 2015 02:20 GMT
#11271
if the function is taking void* and void* to int, then the instantiation of the function template we are comparing this function to is also taking void* and void* to int. you are consistently missing the point, and attempting to make an absurd comparison.

i knew from your initial post that your point would eventually disolve into a pointless truism: complex code is more complex.

what is notable however is that in your confusion you mistook this truism for something substantive that relates C++ and C, and that you underlined this mistake with an example that, without more context (like a constraint on the cardinality of the set, complexity of the function, ...), goes to show the opposite of the point you should have been making in the first place (about implementation, not langauge). which could have been a valuable observation, or an invitation to a more involved discussion, given a more specific problem.

however i beg you to stop instantiating your template inferiority complex.

btw: i didn't see micronesia make a post about it here, tictactoe ai - python, in case anyone missed out.
conspired against by a confederacy of dunces.
delHospital
Profile Blog Joined December 2010
Poland261 Posts
Last Edited: 2015-01-12 04:13:39
January 12 2015 03:52 GMT
#11272
No need to be so hostile. Maybe this example will make it clearer. I installed g++ just for you

C++ code (The example is stupid, I admit. Take a deep breath):
+ Show Spoiler +
#include <cstdio>
#include <vector>
#include <iostream>

int x=0;

class A {
public:
int a;
A(int v) : a(v) { }
bool operator<(const A& rhs) const {
return a > rhs.a;
}
};

class B {
public:
int b;
B(int v) : b(v) { }
bool operator<(const B& rhs) const {
x += b;
return b < rhs.b;
}
};

template<class T>
void f(std::vector<T>& ts) {
for (int i=0; i<ts.size(); i++) {
for (int j=i+1; j<ts.size(); j++) {
if (ts[j] < ts[i]) {
T tmp = ts[j];
ts[j] = ts[i];
ts[i] = tmp;
}
}
}
}

int main() {
std::vector<A> as;
std::vector<B> bs;
int n=4;
while (n--) {
int v;
std::cin >> v;
as.push_back(A(v));
bs.push_back(B(v));
}
f(as), f(bs);
printf("min a: %d\nmin b: %d\nx: %d\n", as[0].a, bs[0].b, x);
return 0;
}


If you run it and pass it four integers, it will print the maximum, minimum, and a weird sum.

Equivalent C code:
+ Show Spoiler +
#include <stdio.h>

int x=0;

struct A {
int a;
};

struct B {
int b;
};

void fa(struct A *ts, int len) {
int i, j;
for (i=0; i<len; i++) {
for (j=i+1; j<len; j++) {
if (ts[j].a > ts[i].a) {
struct A tmp = ts[j];
ts[j] = ts[i];
ts[i] = tmp;
}
}
}
}

void fb(struct B *ts, int len) {
int i, j;
for (i=0; i<len; i++) {
for (j=i+1; j<len; j++) {
x += ts[j].b;
if (ts[j].b < ts[i].b) {
struct B tmp = ts[j];
ts[j] = ts[i];
ts[i] = tmp;
}
}
}
}

int main(void) {
struct A as[4];
struct B bs[4];
int n=4;
int i;
for (i=0; i<n; i++) {
int v;
struct A a;
struct B b;
scanf("%d", &v);
a.a = v, b.b = v;
as[i] = a;
bs[i] = b;
}
fa(as, n), fb(bs, n);
printf("min a: %d\nmin b: %d\nx: %d\n", as[0].a, bs[0].b, x);
return 0;
}


If you look at the C++ code, it looks like f's body could be replaced with a call to std::sort(ts.begin(), ts.end())... until you dig deep enough to discover what B::operator< does...

In C, passing dictionaries of functions that each type implements wouldn't be in the spirit of C. I'm sure you'll agree that functions are passed around much less often in C than objects (with their vpointers) in C++. Instead I did the C thing and implemented separate 'f's for struct A and struct B. I look at 'fa', can it be replaced with a call to qsort? Yes, it can, and I didn't have to look anywhere else to make sure. Can I do the same with 'fb'? Of course not, and I didn't need to look anywhere else to realize this.

C is easier to reason about than C++.

Edit: This example doesn't really show the difference in the amount of code you'd have to look at in C and C++ to make sure that it's safe to replace the function body with a call to 'sort'. But imagine the same in an actual project, the code base of which you're not familiar with. In C, to determine if a seemingly innocent change breaks anything, you'd have to look at that one function, and maybe a couple functions it calls. In C++ you'd have to check a billion classes.

Also, this has nothing to do with templates or C++ in particular. Just OO languages in general lending to spaghetti code (which OO lovers call design patterns or something like that).
nunez
Profile Blog Joined February 2011
Norway4003 Posts
Last Edited: 2015-01-12 06:11:10
January 12 2015 04:47 GMT
#11273
you will forgive my temper, but your lack of humility combined with flagrant ignorance, is an insult to GCC and thus an insult to me personally. you are mixing templates, function / operator overloading, and object oriented programming, the latter i know little about, but the two former are independent of the latter, and templates was the topic i responded to.

your example is unfair and imprecise wrt to templates, and your conclusion is unfair to overloading.

here's an equivalent example using templates (C with templates),
where f<T> = {f<A>, f<B>} ~ {fa, fb}, or alternatively f<A> ~ fa && f<B> ~ fb:
#include<cstdio>

int x=0;

struct
A
{ int a; };

struct
B
{ int b; };

template<class T>
void f(T* ts,int len);

template<>
void f<A>(A *ts,int len){
int i, j;
for (i=0; i<len; i++) {
for (j=i+1; j<len; j++) {
if (ts[j].a > ts[i].a) {
A tmp = ts[j];
ts[j] = ts[i];
ts[i] = tmp;
}
}
}
}

template<>
void f<B>(B *ts,int len){
int i, j;
for (i=0; i<len; i++) {
for (j=i+1; j<len; j++) {
x += ts[j].b;
if (ts[j].b < ts[i].b) {
B tmp = ts[j];
ts[j] = ts[i];
ts[i] = tmp;
}
}
}
}

int main(void) {
A as[4];
B bs[4];
int n=4;
int i;
for (i=0; i<n; i++) {
int v;
A a;
B b;
scanf("%d", &v);
a.a = v, b.b = v;
as[i] = a;
bs[i] = b;
}
f(as, n), f(bs, n);
printf("min a: %d\nmin b: %d\nx: %d\n", as[0].a, bs[0].b, x);
return 0;
}

in this instance you would have to inspect 2 functions in either case, it's equivalent to the function implementation.
this is the worst case scenario for templates, and in any other instance it has the upper hand.

as for function and operator overloading: when you call a binary operator on user defined types, its semantic equivalent is calling a binary function in C (the semantic equivalent of a binary operator on primitive types in C is exactly that same binary operator on primitive types in C++). regardless of if it's a function or operator, and regardless of name or token you would have to inspect its definition to assert its semantic, as i have noted earlier. this is a basic insight into the language, failure to recognize this shall not be mistaken as a shortcoming of the code.

edit: i feel the need to step out of character for a second and add in closing that i like C, a most excellent subset of C++ (the highest of praise) and then some, polaks in general and tlers in particular. do not take my hyperbole too seriously, i am entertaining myself; i am not crazy.
conspired against by a confederacy of dunces.
delHospital
Profile Blog Joined December 2010
Poland261 Posts
January 12 2015 08:21 GMT
#11274
On January 12 2015 13:47 nunez wrote:
you will forgive my temper, but your lack of humility combined with flagrant ignorance, is an insult to GCC and thus an insult to me personally. you are mixing templates, function / operator overloading, and object oriented programming, the latter i know little about, but the two former are independent of the latter, and templates was the topic i responded to.

Templates (which give us parametric polymorphism) are "harmless" in isolation, and so is function/operator overloading (which gives us ad-hoc polymorphism). However the combination of the two, or OOP just by itself, gives us something that isn't possible in pure C without passing around (dictionaries of) functions -- which is an uncommon sight in C, compared to how common classes or templates+overloaded functions are in C++. So, in my defense, it does make sense to talk about all of these concepts at once.

I claim that these features encourage (or maybe even force) a certain style of programming that makes determining what effect a small change will have on other parts of the system much harder (again, assuming that you can only trust the code, and the code may be full of hacks). You're right that my example was flawed, and I won't make another unsuccessful attempt at proving my hypothesis.
nunez
Profile Blog Joined February 2011
Norway4003 Posts
Last Edited: 2015-01-12 09:27:43
January 12 2015 09:20 GMT
#11275
overloading and templates are all resolved transparently at compile-time,
and have exact equivalents in C or non-overloaded, non-template C++,
both on their own and combined:

simply substitute the overloads that would be selected
and the function template instantations with regular non-overloaded,
non-template function calls:

instead of team<T> (T:={int, float)) you write { team_i(int), team_f(float) }
instead of { liquid(int), liquid(float) } you write { liquid_i(int), liquid_f(float) }.

completely possible in C, and will compile to same code, assuming the functions are equivalent.
conspired against by a confederacy of dunces.
Manit0u
Profile Blog Joined August 2004
Poland17255 Posts
Last Edited: 2015-01-12 09:44:09
January 12 2015 09:37 GMT
#11276
I have a weir problem on the server...

.htaccess file

RewriteCond %{HTTPS} off
RewriteRule ^/admin/login$ [url=https://%{HTTP_HOST}%{REQUEST_URI}]https://%{HTTP_HOST}%{REQUEST_URI}[/url] [L, R=301]


I've tried every single mod rewrite way of forcing ssl on the login pages I was able to find on the net to no avail. The only thing that really "worked" was:


Redirect 301 ^/admin/login$ [url=https://%{HTTP_HOST}%{REQUEST_URI}]https://%{HTTP_HOST}%{REQUEST_URI}[/url]


This ends in an infinite loop though so not that good. Do any of you know of a different way of doing it? Just fire away, maybe you'll post a solution I didn't come across yet. God how I despise Apache server...

Heh, the code tag does funny things if you put urls in there.
Time is precious. Waste it wisely.
delHospital
Profile Blog Joined December 2010
Poland261 Posts
Last Edited: 2015-01-12 16:20:27
January 12 2015 09:52 GMT
#11277
On January 12 2015 18:20 nunez wrote:
overloading and templates are all resolved transparently at compile-time,
and have exact equivalents in C or non-overloaded, non-template C++,
both on their own and combined:

simply substitute the overloads that would be selected
and the function template instantations with regular non-overloaded,
non-template function calls:

instead of team<T> (T:={int, float)) you write { team_i(int), team_f(float) }
instead of { liquid(int), liquid(float) } you write { liquid_i(int), liquid_f(float) }.

completely possible in C, and will compile to same code, assuming the functions are equivalent.

Yeah, templates+overloading is just compile time power (and so is Haskell's implementation of polymorphism umm, not always), but it's not to be underestimated. They are what makes all of STL's data structures and algorithms possible. There's a lot of cases in C++ where you just reach for a generic data structure, because it does what you need (and a lot more), while in C, instead of going for a 1:1 translation of that C++ code, you'd hand-craft something much more primitive.
nunez
Profile Blog Joined February 2011
Norway4003 Posts
January 12 2015 10:33 GMT
#11278
yes, or the opposite, in C++ you handcraft, in C you grab a generic library.
might be easier to handcraft in C++ as well, who knows.
you can be as primitive, or generic as you like in both langauges.

when to implement yourself, when to use a library?
a pointless question... too abstract.
conspired against by a confederacy of dunces.
solidbebe
Profile Blog Joined November 2010
Netherlands4921 Posts
Last Edited: 2015-01-13 08:16:41
January 13 2015 00:09 GMT
#11279
In general what do you guys think of recursion?

For instance: were making a footballmanager game for a project, and I had to write a method which would select the player with the highest stat (of defense, attack or somthing like that) which was also available and not on the field yet.

I wrote something like this:

public Player findMaxAvailableAttacker(Team team){
if(team.size() > 0){ //check if arrayList is not empty
Player res = team.get(0);
for(int i = 0; i < team.size(); i++){ //find player with highest stat
if(team.get(i).getAtt() > res.getAtt()){
res = team.get(i);
}
}
if(res.getAvailable() && res.notOnField()){
return res;
} else {
team.remove(res);
return findMaxAvailableAttacker(team);
}
}
return null;
}


Is this a good solution, or perhaps too verbose? Is it better to break down to for loops?

*EDIT* please dont mind the horrible formatting, it took a while before i discovered the [code] tags
That's the 2nd time in a week I've seen someone sig a quote from this GD and I have never witnessed a sig quote happen in my TL history ever before. -Najda
Khalum
Profile Joined September 2010
Austria831 Posts
Last Edited: 2015-01-13 01:44:24
January 13 2015 00:37 GMT
#11280
This is not a case where you need recursion at all.

I'll not write code for you but what you have here are actually three tasks:
1) Find available players
2) Find players that are not on the field
3) Find the player with the best attack value ( I guess that's what getAtt() does )

Implementing these and combining them would lead to a solution that also lets you re-use code instead of one function that does everything.
Prev 1 562 563 564 565 566 1031 Next
Please log in or register to reply.
Live Events Refresh
Next event in 11h 3m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Nina 172
Ketroc 38
StarCraft: Brood War
NaDa 52
MaD[AoV]19
Dota 2
capcasts410
League of Legends
Grubby4748
febbydoto20
Counter-Strike
Fnx 2317
fl0m2106
Stewie2K913
flusha379
Super Smash Bros
hungrybox3444
Mew2King1256
AZ_Axe390
Heroes of the Storm
Khaldor230
Other Games
tarik_tv21770
summit1g15354
gofns9771
JimRising 621
ROOTCatZ307
Maynarde164
Organizations
Other Games
gamesdonequick3098
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 16 non-featured ]
StarCraft 2
• davetesta115
• intothetv
• AfreecaTV YouTube
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• Azhi_Dahaki16
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Stormgate
• mYiSmile10
League of Legends
• Doublelift6703
Other Games
• Scarra2248
• imaqtpie1565
Upcoming Events
Wardi Open
11h 3m
Sparkling Tuna Cup
1d 10h
WardiTV European League
1d 16h
Online Event
1d 17h
uThermal 2v2 Circuit
2 days
The PondCast
3 days
Replay Cast
4 days
Korean StarCraft League
5 days
CranKy Ducklings
5 days
Sparkling Tuna Cup
6 days
Liquipedia Results

Completed

CSLPRO Last Chance 2025
Esports World Cup 2025
Murky Cup #2

Ongoing

Copa Latinoamericana 4
Jiahua Invitational
BSL 20 Non-Korean Championship
BSL 20 Team Wars
CC Div. A S7
Underdog Cup #2
IEM Cologne 2025
FISSURE Playground #1
BLAST.tv Austin Major 2025
ESL Impact League Season 7
IEM Dallas 2025
PGL Astana 2025
Asian Champions League '25

Upcoming

ASL Season 20: Qualifier #1
ASL Season 20: Qualifier #2
ASL Season 20
CSLPRO Chat StarLAN 3
BSL Season 21
RSL Revival: Season 2
Maestros of the Game
SEL Season 2 Championship
WardiTV Summer 2025
uThermal 2v2 Main Event
HCC Europe
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
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.