• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 08:53
CET 14:53
KST 22:53
  • 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
RSL Season 3 - RO16 Groups C & D Preview0RSL Season 3 - RO16 Groups A & B Preview2TL.net Map Contest #21: Winners12Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10[ASL20] Finals Preview: Arrival13
Community News
[TLMC] Fall/Winter 2025 Ladder Map Rotation13Weekly Cups (Nov 3-9): Clem Conquers in Canada4SC: Evo Complete - Ranked Ladder OPEN ALPHA8StarCraft, SC2, HotS, WC3, Returning to Blizzcon!45$5,000+ WardiTV 2025 Championship7
StarCraft 2
General
Zerg is losing its identity in StarCraft 2 [TLMC] Fall/Winter 2025 Ladder Map Rotation Mech is the composition that needs teleportation t RotterdaM "Serral is the GOAT, and it's not close" RSL Season 3 - RO16 Groups C & D Preview
Tourneys
RSL Revival: Season 3 Sparkling Tuna Cup - Weekly Open Tournament Constellation Cup - Main Event - Stellar Fest Tenacious Turtle Tussle Master Swan Open (Global Bronze-Master 2)
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 499 Chilling Adaptation Mutation # 498 Wheel of Misfortune|Cradle of Death Mutation # 497 Battle Haredened Mutation # 496 Endless Infection
Brood War
General
FlaSh on: Biggest Problem With SnOw's Playstyle BGH Auto Balance -> http://bghmmr.eu/ What happened to TvZ on Retro? SnOw's ASL S20 Finals Review BW General Discussion
Tourneys
[Megathread] Daily Proleagues Small VOD Thread 2.0 [BSL21] RO32 Group D - Sunday 21:00 CET [BSL21] RO32 Group C - Saturday 21:00 CET
Strategy
PvZ map balance Current Meta Simple Questions, Simple Answers How to stay on top of macro?
Other Games
General Games
Clair Obscur - Expedition 33 Should offensive tower rushing be viable in RTS games? Path of Exile Stormgate/Frost Giant Megathread Nintendo Switch Thread
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread SPIRED by.ASL Mafia {211640}
Community
General
Things Aren’t Peaceful in Palestine US Politics Mega-thread Russo-Ukrainian War Thread Artificial Intelligence Thread Canadian Politics Mega-thread
Fan Clubs
White-Ra Fan Club The herO Fan Club!
Media & Entertainment
Movie Discussion! [Manga] One Piece Anime Discussion Thread Korean Music Discussion Series you have seen recently...
Sports
2024 - 2026 Football Thread Formula 1 Discussion NBA General Discussion MLB/Baseball 2023 TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
SC2 Client Relocalization [Change SC2 Language] Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List
Blogs
Dyadica Gospel – a Pulp No…
Hildegard
Coffee x Performance in Espo…
TrAiDoS
Saturation point
Uldridge
DnB/metal remix FFO Mick Go…
ImbaTosS
Reality "theory" prov…
perfectspheres
Customize Sidebar...

Website Feedback

Closed Threads



Active: 2241 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
Poland17433 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
Poland17433 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
Poland17433 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
WardiTV Korean Royale
12:00
Group Stage 1 - Group A
WardiTV559
LiquipediaDiscussion
Kung Fu Cup
12:00
2025 Monthly #3: Day 5
Cure vs herOLIVE!
Reynor vs TBD
RotterdaM693
TKL 366
IndyStarCraft 269
SteadfastSC122
IntoTheiNu 43
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
RotterdaM 617
TKL 352
Tasteless 324
Reynor 276
IndyStarCraft 269
Rex 147
SteadfastSC 113
Railgan 25
MindelVK 21
StarCraft: Brood War
Britney 36790
Rain 8932
Sea 4139
firebathero 4096
BeSt 1748
Horang2 1687
GuemChi 939
Soma 605
EffOrt 552
Stork 500
[ Show more ]
Mini 456
actioN 283
Rush 225
Killer 174
Last 146
Hyun 144
scan(afreeca) 136
hero 133
Bonyth 99
Mind 90
Barracks 61
Sharp 51
zelot 50
yabsab 49
Sea.KH 45
sorry 42
Snow 39
sas.Sziky 24
Shinee 18
Hm[arnc] 15
NaDa 8
Bale 6
Dota 2
singsing3070
qojqva1678
Dendi1083
Gorgc737
XcaliburYe301
Counter-Strike
byalli539
x6flipin531
Heroes of the Storm
Khaldor238
Liquid`Hasu193
Other Games
FrodaN4939
B2W.Neo1844
Pyrionflax359
Fuzer 256
KnowMe216
DeMusliM40
Organizations
Dota 2
PGL Dota 2 - Main Stream14873
PGL Dota 2 - Secondary Stream1808
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 14 non-featured ]
StarCraft 2
• Adnapsc2 8
• Dystopia_ 6
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• WagamamaTV606
• Ler66
Upcoming Events
BSL 21
6h 7m
JDConan vs Semih
Dragon vs Dienmax
Tech vs NewOcean
TerrOr vs Artosis
IPSL
6h 7m
Dewalt vs WolFix
eOnzErG vs Bonyth
Replay Cast
9h 7m
Wardi Open
22h 7m
Monday Night Weeklies
1d 3h
Replay Cast
1d 9h
WardiTV Korean Royale
1d 22h
BSL: GosuLeague
2 days
The PondCast
2 days
Replay Cast
3 days
[ Show More ]
RSL Revival
3 days
BSL: GosuLeague
4 days
RSL Revival
4 days
WardiTV Korean Royale
4 days
RSL Revival
5 days
WardiTV Korean Royale
5 days
IPSL
6 days
Julia vs Artosis
JDConan vs DragOn
RSL Revival
6 days
Liquipedia Results

Completed

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

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
SOOP Univ League 2025
YSL S2
BSL Season 21
CSCL: Masked Kings S3
SLON Tour Season 2
RSL Revival: Season 3
META Madness #9
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025

Upcoming

BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter 2026: Closed Qualifier
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
TLPD

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

Advertising | Privacy Policy | Terms Of Use | Contact Us

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