|
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. |
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; }
|
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]](http://i.imgur.com/mvOAXLG.png)
![[image loading]](http://i.imgur.com/um9kVgA.png)
cosine:
![[image loading]](http://i.imgur.com/Xkd1Rrf.png)
![[image loading]](http://i.imgur.com/JO8F5G6.png)
![[image loading]](http://i.imgur.com/Fm36Fwe.png)
sine:
![[image loading]](http://i.imgur.com/ctXpNWL.png)
![[image loading]](http://i.imgur.com/9maYtyf.png)
![[image loading]](http://i.imgur.com/UhvKzYy.png)
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] + + Show Spoiler [1, 355/113] + + Show Spoiler [2, 355/113] + + Show Spoiler [3, 355/113] + + Show Spoiler [4, 22/7] + + Show Spoiler [5, 22/7] + + Show Spoiler [6, 13/4] + + Show Spoiler [7, 3/1] + + Show Spoiler [8, 3/1] +
sines[N, alpha_pi / beta_pi] + Show Spoiler [0, 355/113] + + Show Spoiler [1, 355/113] + + Show Spoiler [2, 355/113] + + Show Spoiler [3, 355/113] + + Show Spoiler [4, 22/7] + + Show Spoiler [5, 22/7] + + Show Spoiler [6, 13/4] + + Show Spoiler [7, 3/1] + + Show Spoiler [8, 3/1] +
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
|
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)
|
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.
|
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; }
|
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.
|
Thanks for your comments everyone . I find its pretty difficult to assess my own solutions to problems
|
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.
|
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.
|
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/
|
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.
|
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.
|
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
|
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.
|
@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?
|
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"
|
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.
|
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?
|
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.
|
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" ));
?>
|
|
|
|