# Recognizing more elegant and concise coding solutions

Page 1 of 1

## 11 Replies - 2025 Views - Last Post: 18 July 2010 - 05:32 PM

### #1 Codebug

Reputation: 31
• Posts: 244
• Joined: 11-October 09

# Recognizing more elegant and concise coding solutions

Posted 15 July 2010 - 01:29 PM

First of all, I'm not quite sure if this is the right place for this, so the mods can feel free to move it if it's in the wrong place.

I usually visit the java forum several times a day to read over posts and ask questions. At this point in my programming "journey" I glean lots more information from the forum than I give. I want so badly to be able to give back to the forum and help the less experienced. Unfortunately, I'm not at that point yet. There was a post in the java forum the other day that involved placing ints in an array a certain way:arranging array

One member posted this solution:

import java.util.Arrays;

public class FunnyNumberSorter {

public static void main(String[] args) {

int[] n = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};

int[] sorted = new int[n.length];

final int center = (n.length / 2) - 1 + (n.length % 2);

for(int i = 1, sgn = -1; i <= n.length; i++, sgn *= -1) {

sorted[center + (sgn*i/2)] = n[i-1];

}

System.out.println(Arrays.toString(sorted));

}
}

I didn't post any code, but on my own, I came up with a solution:

class ArraySort
{
public static void main( String[] args )
{
int[] num = new int[  ]{ 10, 7, 5, 3, 1};

int middle = num.length/2;

int[] numTransfer = new int[ num.length ];

for( int i = 0, j = middle + 1, k = middle - 1; i < num.length; i++ )
{
if ( i == 0 )
{
numTransfer[ middle ] = num[ 0 ];
}

else if( i % 2 == 0 )
{
numTransfer[ k ] = num [ i ];
k--;
}

else
{
numTransfer[ j ] = num [ i ];
j++;
}

}

}
}

Something to note is that my solution does not account for arrays that have an even length. My code will only handle arrays with odd length. The other poster's code will handle both cases in a much simpler, cleaner, compact, and more elegant way. My code does work like it should for odd sized arrays. However, I feel that it is clumsy, bulky, ugly, inefficient etc.

I knew what the algorithm for placing ints in the new array should have been. However, this translated to the slog of code that I posted. I never even thought of determining the center point of the array like the other poster did:

final int center = (n.length / 2) - 1 + (n.length % 2);

I still consider myself a beginner programmer as I've been programming for less than a year. I feel that I am way better than when I first started, but when I see other people's code, I can get discouraged. Generally speaking, at what point should I start to see improvements in my code?

I absolutely love coding, but after reading a few articles online that point out that good programmers are born and not made, I wonder if I have what it takes to improve. These same articles drive home the point that you will make your improvements the first 3 to 4 years of coding.

Like I said, I love programming. Alot. I just wonder if I have what it takes to produce good code or if all I will ever be capable of is clunky mediocre code. It seems that I go through phases where I feel pretty good about my skills, and phases where I feel badly about them.

If you've made it to the end, I applaud you. Tell me what you think.

Thanks

Is This A Good Question/Topic? 0

## Replies To: Recognizing more elegant and concise coding solutions

### #2 Valek

• The Real Skynet

Reputation: 544
• Posts: 1,713
• Joined: 08-November 08

## Re: Recognizing more elegant and concise coding solutions

Posted 15 July 2010 - 02:07 PM

The fact that you write code with good indenting and syntax already puts you ahead of many, many would-be coders. I'd say that honestly, you won't actually notice the improvement as you go, but more of when you go back to an old project, or an old part of a current project you haven't worked on in several months, and you see what you did, and you think "Why did I do it this way? I could have done it this other way and used less memory/made it faster/etc.".

And that will be a crystallizing moment for you. Until then, don't worry about whether or not you can notice your improvements. Just keep coding and strive to learn all you can in terms of doing what your projects call for. Read posts here and eventually you'll start seeing that you know how to answer them. It all comes gradually.

Basically, what I'm saying is, stop worrying and just enjoy programming. The rest will come naturally.

### #3 SpeedisaVirus

• Baller

Reputation: 115
• Posts: 855
• Joined: 06-October 08

## Re: Recognizing more elegant and concise coding solutions

Posted 15 July 2010 - 06:35 PM

Agreed. Your code, just by good indents and structure is above most posted here. A lot of nifty and elegant solutions won't be obvious unless you really scribble over a problem on paper for a bit or if you have a bit of exposure to a similar problem set. At least for me. If you really care about concise and elegant code you will begin to see the light. May not notice it until you look back at your old code but its there...

### #4 baavgai

• Dreaming Coder

Reputation: 7055
• Posts: 14,734
• Joined: 16-October 07

## Re: Recognizing more elegant and concise coding solutions

Posted 16 July 2010 - 05:38 AM

You know, I had to try the puzzle first, without looking at either answer.

Of course, they're half answers, since you're really only giving the order index and not actually sorting a list yet.

Here's mine:
int[] getOrder(int n) {
int[] order = new int[n];
for(int i=0; i<n; i++) {
order[(i%2==0) ? head++ : tail--] = i;
}
return order;
}

Hmm... mine is logically similar to neither, but it's kind of closer to yours. Keep in mind, this is my final version, after all the blood is cleaned up. At some point it would have looked more like yours, with ifs and such. At some point it even had a "boolean isHead" before I realized odd-even would do the job.

The point is, everyone attacks problems differently. Also, the shiny code you see others offer the public might have been a lot less presentable before it arrived at it's current state. Code is a way of organizing thoughts. You throw down the rough draft and then start to look for what phrase fits better and where something you said can be expressed more succinctly.

There is a world of difference between "works" and "elegant". Very little code manages to hit both the first time. As programmers, part of our job is to try to make the complex simple. It's something you will get better at in time. The fact that you're even worried about it at this point is a very good sign.

Realize that there will come a point when you see more places for improvement in your work. This is not bad! It means you've reached that plateau of learning where you have enough experience to critique your performance. Many people get frustrated at this point, but it's how you learn. Striving for improvement will only make you better. Keep up the good work.

### #5 Raynes

• D.I.C Lover

Reputation: 614
• Posts: 2,815
• Joined: 05-January 09

## Re: Recognizing more elegant and concise coding solutions

Posted 16 July 2010 - 10:33 AM

I did the exact same thing:

(defn sideways-sort [aseq]
(reduce
(fn [acc [f x]] (f x acc)) []
(partition 2 (interleave
(cycle [cons #(concat %2 [%])])
(sort #(if (= 1 (compare % %2)) 0 1) aseq)))))

Even wrote a faster, lower-level version:

(defn loop-s-sort [aseq]
(loop [x (sort #(if (= 1 (compare % %2)) 0 1) aseq)
acc []
cons? true]
(if (seq x)
(recur (next x)
((if cons? cons #(concat %2 [%])) (first x) acc)
(not= cons? true))
acc)))

But anyway, baavgai is right. Over the last few years, I've been able to watch myself learn new things and see my knowledge expand. I've been able to see that reflected in my code. As time goes by, you learn new things about your language. You memorize new idioms, and you become familiar enough to begin to *see* various ways to tackle problems. The more problems you tackle, the more obvious it becomes to solve them. Don't stress over how good you are now, and just focus on getting better.

This post has been edited by Raynes: 16 July 2010 - 02:57 PM

• MrCupOfT

Reputation: 2298
• Posts: 9,535
• Joined: 29-May 08

## Re: Recognizing more elegant and concise coding solutions

Posted 17 July 2010 - 09:22 PM

In vb.net using a generic extension method with optional parameters, it can be done in one line.
Public Module Module1
Public Sub Main()
Dim sr = {1, 3, 5, 9, 4, 7, 2}
Dim rr = sr.SidewaysSort()
End Sub

<Runtime.CompilerServices.Extension()>
Public Function SidewaysSort(Of T As IComparable)(ByVal Source As IEnumerable(Of T),
Optional ByVal output As IEnumerable(Of T) = Nothing, Optional ByVal s As Boolean = True) As IEnumerable(Of T)
Return If(Source.Any(),
If(output Is Nothing,
Source.OrderBy(Function(x) x).Reverse.SidewaysSort(Enumerable.Empty(Of T), s),
Source.ToArray.Skip(1).SidewaysSort(If(s,
Source.Take(1).Concat(output),
output.Concat(Source.Take(1))
), Not s)),
If(output Is Nothing, Enumerable.Empty(Of T)(), output))

End Function
End Module

### #7 Raynes

• D.I.C Lover

Reputation: 614
• Posts: 2,815
• Joined: 05-January 09

## Re: Recognizing more elegant and concise coding solutions

Posted 17 July 2010 - 09:40 PM

My first example was a one liner that I formatted over several lines so as to not burn everyone's eyes. When did this turn into a competition? ;o

EDIT: In case you don't get the punchline, all Clojure code is a one liner, but most people like to scroll vertically rather than horizontally, much like C/C++.

This post has been edited by Raynes: 17 July 2010 - 09:51 PM

• MrCupOfT

Reputation: 2298
• Posts: 9,535
• Joined: 29-May 08

## Re: Recognizing more elegant and concise coding solutions

Posted 17 July 2010 - 11:21 PM

C#4 version
public static IEnumerable<T> SidewaySort< T >(this IEnumerable<T> source, IEnumerable<T> output=null,bool s=true)
{
return source.Any()? (output == null) ?
source.OrderBy(x => x).Reverse().SidewaySort(Enumerable.Empty<T>(),s) :
source.Skip(1).SidewaySort( s? source.Take(1).Concat(output) :
output.Concat(source.Take(1)),!s) :
output == null? Enumerable.Empty<T>(): output;
}

### #9 moopet

• binary decision maker

Reputation: 343
• Posts: 1,189
• Joined: 02-April 09

## Re: Recognizing more elegant and concise coding solutions

Posted 18 July 2010 - 01:09 AM

Also, in addition rather than in conflict with what the others have said, don't try too hard to be "elegant".
I remember when I was learning C, it gave me a warm feeling deep inside to cram as much functionality into one statement as possible, using as many shortcuts as I could. If someone else's program was a hundred lines and mine was ten, that was what made mine better... except it wasn't. It's sometimes hard to tell beautiful code from ugly when you're a beginner.

The priorities as I see them are:
Make it work
Make it clear and understandable
Make it simple

And out of that should come the elegance you're looking for. You've already done the first (or at least understand why it doesn't work) and your code is certainly easy to understand without needing extra commenting. Looking at the logic you use, after a while you will just automatically go back over it and reduce it to fewer, more *targetted* statements, *if* that helps.

### #10 mostyfriedman

• The Algorithmi

Reputation: 729
• Posts: 4,473
• Joined: 24-October 08

## Re: Recognizing more elegant and concise coding solutions

Posted 18 July 2010 - 04:59 AM

Codebug, on 15 July 2010 - 10:29 PM, said:

I still consider myself a beginner programmer as I've been programming for less than a year. I feel that I am way better than when I first started, but when I see other people's code, I can get discouraged. Generally speaking, at what point should I start to see improvements in my code?

I absolutely love coding, but after reading a few articles online that point out that good programmers are born and not made, I wonder if I have what it takes to improve. These same articles drive home the point that you will make your improvements the first 3 to 4 years of coding.

Like I said, I love programming. Alot. I just wonder if I have what it takes to produce good code or if all I will ever be capable of is clunky mediocre code. It seems that I go through phases where I feel pretty good about my skills, and phases where I feel badly about them.

If you've made it to the end, I applaud you. Tell me what you think.

Thanks

I haven't looked at your solution or any of the solutions yet, I will also give it a shot later, I am at work now. But anyway I just wanted to tell you that when you look at other people's code, instead of getting discouraged, think "hey, that's a really elegant solution, I should really understand how it works so i could use these ideas later when i try to solve other problems". Looking at other people's code and solutions can be of great use, you can learn different sorts of cool hacks and tricks from others that you could modify and use later, You should however try to solve the problem yourself first before looking at other people's solutions. Good luck

### #11 baavgai

• Dreaming Coder

Reputation: 7055
• Posts: 14,734
• Joined: 16-October 07

## Re: Recognizing more elegant and concise coding solutions

Posted 18 July 2010 - 07:52 AM

Didn't realize this was a multi language affair. Oh, Python:
def strangeSort(a):
sorted = []
for i in range(len(a)):
v = max(a)
a.remove(v)
if i%2==0:
sorted.insert(0,v)
else:
sorted.append(v)
return sorted

Looking at this, I can make it slightly more cute:
def strangeSort(a):
sorted = []
for i in range(len(a)):
v = max(a)
a.remove(v)
sorted.insert(i%2*len(sorted),v)
return sorted

And that's the danger. Optimization is too often obfuscation. It's pretty clear what my first one is doing. The second one, not so much, though it's clever and saves some lines.

C is where this game used to be played the hardest, but other languages are not immune. I program in C# professionally, but it takes me some consideration to follow what Adam's version does.

In programming, simple beats clever every time. Clever solutions are often one offs, useful only for a narrow situation. Simple, clear code is both useful but also more adaptable, serving as a guide for similar jobs. The programmer should always be a generalist.

@moopet: I couldn't agree more.

### #12 cfoley

• Cabbage

Reputation: 2388
• Posts: 5,012
• Joined: 11-December 07

## Re: Recognizing more elegant and concise coding solutions

Posted 18 July 2010 - 05:32 PM

Codebug, you like this line of mine?
final int center = (n.length / 2) - 1 + (n.length % 2);

[s]I'm not so keen actually. It's pretty cryptic. I had previously written a bunch of stuff here but it now makes me feel silly. This is far better:

final int center = (n.length - 1) / 2;

This post has been edited by cfoley: 18 July 2010 - 06:49 PM