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

Website Feedback

Closed Threads



Active: 711 users

The Big Programming Thread - Page 565

Forum Index > General Forum
Post a Reply
Prev 1 563 564 565 566 567 1031 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
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
Poland17255 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
Poland17255 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
Jollibee19346 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
Poland17255 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 1031 Next
Please log in or register to reply.
Live Events Refresh
BSL20 Non-Korean Champi…
18:00
RO8 Round Robin Group - Day 4
Bonyth vs Zhanhun
Dewalt vs Mihu
Hawk vs Sziky
Sziky vs QiaoGege
Mihu vs Hawk
Zhanhun vs Dewalt
Fengzi vs Bonyth
ZZZero.O207
LiquipediaDiscussion
FEL
09:00
Cracow 2025
Clem vs LamboLIVE!
Reynor vs TBD
RotterdaM2476
ComeBackTV 2081
IndyStarCraft 611
WardiTV409
3DClanTV 153
CranKy Ducklings148
EnkiAlexander 120
Rex66
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
RotterdaM 2476
IndyStarCraft 611
Rex 66
StarCraft: Brood War
ZZZero.O 207
firebathero 200
Soulkey 111
NaDa 4
Dota 2
capcasts170
LuMiX1
League of Legends
JimRising 16
febbydoto10
Counter-Strike
fl0m3388
Fnx 2049
flusha384
Stewie2K341
Super Smash Bros
hungrybox3484
Mew2King1420
AZ_Axe119
Westballz8
Heroes of the Storm
Khaldor649
Liquid`Hasu499
Other Games
Grubby2545
B2W.Neo1099
KnowMe172
mouzStarbuck96
Sick4
Organizations
Other Games
gamesdonequick2855
StarCraft 2
angryscii 26
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 22 non-featured ]
StarCraft 2
• davetesta34
• Hupsaiya 21
• LUISG 15
• Legendk 6
• Adnapsc2 3
• Kozan
• intothetv
• IndyKCrew
• LaughNgamezSOOP
• AfreecaTV YouTube
• Migwel
• sooper7s
StarCraft: Brood War
• HerbMon 25
• Azhi_Dahaki12
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• masondota21649
• WagamamaTV908
League of Legends
• Doublelift2922
Other Games
• imaqtpie1550
• Shiphtur516
Upcoming Events
Wardi Open
14h 53m
Sparkling Tuna Cup
1d 13h
WardiTV European League
1d 19h
Online Event
1d 21h
uThermal 2v2 Circuit
2 days
The PondCast
3 days
Replay Cast
4 days
Korean StarCraft League
5 days
CranKy Ducklings
5 days
Sparkling Tuna Cup
6 days
Liquipedia Results

Completed

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

Ongoing

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

Upcoming

ASL Season 20: Qualifier #1
ASL Season 20: Qualifier #2
ASL Season 20
CSLPRO Chat StarLAN 3
BSL Season 21
RSL Revival: Season 2
Maestros of the Game
SEL Season 2 Championship
WardiTV Summer 2025
uThermal 2v2 Main Event
HCC Europe
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
TLPD

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

Advertising | Privacy Policy | Terms Of Use | Contact Us

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