• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 23:11
CET 05:11
KST 13:11
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL22] Finals Preview: Sweet Victory!12[ASL22] Ro4 Preview: Mirror Mirror6[ASL22] Ro8 Preview: Within Reach5[ASL22] Ro8 Preview: In A Tizzy11[ASL22] Ro16 Preview: Holy Diver5
Community News
Weekly Cups (Oct 26 - Nov 1): MaxPax, herO, Solar win0Weekly Cups (October 19-25): Clem triples first in 5.0.175Evil Geniuses - shutting down23ISSL (IntoTheTV x SOOP SC2 League): Premier7Weekly Cups (October 12-18): 5.0.17 era begins1
StarCraft 2
General
[D] Hacker peak in sc2 ? No more SC2 streamers on team liquid? Username Change Request - Toxickej Kapr Liquibets sc2 season 30 Evil Geniuses - shutting down
Tourneys
Sparkling Tuna Cup - Weekly Open Tournament WardiTV Mondays ISSL (IntoTheTV x SOOP SC2 League): Premier Stellar Fest TWO the Moon (Dec 16-20) RSL goes to London! 2026 Offline Finals Nov 21-22
Strategy
[H] ZvP Mid-Late Game: Stalkers Collossi HT
Custom Maps
Starcraft 2 Advance [D] the control group Simple Questions/Answers [G] How to playtest arcade maps
External Content
Mutation # 550 Graveyard Shift The PondCast: SC2 News & Results Mutation # 549 Endless Sparkles Mutation # 548 Shining Bright
Brood War
General
SC4ALL II Brood War Complete Invited Player Lineup Rollback Netcode in Brood War BGH Auto Balance -> http://bghmmr.eu/ Sagi.gg Launcher Released Top Players of October 2026 (EBPD Rankings)
Tourneys
[$1250] International ShieldBattery League [Megathread] Daily Proleagues KCM Race Survival 2026 Season 4 [Mixed-Gender CK] Rush+4 vs Best+4
Strategy
50,000-Word Terran Builds Memo 2026-10-22 Cliff Jump Revisited (1 in a 1000 strategy) Simple Questions, Simple Answers
Other Games
General Games
Stormgate/Frost Giant Megathread Deus Ex 3!? Nintendo Switch Thread Mobile Legends: Bang Bang Armies of Exigo - YesYes?
Dota 2
Dota 2 Champions League Season 3 Begins April 25!
League of Legends
[TL LoL EUW IHs] Teemo shall perish
Heroes of the Storm
Heroes of the Storm 2.0
Hearthstone
Deck construction bug
TL Mafia
TL Mafia Community Thread
Community
General
Things Aren’t Peaceful in Palestine US Politics Mega-thread Canadian Politics Mega-thread Russo-Ukrainian War Thread The Chess Thread
Fan Clubs
Fan Club Resource Thread Reynor Fan Club The Flash Fan Club
Media & Entertainment
Anime Discussion Thread Movie Discussion! [Manga] One Piece
Sports
Football (Soccer) Thread TeamLiquid Health and Fitness Initiative For 2023 MLB/Baseball 2023
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
Recent Gifted Posts
Blogs
Why I built Repalyzer (1.1.…
BlueStar
Innovate or Game Over?
TrAiDoS
ShieldBattery on Mac
Kraekkling
[ASL22] Ro4 Day1 Ticket Giv…
bITt.mAN
Can Bots Beat Pros?? Starcr…
namkraft
Customize Sidebar...

Website Feedback

Closed Threads



Active: 29857 users

The Big Programming Thread - Page 564

Forum Index > General Forum
Post a Reply
Prev 1 562 563 564 565 566 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.
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
Poland17871 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
Poland17871 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 1032 Next
Please log in or register to reply.
Live Events Refresh
OSC
08:00
OSC Elite Rising Star #21
CranKy Ducklings SOOP33
CranKy Ducklings25
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
WinterStarcraft296
RuFF_SC2 177
EnDerr 13
StarCraft: Brood War
Rain 2803
GuemChi 1839
Artosis 497
ProTech149
Dewaltoss 40
Force[name] 7
Icarus 5
League of Legends
Doublelift4947
Counter-Strike
taco 642
Other Games
summit1g10694
singsing1522
Coldzera 847
JimRising 577
C9.Mang0294
XaKoH 275
Maynarde113
ViBE77
NeuroSwarm58
Fuzer 41
Organizations
Other Games
BasetradeTV169
Counter-Strike
PGL114
[ Show 11 non-featured ]
StarCraft 2
• davetesta22
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• Laughngamez YouTube
• Migwel
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Lourlo451
Upcoming Events
IntoTheTV X SOOP
1d 6h
Reynor vs Solar
ByuN vs SHIN
Clem vs MaxPax
herO vs Rogue
IPSL
1d 12h
WorsT vs nOmaD
Dewalt vs andersOn
AI Arena Tournament
1d 14h
IntoTheTV X SOOP
2 days
IPSL
2 days
Azhi_Dahaki vs ggnore13
Double vs WIZARD
Replay Cast
2 days
Replay Cast
3 days
Sparkling Tuna Cup
4 days
WardiTV Invitational
4 days
YoungYakov vs Lambo
SHIN vs TBD
Percival vs Shameless
Solar vs TBD
PiGosaur Cup
4 days
[ Show More ]
The PondCast
6 days
KCM Race Survival
6 days
WardiTV Invitational
6 days
Liquipedia Results

Completed

Proleague 2026-11-04
Blizzard Classic Cup 2026
HCC Season 3

Ongoing

Acropolis #5
KCM Race Survival 2026 Season 4
International ShieldBattery League
BSL Season 23
IPSL Winter 2026-27
Calamity Cup Div. A Season 8
IEM Beijing 2026
PGL Masters Bucharest 2026
Stake Ranked Episode 5
1win Private Club #2
Thunderpick World Champ. '26
ESL Pro League Season 24
Stake Ranked Episode 4
1win Private Club #1
Logitech G Play Connect 2026
SL StarSeries Fall 2026
FISSURE Playground #3
BLAST Open Fall 2026

Upcoming

Sector 951
SC4ALL II: Brood War
BSL 23: Non-Korean Championship
HSC XXX
Stellar Fest 2: Lunar Cup
SC4ALL II: StarCraft II
Kung Fu Cup 2026 Grand Finals
RSL Offline Finals
Underdog Cup 2026 Div 2-3
PGL Bucharest 2027
BLAST Bounty Winter 2027
eXTREMESLAND 2026
PGL Major Singapore 2026
Stake Ranked Episode 6
BLAST Rivals Fall 2026
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2026 TLnet. All Rights Reserved.