• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 12:58
CEST 18:58
KST 01:58
  • 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] Ro16 Preview: Rough Waters10[ASL22] Ro24 Preview: Siren's Call8[ASL22] Ro24 Preview: Summer's End9Serral wins HomeStory Cup 2915Serral wins Maestros of the Game 244
Community News
Weekly Cups (Aug 30-Sep 7): herO thrives amid growing schism10Official StarCraft website teases new content ahead of BlizzCon?134Stellar Fest TWO the Moon (Dec 16-20)9Weekly Cups (August 24-30): Patches' balance mod takes over3New 3v3 BGH Ladder (and more) on ShieldBattery!46
StarCraft 2
General
Balance hotfix patch 5.0.16b (July 16) Team Liquid Map Contest #22: Results and Winners Weekly Cups (Aug 30-Sep 7): herO thrives amid growing schism SC4ALL: II Winner will earn a spot at HSC 30! SC4ALL II: StarCraft 2 Player Announcement 7/8
Tourneys
RSL goes to London! 2026 Offline Finals Nov 21-22 KSL Week #92 IntoTheTV X SOOP SC2 League : Weekly & Monthly 2026 GSTL Announcement Sparkling Tuna Cup - Weekly Open Tournament
Strategy
[G] Having the right mentality to improve
Custom Maps
Nexus Wars 2021 GUIDE [M] (2) Industrial Park
External Content
Mutation # 542 The Ascended Mutation # 541 Binary Choice The PondCast: SC2 News & Results Mutation # 540 Dodge This
Brood War
General
Official StarCraft website teases new content ahead of BlizzCon? BGH Auto Balance -> http://bghmmr.eu/ Practice Partners (Official) Broodwar Prediction Market [D] Brainstorming a balance patch for Brood war
Tourneys
[ASL22] Ro16 Group A [ASL22] Ro16 Group B Escore Tournament - Season 3 Small VOD Thread 2.0
Strategy
Replay Review Process - What do you do? Simple Questions, Simple Answers Odyssey Mineral Stack Saturation Game Theory for Starcraft
Other Games
General Games
Nintendo Switch Thread EVE Corporation Diablo IV [Maplestory Hardcore] Let's Play~!! General RTS Discussion Thread
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
[TL LoL EUW IHs] Teemo shall perish TSM pausing esports and CLG Dead
Heroes of the Storm
Heroes of the Storm 2.0
Hearthstone
Deck construction bug
TL Mafia
TL Mafia Community Thread
Community
General
Things Aren’t Peaceful in Palestine US Politics Mega-thread Trading/Investing Thread Russo-Ukrainian War Thread European Politico-economics QA Mega-thread
Fan Clubs
MarineLorD Fan Club The Creator Fan Club The ShoWTimE Fan Club
Media & Entertainment
Movie Discussion!
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
The Automated Ban List Northern Ireland Global Starcraft
Blogs
Virtual Romance, Real-Life C…
TrAiDoS
Regacy Esports:Our Goa…
regacyesports
Dreaming of BW patches (mod…
c3rberUs
LOCKPICKING NOOB
LUCKY_NOOB
Customize Sidebar...

Website Feedback

Closed Threads



Active: 6028 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
Poland17843 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
Poland17843 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
Next event in 2m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
Tasteless 221
SpeCial 191
BRAT_OK 39
MindelVK 17
StarCraft: Brood War
Britney 30544
Calm 4760
Shuttle 983
firebathero 622
Artosis 379
actioN 232
910 91
Dewaltoss 87
Bonyth 78
Mini 62
[ Show more ]
Liquid`Ret 56
Mong 52
Rock 25
Hm[arnc] 17
Pusan 16
SilentControl 9
Noble 5
Dota 2
qojqva3152
Dendi1467
420jenkins338
LuMiX1
Counter-Strike
fl0m1065
Fnx 625
edward18
Heroes of the Storm
Liquid`Hasu375
Trikslyr1
Other Games
singsing1436
Grubby1353
B2W.Neo821
XaKoH 138
QueenE36
Organizations
Other Games
EGCTV1227
StarCraft 2
StarCraft791
Heroes of the Storm
Heroes of the Storm472
[ Show 16 non-featured ]
StarCraft 2
• 3DClanTV 86
• poizon28 74
• StrangeGG 48
• Migwel
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
StarCraft: Brood War
• Airneanach20
• FirePhoenix10
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• C_a_k_e 4302
League of Legends
• Jankos1716
Other Games
• Shiphtur178
Upcoming Events
AI Arena Tournament
2m
Laughngamez YouTube
OSC
3h 32m
Sparkling Tuna Cup
17h 2m
WardiTV Invitational
18h 2m
ByuN vs Percival
Cure vs Classic
Shopify Rebellion Sundays
22h 2m
Spirit vs Mixu
Clem vs TBD
RSL Revival
23h 2m
Serral vs Rogue
BlizzCon
1d 1h
IdrA vs MC
Replay Cast
1d 7h
Afreeca Starleague
1d 17h
Light vs JyJ
Soulkey vs hero
WardiTV Weekly
1d 18h
[ Show More ]
Monday Night Weeklies
1d 23h
Afreeca Starleague
2 days
Snow vs Shinee
Shine vs EffOrt
GSL
2 days
PiGosaur Cup
3 days
The PondCast
3 days
Kung Fu Cup
3 days
Replay Cast
4 days
KCM Race Survival
4 days
IntoTheTV X SOOP
4 days
Replay Cast
5 days
IntoTheTV X SOOP
5 days
Replay Cast
6 days
GSL
6 days
Liquipedia Results

Completed

Acropolis #5 - TRS
PiG Sty Festival 8.0
Big Dog Cup 2026 Div 1

Ongoing

KCM Race Survival 2026 Season 3
K-JUNGMAN
ASL Season 22
Super Anchor Qualifying S3
CSL 2026 AUTUMN (S22)
Acropolis #5
RSL Revival: Season 6
Calamity Invitational
FISSURE Playground #3
BLAST Open Fall 2026
Esports World Cup 2026
BLAST Bounty Summer 2026
BLAST Bounty Summer Qual
Stake Ranked Episode 3
XSE Pro League 2026

Upcoming

Blizzard Classic Cup 2026
Acropolis #5 - GSA
Acropolis #5 - GSB
Acropolis #5 - GSC
SC4ALL II: Brood War
HSC XXX
Stellar Fest 2: Lunar Cup
SC4ALL II: StarCraft II
Kung Fu Cup 2026 Grand Finals
RSL Offline Finals
Blizzard Classic Cup 2026
PGL Major Singapore 2026
Stake Ranked Episode 6
BLAST Rivals Fall 2026
IEM Beijing 2026
Stake Ranked Episode 5
PGL Masters Bucharest 2026
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
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.