optimizing an expression

M

Moi

Next attempt (a bit inspired by de Bruijn numbers ...) :

*****************************************************/

int median3x(int a,int b,int c)
{
/* 2.0 1.1 0.2 0 */
switch( (0x2148U >> (idx=(((a>b)<<1)+((b>c)<<2)+((c>a)<<3)))) &3) {
case 0: return a;
case 1: return b;
case 2: return c;
}
}

***********************/


Still want to get rid of that switch...

AvK
 
S

spinoza1111

I know its straightforward.  It's still clunky and unclear.  If you
really want that interpretation, but some brackets in there.  Program
as you if expect other people to read your code. Express your intent,
and don't expect everyone to enjoy C's more pointless idioms as much
as you do.

The idiom isn't "pointless". It shows in fact that logic can be as
elegantly expressed as mathematics. It's one step away from Cobol.
You should use the features of the language when there is a benefit to
doing so, other than less typing.  That way, Perl Golf lies.  There's
no benefit to your code, except that is slightly harder to parse.

If you write code to demonstrate how smart you are, or how much of the
language you have mastered, you'll write unmaintainable code.  Master
the language, but then exhibit good taste, and respect for people
who've not reached your level of mastery.

It's an Urban Legend that the software crisis was caused by
"pretentious" programmers using "obscure" constructs in order to "show
how smart they were".

In actuality, it was caused by savage managers who drove programmers
to ship at places like IBM in 1965 and Apple in 1981, not giving a
**** about the damage they caused to people's lives in their greed.

It meant that many programmers were unfamiliar with the languages they
used, being thrown with too little training on Death March projects
with insanse deadlines.

It is now accepted as a condition of employment that managers may make
absurd claims as to the doability of systems by such and such a date
in a forty hour week, and that the programmers will work 120 hour
weeks to make the deadline prediction come true and the manager look
good.

As a result, programmers hate their jobs and their lives, and the
notion of joyously coding

intSignum = intX > 0 ? 1 : (intX < 0 ? -1 : 0)

as opposed to this crap

if (s>0) return 1; return -1;

is now "pretentious". The former code snippet offends brutalized
programmers for the same reason people here confuse complete sentence
structure and accurate spelling with verbosity.
Good programming involves writing code that is easy to understand by
someone who is not a good programmer.  Much as good technical writing
is writing that is easy to understand by someone who does not know the
product as well as the writer.

So runs the hymnbook. The problem is that such boilerplate ignores the
fact that "easy to understand" is not itself a simple concept. The
fact is that some programmers are so brutalized and so subject to food
and other forms of addiction, that they labor to understand almost
anything, and efforts to clarify only confuse. They then use a
remythologised Urban Legend of "structured programming" to mean
"something that fits my prejudices and that I understand without
mental effort".

[Such as an implementation of signum that divides by zero when x is
zero.]

It would take a Habermas to show the fundamental contradiction in
software development, but I shall try. Habermas, a German philosopher,
draws a distinction between language used to make money (the language
of business) and language used when discussing affairs between friends
in what he calls "civil" society, a conversation where we try to
arrive at scientific or political truth without worrying about
economic success or failure.

Gerald (The Psychology of Computer Programming) Weinberg discovered
that in the "structured walkthough", the fair, dialogic, and open
conversation typical of friends agreeing, or agreeing to disagree, in
a sidewalk cafe was more productive in commercial software than the
hiding of information, personality destruction, and competitiveness
characteristic of business.

Years later, "open source" found that people were more productive when
coding for free and not looking over their shoulders to see if their
fat salaries were under threat, since the fat salaries weren't there.
In parts of open source, Habermasian civil society makes the process
fairer and less competitive, a common search for truth (something that
works).

Dijsktra, finally, discovered that debugging is a matter of applying
the scientific method; but the prevelance of Fundamentalist religion
and various forms of cultish denial (Holocaust denial, denial that
Shakespeare wrote "Shakespeare", Creationism and Zionism) amongst
technical people show that they are unclear on the concept of
scientific method and prefer a sort of folklore in programming, which
includes saws such as "keep it simple", saws that have the property
that their referents are vague.

Owing to the fact that most software conversations take place in the
competitive business arena, they are ridden by hypercompetitive
nastiness, which also infects these conversations here because so many
people crawl in here brutalized by capitalism and anxious to retrieve
their lost manhood by being bullies. Also, it's quite possible that
some people, who post compulsively and continuously, are being paid to
trash this conversation, transforming it from an adult, civil and
Habermasian search for agreement and truth to howling at the
moon...lest these threads turn out to be a basis for labor solidarity
and organization.

Of course, most Americans and UK subjects have no concept whatsoever
of Habermas' distinction between biz-talk and a common search for
truth in civil society. They are taught instead that in the modern,
globalized-capitalist world, enormous fortunes are made by brilliant
men far more talented than they, despite the fact that Tim Berners-Lee
really screwed up the design of the Internet and that Bill Gates could
not even program Donkey Kong.

Furthermore, popular culture (cf Zizek) can be usefully viewed as
proposing to destroy the space of civil conversation, and replace it
with dreams that in Adorno's words have no dreams: movies, substance
abuse and trivial bullshit instead of a common search for truth.
 
M

Moi

Hope the compiler will see the CSE in this one:

***********************************/

int median3(int a,int b,int c)
{
/* 2.0 1.1 0.2 0 */
return (( (0x2148U >> ((((a>b)<<1)+((b>c)<<2)+((c>a)<<3)))) &3) ==0)*a
+ (( (0x2148U >> ((((a>b)<<1)+((b>c)<<2)+((c>a)<<3)))) &3) ==1)*b
+ (( (0x2148U >> ((((a>b)<<1)+((b>c)<<2)+((c>a)<<3)))) &3) ==2)*c
;
}

/**********************************

AvK
 
B

Ben Bacarisse

Phil Carmody said:
printf("I see %u ship%s.\n", nships, "s"+(nships==1));

While we are composing variations on this theme:

printf("I see %u ship%.*s.\n", nships, nships != 1, "s");

but in practise I do it Gareth's way because I don't want the code to
depend in the length of the plural ending; even though it is fixed for
any one word.
 
M

Moi

This version still has one conditional jump too many in the code path.
( GCC needs the temp, because it does not appear to recognize the CSE)

************************/

int median3(int a,int b,int c)
{
/* register */ unsigned tmp;

/* 2.0 1.1 0.2 0 */
tmp = ( (0x2148U >> ((((a>b)<<1)+((b>c)<<2)+((c>a)<<3)))) &3);
return tmp & 2 ? c : tmp ? b : a;
}

/***********************


AvK
 
B

Ben Pfaff

Phil Carmody said:
printf("I see %u ship%s.\n", nships, "s"+(nships==1));

This sort of thing is always clever, but it falls down badly when
you need to internationalize your code.
 
K

Keith Thompson

Phil Carmody said:
Better written as:

puts(condition ? "A message" : "Another message");

Ok, I picked a poor example.

What I object to is code that uses ?: rather than if-else for no good
reason. Avoiding writing the same code twice (the puts() call) can be
a good reason. So can writing code for a function-like macro. Saving
keystrokes is not.

[...]
A coding standard which is 100% strict about how wide a tab is
may also approve or demand the use of tabs.

In my experience, nothing works better than a complete ban on tabs in
source code. There are too many different opinions on how wide a
tabstop should be (which is, or should be, a different question than
what an indentation level should be).
 
N

Nisse Engström

I do sometimes write fairly long *linear* chains of conditional
operators. For example:

printf("x = %d = %s\n",
x,
x == SOME_CONSTANT ? "SOME_CONSTANT" :
x == ANOTHER_CONSTANT ? "ANOTHER_CONSTANT" :
x == YET_ANOTHER_CONSTANT ? "YET_ANOTHER_CONSTANT" :
/* ... */
"???");

I sometimes find chains like the above to be much
clearer than some long unwieldy if-else ladder.
Here's another example, from a few years back:

(offLmod == offRmod ? ror_d0 :
minlen <= BITS ? ror_short :
offLmod < offRmod ? ror_long_dn :
ror_long_up )
(bsL->data+offLdiv, bsR->data+offRdiv, offLmod, offRmod, minlen);

I realize now that maybe it should've been:

void (*fptr)(/* args */) =
(offLmod == offRmod ? ror_d0 :
minlen <= BITS ? ror_short :
offLmod < offRmod ? ror_long_dn :
ror_long_up);

(*fptr) (bsL->data+offLdiv, bsR->data+offRdiv, offLmod, offRmod,
minlen);

I think both are very readable and maintainable because
of the way the conditions and results are listed in
separate columns, and because the function arguments
only have to be spelled out once.


/Nisse
 
N

Nisse Engström

Better still, wrap up the complexity in a function:

typedef void ror_function_type( /* args */ );

/* ... */

ror_function_type *p = get_ror_function(offLmod, offRmod, etc!);

(*p)(args);

A typedef for the function declaration is definitely
a win.

I think that the control logic (in this case where
it is used only once) is a little to short to be moved
away into a separate function, but I'll concede that
you have /at least/ half a point.

On the other hand, the exact same logic appears in
several files, but with a different set of functions.
That may yet give cause for some creativity.


/Nisse
 
S

spinoza1111

This sort of thing is always clever, but it falls down badly when
you need to internationalize your code.

So would the equivalent if else. I am aware that in practical
internationalization, programmers are directed to use "resources" of
strings with the "right" translations normally prepared by technical
writers and translators. Correspondingly, they are discouraged in my
experience from writing code like the above which seems and is rather
clever...but ties the program to English, thereby increasing le
dominance Anglo-Saxonne over tout le monde in fashion neo-colonialiste
alors peut etre Fasciste.

My own theory is that programmers should be widely and deeply cultured
with the resulting awareness of when they are building in such a
dependency. The problem being that most programmers are what the
Russians would call ne kulterni and what Indian chaps call jungly.

It is a wicked world. When I first read, in Frederick Brooks' The
Mythical Man Month, of the concept of The Chief Programmer, I saw

Hor. Where my Lord?
Ham. In my Minde's Eye, Horatio.

Klaatu from The Day the Earth Stood Still, in his cool spaceship in a
business suit like my father

Ham. I thinke I see my Father

But then I woke up and looked about me. The head of my company,
despite his reputation as being a "great" programmer (he'd developed
credit reporting systems which now mess up our lives) was to my father
Hamlet's "satyr" to "Hyperion", a man who looked like a frog with no
table manners or any other manners worthy of note.

I could see that the position of Chief Programmer would always go
unfilled. But a Chief Programmer would know as much about
internationalization as does Bjarne Stroustrup, without having
Stroustrup's many illusions.

One peruses Zizek and Lacan because of this paradox. A society which
worships power and control takes it away from each one of its members.
 
S

spinoza1111

Oh, that's pretty. I'm not sure I like it, but it's pretty.

Away with this Bauble, as Cromwell said of the Parliamentary mace. It
is an IDIOM. It's like saying in Cantonese "lok gau si" or "falling
dog poo" (¸¨ª¯«Ë: the Cantonese idiom for "raining cats and dogs"). It is
falling C poo.

Furthermore I do not see why this false cleverness gets even qualified
praise when people here defend nonsense such as

a=*b; // Not even needed in C sharp

or

return x>0 ? 1 : -1; // "Signum" my ass
 
S

spinoza1111

So would the equivalent if else. I am aware that in practical
internationalization, programmers are directed to use "resources" of
strings with the "right" translations normally prepared by technical
writers and translators. Correspondingly, they are discouraged in my
experience from writing code like the above which seems and is rather
clever...but ties the program to English, thereby increasing le
dominance Anglo-Saxonne over tout le monde in fashion neo-colonialiste
alors peut etre Fasciste.

My own theory is that programmers should be widely and deeply cultured
with the resulting awareness of when they are building in such a
dependency. The problem being that most programmers are what the
Russians would call ne kulterni and what Indian chaps call jungly.

It is a wicked world. When I first read, in Frederick Brooks' The
Mythical Man Month, of the concept of The Chief Programmer, I saw

Hor. Where my Lord?
Ham. In my Minde's Eye, Horatio.

Klaatu from The Day the Earth Stood Still, in his cool spaceship in a
business suit like my father

Ham. I thinke I see my Father

But then I woke up and looked about me. The head of my company,
despite his reputation as being a "great" programmer (he'd developed
credit reporting systems which now mess up our lives) was to my father
Hamlet's "satyr" to "Hyperion", a man who looked like a frog with no
table manners or any other manners worthy of note.

I could see that the position of Chief Programmer would always go
unfilled. But a Chief Programmer would know as much about
internationalization as does Bjarne Stroustrup, without having
Stroustrup's many illusions.

One peruses Zizek and Lacan because of this paradox. A society which
worships power and control takes it away from each one of its members.



- Show quoted text -

That is, Babbage was prescient if also a horse's ass in naming his
book Life of a Philosopher: for I've always believed that the only
people qualified to be programmers would be philosophy majors.

Let the è½ç‹—屎 begin...
 
P

Phil Carmody

Seebs said:
Oh, that's pretty. I'm not sure I like it, but it's pretty.

I'm surprised. I would have expected a response more like:
"Oh, that's ugly. I'm pretty sure I like it, but it's ugly."

Phil
 
P

Phil Carmody

Richard Heathfield said:
It's very 90s. (Sorry, Phil, but it is.)

I think I first used its BASIC equivalent in about 1982 on my ZX-81,
when coding 99-bottles. So you've flattered me enormously by calling
it 90s!
So is:

printf("I see %u ship%s.\n", nships, &(nships==1)["s"]);

That's IOCCC-ies.

Phil
 
P

Phil Carmody

Ben Pfaff said:
This sort of thing is always clever, but it falls down badly when
you need to internationalize your code.

But there it falls down on the 9th character, not at the 38th.

Phil
 
R

Richard Bos

Ben Pfaff said:
This sort of thing is always clever, but it falls down badly when
you need to internationalize your code.

True, but when you need that, there is no single printf() call that
prints that sentence reliably. Even

if (nships==1)
printf(inter("I see 1 ship.\n"));
else
printf(inter("I see %u ships.\n"), nships);

while a lot more internationalisable, is not enough to guarantee
portability to all languages.

Richard







(Hint: two.)
 
R

Richard Bos

Phil Carmody said:
A coding standard which is 100% strict about how wide a tab is
may also approve or demand the use of tabs.

If so, such a coding standard will only work in-house, on a strictly
controlled set of hardware. It's possible, but it's harder work than a
coding standard should want to do.

Richard
 
S

sfuerst

It's very 90s. (Sorry, Phil, but it is.)

I think I first used its BASIC equivalent in about 1982 on my ZX-81,
when coding 99-bottles. So you've flattered me enormously by calling
it 90s!
printf("I see %u ship%s.\n", nships, &(nships==1)["s"]);

That's IOCCC-ies.

Phil

Nah, this is IOCCCness...

printf("I see %u ship%s.\n", nships, "s"+!~-nships);

Using all three types of negation in one expression is priceless, the
C equivalent of Euler's idenity.
(Assuming 2's complement arithmetic, of course.)

Steven
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,278
Latest member
BuzzDefenderpro

Latest Threads

Top