• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 12:15
CEST 18:15
KST 01:15
  • 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?133Stellar 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
Trading/Investing Thread US Politics Mega-thread Things Aren’t Peaceful in Palestine 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: 6840 users

The Big Programming Thread - Page 565

Forum Index > General Forum
Post a Reply
Prev 1 563 564 565 566 567 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.
nunez
Profile Blog Joined February 2011
Norway4003 Posts
Last Edited: 2015-01-13 02:57:07
January 13 2015 02:56 GMT
#11281
i thought your code was easily readable, and i had no problem understanding what your function did.
i suspect that it might be a bit inefficient however, but maybe this is not a problem at all.

recursion is sweet in general.
did you consider no recursion as well? maybe something along the lines of this? (disclaimer i not java)

public Player findMaxAvailableAttacker(Team team){
Player res = team.get(0);
for(int i = 0; i < team.size(); i++){ //find player with highest stat
Player cand=team.get(i);
if(cand.getAvailable()||cand.notOnField()){
if(res==null||res.getAtt()<cand.getAtt()){
res=cand;
}
}
}
return res;
}
conspired against by a confederacy of dunces.
nunez
Profile Blog Joined February 2011
Norway4003 Posts
Last Edited: 2015-01-13 06:32:17
January 13 2015 05:54 GMT
#11282
wanted rational approximations of sin x and cos x for some pet project,
wrote a function to generate the coefficients of the polynomial in the numerator of
their maclaurin series represented as a fraction.

when i say "order" i really mean N, where the order of the polynomial is 2*N for cos and 2*N+1 for sine...

maclaurin series of "order" N as a fraction with (alpha_pi = phi_max for convenience):
[image loading]
[image loading]

cosine:
[image loading]
[image loading]
[image loading]

sine:
[image loading]
[image loading]
[image loading]

work in progress, but posting this now since i thought the immediate results looked neat!
didn't compare them to a proper reference though, but will do that later.
maybe some of you can spot some errors or propose alternate approach in code or math.

plots for various pi fractions and orders (pi fraction used for orders up to overflow),
plotted over -alpha_pi to alpha_pi, with a step of 2*alpha/256.

cosines[N, alpha_pi / beta_pi]
+ Show Spoiler [0, 355/113] +
[image loading]

+ Show Spoiler [1, 355/113] +
[image loading]

+ Show Spoiler [2, 355/113] +
[image loading]

+ Show Spoiler [3, 355/113] +
[image loading]

+ Show Spoiler [4, 22/7] +
[image loading]

+ Show Spoiler [5, 22/7] +
[image loading]

+ Show Spoiler [6, 13/4] +
[image loading]

+ Show Spoiler [7, 3/1] +
[image loading]

+ Show Spoiler [8, 3/1] +
[image loading]


sines[N, alpha_pi / beta_pi]
+ Show Spoiler [0, 355/113] +
[image loading]

+ Show Spoiler [1, 355/113] +
[image loading]

+ Show Spoiler [2, 355/113] +
[image loading]

+ Show Spoiler [3, 355/113] +
[image loading]

+ Show Spoiler [4, 22/7] +
[image loading]

+ Show Spoiler [5, 22/7] +
[image loading]

+ Show Spoiler [6, 13/4] +
[image loading]

+ Show Spoiler [7, 3/1] +
[image loading]

+ Show Spoiler [8, 3/1] +
[image loading]


ghetto code
+ Show Spoiler [plot.sh] +
#!/bin/sh
order=$1

/usr/bin/gnuplot -p << EOF
set terminal png size 640 480
set term png font "OpenSans-Regular,8"
set obj 1 rectangle behind from screen 0,0 to screen 1,1
set obj 1 fillstyle solid 1.0 fillcolor rgbcolor "white"
set title "${order} maclaurin series of cosine with rational approxmation to pi"
set output 'cosine${order}.png'
plot 'cosine${order}.dat' using 1:2 with linespoints lc rgbcolor "black"
set title "${order} maclaurin series of sine with rational approxmation to pi"
set output 'sine${order}.png'
plot 'sine${order}.dat' using 1:2 with linespoints lc rgbcolor "black"
EOF

+ Show Spoiler [work.cpp] +
#include<algorithm>
#include<iostream>
#include<iterator>
#include<fstream>
#include<numeric>
#include<string>
#include<utility>
#include<vector>

template<class value_type>
value_type
power(value_type argument,unsigned int exponent)
{ return (exponent==0)?1:argument*power(argument,exponent-1); }

namespace maclaurin{namespace guts{

struct sine{};
struct cosine{};

//generate {beta_0, ..., beta_N}, done in reverse since beta_i-1 = beta_i * beta_pi
template<class value_type>
std::vector<value_type>
make_beta_sequence(value_type beta,unsigned int order)
{
std::vector<value_type> beta_sequence(order+1);
value_type variable{1};
std::generate(
beta_sequence.rbegin(),
beta_sequence.rend(),
[&]{
auto tmp=variable;
variable*=(beta*beta);
return tmp;
}
);
return beta_sequence;
}

constexpr unsigned int index_delta{2};

//only difference twixt sine and cosine coefficients for the
//pi seuuence is the last index. last because we are generating
//them in reverse...

template<class tag>
constexpr unsigned int
last_index(unsigned int);

template<>
constexpr unsigned int
last_index<sine>(unsigned int order)
{ return index_delta*order+1; }

template<>
constexpr unsigned int
last_index<cosine>(unsigned int order)
{ return index_delta*order; }

//generate product sequence {product_0, ..., product_t}, done in reverse
template<class tag,class value_type>
std::vector<value_type>
make_pi_sequence(unsigned int order)
{
std::vector<value_type> pi_sequence(order+1);

unsigned int index{last_index<tag>(order)};
value_type variable{1};
std::generate(
pi_sequence.rbegin(),
pi_sequence.rend(),
[&]{
auto tmp=variable;
for(unsigned int iterator=0;iterator<index_delta;++iterator,--index)
variable*=index;
return tmp;
}
);
return pi_sequence;
}

//generate coefficient sequence
//coefficient_i = (-1)^i * beta_i * pi_i
template<class tag,class value_type>
std::vector<value_type>
make_coefficient_sequence(value_type beta,unsigned int order)
{
auto beta_sequence{make_beta_sequence(beta,order)};
auto pi_sequence{make_pi_sequence<tag,value_type>(order)};
short sign{-1};

auto& coefficient_sequence{beta_sequence}; //generate sequence in place
std::transform(
std::begin(pi_sequence),
std::end(pi_sequence),
std::begin(beta_sequence),
std::begin(coefficient_sequence),
[&](auto pi_i,auto beta_i){
sign*=-1;
return sign*pi_i*beta_i;
}
);

return coefficient_sequence;
}

}

//function aliases for make_coefficient_sequence with sine and cosine tags
template<class value_type>
constexpr auto sine=guts::make_coefficient_sequence<guts::sine,value_type>;

template<class value_type>
constexpr auto cosine=guts::make_coefficient_sequence<guts::cosine,value_type>;

}

int
main()
{
using namespace std;
unsigned int order;
long alpha;
long beta;
cout<<"enter pi fraction numerator: ";
cin>>alpha;
cout<<"enter pi fraction denominator: ";
cin>>beta;

unsigned int resolution{256};

vector<double> coordinates(resolution+1);

{
unsigned int iterator{0};
generate(
begin(coordinates),
end(coordinates),
[&]{ return -alpha+(double)2*alpha*iterator++/resolution; }
);
}

cout<<"enter order: "; cin>>order;
{
string filename(string("sine")+to_string(order)+".dat");
ofstream file(filename.c_str());

auto sine_sequence=maclaurin::sine<long>(beta,order);
cout<<"\nsine sequence: ";
copy(begin(sine_sequence),end(sine_sequence),ostream_iterator<long>(cout," "));
cout<<endl;

file<<"#x y\n";

//for sine the denominator is coefficient_0*beta
auto denominator=sine_sequence.front()*beta;
for(auto coordinate:coordinates){
int index{0};
long numerator{0};
for(auto coefficient:sine_sequence){
numerator+=coefficient*power(coordinate,2*index+1);
index++;
}
file<<coordinate<<" "<<((double)(numerator))/(denominator)<<endl;
}
}{
string filename(string("cosine")+to_string(order)+".dat");
ofstream file(filename.c_str());

auto cosine_sequence=maclaurin::cosine<long>(beta,order);
cout<<"\ncosine sequence: ";
copy(begin(cosine_sequence),end(cosine_sequence),ostream_iterator<long>(cout," "));
cout<<endl;

file<<"#x y\n";
//for cosine thedenominator is just coefficient_0
auto denominator=cosine_sequence.front();
for(auto coordinate:coordinates){
int index{0};
long numerator{0};
for(auto coefficient:cosine_sequence){
numerator+=coefficient*power(coordinate,2*index);
index++;
}
file<<coordinate<<" "<<((double)(numerator))/denominator<<endl;
}
}
}

+ Show Spoiler [makefile] +
CXX = g++-5.0
CXXFLAGS = -std=c++14 -I. -I../ -Wfatal-errors -fdiagnostics-color -fmessage-length=64 -O2
LDFLAGS = -lpthread -lrt


all: work clean

work:work.o
$(CXX) -o $@ $^ $(LDFLAGS)

work.o:work.cpp
$(CXX) -c $(CXXFLAGS) $<

.PHONY: clean

clean:
rm -rf *.o


ref
rational pi approximations
conspired against by a confederacy of dunces.
Deleted User 101379
Profile Blog Joined August 2010
4849 Posts
Last Edited: 2015-01-13 08:21:43
January 13 2015 08:21 GMT
#11283
On January 13 2015 09:09 solidbebe wrote:
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



For everything solved with recursion, there is a more efficient and prettier solution that is not using recursion.

The only place where I consider recursion good is tree traversal, e.g. going through directory trees or branches of decision trees. In all other cases, forget recursion. It sounds nifty when you can say "I used recursion to solve this", but usually it means "I used a less efficient and less readable solution for the problem because I couldn't think of a good solution".


public Player findMaxAvailableAttacker(Team team)
{
Player res = null;
for (int i = 0; i < team.size(); ++i)
{
Player player = team.get(i);
if (player.getAvailable() || player.notOnField())
{
if ((res == null) || (player.getAtt() > res.getAtt()) {
res = player;
}
}
}
return res;
}


(Code not tested)
Cyx.
Profile Joined November 2010
Canada806 Posts
January 13 2015 08:57 GMT
#11284
On January 13 2015 17:21 Morfildur wrote:
For everything solved with recursion, there is a more efficient and prettier solution that is not using recursion.

The only place where I consider recursion good is tree traversal, e.g. going through directory trees or branches of decision trees. In all other cases, forget recursion. It sounds nifty when you can say "I used recursion to solve this", but usually it means "I used a less efficient and less readable solution for the problem because I couldn't think of a good solution".


public Player findMaxAvailableAttacker(Team team)
{
Player res = null;
for (int i = 0; i < team.size(); ++i)
{
Player player = team.get(i);
if (player.getAvailable() || player.notOnField())
{
if ((res == null) || (player.getAtt() > res.getAtt()) {
res = player;
}
}
}
return res;
}


(Code not tested)

I'm not 100% convinced of 'for everything solved with recursion...' but I really agree in this situation, this is wayyy more legible to me than the recursive version.
Manit0u
Profile Blog Joined August 2004
Poland17843 Posts
Last Edited: 2015-01-13 09:11:39
January 13 2015 09:06 GMT
#11285
It would be even nicer and more legible with foreach through a list. But that's just my opinion.


public Player findMaxAvailableAttacker(Team team)
{
Player res = null;

for (Player player : team) {
if (player.getAvailable() || player.notOnField()) {
if ((res == null) || (player.getAtt() > res.getAtt()) {
res = player;
}
}
}

return res;
}
Time is precious. Waste it wisely.
MaGariShun
Profile Joined May 2010
Austria305 Posts
January 13 2015 09:22 GMT
#11286
On January 13 2015 17:21 Morfildur wrote:
For everything solved with recursion, there is a more efficient and prettier solution that is not using recursion.

The only place where I consider recursion good is tree traversal, e.g. going through directory trees or branches of decision trees. In all other cases, forget recursion. It sounds nifty when you can say "I used recursion to solve this", but usually it means "I used a less efficient and less readable solution for the problem because I couldn't think of a good solution".

Not necessarily.
What you are saying certainly applies to the most common C-Style imperative languages like Java, C++ etc. If the language of your choice supports tail recursion however, it's not less efficient *. Some programming languages (generally functional ones) favour recursion over iteration e.g. Haskell, Scheme.

The solution being 'pretty' is personal opinion, and while I side with you simply because I am used to an imperative programming style, I have no trouble believing that for some people (presumably the more mathematically inclined) the recursive approach is prettier.


* Tail recursion basically is when the compiler automatically recognizes a recursive function call at the end of a function and optimizes it to iterative code, thus eliminating the creation and preservation of stack frames, which is what makes recursion expensive in traditional languages.
solidbebe
Profile Blog Joined November 2010
Netherlands4921 Posts
January 13 2015 12:11 GMT
#11287
Thanks for your comments everyone . I find its pretty difficult to assess my own solutions to problems
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
ZenithM
Profile Joined February 2011
France15952 Posts
January 13 2015 15:00 GMT
#11288
Hmm, no way the non-recursive solution is "prettier" than the recursive solution in some problems. Those are not often real world problems though, I'll give you that. More efficient, yes, I can get behind that.
I had to code recently something to compute the number of perfect matchings in bipartite graphs (which is actually real-world enough of a problem ;D), and the "natural" solution was "naturally" recursive. Everything that involves enumerative combinatorics in general often present itself recursively.
And more obviously, inductive data structures naturally yield inductive algorithms.
fdsdfg
Profile Blog Joined February 2010
United States1251 Posts
Last Edited: 2015-01-13 15:36:35
January 13 2015 15:28 GMT
#11289
I wrote a method for a game that would compute the 'score' of certain poker hands. Like if you have 7 cards in your hand, what is the best 5-card combo?

Recursion was the natural way to do it for arbitrary hand size. Something like this:


public int getHandScore(Hand hand){
if (hand.size > 5) {
int bestScore = 0;
for(card c : hand.getCards()){
Hand temp = hand.clone();
temp.remove(c);
int score = getHandScore(temp);
if (score > bestScore){
bestScore = score;
}
}
return bestScore;
}else{
//return the score of hand of 5 cards
}
}



Solving this without recursion would stink.
aka Siyko
Manit0u
Profile Blog Joined August 2004
Poland17843 Posts
Last Edited: 2015-01-13 16:00:13
January 13 2015 15:48 GMT
#11290
On January 14 2015 00:28 fdsdfg wrote:
I wrote a method for a game that would compute the 'score' of certain poker hands. Like if you have 7 cards in your hand, what is the best 5-card combo?

Recursion was the natural way to do it for arbitrary hand size. Something like this:


public int getHandScore(Hand hand){
if (hand.size > 5) {
int bestScore = 0;
for(card c : hand.getCards()){
Hand temp = hand.clone();
temp.remove(c);
int score = getHandScore(temp);
if (score > bestScore){
bestScore = score;
}
}
return bestScore;
}else{
//return the score of hand of 5 cards
}
}


Solving this without recursion would stink.


Playing Doomtown much?

Also, this problem reminds me of this:

Split an array of numbers into a specified number of groups so that the sum of all elements in each group would be as equal as possible. Eg.

	
You have these numbers:
1,2,4,7,1,6,2,8

Lets split them into 3 groups:
8,2 = 10
7,2,1 = 10
6,4,1 = 11


And this (to an extent):

Print an associative array as an ASCII table. Eg.


array(
array(
'Name' => 'Trixie',
'Color' => 'Green',
'Element' => 'Earth',
'Likes' => 'Flowers'
),
array(
'Name' => 'Tinkerbell',
'Element' => 'Air',
'Likes' => 'Singning',
'Color' => 'Blue'
),
array(
'Element' => 'Water',
'Likes' => 'Dancing',
'Name' => 'Blum',
'Color' => 'Pink'
),
);

Expected output:

+------------+-------+---------+---------+
| Name | Color | Element | Likes |
+------------+-------+---------+---------+
| Trixie | Green | Earth | Flowers |
| Tinkerbell | Blue | Air | Singing |
| Blum | Pink | Water | Dancing |
+------------+-------+---------+---------+


Source: http://phpixie.com/blog/test-tasks-for-php-interviews-that-developers-will-enjoy-solving/
Time is precious. Waste it wisely.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
January 13 2015 18:54 GMT
#11291
There are plenty of cases where recursion results in intuitive and readable code. We're not talking performance because we didn't profile.

I once wrote a piece of code that was similar to the HandScore thing by fdsdfg, just about 10 times more complex (although the recursion termination was significantly simpler, very convenient for recursion). The non-recursive version would have been a nightmarish abomination. I tried it.
If you have a good reason to disagree with the above, please tell me. Thank you.
RoyGBiv_13
Profile Blog Joined August 2010
United States1275 Posts
January 13 2015 20:19 GMT
#11292
Oh man, I'm not on TL for a day and I miss a C vs C++ discussion (my favorite) and recursion vs non recursion...

Not that the C vs C++ discussion will ever result in a changed mind, as most people use what they are familiar with and both can take care of most problems (with notable exceptions that C has embedded cornered, and C++ has graphics nailed down).

In no particular order, here are my comparisons of the languages I love.

Performance
------------------
People like numbers though, so there's a benchmarking suite just for comparing C++ versus C for compiler makers to check their performance. http://stlab.adobe.com/performance/ offers a reference C implementation and then uses various C++ abstraction layers to see how much using C++ hurts for performance. Most implementations of common abstractions have either no impact or are only 1.5x as slow. Some library implementations are 4-5x as slow as a C implementation.

Note that we have exception handling turned off for our benchmarking so that we don't get hosed, since our exception handling is not very fast. I don't know of an implementation of C++ that does have fast exceptions, so keep that in mind.

I just finished a 4k loc project written in C++. It had a couple of code areas that were ran at 1k Hz for processing data while the graphics updated its frame at 60 Hz. Needless to say, my fast processing code is pretty much straight C code. It had been some time since I wrote C++, so the graphics code was messy and didn't take advantage of many of the great features of C++, but had I tried to do the graphics processing in C, I would have never have finished.

Code debugging
-----------------------

As delHospital pointed out, it's quite easy to figure out what a chunk of procedural C code is supposed to do, as opposed to tracing through the potential maze Object Oriented C++ can become. I don't like that argument as OOP is almost always more difficult to debug than procedural or functional code, as it can be easier write and design correct programs using OOP, so benefits and drawbacks I guess.

The fact is, as long as you're using a breakpoint debugger that has a global understanding of the system, you should be able to nail down even the most heinous bugs in a C program in a bounded amount of time (assuming the bug is reproducible).

Conversely, C++ is a serious pain in the butt to debug as if it's a procedural language. Of course, many bugs can be tracked down using traditional breakpoint debugging, but the heinous bugs can be completely missed due to the large surface area polymorphism and template engines can create. Alternatively, C++ offers much better high level concepts for tracking your code and making sure it's correct. Being able to look in a debugger to see that your Crazy_Complicated_DataStructure object is correct is certainly very handy in tracking down why your pathfinding algorithm has sent you off a cliff.

Since most the code I write is procedural, I find it easier to fall back to C. It would be no easier nor harder to debug a faulty path finding algorithm in C versus C++.

+ Show Spoiler +
My very favorite bug I've ever run into was due to a C++ constructor causing side effects using virtual functions to redirect a hardware exception handler. It resulted in a volatile const DataAbortHandler * volatile foo; call, which broke all sorts of brain cells to comprehend.


Static Weak versus Static Strong Types
-----------------------------------------------------------

Arguments as to the benefits of each of these approaches are manifold. The weak types in C have a profound effect on the programmer that makes them feel as if they are using a portable assembler instead of a fully featured type-checking language. One of the most common forms of undefined behaviour I've run into is illegal type punning.

The strong types in C++ ignore the underlying simplicity of the data the types represent, forcing the programmer to be safer but also encourages many unneeded layers of abstraction.



On January 14 2015 03:54 spinesheath wrote:
There are plenty of cases where recursion results in intuitive and readable code. We're not talking performance because we didn't profile.


These are wise words. Be wary of the sexiness of recursion, as it's often the less sexy approach that generates better code.


Any sufficiently advanced technology is indistinguishable from magic
Blisse
Profile Blog Joined July 2010
Canada3710 Posts
January 14 2015 01:46 GMT
#11293
I avoid recursion unless it's just polymorphic recursion like in the poker hand thing above. Then I'm okay-ish but you can end up in weird places.

Interning at Microsoft on the Shell/Desktop team right now, the C++ is crazy :'D
There is no one like you in the universe.
netherh
Profile Blog Joined November 2011
United Kingdom333 Posts
January 14 2015 02:19 GMT
#11294
On January 13 2015 18:06 Manit0u wrote:
It would be even nicer and more legible with foreach through a list. But that's just my opinion.


public Player findMaxAvailableAttacker(Team team)
{
Player res = null;

for (Player player : team) {
if (player.getAvailable() || player.notOnField()) {
if ((res == null) || (player.getAtt() > res.getAtt()) {
res = player;
}
}
}

return res;
}


Depending on the underlying intentions of the original code, I'd be tempted to actually get rid of getAvailable() and notOnField() and just store lists of players instead. If you're picking several players in a row, you can then sort the availablePlayers list by attack strength; that way you always know which the next player is, and you can pop them off and add them to the playersOnField list...

If you have several different attributes (e.g. attack, defense, shoe size) you could either not sort the availablePlayers list, or store multiple sorted lists.
nunez
Profile Blog Joined February 2011
Norway4003 Posts
Last Edited: 2015-01-14 03:14:41
January 14 2015 02:55 GMT
#11295
@biv
delHospitals 'critique' was confusion about operator / function overloading and templates.
neither of these concepts are dependent on OOP, nor do they increase surface area.
overloading is cosmetic. templates on the contrary, are excellent for minimizing (code) surface area,
only in the worst case is a template implementation equivalent to non-templates in this context.
any requirements on instantiations can be asserted compile time.

for a meaningful discussion about the merits of the various kinds of soups that the language the C++ menu
has to offer in addition to bread and butter C, you ought to focus, and shift to soup mode.

would you like to write { function_i(int) function_f(float) } or { function(int), function(float) } and would you like some butter on your butter?
would you like to write function<T> or { function(int), function(float) }, and would you like to assemble two halves of a spoon or just get a spoon?
conspired against by a confederacy of dunces.
icystorage
Profile Blog Joined November 2008
Jollibee19350 Posts
January 14 2015 05:20 GMT
#11296
Overheard from the office:

guy 1: "Hey can you access stackoverflow?"
guy 2: "No, i think it's down"
guy 1: "omg we're gonna be out of work"
LiquidDota StaffAre you ready for a Miracle-? We are! The International 2017 Champions!
Manit0u
Profile Blog Joined August 2004
Poland17843 Posts
Last Edited: 2015-01-14 09:06:44
January 14 2015 09:06 GMT
#11297
On January 12 2015 18:37 Manit0u wrote:
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.


Since no one jumped on it I'll solve my own problem:

All the problems stemmed from me not noticing the "RewriteBase /" line in this huge .htaccess file, so my rules should look like that:


RewriteRule ^admin/login$ # no leading slash!


It's the easiest things that get you most of the time.

And I still hate Apache.
Time is precious. Waste it wisely.
fdsdfg
Profile Blog Joined February 2010
United States1251 Posts
January 14 2015 16:01 GMT
#11298
I've got a question and my google-fu is failing me on this.

My programming background is in Java and C#, and now I'm trying to write something where data is exchanged between the Javascript front-end and PHP back-end.

My biggest problem is with the data structures. In Java, I'd just create a Class object which may contain a few integers, a few booleans, a list of strings, etc. Any time I reference that class, I know exactly what I'm doing.

Now in these two languages I don't seem to have the same ability to make Class objects. I can create associated arrays in PHP and JSON objects in JS, but neither of them have the same structure and rigidity I'm used to. In fact, it becomes very painful when I need to prepare a large data object to be transferred through ADAX, and I have to read it different.

Is there some way I can implement classes in both of these languages similarly to how I do in Java?
aka Siyko
ComaDose
Profile Blog Joined December 2009
Canada10357 Posts
Last Edited: 2015-01-14 16:16:39
January 14 2015 16:13 GMT
#11299
Not sure if this will help answer your question but the JSON extension is bundled and compiled into PHP by default now. you can use json_decode to convert a JSON object into associative arrays in PHP.

but re-reading i understand better now that you want classes instead of passing strings around so sorry I don't know about that.
BW pros training sc2 is like kiss making a dub step album.
Deleted User 101379
Profile Blog Joined August 2010
4849 Posts
January 14 2015 17:09 GMT
#11300
On January 15 2015 01:01 fdsdfg wrote:
I've got a question and my google-fu is failing me on this.

My programming background is in Java and C#, and now I'm trying to write something where data is exchanged between the Javascript front-end and PHP back-end.

My biggest problem is with the data structures. In Java, I'd just create a Class object which may contain a few integers, a few booleans, a list of strings, etc. Any time I reference that class, I know exactly what I'm doing.

Now in these two languages I don't seem to have the same ability to make Class objects. I can create associated arrays in PHP and JSON objects in JS, but neither of them have the same structure and rigidity I'm used to. In fact, it becomes very painful when I need to prepare a large data object to be transferred through ADAX, and I have to read it different.

Is there some way I can implement classes in both of these languages similarly to how I do in Java?


json_encode to pass data to javascript, json_decode to unserialize data from javascript.

You can't pass actual classes around without a lot of overhead, only anonymous data structures, but usually you'll just need the data anyways. It is possible, e.g. with JQuery converters that use the response to build the actual classes, though I haven't seen that being used in the wild.


JS:

var someData = {
foo: "bar",
baz: 123,
x: {
a: 1,
b: 2
}
};

$.ajax({
dataType: "json",
url: url,
data: someData,
success: function(data, status, xhr) {
alert(data.result);
}
});

PHP:

<?php

echo json_encode(array(
"foo" => $_REQUEST['foo'],
"x_a" => $_REQUEST['x']['a'],
"result" => "success"
));

?>
Prev 1 563 564 565 566 567 1032 Next
Please log in or register to reply.
Live Events Refresh
Next event in 45m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
SpeCial 116
SHIN 104
MindelVK 21
StarCraft: Brood War
Britney 35362
Calm 5660
Shuttle 962
firebathero 560
Soma 396
Rush 299
910 110
Dewaltoss 75
Bonyth 74
Mong 57
[ Show more ]
Liquid`Ret 53
Rock 23
Pusan 19
Hm[arnc] 14
SilentControl 12
Noble 4
Dota 2
qojqva3134
Dendi1554
syndereN601
420jenkins309
LuMiX1
Counter-Strike
fl0m191
Other Games
singsing1774
mouzStarbuck328
B2W.Neo144
XaKoH 131
QueenE57
Rex29
Organizations
Other Games
EGCTV1249
[ Show 17 non-featured ]
StarCraft 2
• poizon28 77
• 3DClanTV 75
• LUISG 28
• StrangeGG 20
• Migwel
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
StarCraft: Brood War
• Airneanach14
• FirePhoenix11
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• C_a_k_e 3802
League of Legends
• Jankos1866
Other Games
• Shiphtur182
Upcoming Events
AI Arena Tournament
45m
OSC
4h 15m
Sparkling Tuna Cup
17h 45m
WardiTV Invitational
18h 45m
ByuN vs Percival
Cure vs Classic
Shopify Rebellion Sundays
22h 45m
Spirit vs Mixu
Clem vs TBD
RSL Revival
23h 45m
Serral vs Rogue
BlizzCon
1d 2h
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.