How concise should I make my ruby? [closed] - ruby

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In ruby or programming in general is the best practice to be as concise as the language allows or to be concise while still readable? For example:
animals = %w{ cat dog bird }
chosen_animal = rand(animals.length)
random_animal = animals[chosen_animal]
Or
animals = %w{ cat dog bird }
random_animal = animals[rand(animals.length)]
I have a feeling the second one is better code. Is there any benefit of using the first one? Which would you use and why?

as concise as the language allows or to be concise while still readable?
Always, always prefer readability. Conciseness is only useful when it makes your code more readable (i.e., less verbosity and clutter to wade through). It saves you nothing if it obscures the code and serves only to slow development down.
Readability/maintainability only takes a back seat to performance concerns and only when absolutely necessary. This is not often the case in a language like Ruby, more common in a language like C when a bottleneck has been shown to exist that can only be remedied by performing some amount of low level optimizations that may make the code slightly more difficult to comprehend. In this case, add comments that explain the behavior of the code thoroughly.

This is a very broad question with plenty of room for subjective bias.
It is generally accepted that readability is always a good thing. However what is readable varies from person to person.
For example, from your example I would actually prefer the second variant.
There are plenty of people that would say, spread your code out, it helps, but then there are those (myself included) who prefer code that is not so spread out (within limits!) because it allows me to more easily get a feel for the "shape" of the code (structure, loops, conditionals etc) at a distance.
In your example, using one or the other variant does little to affect the readability. But suppose you have a formula like:
r1 = $r*(($objcols-i).to_f+j+k)*3/total_objs
That has a lot more terms in it so it's a lot harder to eyeball. You could pull it apart:
t1 = ($objcols-i).to_f
t2 = t1 + j + k
t3 = $r * t2 * 3
r1 = t3 / total_objs
But does that make it any more readable? In reality this particular formula is just a magic formula to produce a nice random-looking rotation.
You can compromise by spreading it out horizontally:
r1 = $r*( ($objcols-i).to_f+j+k ) * 3 / total_objs
Which at least serves to group the major terms.
But at the end of the day, we are talking about the micro. Whether someone takes 3 seconds or 10 to understand that snippet is not what's important. These are more important:
The reason for the expression must be obvious. IF it's not obvious from the code itself then it needs a comment explaning it.
The code should be easily navigable. This means:
eliminating/reducing repeating code
breaking your program into functions that aren't to small or too large. Again, "too small" and "too large" are subjective terms and there are often exceptions.
Explaining the more complex and high-level structures (e.g. large networks of interacting classes) with plenty of comments.
Lastly, did you know you can do this? (At least in ruby 1.9+):
random_animal = animals.sample
which takes a random element from animals.

Related

Features of good Prolog code? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
What are the design heuristics one has to master to write good Prolog? I've heard it takes an experienced programmer about two years to become proficient in Prolog. Using recursion effectively is part of it, but that seems to be a relatively minor hurdle. What exactly is it that gives programmers so much trouble? What should I be looking for in sample code to judge its quality?
The major difficulty in writing good Prolog code lies in not only understanding but also adequately transmitting the intention or purpose of a program. In contrast to other programming languages there are several quite different kinds of Prolog code often within the same program. By confusing such levels bugs and problems ensue:
Pure, monotonic code.
This code lies at the heart of Prolog. In such code a lot of algebraic properties hold, and the actual problems are described in the pure, ideal manner which Prolog is often advertised with. Yet, even in such parts certain procedural properties may surface, such as non-termination. Take as an example the commutativity of conjunction. In pure, monotonic code, ( A, B ) and ( B, A ) describe the same relation. The only differences may lie in different termination behavior and the sequence how answers appear. Ideally, the names of pure predicates communicate that the predicates are relations. Imperatives are definitely not a good choice here.
Side-effectful code.
The other extreme is code that can only be understood by effectively executing it, either by machine or in the mind. There are no simple invariants in the program. But even in such parts, there might still be certain properties observed like steadfastness. Effectively such code is not much different to other programming languages.
Often, the side-effectful part "eats up" the pure side since programmers are used to an imperative, command-oriented do-this do-that thinking. To lean into the other direction, think of which properties you will lose or gain. Think how easy it will be to test your program: The purer a program the easier it is to test without any extra sandbox around. A simple toplevel query is good enough.
Some examples, how the pure side can be expanded at the expense of seemingly necessary side-effects:
What are the pros and cons of using manual list iteration vs recursion through fail
Prolog Recursion skipping same results
Or simply these answers.
Edit: In your comment, you ask for "advice for learning". So here is some:
Stick to writing pure, monotonic code only. You can only judge to choose one or the other side if you know both. I assume you have some previous experience producing side effects in some command-oriented language, but none with pure code. As a consequence this will mean that you will refrain from writing inherently non-monotonic code.
Play with the toplevel. Imagine, the toplevel is the only way to access your programs. How would you formulate a problem such that it fits into this format? The SWI, Scryer and Trealla toplevel have been specifically designed to permit such light-weight interaction.
Use clpfd for arithmetics. Don't use (is)/2, it makes your code much too moded.
Enjoy the algebraic properties of pure, monotonic code. Think of it: You add a goal, no matter where, and still you can predict that this goal will specialize your program (and at best leaves it as is). You can - blindly - remove a goal, and still you know (part of) its effect.
Study the notion of a failure-slice to master non-termination.
Do not use a step-by-step tracer/debugger, as it is offered in many Prologs. It only shows you the precise steps Prolog takes. It does not show you anything directly related to the meaning of the program. It reinforces a step-by-step thinking.
Watch your language. The way how you talk about a program influences the way you think about it. So, if you use a lot of operationalizing language (like: This does this etc), chances are you reinforce the command-oriented view. There is a cleaner way of talking about things, but you need to find it. This is probably the hardest part.

Math/Algorithm for Simple Game Programming (Newbie)? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am a newbie on game programming, i usually programmed enterprise software.
my questions is which math do i need to learn in order for me to create these games
Snake game
Tetris
Card Games like solitaire and the like
Any reference/books that will help me to create this game is very much appreciated
Many thanks.
You don't need much math for those games if you know how to handle some basic data structures like lists and "two-dimensional" arrays.
EDIT:
In addition, that kind of game logic probably comprises a rather small fraction of the code in your game. The rest is handling user input, graphics, sound, time etc., and doing this properly (having a good architecture in the program) is a more challenging task. On the other hand, at least some of these things can be delegated to a ready-made game engine / framework.
Just as a general guideline, you probably don't have to worry about "which math do i need to learn" unless you're using programming to solve a math problem.
For stuff like programming simple games, it's much more important to learn your data structures and algorithms well, and to be able to design and implement clean, correct, and maintainable code. Math doesn't usually come into the picture unless you're trying to compare two different implementations, and even then, you really only need enough to have an intuitive sense of what constitutes fast enough for what you need.
For programming simple games, the only math you will need is very basic spatial reasoning so that you can tell the compute where to draw/animate objects on the screen. Hence in this case I wouldn't worry about a lack of math background. You may need math as you write more complex games but I recommend just exploring game development freely and brushing up mathematically as required :)
Since you specifically asked about simple games, here are some examples of the kinds of math problems you would have to solve for the games you've described:
Suppose you're coding up a solitaire game and the cards are w pixels wide each, laid out horizontally, separated by p pixels each. You would have to deduce that the nth card is at position (w + p) * n.
Let's say you're programming tetris, you might want the blocks glide smoothly to the next grid cell every m milliseconds. Well then you'd need to move each block by [grid cell size] * 1000 / (m * [frames per second]) pixels each frame.

Looking for good bonus quiz to test efficiency (specifically efficiency related to time) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am doing a Introductory to Computer Science lab once a week. I was hoping to have a quick contest at the end of my next lab. I want to give them a block of code like this:
public class EfficientCode{
public static void main(){
long startTime, endTime, executionTime;
startTime = System.currentTimeMillis();
yourEfficientMethod():
endTime = System.currentTimeMillis();
executionTime = endTime – startTime;
}
public static void doSomething(){
// you do this part.
}
}
They will implement the doSomething method and the person with the fastest code will get a handful of bonus marks.
The problem is that the question needs to be somewhat simple. The students have a good grasp of: loops, if/else, Strings, adding, arrays, etc.
Here are my ideas for what the question could be:
find all the perfect numbers between 1 and 1,000,000. (A perfect number is a number where all of the number's factors add up to the number. Ie: 6 = 3 + 2 + 1)
find all prime numbers between 1 and 1,000,000
I think in order for there to be a measurable difference in performance between methods you must do something many times.
Agreed about 'many times' for short operations, but for longer ones, once might be enough on its own.
I suggest looking into Project Euler, an excellent collection of programming questions. The best part is that the problems are designed with a "one minute rule" in mind, that most problems should take a moderate computer less than one minute to execute an efficient algorithm to find the answers. So an excellent place to start. :)
Two things.
First, efficiency is about more than execution time. It also is about memory usage, memory access, file-system/resource access, etc. There are tons of things that go into efficiency. So please be explicit that you're looking for the routine with the shortest run-time. Otherwise you are sending a mixed message...
Second, I heard this problem about 15 years ago, and I can't forget it:
Produce a list of all 5-digit number pairs that sum to 121212. However, neither of the 2 numbers can repeat a decimal digit. So 1 can only appear once in either number. So an example result pair is 98167 + 23045. There are a fair number, and it's easy to build a brute-force solution, but an efficient solution requires some thought. There are 192 unique pairs...
Because this is an introductory class and your students haven't covered sorting yet I think it's going to be very hard to come up with something simple enough to do, interesting enough to have a few different ways of doing it, and complex enough that there is an appreciable difference in speed between the different implementations on a modern computer. Your real problem, though, is that anything simple enough for them to try already has a canonical implementation only a short Google search away.
My suggestion is to invert the challenge. Have your students compete to come up with the gnarliest, slowest, most memory hogging solution they can think of. I believe it's as educationally valuable to think about all the wrong ways of doing something as it is to think about the right, and it's just as hard to be the worst as it is to be the best. It's easier to see results subjectively as well since bad code will be really slow. No Googling for an answer either. Finally, in my (irrelevant) opinion, this has the added bonus of making the challenge more fun.
Something like finding a string within another string is easier made bad than good. Maybe have them extract all the prime numbers from a 2kb string of random alphanumeric characters. Lots of ways to make a pig's ear of that problem.
Those are good ideas. What about having a sorting question?
Sorting an array of numbers might also be a good idea, since there are a whole bunch of algorithms for it (insertion, selection, quick, heap, etc.) that all have different performance characteristics. This would also give students a chance to learn about big-O notation, etc.

Is Erlang a concise language from a programmer's perspective? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Where would Erlang fall on the spectrum of conciseness between, say, Java/.net on the less concise end and Ruby/Python on the more concise end of the spectrum? I have an RSI problem so conciseness is particularly important to me for health reasons.
Conciseness as a language feature is ill defined and probably not uniform. Different languages could be more or less concise depending on the problem.
Erlang as a functional language can be very concise, beyond Ruby or Python. Specifically pattern matching often replaces if statements and recursion and list comprehensions can replace loops.
For example Java would have something like this:
String foobar(int number){
if (number == 0) {
return "foo";
} else if (number == 1) {
return "bar";
}
throw new Exception();
}
while Erlang code would look like:
foobar(0) -> "foo";
foobar(1) -> "bar".
With the exception being inherent because there is no clause for input other then 0 or 1. This is of cause a problem that lends itself well to Erlang style development.
In general anything you could define as a transformation will match a functional language particularly well and can be written very concise. Of cause many functional language zealots state that any problem in programming is a transformation.
Erlang allows you to realize functionallity in very few lines of code, compared to my experiences in Java and Python. Only Smalltalk or Scheme came near for me in the past. You've get only little overhead, but you typically tend to speaking identifiers for modules, functions, variables, and atoms. They make the code more readable. And you've got lot's of normal, curly, and square braces. So it depends on your keyboard layout how comfortable it will be. You should give it a try.
mue
Erlang is surprisingly concise especially when you want achieve performance and reliability.
Erlang is concise even when compared to Haskell:
http://thinkerlang.com/2006/01/01/haskell-vs-erlang-reloaded.html
And is surprisingly fast (and reliable) even when compared to C++:
http://www.erlang.se/euc/06/proceedings/1600Nystrom.ppt
(18x less SLOC is not surprise).
Anyway it always depends of your preferences and goal what you want achieve.
You have to spend some time, write code, to understand erlang's sweet spot, vs. all the other emerging tools, DHT, doc stores, mapreduce frameworks, hadoop, GPU, scala, ... If you try to do, say SIMD type apps outside the sweet spot, you'll probably end up fighting the paradigm and writing verbose code, whereas if you hit problems that need to scale servers and middleware seamlessly up and down, it flows naturally. (And the rise of scala in its sweet spot is inevitable, too, I think)
A good thing to look up would be the Tim Bray Wide Finder experiment (distilling big apache log files) from a couple years ago, and how he was disappointed with erlang.
I generally don't recommend putting much store in the Alioth shootout, given you inevitably end up comparing really good and bad code, but if you need to put numbers of LOC, erlang vs. C, ruby, whatever
https://benchmarksgame-team.pages.debian.net/benchmarksgame/faster/erlang.html

Algorithm/Data Structure Design Interview Questions [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
What are some simple algorithm or data structure related "white boarding" problems that you find effective during the candidate screening process?
I have some simple ones that I use to validate problem solving skills and that can be simply expressed but have some opportunity for the application of some heuristics.
One of the basics that I use for junior developers is:
Write a C# method that takes a string which contains a set of words (a sentence) and rotates those words X number of places to the right. When a word in the last position of the sentence is rotated it should show up at the front of the resulting string.
When a candidate answers this question I look to see that they available .NET data structures and methods (string.Join, string.Split, List, etc...) to solve the problem. I also look for them to identify special cases for optimization. Like the number of times that the words need to be rotated isn't really X it's X % number of words.
What are some of the white board problems that you use to interview a candidate and what are some of the things you look for in an answer (do not need to post the actual answer).
I enjoy the classic "what's the difference between a LinkedList and an ArrayList (or between a linked list and an array/vector) and why would you choose one or the other?"
The kind of answer I hope for is one that includes discussion of:
insertion performance
iteration performance
memory allocation/reallocation impact
impact of removing elements from the beginning/middle/end
how knowing (or not knowing) the maximum size of the list can affect the decision
Once when I was interviewing for Microsoft in college, the guy asked me how to detect a cycle in a linked list.
Having discussed in class the prior week the optimal solution to the problem, I started to tell him.
He told me, "No, no, everybody gives me that solution. Give me a different one."
I argued that my solution was optimal. He said, "I know it's optimal. Give me a sub-optimal one."
At the same time, it's a pretty good problem.
When interviewing recently, I was often asked to implement a data structure, usually LinkedList or HashMap. Both of these are easy enough to be doable in a short time, and difficult enough to eliminate the clueless.
This doesn't necessarily touch on OOP capabilities but in our last set of interviews we used a selection of buggy code from the Bug of the Month list. Watching the candidates find the bugs shows their analytical capabilities, shows the know how to interpret somebody elses code
Write a method that takes a string, and returns true if that string is a number.(anything with regex as the most effective answer for an interview)
Please write an abstract factory method, that doesn't contain a switch and returns types with the base type of "X". (Looking for patterns, looking for reflection, looking for them to not side step and use an if else if)
Please split the string "every;thing|;|else|;|in|;|he;re" by the token "|;|".(multi character tokens are not allowed at least in .net, so looking for creativity, the best solution is a total hack)
Graphs are tough, because most non-trivial graph problems tend to require a decent amount of actual code to implement, if more than a sketch of an algorithm is required. A lot of it tends to come down to whether or not the candidate knows the shortest path and graph traversal algorithms, is familiar with cycle types and detection, and whether they know the complexity bounds. I think a lot of questions about this stuff comes down to trivia more than on the spot creative thinking ability.
I think problems related to trees tend to cover most of the difficulties of graph questions, but without as much code complexity.
I like the Project Euler problem that asks to find the most expensive path down a tree (16/67); common ancestor is a good warm up, but a lot of people have seen it. Asking somebody to design a tree class, perform traversals, and then figure out from which traversals they could rebuild a tree also gives some insight into data structure and algorithm implementation. The Stern-Brocot programming challenge is also interesting and quick to develop on a board (http://online-judge.uva.es/p/v100/10077.html).
Follow up any question like this with: "How could you improve this code so the developer who maintains it can figure out how it works easily?"
Implement a function that, given a linked list that may be circular, swaps the first two elements, the third with the fourth, etc...
I like to go over a code the person actually wrote and have them explain it to me.
Asking them to write a recursive algorithm for a well known iterative solution (i.e. Fibonacci etc. -- we give them an iterative function, if needed) and then have them compute the run time for it.
Many times the recursive function involves a tree data structure. The number of times the person has failed to recognize that baffles me. It becomes slightly difficult to calculate the run time until you can see that it's a tree structure...
I find that this problem covers many areas. Namely, their code-reading ability (if they are given an iterative function), code-writing ability (since they write a recursive function), algorithm, data-structure (for run-time)...
A trivial one is to ask them to code up a breadth-first search of a tree from scratch. Yeah, if you know what you're doing it is trivial. But a lot of programmers don't know how to tackle it.
One that I find more useful still is as follows. I've given this in a number of languages, here is a Perl version. First I give them the following code sample:
# #a and #b are two arrays which are already populated.
my #int;
OUTER: for my $x (#a) {
for my $y (#b) {
if ($x eq $y) {
push #int, $x;
next OUTER;
}
}
}
Then I ask them the following questions. I ask them slowly, give people time to think, and am willing to give them nudges:
What is in #int when this code is done?
This code is put into production and there is a performance problem that is tracked back to this code. Explain the potential performance problem. (If they are struggling I'll ask how many comparisons it takes if #a and #b each have 100,000 elements. I am not looking for specific terminology, just a back of the envelope estimate.)
Without code, suggest to make this faster. (If they propose a direction that is easy to code, I'll ask them to code it. If they think of a solution that will result in #int being changed in any way (eg commonly order), I'll push to see whether they realize that they shouldn't code the fix before checking whether that matters.)
If they come up with a slightly (or very) wrong solution, the following silly data set will find most mistakes you run across:
#a = qw(
hello
world
hello
goodbye
earthlings
);
#b = qw(
earthlings
say
hello
earthlings
);
I'd guess that about 2/3 of candidates fail this question. I have yet to encounter a competent programmer who had trouble with it. I've found that people with good common sense and very little programming background do better on this than average programmers with a few years of experience.
I would suggest using these questions as filters. Don't hire someone because they can answer these. But if they can't answer these, then don't hire them.

Resources