text:
DISARM THE B.O.M.B.!
You have been hired for your tech knowledge as a Secret Agent's sidekick to ensure that the good guy can get his job done and the world can be saved.
This is your last mission before retiring with a high paycheck and the gratitude of the whole world. But before you have to disarm the Evil Genius' Big Overly Massive BOMB (seems that the evil genius is a smart ass who likes recursive acronyms). Anyways you and your buddy are in the very core of the Evil Genius secret base, ready to disarm the BOMB that could wipe the continent out. In your previous mission you managed to get the disarm code that to your astonishment is just "PASSWORD_01". You connect your keyboard to the BOMB but when you are ready to go, the Evil Genius' henchmen enter in with a barrage of bullets. Unfortunately one of these bullets impacts on your keyboard. "Finish the job while I distract those d*ckheads!" says your buddy and then begins to fire his gun. But how could you finish the job with only half a keyboard?
SPECS

Write a program that outputs in any way you want the string PASSWORD_01 (uppercase).
Since your keyboard has been hit by a bullet, you can only use these keys:
1 2 3 4 5
Q W E R T
A S D F G
< > Z X C
Ctrl Shift Tab Space
Using the Shift key, your keyboard allows you to use these characters:
! " · $ %
You don't have any other hardware than the keyboard and the screen (a mouse for example), nor a file with the password written in your computer.
You don't have an Internet connection.
You can assume you have the interpreter shell / source editor opened before the bullets came in. Sadly you have not written anything in it before the keyboard was hit.
You don't have a virtual keyboard. In fact the BOMB has a TOO_FUNNY detector that will make it explode if you try to use the Standard loopholes.
Since your buddy is waiting for you to finish soon to escape off the Secret Base, you will have to write the smallest code possible (so it's restricted-source and code-golf!).

Good luck because the count down has begun!
HELP MODE: Also a KEY (only one Key you want from the keyboard, but not the Shift + Key or any other combination) has miraculously survived too. E.g.: You can use =, or 0 or /… This extra key cannot be any of the letters in PASSWORD_01 (so you cannot add P or O). Name that key in your answer. You have a penalization of 10 characters for use of this key regardless of how many times you use the key.

Any chance you could include the characters : = or I cant even attempt this challenge since I need to assign values :P Also, are the arrow keys still working?

@TeunPronk added Help Mode ;)

Can I change the layout of the keyboard to DVORAK?

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ No, sorry. I'm afraid that the Agency only provide you a Qwerty Keyboard :S

Can I assume I'm running in a Python or JS console? Because I can't think of a language where I can actually print anything at all without the right side of the keyboard :s

@Tal You can assume it while you play in the spirit of the challenge.

What's the third Shift character? (It doesn't look like a period or a hyphen, so...)

@Volatility · A middle dot (In my keyboard... I say in the Agency Keyboard is Shift + 3)

What bastardised version of the Spanish keyboard layout are you using which puts & on shift-5 rather than %?

Deleted my answer, will look for a better solution. So to make sure, besides the keys you named nothing else works? not even the keys that don't generate input?

@PeterTaylor my bad! It's a %. Fixed. Hope not to cause any disrupt to other answers.

no parenthesis, no square brackets, no chain brackets... well that must eliminate 99% of languages.

It's much more troublesome without &.

Do we get the enter key at least?

Is "·" === "." ?
This will brainfuck brainfuck....

@TejasKale I hope it is, because otherwise I actually can't think of how to do this at all.

Thinking about it again, "·" is coming from Shift + 3and is not equal to "."

. is not equal to · Also, maybe we could allow multiple uses of help mode adding 10 to the code count for each new key saved.

Where's my CAPS LOCK? Must have been multiple bullets...

@Averroes yes do that :D are we gonna do that? :P

@Averroes Also, can you pick any key you want for the help mode?

@TeunPronk I would like to prevent someone just picking all the letters from PASSWORD_01.

Whitespace, here is your big chance!

"You have a penalization of 10 characters for use this key." Is that 10 for each press of the key, or for each distinct character used? You might want to make that clear, since current answers are scoring it the latter way.

What about boilerplate code created by your IDE, which included disallowed characters. Can they still be there, I don't want to copy/paste from it or anything like that, if not then this excludes languages like C# and Java doesn't it?

Wouldn't you only be able to use the keys on the broken keyboard to write the program too?

@Geobits +10 for use the Help mode. Then you can use that key as many times as you want (edited, thanks).

@BumblebeeMan I'm afraid that it will open the door to more changes and ambiguities in the specs.

@Averroes No worries, at least now I can claim that I totally could have completed the challenge otherwise...honest

If only I had some parenthesis :(

hopefully, before the mission i configured my PHP installation with asp_tags, so i can start with <%. * hands on *..... can't use functions nor arrays.... * run run run *

Can the Help Mode key be one from the number pad section of the keyboard?

Why couldn't the password have been stewardesses?

Is the character map a virtual keyboard?
http://i.imgur.com/Bk9PHv9.png

Is this one of these weird keyboards that doesn't have an Alt key?How did my control key survive, and my spacebar, but not my alt?

@Shane nice try but how did you get there? :P

@NateKerkhofs It was a JFK bullet. It hit the keyboard multiple times.

@BradleyUffner Nope. You can get a character but not a function or something like that. You could have the number nonetheless.

Joke answer: I'm a spy, I switch to the backup keyboard hidden in my watch.

@NateKerkhofs or the one in your shoe!

I also hope whoever needs to enter this code can touch type really well, because  there's no backspace to correct mistakes.

Every code-golf users should look at this question for how to create an interesting background story.

Can I use the Tab key for auto-completion in bash?

@user80551 I would say autocompletion will go against the spririt of the game if it make your work very easy.

Can I use vi or emacs? or would it be a loophole? :grin:

"This is your last mission before retiring" - well, there's no way I'm surviving the day, then. I suppose copy-pasting characters from places like other documents or desktop icon names is out of the question; is it?

< and > aren't on the left part of a keyboard

@kinokijuf mine yes

@user2357112 I would say it is

This is a bitch in PHP :( Can't use any function because of the (), and a lot of functions have an underscore in them.

@Martijn next challenge will be with the other side of the keyboard :P

“Big Overly Massive BOMB” is not a recursive acronym because the B is fixed.

@kinokijuf: It is. It's a tail recursive acronym.

does the mouse work?

@StackTracer Nope, you haven't a mouse.

Although the TOO_FUNNY detector catches the standard loopholes (which is a neat idea to get around those), I’d be somewhat intrigued to see which of the standard loopholes can still work here.

What happens is you do Shift-<>?

-1: doesn't include the ; line ending that is required for many languages, not to mention , these challenges are typically not well received in the first place...

@tuskiomi You having a bad day? You realize this challenge is amazingly received and 2 years old? Look at the successful answers. Go learn some more languages besides Java. I literally just solved the challenge, so it's do-able.

@mbomb007 not having a bad day. I'm strongly against challenges that promote golf / esoteric languages.

@tuskiomi I see a Ruby answer, a Perl answer, and multiple Python answers...

@StevenH. that's good.

@german_guy You don't have the Enter or Return keys, so there is no WS support here.

Can I swap those unusable characters with their ascii codes, represented with 1 to 5?

@MatthewRoh By the spec, yes.

Uh trying to do this in JavaScript is hard, I can't seem to get to a point of getting any useful characters...

The thing is English generally use keys on the right side of the keyboard to form a word...

CJam - 24 + 10 (() = 34
"Q"c("ASSW"1$("aRD"(((T1

No additional key - 39
211 131%c"ASSW"211 132%c"RD"321 113%cT1

Try it at http://cjam.aditsu.net/

Background music: https://www.youtube.com/watch?v=6iaR3WO71j4

bash, vim and dc (343)
I'm sitting at a bash prompt which has been configured by the Evil Genius, and of course he has VISUAL=vim in the default environment. Using the default bash binding for edit-and-execute-command (C-x C-e) bash invokes $VISUAL and will execute its buffer contents on exit (ZZ). I type in the following sequence (Note: kbd-mode are commands issued in normal mode and control sequences):

C-xC-e

acat<<<45C-c4C-aaa
Now the vim buffer contains cat<<<49a. Continuing ...

45C-c3C-aaa

54C-c41C-aaa

55C-c13C-aaa
Now the vim buffer contains cat<<<49a48a95a68a. Continuing ...

51C-c31C-aaa

55C-c24C-aaa

44C-c43C-aaa

42C-c41C-aaa

42C-c41C-aaa

54C-c11C-aaa

55C-c25C-aaa>s
Now the vim buffer contains cat<<<49a48a95a68a82a79a87a83a83a65a80a>s
Get out of insert mode, save and exit

C-cZZ
The s file now contains a dc script that generates the desired string on the stack, now we need to add print commands.

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ
Repeat the above command 9 times.

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eacat<<< f >>s
Execute the dc script:

C-xC-eadc sC-cZZ

Output:
PASSWORD_01

Contents of the s file:
49a48a95a68a82a79a87a83a83a65a80a
P
P
P
P
P
P
P
P
P
P
f

I was thinking to do a vim script because of the Ctrl character; good thinking to pair it with dc! Also, excellent solution :)

How long did it take you to write all those  tags?

@justhalf: I wrote it in vim with <Leader>k bound like this map <Leader>k i<kbd></kbd>^[F>a, so it wasn't as bad as it looks :-).

Now it's apparent that Agent Thor knows his tool thoroughly. You deserve the retirement, sir!

Ruby, 57 + 10 (*) = 67
$*<<4*4*5<<214%135<<44%25*5<<1%1
$><<"%cASSW%cRD%c%d1"%$*

This answer uses * and % to build the ASCII values of the missing characters (and 0 as Fixnum) and pushes them into $* (ARGV). This array is then used in combination with a format string to generate the correct password, which is printed with $><< ($> is stdout).
Ruby, 62 + 10 (.) = 72, no linebreak
$>.<< "%cASSW%cRD%c%d1".% %w%%<<311%231<<214%135<<321%113<<1%1

Roughly the same principle as the above version, except that here the array is built from an empty array literal (%w%%). Some fiddling with . is needed to get the desired operator precedence.

"This is your last mission before retiring with a high paycheck and the gratitude of the whole world." Congratulations, we all thank you :)

The ultimate proof that Perl is one of the biggest inspiration of Ruby.

How did you do the linebreak?

@Arian The same way nneonneo runs his Python code after typing it into the REPL ... I'll add a version without linebreak.

Does the evil genius have ruby installed?

Whitespace (148 + 10 = 158)
Enter key needs to be used here.
SS+1010000L // Push code of P
TLSS        // Output character
SS+1000001L // Push code of A
TLSS        // Output character
SS+1010011L // Push code of S
SLS         // Duplicate top stack
TLSS
TLSS
SS+1010111L // Push code of W
TLSS
SS+1001111L // Push code of O
TLSS
SS+1010010L // Push code of R
TLSS
SS+1000100L // Push code of D
TLSS
SS+1011111L // Push code of _
TLSS
SS+0L       // Push 0
TLST        // Output number
SS+1L       // Push 1
TLST        // Output number
LLL         // End program

My notation's explanation:

S, +, 0 are spaces.
T, 1 are tabs.
L is new line.
// starts comment.

Each line is a command in whitespace language.
Demo

Ah man... I was just working on that :(

Me too, but I gave up on this knowing someone would be faster

I thought 'L' wasn't available?

@500-InternalServerError: Actually L stands for new line character. Check the Demo for the real code. What I posted is a readable version.

Ah, I get it now.

I know it's been almost 4 years, but you can golf the three trailing new-lines. Try it online.

@KevinCruijssen Is it part of the specs, or implementation-dependent?

Implementation-dependent I guess. The specs say a program should end with three LF, but many interpreters will run without. Got it from the Whitespace tip thread.

101 bytes. Here a highlighted/commented version: Try it online. It basically utilizes this Whitespace tip of mine, and the best constant 80 is generated with a Java program.

@KevinCruijssen: Please go ahead and post your solution as an answer :)

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Done. :)

Insomnia 39 35 31 29
This language comes up when I was looking around for a language that encodes its instructions with single ASCII character. The language actually operates on the decimal ASCII code of the character, so it is still quite flexible with half of the keyboard destroyed.
Drop it down further to 29 characters, which is possible after reducing memory usage and increases the search space:
FdFzt%dF<rGdt>tt Gtreeet t%4s

I decided to run my tweaked up program on the full set of allowed characters, and cut the solution down to 31 characters:
FdFGt dtreeC>tt FFdx<Fdtr ztq4s

I used a program to search for this solution. It is one among many solutions returned by my program, all with the same size.
Fddx>"eCeezdC>CefCdddzCzzfCqred>r4s

Old version constructed by hand. I remember staying up till morning to do this.
Fddx>"eCeezdC>Cef>dx"dCezeeedeCrqeeC%4s

Here is the Insomnia interpreter for testing.

+1 for the "staying up till morning" match with your programming language choice.

Python (2200 395 + 10)
exec"""exec"exec"+"%ca"%34+"%c52+53"""+"%c55+55"%44+"%c34"%44+"%c45+35"%44+"%c"%44+"""34%%cexec"%"""+"%c"%54+"""1+"%c"%34+"%%5%c+"%5"""+"%c"%55+"""+"%c"%34+"%c"""+"%c"%112+"""r%%c%%ct%%c%%cASSW"+"%c%%34+"%34+"%c%%cRD"%34+"%c%%"""+"%c"%55+""""%34+"%c+"%5"""+"%c"%55+"""+"%c%%c"%34+"%c%%"%34+"%c5+"%5"""+"%c"%55+"""+"%c"%34+"%c1%%c"+"%c%%4"%34+"%c+"%5"""+"%c"%54+"""+"%c"%34+"%c%%a"+"%c%%34"%34"""

I needed the + character (costing +10), which can be obtained from the numpad (or on certain key layouts).
Yeah, the BOMB probably went off while I was typing that.
The basic approach is to construct ever larger character sets by using exec and "%c"%(number). There are four execs nested inside each other. Gradually, my digit set progresses up from

12345
1234567 (6 = ASCII 54, 7 = ASCII 55)
123456789 (8 = ASCII 56, 9 = ASCII 57)
0x0123456789abcdef

so that in the final iteration it is possible to express any character (so that the innermost version can actually run any program at all).
Around 50% of the program is just quote characters ("%c"%34 is a double quote), because the nested nature of the exec statements demands "escaping" quote characters aggressively.

If you use the "+" from the numeric keypad, you are independent from the keyboard language.

@celtschk: Good point! I will edit that in.

Rather than constructing digit sets with nested execs, couldn't you get numbers using arithmetic? Ex. exec '%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c'%(112,114,51+54,55+55,1+115,32,4+35,25+55,11+54,31+52,31+52,32+55,24+55,31+51,13+55,41+54,3+45,4+45,4+35)

Because you can't get both parens. (I did consider this!)

Additionally, Python doesn't have a lot of operators that bind more strongly than %. ** is one, but it tends to be fairly useless for constructing most terms.

Vim + PHP on Some Window Managers
65 keys in 44 strokes, with a 10-point penalty for using =.
aEACE<Alt+Tab>z=5<Alt+Tab>$xxxxaASSWRD<Alt+Tab>z=1<Alt+Tab>
$a$aA<Alt+Tab>==wxx$r1<^X>a1

A breakdown:

Alt+Tab appears to work like Esc with Vim, or perhaps with this terminal emulator. Thanks for teaching me something new!
aEACE<Alt+Tab>: Enter append mode and insert “EACE”. Exit.
z=5<Alt+Tab>: Perform spelling correction. Select 5, “PEACE”. Exit. (Esc seems to work as Enter here!)
$xxxxaASSWRD<Alt+Tab>: Go to the end of the line. Delete 4 characters and add ASSWRD, resulting in PASSWRD. Back to normal mode. (No, 4x won’t work.)
z=1<Alt+Tab>: PASSWORD is probably going to be the first correction for this. Select it.
$a$aA<Alt+Tab>: Go to the end of the line, and add a $aA. Back to normal mode.
==: Format this line of PHP nicely, changing the camelCase $aA to $a_a. This also moves the cursor back to the start of the line.
wxx: Go forward a word; the cursor is now before $. Delete two characters – the $ and the a – to make PASSWORD_a.
$r1: Go to the end of the line and replace the current character (i.e. a) with 1, resulting in PASSWORD_1.
^X: Decrement the integer under the cursor, resulting in PASSWORD_0.
a1: Finally, append 1, for PASSWORD_01!

I can't replicate == command, it just toggles large indentation mode in my vi setup (debian 7, v7.3.547)

Python 2, 75889 bytes
No extra character!
Unfortunately, the code is super long. So instead, here's the code to generate the program:
x=[2**n for n in xrange(16)]
y=-5
print('exec"""exec'+x[7]*'%'+'c""'+x[6]*'%'+'cr'+x[-2]*'%'+'c'+x[-1]*'%'+'ct'+x[8]*'%'+'c'+x[-4]*'%'+'cASSW'+x[-5]*'%'+'cRD'+x[-3]*'%'+'c'+x[0]*'%'+'s1'+x[10]*'%'+'c '+x[9]*'%'+'c""'+x[y]*'%'+x[1]*'%'+'s'+x[y]*'%'+x[2]*'%'+'s'+x[y]*'%'+x[3]*'%'+'s'+x[y]*'%'+x[4]*'%'+'s'+x[y]*'%'+x[5]*'%'+'s"""'+'%`1>>1`%`2531>>5`%`321>>2`%`1521>>4`%`211>>1`%`221>>1`%112%34%34%34%34')

Try it online
(to run the code, change the outer print into an exec. Or, generate the program, then paste and run. Or copy from the hastebin linked below.)
Explanation:
The goal is to execute:
print"PASSWORD_01"

To avoid using ()+ chars, we have to use multiple string format operations chained together. This means that each step added effectively doubles the number of % characters needed for each previous step:
print"%cASSW%%cRD%%%%c%%%%%%%%c1"%80%79%95%48

This is not enough though, because some of the numbers required cannot be created, and neither can we create print. So we add a level of abstraction with exec for printing, and a level for the ASCII code points we cannot create to format with. The following is essentially my answer, but with each string of % reduced to a single one (note that the %s%s%s%s%s is not an accurate representation, failing to account for the literal %'s required before each):
exec"""exec%c""%cr%c%ct%c%cASSW%cRD%c%s1%c %c""%s%s%s%s%s""" % `1>>1`%`2531>>5`%`321>>2`%`1521>>4`%`211>>1`%`221>>1`%112%34%34%34%34

The First Step: Outermost exec:
exec""" ... ASSW%cRD ... %s%s%s%s%s""" % `1>>1` % `2531>>5` % `321>>2` % `1521>>4` % `211>>1` % `221>>1`

1>>1: 0, used for the 0 in PASSWORD_01
2531>>5: 79, used for inner exec to create O
321>>2: 80, used for inner exec to create P
1521>>4: 95, used for inner exec to create _
211>>1: 105, used for inner exec to create i
221>>1: 110, used for inner exec to create n

Second Step: Prepare Inner exec
After the above, the inner exec is something like this:
exec%c""%cr%c%ct%c%cASSWORD%c01%c %c""%79%80%95%105%110

Except that you wouldn't quite get that. Still wtih the simplifications, you'd get this:
exec%c""%cr%c%ct%c%cASSWORD%c01%c %c""798095105110

The literal %'s need to be included. So basically I had to add a bunch of them before each %s to end up with literal %'s left after all the formatting. 2**11 of them. Times five.
The rest of the outer exec string format operations are %112%34%34%34%34. The 112 is for p, and the others are quotation marks. After applying those, the result is something like this:
exec"""pr%c%ct"%cASSW%cRD%c01" """%79%80%95%105%110

But in reality it has a bunch more %. It's this:
exec"""pr%%%%%%%%c%%%%%%%%%%%%%%%%ct"%%cASSW%cRD%%%%c01" """%79%80%95%105%110

The final step is to simply run that, after which you get the necessary output.

Full code here: https://hastebin.com/ehemizivum.apache

Impressive! You typed all that by hand before the BOMB exploded? Without making any mistakes (no backspace key)? You, sir or madam, deserve your pension. ;D

bash + vim (56)
Borrowing the Ctrl-XCtrl-E bash trick from Thor's solution, here is how I would do it in bash+vim:
C-XC-E starts default editor (usually vim)
a starts insert mode
.space
ASSW
C-Vx4f inserts O
RD
C-Vx5f inserts _
1
C-3 is equivalent to escape (not just in vim, but anywhere in a terminal)
C-X subtracts 1 from the 1 i just typed
a insert mode again
1
C-3
buffer content is now . ASSWORD_01
<< unindent line (a no-op, since line is not indented) and move cursor to 1st column
a
C-X start word completion
C-V complete with ex command
C-V 9 more times selects the entry Print
C-3 back to normal mode
XXXxx deletes rint
<
< back to column 1
s delete ., start insert mode
e
c
C-X
C-V ex command completion once again, entry echo already selected because of the ec i just typed
space
C-3 buffer content now echo PASSWORD_01
Z
Z save buffer, close vim, bash executes file content, i.e. echo PASSWORD_01
By the way: C-3 has many useful brethren: C-J is Enter, C-I is Tab, C-H is Backspace, C-2 is C-@ (i.e. a null-byte). And for emacs users it is nice to know that Escape followed by another key is equivalent to Alt + that key. So, even without Escape and Alt you can still type Meta-x like this: C-3x

Perl, (31+10 / 41+10 / 64+10)
(^ key used, 3 ways)
exec"easswsrdcqw"^"5    <  <AF"                   # exec "PASSWORD_01"

Valid if running as a system command qualifies as "output."

exec"QQZSqeasswsrdcqw"^"422<Q5    <  <AF"         # exec "echo PASSWORD_01"

Valid if I'm allowed to use external/OS commands. (Run here)

exec"EQAXqwQqQZQxqeasswsrdcqwxqq"^q!5434QZ4S534$S5    <  <AF$SS!
                  # exec "perl -e\"die\\\"PASSWORD_01\\\"\""

Valid if I can execute Perl via the system. (Run here) <-- this one uses print instead of die

The scripts use Perl's bitwise string XOR operator ^, which does an XOR on the character bits of the two strings. This lets me recreate the missing characters for PASSWORD_01, and create the characters for the system command.
I made the three variants depending on how lenient the rules are. I assume that since variants 2 and 3 actually output the words on Ideone, the solutions are valid. I removed the little story I had here since I figured no one would read it, but you can read it in the edits if you're curious!

MS-DOS .COM 8086 machine code (72 bytes)
Time is precious, so no time to dilly-dally with compilers or interpreters! Simply open your text editor of choice and type in the following (replace \t with TAB):
451D<1DAQX1D11D3AQX4c1DDQX4<SZ!Gq\tGq3WqEEEEESX5\t\t2!<<<<<<<<<eASSWzRD<11$

As a hexdump:
00000000 : 34 35 31 44 3C 31 44 41 51 58 31 44 31 31 44 33 : 451D<1DAQX1D11D3
00000010 : 41 51 58 34 63 31 44 44 51 58 34 3C 53 5A 21 47 : AQX4c1DDQX4<SZ!G
00000020 : 71 09 47 71 33 57 71 45 45 45 45 45 53 58 35 09 : q.Gq3WqEEEEESX5.
00000030 : 09 32 21 3C 3C 3C 3C 3C 3C 3C 3C 3C 65 41 53 53 : .2!<<<<<<<<<eASS
00000040 : 57 7A 52 44 3C 31 31 24                         : WzRD<11$

Save as a .COM file and run it to save the day.
The code assumes certain start values for registers, so might not work for all DOS flavours. Just hope that someone risked being fired by not buying IBM.
Slightly more understandable representation:
org 0x100
bits 16
cpu 8086

; Assumes the following start values for registers (as per http://www.fysnet.net/yourhelp.htm):
;
;   AX = 0
;   BX = 0
;   CX = 0x00ff
;   SI = 0x100

; Change e => P and z => O
    xor al, 0x35
    xor [si+0x3c], ax
    xor [si+0x41], ax

; Fix int 0x21 and ret
    push cx
    pop ax              ; AX = 0xFF
    xor [si+0x31], ax
    xor [si+0x33], ax

; Change <1 => _0
    inc cx              ; CX = 0x100
    push cx
    pop ax              ; AX = 0x100
    xor al, 0x63        ; AX = 0x163
    xor [si+0x44], ax

; We're using DOS interrupt 0x21, function 0x09 to output the final string.

; AH must equal 0x09 to select the function.
; DS:DX must point to the $-terminated string we want to output.

; Get DX to the correct value (0x13c)
    push cx
    pop ax              ; AX = 0x100
    xor al, 0x3c        ; AX = 0x13c
    push bx
    pop dx              ; DX = 0

; We use part of the Program Segment Prefix to temporarily store the value,
; since MOVing or PUSHing AX is impossible.
; The part in question is the second File Control Block, which we will not use anyway.
    and [bx+0x71], ax
    or [bx+0x71], ax
    xor dx, [bx+0x71]   ; DX = 0x13c

; NOPs to get int 0x21 and ret on high enough addresses
    inc bp
    inc bp
    inc bp
    inc bp
    inc bp

; Set AH to the correct value. AL is set too, but is ignored by the DOS interrupt.
    push bx
    pop ax              ; AX = 0
    xor ax, 0x0909      ; AX = 0x0909

; What will become instructions int 0x21 and ret
    db 0x32, 0x21
    db 0x3c

; Padding to have the password at an address we can refer to.
    times 60-($-$$) db '<'

; Password
    pw  db  "eASSWzRD<11$"

oOo code (300)
QwerTaSdfGzxCqwertAsDfgZxCQwerTasDfgZxcQweRtaSDfgZxCqwertAsDFgZXcQWeRtaSdFGzxcQwERTasdfGzxc
QwErtAsdFgzxcqWeRtaSdFGzxcQweRtaSDfGZxCqWErTAsDFgZXCqWerTasDfgZxcQweRtaSdfGzxCQwErTAsDFgZXC
qWertAsDfgzxcQwERtASdFGzXcqWeRTasdFGzXcQWeRtAsDfgzxcQwERtASdFGzXCqWerTaSDfgzXcQWErTaSdFgZxc
QwertaSdFgzXcQWertASdFgZXCq

Easy. (Linefeeds are optional, and just here to make the code "more readable")
Code generator used:
o=lambda b,c:"".join(i.upper()if j else i for i,j in zip(__import__('itertools').cycle(c),map(int,"".join((3-len(i))*'0'+i for i in(bin('><[]-+.,'.index(i))[2:]for i in b)))))

The same code in a less silly encoding:
EeeeEeEeeEeeEeeeeeEeEeeEeEEeeeEeeEeeEeeEeeEeeEEeeEeEeeeeeEeEEeEEeEEeEeeEeEEeeeEeEEEeeeeEeee
EeEeeEeeEeeeeeEeEeeEeEEeeeEeeEeeEEeEEeEeEEeEEeEEeEEEeEeeEeeEeeEeeEeeEeeEeeEeeEEeEeEEeEEeEEE
eEeeeEeEeeeeeEeEEeEEeEEeEeeEeEEeeeEEeEeEEeEeEeEeeeeeEeEEeEEeEEeEEeEeeEeEEeeeEeEEEeEeEeEeEee
EeeeeeEeEeeEeEEeeeEEeEeEEEe

But silly encoding is so much more fun

brainfuck, 400 + 10 (+) = 410 bytes
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.<.>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++..++++.<<++++++++++++++.+++.>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.<++++++++.>>>>++++++++++++++++++++++++++++++++++++++++++++++++.+.<

Try it online!

You can remove the < at the end.

Poetic, 319 bytes
war restarts.a test.a craze.a few desecrated areas.a few deceased staff.a sad defeat.waters red.we start a retreat after a war.a carcass wasted.a war act started warfare.war gets screwed.crew defeated.targets set.war affects qatar.a red war creates regret.a war deterred far extra starred staff.we scatter.gee!a regress

Try it online!
Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.
It was an interesting challenge to write a piece of text with certain word lengths without the right side of the keyboard (or many spaces or punctuation marks). I can only hope that it was worth it.

JS-Forth, 103 bytes
The string will be returned on the stack as an array of characters.
12544 1 3 << >> 24 1 << 1521 4 >> 34 1 << 41 1 << 2531 5 >> 351 2 >> 332 2 >> 32 2 >> 131 1 >> 321 2 >>

Try it online - Commented version

Explanation:
I first found the list of allowed words. Essentially, the only things I could use that would be useful are:

12345 Numeric constants
<< Shift left
>> Shift right
s>f Push single to float stack
f>d Pop double from float stack
fsqrt Square root on float stack

So I could use numeric constants, bit-shift, and compute a square root using the following (>> replaces drop, shifting by 0 to remove the 0):
s>f fsqrt f>d >>

Fortunately, I found possible bit-shifts for every constant I needed to create that were shorter than using square roots. For the most part, I searched by simply printing each number squared, or a larger power of two if any of them contained a digit 6-0. Then, I realized I could use loss of precision from f>d to find more possibilities. (I could add to the number, but still get the same integer square root.) A bit later, I started using bit-shifting to find some, and then all, of the constants. The greater the >> bit-shift, the more I could add to the "magic number" and still get the same result. So I found the smallest bit-shifts I could use to get the necessary results. Even numbers could sometimes use <<, odds had to use >>.
Commented code (\ starts a comment):
\ 49
12544 1 3 << >>

\ 48
24 1 <<

\ 95
1521 4 >>

\ 68
34 1 <<

\ 82
41 1 <<

\ 79
2531 5 >>

\ 87
351 2 >>

\ 83 (x2)
332 2 >> 332 2 >>

\ 65
131 1 >>

\ 80
321 2 >>

gForth does not have the words << or >>. Instead it has lshift and rshift, which I could not use.

ferNANDo, 179 + 10 = 189 bytes
2 1
1 2 1 2 1 1 1 1
1 2 1 1 1 1 1 2
1 2 1 2 1 1 2 2
1 2 1 2 1 1 2 2
1 2 1 2 1 2 2 2
1 2 1 1 2 2 2 2
1 2 1 2 1 1 2 1
1 2 1 1 1 2 1 1
1 2 1 2 2 2 2 2
1 1 2 2 1 1 1 1
1 1 2 2 1 1 1 2

Try it online!
Enter used. I'd use 0 and 1 to make the code more readable but I can't use 0.

I think enter is allowed.

OP didn't say Enter was allowed.

Decimal, 190 180 + 10 = 190 bytes
12055D12025D41D301212055D12010D41D301212055D12025D41D12003D41D30130112004D41D301212055D12024D41D30112003D41D301212055D12013D41D301212055D12040D41D301212045D12003D41D30112001D41D301

Try it online! Decimal is an esoteric language that uses nothing but decimals and the letter D. However, I needed the +10 penalty because almost every command uses 0.
Luckily, all of the commands needed to print PASSWORD_01 don't require any numbers over 6:

12...D - push a character
2 - pop a value
41D - pop top two stack values, multiply and push result
301 - print DSI (default stack index)

By repeatedly pushing character values that only use the digits 1 through 5, then adding them, I can make the character values for each letter in PASSWORD_01.
Ungolfed and commented:
12055D     ; push char 55 to stack
12025D     ; push char 25 to stack
41D        ; pop [DSI] and [DSI-1], add and push result
3012       ; print from stack to output, pop
12055D     ; push char 55 to stack
12010D     ; push char 10 to stack
41D        ; pop top two stack values, add and push result
3012       ; print from stack to output, pop
12055D     ; push char 55 to stack
12025D     ; push char 25 to stack
41D        ; pop x2, add, push
12003D     ; push char 3 to stack
41D        ; pop x2, add, push
301301     ; print, print
12004D     ; push char 4 to stack
41D        ; pop x2, add, push
3012       ; print, pop
12055D     ; push char 55 to stack
12024D     ; push char 24 to stack
41D        ; pop x2, add, push
301        ; print
12003D     ; push char 4 to stack
41D        ; pop x2, add, push
3012       ; print, pop
12055D     ; push char 55 to stack
12013D     ; push char 13 to stack
41D        ; pop x2, add, push
3012       ; print, pop
12055D     ; push char 55 to stack
12040D     ; push char 40 to stack
41D        ; pop x2, add, push
3012       ; print, pop
12045D     ; push char 45 to stack
12003D     ; push char 3 to stack
41D        ; pop x2, add, push
301        ; print
12001D     ; push char 1 to stack
41D        ; pop x2, add, push
301        ; print

Stax, 91+10 bytes
"W"EEEd$"$"1 !$Re]"$""ASSW"R"$""a"EEE$"$"a$Re]R"$""RD"R"$""a"EEEd$"$""5"Re]R"$"1 !$R"$""1"R

Try it online!
Uses ] to make singletons.
Explanation
Let's see how "P" is generated and how the "ASSW" is appended without using the usual +.
"W"                             Push "W", or [87]
   E                            Convert to a scalar, 87
    E                           Convert to an array of digits, [8,7]
     E                          Push 8 on the stack, then push 7.
      d                         Pop the 7 and discard it.

                                Start making components of regex substitution
       $                        Pop 8, push "8"
        "$"                     Push "$"
           1 !                  Push 0. The space is necessary because normally one doesn't do 1! to obtain 0
              $                 Pop 0, push "0"
               R                Do regex substitution 's/$/0/g' on the string "8"

                                Basically doing "8"+"0" without using +
                e               Pop "80", push 80
                 ]              Singleton. Pop 80, push [80], or "P"
                  "$""ASSW"R    Use the same trick again to append "ASSW" to "P"

The rest are just repeating the same trick.
"a"EEE$"$"a$Re]R swaps the digits of "a" or [97] to make [79] or "O" and appends it to the string.
"$""RD"R appends "RD".
"$""a"EEEd$"$""5"Re]R uses "a" again to obtain "9" and discards the "7", then combines the "9" with a literal "5" to form [95] or "_", and appends it to the string.
"$"1 !$R obtains a zero by logical not of 1 and appends it to the string.
"$""1"R appends the final "1" and we are done.
Implicit output.

O_O ... this is clever.

Thank you for your appreciation. I believe it can be made shorter (perhaps by choosing a different key?) though.

Emacs (running in a terminal), 26 bytes (possibly 24 bytes)
The program itself (the commas delimit the boundaries between bytes in the on-the-wire format that Emacs uses to accept its input):

W, S, Ctrl-3, $, D, A, Ctrl-T, S, R, W, D, Ctrl-3, $, 5, Ctrl-Q, 5, f, Ctrl-X, r, Ctrl-Space, 1, Ctrl-X, r, g, 1, Ctrl-T

Encoding of this as raw bytes, to prove byte count:
00000000: 5753 1b24 4441 1453 5257 441b 2435 1135  WS.$DA.SRWD.$5.5
00000010: 6618 7200 3118 7267 3114                 f.r.1.rg1.

(Note: some of the details may vary based on how Emacs is configured; this answer requires quoted-char-radix to be set to 16, and for Emacs to use the spellcheck dictionary that's default on my British English system. Both of these seem like reasonable configuration settings, but it's possible that your copy of Emacs may be configured differently. A different dictionary would likely still give a 26-byte program, but slightly different misspellings might need to be used so that the corrections we wanted can be accepted by non-bullet-ridden keys.)
Note about scoring
In addition to the keys specified in the question, I originally thought this answer required either Esc or Alt to work. (Esc is on the half of the keyboard that's still intact, so it morally feels like it should be allowed, but it isn't explicitly permitted.) However, user2845840's answer points out that (with the usual encoding of terminal control codes) Esc can alternatively be typed as Ctrl-3, and that is explicitly permitted by the question. (An aside: while testing this, I learned some other interesting ways to type control codes, with Ctrl-2 typing NUL, and Ctrl-4…7 typing character codes 28…31 respectively. Note that the default configuration of many terminals is to interpret a character code 28 coming from user input as a request to crash the currently running program, so be careful testing this.)
Alt is also on the intact half of the keyboard but isn't mentioned in the question. Although Alt and Esc have different encodings in some terminals, they are encoded the same way in other terminals, and (presumably to work around these compatibility issues) Emacs interprets the two keys (and their encodings) as entirely equivalent to each other. If we could use Alt, though, it would save two bytes (because it has a shorter encoding than Esc does).
Explanation
I'm not sure whether it should have any influence on the editor wars, but Emacs seems to beat vim at least in the case of this question. Emacs is pretty suited to editor golf measured in bytes, because it relies heavily on chords which take up multiple keypresses but only a single byte (thus an Emacs program is often slower to type than the equivalent Vim program, but shorter on disk). Additionally, most of the most important Emacs commands are in the bottom-left corner of the keyboard, to be close to Ctrl, very helpful with a question like this one.
"You can assume you have the interpreter shell / source editor opened before the bullets came in. Sadly you have not written anything in it before the keyboard was hit.", so I'm assuming that we have an empty file open in Emacs and need to type the password into it. (We'd need to save the file afterwards, and probably exit Emacs, but the bytes for that aren't being counted in other people's answers so I'm not counting them here either. It's totally doable using the left hand side of the keyboard, though, Ctrl-X, Ctrl-S, Ctrl-X, Ctrl-C.)
Taking it a command (or block of similar commands) at a time:

W, S: Enter WS into the document.
Ctrl-3, $: Invoke the spellchecker. WS isn't a real word, but it finds lots of similar two-letter words. (The usual way to invoke the spellchecker is Alt-$; here, we're using Ctrl-3 as a stand-in for Esc, which in turn is a stand-in for Alt.)
D: Using the spellchecker, correct WS to PS. (When the spellchecker is invoked using Alt-$, as happened here, it only checks one word, so it deactivates after doing this.)
A: insert A, giving PSA.
Ctrl-T: Swap the previous two characters, giving PAS.
S, R, W, D: Type SRWD, giving PASSRWD.
Ctrl-3, $, 5: We invoke the spellchecker again, because we want to correct our misspelled PASSRWD into PASSWORD. Note that we can't have it guess the word we want on our first try, like it would with PASSWRD, because the key to accept the closest real word is 0 which we can't press. As a result, the slightly more extreme misspelling PASSRWD is used to push the word we want into position 5, where we can accept it.
Ctrl-Q, 5, f: Insert the character with character code U+5f, i.e. _. The document now reads PASSWORD_ (or will when we start typing the next command; before then, the underscore doesn't appear in case we type another hex digit).
Ctrl-X, r, Ctrl-Space, 1: Store the current cursor position (relative to the start of the file) in register 1. For some bizarre reason, this is 1-indexed, so (having written 9 characters so far) the cursor is at position 10.
Ctrl-X, r, g, 1: Copy the content of register 1 into the document. It now reads PASSWORD_10.
Ctrl-T: Swap the two characters before the cursor. We now have PASSWORD_01, like the question asks for.

If we're allowed to use Alt, we can probably encode the "invoke spellchecker" command as the single byte a4 rather than spelling it out as 1b 24; it appears twice, so that leads to two bytes of savings. (Most modern terminals use 1b 24 as the encoding for Alt-$ to avoid clashes with UTF-8, but the a4 encoding is also encountered from time to time, sometimes available as a configuration option.)
Possible byte savings probably involve golfier misspellings to correct. PSASWRD would be a byte shorter to type, but unfortunately, the spellchecker doesn't seem capable of gleaning PASSWORD out of that, so PASSRWD is the best approach I've found so far. The register-based approach to gaining 10 is also ridiculously unwieldy, but there aren't many ways of creating numbers from nowhere in Emacs, and 0 is a painful character to get hold of otherwise. (At least there were a couple of amazingly useful coincidences: the cursor just happening to end up in position 10, which contains a 0, right when needed; and the fact that Emacs accepts the redundant g register operation to insert the contents of a register into the document, in addition to the more intuitive i.)

Whitespace, score: 111 (101 bytes + 10 for Enter)
[S S T  T   T   T   T   T   N
_Push_-31_1][S S T  T   S S S S S N
_Push_-32_0][S S S T    T   T   T   N
_Push_15__][S S T   T   T   S S N
_Push_-12_D][S S S T    S N
_Push_2_R][S S T    T   N
_Push_-1_O][S S S T T   T   N
_Push_7_W][S S S T  T   N
_Push_3_S][S N
S _Duplicate_3_S][S S T T   T   T   T   N
_Push_-15_A][S S S N
_Push_0_P][N
S S N
_Create_Label_LOOP][S S S T S T S S S S N
_Push_80][T S S S _Add][T   N
S S _Output_as_character][N
S N
N
_Jump_to_Label_LOOP]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Try it online (with raw spaces, tabs and new-lines only).
Explanation in pseudo-code:
This solution is shorter than the existing Whitespace answer (@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ asked me to post it as a separated answer when I suggested it as golf) by utilizing this Whitespace tip of mine.
Push the code-points for the characters of "10_DROWSSAP" minus constant 80 to the stack
Start LOOP:
  Add 80 to the current code-point
  Pop and output it as character
  Go to the next iteration of LOOP

The constant 80 has been generated with this Java program, which I've created and used for some previous Whitespace answers of mine.

Befunge-98, 43 +10 = 53 bytes
"1qA·DR·WSSA·g"%,$,,,,$"s"%,,,$"c"%,%,,q

Try it online!
The 10 byte penalty is for the use of the , key (not sure why this couldn't be accomplished with Shift+<, but that seems to be the rule). And although the source is technically 40 characters, the three · characters contribute an additional three bytes because of their UTF-8 encoding.

05AB1E, 87 86 bytes
"."A1.$R24.$AT<.$R15>.$A21<.$R5.$.V.VD21s.V.V15>X.V"ASSW"15X.V"RD"122D<s2X.V.VTRTX.V.V

Try it online!
Maybe the longest 05AB1E code ever?
Unfortunately the language doesn't support things like "Q"< for "decrement Q to get P"
My extra key is the V.
Thanks to @Kevin Cruijssen for -1 byte.
Code:
Build the string ".b". This is the code to turn integers to upper case letters:
"."             push "."
A               push the lower case alphabet
1.$             drop the first letter of that
R               reverse the remaining string
24.$            drop the first 24 letters of that, so only "b" remains
AT<.$R15>.$     do the same trick for "j"
A21<.$R5.$      and for "u"
.V              run "u" as code to turn "j" to "J"
.V              run "J" as code, to join ".", "b" to ".b"

Save that string for later use:
D               duplicate
21              push 21
s               switch the top two elements [".b", 21, ".b"]
.V              run ".b" as code, to get "U"
.V              run "U" as code, to save ".b" in X

Build password string:
15>X.V          push the 16th letter of the alphabet ("P")
"ASSW"          push "ASSW"
15X.V           push "O"
"RD"            push "RD"
122D<s2X.V      push 121, 122, "B"
.V              run that as code to push "_"
TR              push 01
TX.V            push "J"
.V              run that as code, to join everything to the desired string

For comparison: The shortest way to print "PASSWORD_01" is 6 bytes long
Try it online!

"Maybe the longest 05AB1E code ever?" Nah, this one of mine is almost 6 times as large. ;p Nice answer regardless. It's hard to only use a certain amount of allowed ASCII character. So many convenient builtins aren't allowed for this challenge. :(

-1 byte by using TR instead of 1<1 for the 01 part of the output.

Lenguage, 814814390776628060509605577373181765864505940171473720140916436885644483746988990322785194756 bytes
Converted from this program:
++++++++++[>++++++++>+++++++>+++++++++>++++++++++>+++++<<<<<-]>.>-----.<+++..>>---.<<----.+++.>+++.>>-----.>--.+.

Try BF code online!

Width, 23 + 10 (m) = 33 bytes
GFmaaAfAfAAFGAiawwafwfG

Try it online!

This language reminds me of the CUNEIFORM NUMERIC SIGN NINE SHAR2: , an awesome character that is awesome because it's a single character

Knight, 63 62 + 10 (+) bytes
E++A+55 24+A34+A+55 25+"ASSW"+A+55 24+"RD"+A+54 41+A+45 3 1A34

Try it online!
As noted on Encode your program with the fewest distinct characters possible, Knight needs a minimum of AE +1 to be fully usable (even if it is more torturous than Brainfuck). The + is required to do ASCII arithmetic.
This program generates the string O"PASSWORD_01" by assembling codepoints, and EVALs it with E.
XXX: check if SUBSTITUTE is beneficial here

Knight, 113 110 bytes
E S S S S S S S"ASSWRD1"%21 14F A34%21 15F A%152 52%21 15F A%321A"q"4F A%211 132F!1A%211 131F!1A34F!1A%211 132

Try it online!
Even without +, we can still do this. SUBSTITUTE can allow us to insert strings into other strings, and we can still generate single chars with A%x y. But I think + is worth it, no?
Generates the same string.
For the reference, the magic numbers are:
%21 14   -> 7
%21 15   -> 6
%152 52  -> 48 ('0')
%321A"q" -> %321 113 -> 95 ('_') # used to prevent token collision
%211 132 -> 79 ('O')
%211 131 -> 80 ('P')

3 bytes: use !1 instead of F to avoid token collisions

Julia 1.5, 38 +10 (ENTER) = 48 "bytes"
The keystrokes not available are, of course, PO_0. For Julia, the others are all simple, and simply outputting the string "PASSWORD_01" should count by the rules. Also required: ENTER, as the alternate way to process that in Julia's REPL is Ctrl-J, and J isn't available.
Fortunately, one of the inbuilt commands that you can use TAB to autocomplete is DEPOT_PATH, which provides access to three of the characters. And shortcuts can handle deleting the undesired letters and positioning the cursor to add the missing ones. To get the 0, the easiest method I've found is to use autocomplete to get frexp, and then exp10.
Inputs
Type: frTABCtrl-ACtrl-DCtrl-DCtrl-E1TAB
Result: exp10
Type: Ctrl-ADETAB
Result: DEPOT_PATHexp10
Type: Ctrl-A"Ctrl-DCtrl-DCtrl-FASSWCtrl-FCtrl-DRDCtrl-FCtrl-DCtrl-DCtrl-DCtrl-DCtrl-DCtrl-DCtrl-DCtrl-FCtrl-T"ENTER
Result: "PASSWORD_01" as output (rather than command) on hitting enter.
Explanation
Autocomplete with TAB will work as long as there is only one known autocomplete option (otherwise, double-tab will bring up a list of possible completions).
Ctrl-A moves the cursor to the start of the line, Ctrl-D deletes the next character, Ctrl-F advances the cursor forward one space, and Ctrl-T switches the positions of the characters before and after the cursor (and moves the cursor forward one place).

Pyth, 39 + 10 (+) = 49 bytes
r1++++++C+55 25"ASSW"e<G15"RD"C+54 41Z1

Try it online!
This could probably be golfed a bit more but I give up. :)  The code adds a series of strings to the stack, appends them all, and then translates the whole thing to uppercase. That leaves one string on the stack which is printed automatically when the code exits.
The Pyth specific tricks used here are related to getting the characters not available on the limited keyboard.  The P and _ characters are generated by computing the codepoint of the character and using the Pyth C function.  And the o character is extracted from the G variable, which is pre-defined to hold the alphabet.  The r1 translation is needed just for that, since the alphabet constant is lowercase.  That turns out to be the same number of characters as the codepoint method, so left both in the code.
I had to add the + character so the code gets a +10 penalty.
         +55 25                         - push 75 on the stack
        C                               - convert codepoint to "P"
               "ASSW"                   - push "ASSW" to the stack
       +                                - append top two stack entries
                       G                - push "abc...xyz" to the stack
                      < 15              - take 15 char substring
                     e                  - take last char on string "o"
      +                                 - append top two stack entries
                          "RD"          - push "RD" into the stack
     +                                  - append top two stack entries
                               +54 45   - push 95 on the stack
                              C         - convert codepoint to "_"
    +                                   - append top two stack entries
                                     Z  - push 0 onto the stack
   +                                    - append top two stack entries
                                      1 - push 1 onto the stack
  +                                     - append top two stack entries
r1                                      - convert to uppercase

Deadfish~, 154 + 10 bytes
iiissdcdddddddddddddddciiiiiiiiiiiiiiiiiicciiiicddddddddciiicddddddddddddddciiiiiiiiiiiiiiiiiiiiiiiiiiicdddddddddddddddddddddddddddddddddddddddddddddddcic

Try it online!
No {} :(
Needs i, you can't do anything without it...

@Wasif See Help Mode.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳


text:
Find nearest number in a given array
This is inspired by a real world problem I had. I'm curious to see if there is any clever way to go about this.
You are given two unsorted arrays, A and B, each containing an arbitrary number of floats. A and B don't necessarily have the same lengths. Write a function that takes the elements of A sequentially and finds the nearest value in array B. The result has to be contained in a new array.
Win condition
Shortest code wins (as usual).

Round to the nearest integer?

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ I read that as "round each element of A to the nearest element of B"

@JanDvorak: Well, I understand the part about rounding direction, but the problem didn't specify to how many digits.

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Round to nearest float. The answer has to output floats from array/list B.

For example, given A = [38.56] and B = [40.59], I can round it to 38.6 or 39 or 40 depending on the number of significant digits.

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ it is possible to do exactly. I assume you have to.

You have to round it to 40.59. It's not so much of a rounding operation as it is to find a closest match.

Then just redefine the problem to "For each number in array A, find a number from array B that is nearest to the given number". It is much clearer than using the term "rounding".

Will arrays A and B be sorted?

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ "map", not "print"

@steveverrill will it help you if they are?

@JanDvorak I would certainly think it would, though I haven't analysed the problem fully. So I think it's a valid question.

@steveverrill I'd be curious to see if it can lead to a shorter solution, because in the practical case, they are. For this problem, I'm not sure if it'd be fair to change it now. Let's assume they are not to stay more general. But it'd be very nice if you provided both solutions.

@Orhym good decision. I put it in the question. I see you're new round here. With code golf it is very important to specify clearly, and you've done very well for a new user. You'd be amazed how many questions we get from new users that get closed due to vague specification.

Not sure you'll get anything "clever" from code golf because most are going to go about it in the most straight-forward (less code) way possible (for each element in a, loop through b to find min difference and select).  If B is sorted then finding that min difference can be improved, but at the expense of code length (so no one will post it).

Shortest code is not always the best code! I would recommend you post the problem statement and your way of solving the problem (with your code) on Code Review and ask for a review of your code. There has been some questions in the past about arrays there but I don't think there's been this one.

APL, 13 17
(21 byte in UTF-8)
B[{↑⍋|⍵-B}¨A]

If you want true lambda (A as left argument and B as right):
{⍵[⍺{↑⍋|⍺-⍵}¨⊂⍵]}

How it works:
{...}¨A invokes lambda function {...} with every A value (instead of invoking with A as array), gathering results to array of same shape
|⍵-B computes absolute values of difference between argument ⍵ and all in B (- is subtraction, | is abs).
↑⍋ takes index of least element (⍋ sorts array returning indices, ↑ get first element)
B[...] is just fetching element(s) by index(es).
The solution is quite strightforward, altough it uses
wonderful feature of APL's sorting function returning permutation vector (sorted element's indices in original array) rather than sorted array itself.

How does this work?

Explained in answer

How on earth do you know how to write this?

This is like writing chinese. For me, there's no great difference writing either alien words or alien characters...

Mathematica - 17
#&@@@Nearest@A/@B

How does it work?  Yes, I admit that there's a bit of cheating here because Mathematica has built-in nearest functionality.  The rest is straightforward and is concerned with arranging the result in a 1D array.  It looks ugly only because of the extra effort to make it short.

Ha!  Welcome! :)

C# - 103 97 87 Bytes
I'm not quite sure if I understood this question correctly but here is my solution anyway.
I used Lists instead of arrays, because it allows me to write shorter code.
A integer array is shorter than a integer list.
Input:
t(new int[] { 0, 25, 10, 38 }, new int[] { 3, 22, 15, 49, 2 });

Method:
void t(int[]a,int[]b){var e=a.Select(c=>b.OrderBy(i=>Math.Abs(c-i)).First()).ToArray();

Output:
2, 22, 15, 49

If my answer isn't correct, please leave a comment below it.
EDIT:
AS @grax pointed out, the question is now about floats. Therefore I'd like to include his answer too.
95 Bytes(Grax's answer)
float[]t(float[]a,float[]b){return a.Select(d=>b.OrderBy(e=>Math.Abs(e-d)).First()).ToArray();}

Lists are fine too.

Rename item to i and you will safe 6 additional characters ;)

@Aschratt thank you very much!

The function doesn't specifically say to return the new value, but I think you should.  2.  Since the question called for float, I think you should use float float[] t(float[] a, float[] b) {return a.Select(d=>b.OrderBy(e=>Math.Abs(e-d)).First()).ToArray();}

@Grax As I wrote my first answer, the question wasn't about floats. Since the question has been updated, I included your answer too. Thank you very much.

R, 41 chars
B[apply(abs(outer(A,B,`-`)),1,which.min)]

Explanation:
outer(A,B,`-`) computes for each element x of A the difference x-B and outputs the result as a matrix (of dimension length(A) x length(B)).
which.min picks the index of the minimal number.
apply(x, 1, f) applies function f on each row of matrix x.
So apply(abs(outer(A,B,`-`)),1,which.min) returns the indices of the minimal absolute difference between each element of A and the elements of vector B.
Usage:
> A <- runif(10,0,50)
> B <- runif(10,0,50)
> A
[1] 10.0394987 23.4564467 19.6667152 36.7101256 47.4567670 49.8315028  2.1321263 19.2866901  0.7668489 22.5539178
> B
[1] 44.010174 32.743469  1.908891 48.222695 16.966245 23.092239 24.762485 30.793543 48.703640  6.935354
> B[apply(abs(outer(A,B,`-`)),1,which.min)]
[1]  6.935354 23.092239 16.966245 32.743469 48.222695 48.703640  1.908891 16.966245  1.908891 23.092239

CJam - 14
q~
f{{1$-z}$0=\;}
p

The main code is on the second line, the rest is for using the standard input and pretty output.
Try it at http://cjam.aditsu.net/
Explanation:
q~ reads and evaluates the input
f{...} executes the block for each element of the first array and the next object (which is the second array), collecting the results in an array
{...}$ sorts the second array using the block to calculate a key for each item
1$ copies the current item from the first array
-z subtracts then takes the absolute value
0= takes the first value of the sorted array (the one with the minimum key)
\; discards the item from the first array
p prints the string representation of the result
Examples (inspired from other answers):
Input: [10.1 11.2 12.3 13.4 9.5] [10 12 14]
Output: [10 12 12 14 10]
Input: [0 25 10 38] [3 22 15 49 2]
Output: [2 22 15 49]

Python 3.x - 55 chars
f=lambda a,b:[min((abs(x-n),x)for x in b)[1]for n in a]

a and b are the input arrays, and the desired array is the expression's result.

I edited the answer to make it a function since the question requires a function.

Javascript (E6) 54 56 59
Minimize distance. Using square instead of abs just so save chars.
Edit algebra ...
Edit fix useless assignment (a remainder of a test w/o the function definition)
F=(A,B)=>A.map(a=>B.sort((x,y)=>x*x-y*y+2*a*(y-x))[0])

Was F=(A,B)=>D=A.map(a=>B.sort((x,y)=>((x-=a,y-=a,x*x-y*y))[0])
Test
F([10.1, 11.2, 12.3, 13.4, 9.5],[10, 12, 14])

Result: [10, 12, 12, 14, 10]

D= isn't needed, as map returns a new array. Alternative (same length) sort function: (x,y)=>(x-=a)*x-(y-=a)*y

PowerShell - 44
$a|%{$n=$_;($b|sort{[math]::abs($n-$_)})[0]}

Example
With $a and $b set to:
$a = @(36.3, 9, 50, 12, 18.7, 30)
$b = @(30, 10, 40.5, 20)

Output is
40.5, 10, 40.5, 10, 20, 30

you could use floats in the example to make it clear it handles floats too

@bebe - Thanks, updated to make that clear.

-3 bytes: $a|%{$n=$_;($b|sort{($n-$_)*($n-$_)})[0]}

Haskell, 55
c a b=[[y|y<-b,(y-x)^2==minimum[(z-x)^2|z<-b]]!!0|x<-a]

At first, I thought to use minimumBy and comparing, but since those aren't in Prelude, it took a ton of characters to qualify them. Also stole the squaring idea from some other answers to shave off a character.

Ruby, 40
f=->a,b{a.map{|x|b.min_by{|y|(x-y)**2}}}

Same as the Python answer, but squaring is a little terser than any way I could think of to take absolute value.

TI-BASIC, 24
∟A+seq(min(∟B+i²∟A(N)),N,1,dim(∟A

Doesn't come close to APL, but uses less powerful functions-- this uses no "sorted by" or "index of least" function. The disadvantage of TI-BASIC here is its lack of those functions and multidimensional arrays.
Ungolfed:
seq(       ,N,1,dim(∟A           #Sequence depending on the Nth element of list A
    ∟A(N)+min(   +0i)            #Number with minimum absolute value, add to ∟A(N)
              ∟B-∟A(N)           #Subtracts Nth element of ∟A from all elements of B

The min( function has two behaviors: when used with real numbers or lists, it gives the smallest value; however, when used with complex numbers or lists, it gives the value with the smallest absolute value. Adding 0i or multiplying by i^2 causes the interpreter to use the second behavior, so min(1,-2) returns -2 whereas min(1+0i,-2+0i) returns 1.

Pyth - 12 11 bytes
Note: Pyth is much younger than this challenge, so this answer is not eligible to win.
Simple method, uses o order function to get minimal distance and maps it over list a.
mho.a-dNQvz

m    vz    Map over evaled first input and implicitly print
 ho Q      Minimal mapped over evaled second input
  .a-      Absolute difference
   d       Lambda param 1
   b       Lambda param 2

Try it online here.

@Jakube oh yeah, sorry.

Fortran 90: 88
function f();integer::f(size(a));f(:)=[(b(minloc(abs(a(i)-b))),i=1,size(a))];endfunction

This requires it to be contained within a full program:
program main
   real :: a(5), b(3)
   integer :: i(size(a))
   a = [10.1, 11.2, 12.3, 13.4, 9.5]
   b = [10, 12, 14]
   i = f()
   print*,i
 contains
   function f()
     integer :: f(size(a))
     f(:)=[(b(minloc(abs(a(i)-b))),i=1,size(a))]
   end function
end program main

The square braces declare an array while (...,i=) represents an implied do loop; I then return the value of b for which element a(i)-b is minimized.

Matlab: 48
f=@(a)B(abs(B-a)==min(abs(B-a)));C=arrayfun(f,A)

Assumes that A and B are 1D matrices in the workspace, Final result is C in the workspace.  This would likely also work in Octave as well.  Conditional indexing makes doing this fairly trivial.

C 144 163
#define f float
f T, *C, m;
f *q(f *A, f *B, int S, f s)
{
    if(m)
        return abs(T - *A) - abs(T - *B);
    for (
        C = malloc(S * 4);
        m = S--;
        C[S] = *B
    )
        T = A[S],
        qsort(B, s, 4, q);
    return C;
}

Okay... I think this little code needs explanation.
At first i tried to do the job with two level of for loop finding the min difference and set the current value to min of B's value. That's very basic.
The same thing can be reached with qsort and a comparator function. I make it sort B by the difference instead of B's elements. Too many functions for such a little algorithm. So the function q now serves two purposes. At first, it's the algorithm itself, secondly (when qsort calls it) a comparator. For communication between the two states, I had to declare globals.
m stands for whether it's in comparator state or the main one.
example:
float A[] = {1.5, 5.6, 8.9, -33.1};
float B[] = {-20.1, 2.2, 10.3};
float *C;

C = q(A, B, sizeof(A)/sizeof(*A), sizeof(B)/sizeof(*B));
// C holds 2.2,2.2,10.3,-20.1

Does the 166/163 count the whitespace or not?

Of course not. Spaces and newlines are for ease of understanding.

GolfScript, 49 bytes
Note: this is a partial solution. I'm working on making it a complete solution
{{\.@\.[.,,\]zip@{[\~@-abs]}+%{~\;}$0=0==}%\;}:f;

Yes. GolfScript does support floating point. Try it out here. Example:
# B is [-20.1 2.2 10.3]
[-201 10 -1?*
22 10 -1?*
103 10 -1?*]

# A. No floating point numbers allowed here.
# This is because 1.5{}+ (where the 1.5 is a
# single floating point number, not 1.5,
# which would be 1 1 5) results in the block
# {1.5 }, which leads to 1 1 5 when executed
[1 5 9 -30]

Output:
[2.2 2.2 10.3 -20.1]

C# 262
Program finds min differences and saves closest value from Array B. I'll work on the golfing shortly.
List<float> F(List<float> a, List<float> b)
{
List<float> c = new List<float>();
float diff,min;
int k;
for(int i=0; i<a.Count;i++)
{
diff=0;
min=1e6F;
k = 0;
for(int j=0; j<b.Count;j++)
{
diff = Math.Abs(a[i] - b[j]);
if (diff < min)
{
min = diff;
k = j;
}
}
c.Add(b[k]);
}
return c;
}

Full program with test code
using System;
using System.Collections.Generic;
public class JGolf
{
    static List<float> NearestValues(List<float> a, List<float> b)
    {
        List<float> c = new List<float>();
        float diff,min;
        int k;
        for(int i=0; i<a.Count;i++)
        {
            diff=0;
            min=1e6F;
            k = 0;
            for(int j=0; j<b.Count;j++)
            {
                diff = Math.Abs(a[i] - b[j]);
                if (diff < min)
                {
                    min = diff;
                    k = j;
                }
            }
            c.Add(b[k]);
        }
        return c;
    }

    public static void Main(string[] args)
    {
        List<float> A = RandF(8413);
        Console.WriteLine("A");
        Print(A);
        List<float> B = RandF(9448);
        Console.WriteLine("B");
        Print(B);

        List<float> d = JGolf.NearestValues(A, B);
        Console.WriteLine("d");
        Print(d);
        Console.ReadLine();
    }

    private static List<float> RandF(int seed)
    {
        Random r = new Random(seed);
        int n = r.Next(9) + 1;
        List<float> c = new List<float>();
        while (n-- > 0)
        {
            c.Add((float)r.NextDouble() * 100);
        }
        return c;
    }

    private static void Print(List<float> d)
    {
        foreach(float f in d)
        {
            Console.Write(f.ToString()+", ");
        }
    }
}

C#: 120
Linq is awesome:
float[] t(float[] A, float[] B){return A.Select(a => B.First(b => Math.Abs(b-a) == B.Min(c=>Math.Abs(c-a)))).ToArray();}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

sort: votes


text:
Efficient error-free* encoding
The mission
As is well known, the genetic material of all known creatures on Earth is encoded in DNA; using the four nucleotides adenine, thymine, cytosine, and guanine. (Commonly represented by ATGC).
A bioinformaticist wishing to store an entire genome would of course not want to store this as ASCII, because each choice can be represented by a mere two bits!
The specification
Your mission, should you choose to accept it, is to write a pair of programs, functions or methods to convert an ASCII representation to a binary representation and back; representing A as b00, T as b01, G as b10, and C as b11 (henceforth "units").
In addition, the high bits of each byte should contain the count of units in the byte, making each byte represent a triplet.
For example: "GATTACCA" becomes b11 100001 b11 010011 b10 1100xx.
In the ASCII to binary input, spaces, tabs and newlines should be ignored. Any character not in the set of [ \r\n\tATGC] is an error and may either be ignored or terminate processing.
In the binary to ASCII input, bytes whose two high bits are b00 may be ignored.
The ASCII output may contain whitespace; but should never be more than 4 times the size of the binary input plus one byte long, and must end with a newline.
The binary output may contain an arbitrary number of b00xxxxxx "control" bytes; but must never be longer than the ASCII input.
Each conversion program must support input of arbitrary length; and should complete the encoding or decoding in approximately linear time.
The twist
Unfortunately for the bioinformaticist for whom you are performing this task, he has in some way wronged you, on a personal yet perhaps petty level.
Perhaps he went out with your sister once, and never called her again. Perhaps he stepped on your dog's tail. The specifics are not really important.
What is important is that you have a chance for payback!
The details
Each conversion should introduce a small error rate; on the order of one error per ten thousand to a million units processed.
An error can be one of the following:

Duplication errors: "GAT TAC CA" becomes "GAT TAA CCA"
Deletion errors: "GAT TAC CA" becomes "GAT TAC A"
Translation errors: "GAT TAC CA" becomes "GTA TAC CA"
Triplet duplications: "GAT TAC CA" becomes "GAT TAC TAC CA"
Triplet slippages: "GAT TAC CA" becomes "TAC GAT CA"
Triplet reversals: "GAT TAC CA" becomes "GAT CAT CA"

That errors will be introduced should of course not be immediately obvious from the code; and irrespective of the length of the input; the conversion should introduce at least one error.
Two runs with identical inputs should not necessarily produce identical outputs.
The trick
The vile bioinformaticist is a moderately competent coder; and as such, some constructs will be automatically discovered, and are as such banned:

He will automatically discover any calls to system random number generators, such as rand(), random(), or reading from /dev/urandom or /dev/random (or whatever the language equivalent is).
He will also notice any superfluous variables, counters or loops.

The scoring
The encoder and decoder will be scored individually.
Each will be run 3 times against a set of 100 randomly generated input files, each file with a size on the order of 3 million units.
The data for the encoder test cases will be created approximately as so:
for (l = 1 => bigNum)
  for (t = 1 => 20)
    random_pick(3,ATGC)
    t == 20 ? newline : space

The data for the decoder test cases will be created approximately as so:
for (u = 1 => bigNum)
  for (t = 1 => 20)
    random_byte() | 0b11000000
   0x00

The encoder

Each byte missing from the expected minimum length in the actual length will score -1 points, up to a maximum of -1000. (The expected minimum length is ceil(count(ATGC) / 3).)

The decoder

Each byte over the expected maximum length in the actual length will score -1 points, up to a maximum of -1000. (The expected maximum length is size(input) * 4 + 1.)

Both

Each kind of error that can be produced will score 100 points; for a total of 600 points possible for each, 1200 total.
Each test case for which the encoder produces more than 30% more or less errors than its own average will be penalized by -5 points.
Each test case for which the encoder produces less than 15% more or less errors than its own average will be given 5 points.
Each test case where all three runs produce identical outputs will be penalized by -10 points.

Hard requirements
An entry will be disqualified if:

For any valid input longer than one triplet it fails to produce even one error.
Its performance is such that it cannot complete the test gauntlet within approximately one hour.
It on average produces more than one error in every ten thousand units.
It on average produces less than one error in every million units.

The interface
The entrants should accept input on the standard input, and output to the standard output.
If the entry is one program with dual function; the switches -e and -d should set the program for encoding and decoding, respectively.
Example invocations:
$ encoder <infile.txt >outfile.bin
$ decoder <infile.bin >outfile.txt
$ recoder -e <infile.txt >outfile.bin

The winner
The winner is the entry with the highest score; the theoretical maximum being 1200 for error kinds plus 3000 points for stability in error generation rate.
In the unlikely event of a draw; the winner will be determined by vote count.
The additional notes
For the purposes of running the test gauntlet, each entry should include run or compilation instructions.
All entries should preferably be runnable on a Linux machine without X.

Changed the tag. KotH is for challenges where submissions interact with each other. Also I'm afraid it will be difficult to impossible to enforce the "underhanded" component objectively.

I agree with @m.buettner's comment that the underhanded part is difficult to judge. On the other hand I feel that this is the only interesting part in the challenge. I can guarantee that the error generation and rate are exactly within the specifications and therefore have the maximum points. Or do I miss something from the spec? Moreover, If an additional kind of error is accepted, it will be added to the above list; and all answers will be scored on it. sounds like you are going to change the challenge after people started working or submitting solutions which I think is not a good idea.

@Howard: Noted. The rules are updated with specific underhandedness criteria; and the mutational aspect wrt. errors is removed.

@WillihamTotland I think "superfluous" is still not quite objective, but this may be a bit better now.

@m.buettner: Given the simplicity of the core task; pretty much any loop apart from the main reading/writing loop would be superfluous.

I am going to give my answer.. but I think the two sentences "Each conversion should introduce a small error rate; on the order of one error per ten thousand to a million units processed." and "An entry will be disqualified if: It on average produces more than one error in every ten thousand units."  are incompatible. The same between "Each conversion should introduce a small error rate; on the order of one error per ten thousand to a million units processed." and "An entry will be disqualified if: It on average produces less than one error in every million units."

@Mattsteel I don't think the requirements are incompatible; they just explicitly state that the error rate should be between 1 : 10 000 and 1 : 1 000 000.

@WillihamTotland. Now I see the correctness of your sentences. I simply wrongly flipped the two fractions. My only justification is that I am not English native speaking.

There is a problem with the hard limits in this question. Say the input to the encoder consists of two triplets. If it doesn't produce an error, it's disqualified. If the input consists primarily of such cases, and it produces at least one error for all of them, its disqualified for producing too many errors.

@ppperry You're right, kind of. I'll address that in the morning.

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

Perl 5.10
I'm glad to present my solution in Perl.
When I started the challenge I was quite sure that Perl would stay well below the limit of 1 hour.
For testing purpose I developed a plain sample generator and a coded sample generator.
Then I developed the encoder that took a bigger effort and produced a longer code.
The encoder works as follow:

first loop reads the whole file and splits data to have an array of all triplets
second loop traverses the array and prepend to each element its length
third loop traverses again and maps each character to give the output.

The coded binary output is so formatted as new-line terminated "lines" of 20 octets where each octet codes one triplet,
with two characters of prefix (like a cyclical line-number).
for example, the shortest three byte input:
AAA

should give the shortest output of three bytes plus new-line.
00ÿ

that is
30 30 FF 0A

and
AGG CGC AAC GGC TAA ATC GTT TTC ACA CCA CGT TTG AAA CGG GTG ACA CGA GAT TTA GTC
TAT GGT ACT AGG TAC GCC GTG GTG CGT GCG GAG TTA CTA GAT GTG TTA GTA CGC CAT CGT

should give the following binary.
01ÊûÃëÐÇå×ÌüùÖÀúæÌøáÔç
00ÑéÍÊÓïææùîâÔôáæÔäûñù

Should because of the small error rate:
For the smallest input, the script introduces 1 error.
For a 3 million triplets file run, the encoder introduces 11 errors.
Provided that the script is dnacodec3.pl, the run is invoked at command prompt as usual:
$> perl dnacodec3.pl -e < plain.txt > coded.txt

The decoder works as follow:

first loop reads the whole file and splits data to have an array of all octets. It keep track of every new-line.
second loop examines each octet, retaining those not beginning with 00 and disregards the rest. The plain Ascii output is formatted as new-line terminated lines of triplets separated by one space. The new-line are in the same position as they were in the input.

I prepared a 3 million triplets sample test file (about 12MByte) and tested for timing.
Using my laptop with an Intel Core i5 vPro at 2.6 GHz, the 3M encoder run always takes less than 20 sec.
During the run it takes 200-220 MByte of RAM. What a waste!
The decode run takes less than 10 sec. It cannot introduce errors... for now.
Again, for the decoding run
$> perl dnacodec3.pl -d < coded.txt > plain.txt

Here is the code
#!/usr/bin/perl
use strict ;
use warnings ;
my $switch = shift || die "usage $0 [-e|-d]\n";
my %map = qw( x 10  X 11  c 0b  ? 00
              A 00  T 01  G 10  C 11
              0 00  1 01  2 10  3 11
              00 A  01 T  10 G  11 C  ) ;
my $r = 20 ;
my @dummy = unpack ( '(A4)*', '0xxx' x $r ) ;
my $map = oct( $map{ c } . ($map{ C } x 9) ) ;
my $t = time() ;
my @inp = () ;
my @out = () ;
my @buf = () ;
my $n ;

sub arch {
    push @buf, @dummy[ 0 .. $r - $#buf - 2 ] ;
    push @out, "@buf" ;
    @buf = () ;
}

sub encode {
    my $mask = '(A3)*' ;
    while ( my $row = <STDIN> ) {
        chomp $row ;
        $row =~ s/\s+//g ;
        $row =~ s/[^\r\n\tATGC]//g ;
        next unless $row ;
        my @row = unpack( $mask, $row ) ;
        push @inp, @row if $row ;
    }
    $n = scalar @inp ;
    $r = $n if $r > $n ;
    for ( my $i = $n - 1 ; $i >= 0 ; --$i ) {
        my $e = $inp[$n-$i-1] ;
        my $l = length( $e ) ;
        my $d = $e =~ /\?/? 0: $l ;
        push @buf, ( $d -((($i-($n>>1))&$map)?0:1) )
           . $e . 'x'x(3-$l) ;
        arch unless $i % $r ;
    }
    arch if scalar @buf ;
    my $m = scalar @out ;
    for ( my $j = $m - 1 ; $j >= 0; --$j ) {
        my @ary = () ;
        my $e = $out[$m-$j-1] ;
        for my $byte ( split / /, $e ) {
            my @byte = split ( //, $byte ) ;
            my @trad = map { $map{ $_ } } @byte ;
            my $byte = join( '', @trad ) ;
            push @ary, $byte ;
        };
        my $row = sprintf( '%02d', $j % $r) ;
        $row .= pack( '(B8)*', @ary ) ;
        print "$row\n" ;
    }
}

sub decode {
    my $mask = '(B8)*' ;
    while ( my $row = <STDIN> ) {
        chomp $row ;
        next unless $row ;
        my @row = unpack( $mask, $row ) ;
        push @inp, @row[0..$#row], '?' if $row ;
    }
    $n = scalar @inp ;
    my @ary = () ;
    for ( my $i = $n - 1 ; $i >= 0 ; --$i ) {
        my $e = $inp[$n-$i-1] ;
        if ( $e ne '?' ) {
            my $u = oct( '0b'. substr($e,0,2) ) ;
            my $a = '' ;
            for my $j ( 1 .. $u ) {
                $a .= $map{ substr($e,$j+$j,2) } ;
            }
            push @ary, $a if $u ;
        }
        else {
            my $row = "@ary" ;
            $row =~ s/\s{2,}//g ;
            print "$row\n" if $row ;
            @ary =() ;
        }
    }
}

decode if $switch eq '-d' ;
encode if $switch eq '-e' ;

And here is the sample generator:
sub test_coder {
    my $n = shift || 1000 ;
    my @b = qw( A C G T ) ;
    for (my $l = 0; $l < $n; $l++) {
        my @ary = () ;
        for (my $t = 0; $t < 20; $t++) {
            push @ary, $b[ int(rand(4)) ] . $b[ int(rand(4)) ] . $b[ int(rand(4)) ] ;
        }
        print "@ary\n" ;
    }
    1;
}

sub test_decoder {
    my $n = shift || 1000;
    for (my $l = 0; $l < $n; $l++) {
        my @ary = () ;
        for (my $t = 0; $t < 20; $t++) {
            push @ary, int(rand(256)) | 0b11000000 ;
        }
        my $row = pack( 'C*', @ary ) ;
        print "$row\000" ;
    }
    1;
}

test_coder( @ARGV ) if $switch eq '-g' ;
test_decoder( @ARGV )  if $switch eq '-h' ;

I forgotten to show where the error is injected: the push @buf in the second loop does the trick.

It's subtle, I'll give you that. I won't be running full-scale tests until there is more than one competitor, but this is good stuff. :)

Thanks. I know this is a suggestion for other friends...I would like to improve the randomness of error position using the (still unused) time func: starting run at odd or even seconds should yield different output

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Sort numbers represented in an unknown base
Given a list of strings, sort the list as numbers without knowing what base is used. The values of the digits are also unknown (it is possible that '1' > '2').
Since the values of digits are unknown, use Benford's Law (or First Digit's Law) to determine the relative value of the digits. For distributions that follow Benford's Law, lower valued digits appear as a leading digit more frequently than higher valued digits.
Rules

This is code-golf
The list of strings can come from a source of your choosing (stdin, variable, file, user, etc.)
Strings are limited to ASCII characters.
Characters that do not appear as a leading character have the highest values. (assume there are no zeros, and sort strictly by leading frequency.)
Characters that appear as leading digits the same number of times as other characters are weighted equally.

Example
Unsorted
['c','ca','ac','cc','a','ccc','cx','cz','cy']

Sorted
['c','a','cc','ca','cz','cy','cx','ac','ccc']

Note: In the example, 'cz','cy' and 'cx' can appear as the 5th, 6th and 7th elements in any order since the digits 'x','y' and 'z' are equally weighted.

"Strings are limited to ASCII characters."  Your example only shows alphanumerics (actually only alphabetic characters).  Do you mean all ASCII characters, or just [0-9a-zA-Z], and do lower case letters count the same or differently from upper case characters?

All ASCII characters should be supported, and uppercase and lowercase are different.

Python, 59 108 112
sorted(a,None,lambda x:(-len(x),map(zip(*a)[0].count,x)),1)

Input is provided as the list a, and this expression produces the sorted list (+2 characters to assign to a variable). This sorts the list in reverse by negated length and then by frequency.

+1 Nicely done.  Didn't think it could be done space efficiently in single expression.

Nice! I didn't know about zip with None. Though it doesn't work in Python 3 which would use itertools.zip_longest.

None can't compare to integers in Python 3, so it would fail anyway.

@nneonneo Right, fillvalue would have to be set to something less than the smallest value.

And I thought I knew something about python - nope. Could you explain your code somewhat more detailed? I'd be very happy - python newbie here.

Ruby, 65
f=->a{a.sort_by{|s|[s.size,s.chars.map{|c|a.count{|t|t[0]!=c}}]}}

Sorts lexicographically on the string's size, then each character's frequency as not the leading digit.

Javascript (E6) 147
F=i=>(f={},i.map(x=>(f[x[0]]=-~f[x[0]])),i.map(x=>[x,[...x].map(y=>1e9-~f[y]+'')]).sort((a,b,d=a[0].length-b[0].length)=>d||a[1]<b[1]).map(x=>x[0]))

Limit
Frequency values up to 1000000000: for sorting, the frequency values are merged in a big padded string
Ungolfed
F=i=>(
  f={}, //init frequency map
  i.map(x => (f[x[0]]=-~f[x[0]])), // build frequency map
  i.map(x => [x, [...x].map(y=>1e9-~f[y]+'')]) // add frequency info to each element of input list
 .sort((a,b,d=a[0].length-b[0].length)=>d || a[1]<b[1]) // then sort by lenght and frequency
 .map( x => x[0]) // throw away frequency info
)

Sidenote X-~ increment by 1 even if the original number X is undefined or NaN
Usage
F(['c','ca','ac','cc','a','ccc','cx','cz','cy'])

Output: ["c", "a", "cc", "ca", "cx", "cz", "cy", "ac", "ccc"]

Java (261)
void s(String[]s){int[]a=new int[128];for(String t:s)a[t.charAt(0)]++;java.util.Arrays.sort(s,(o,p)->{int j=o.length()-p.length();if(j!=0)return j;for(int i=0;i<Math.min(o.length(),p.length());i++){j=a[p.charAt(i)]-a[o.charAt(i)];if(j!=0)return j;}return 0;});}

void s(String[] s) {
    int[] a = new int[128];
    for (String t : s) {
        a[t.charAt(0)]++;
    }
    java.util.Arrays.sort(s, (o, p) -> {
        int j = o.length() - p.length();
        if (j != 0) {
            return j;
        }
        for (int i = 0; i < Math.min(o.length(), p.length()); i++) {
            j = a[p.charAt(i)] - a[o.charAt(i)];
            if (j != 0) {
                return j;
            }
        }
        return 0;
    });
}

The methods takes an array of strings, and sorts the array in place. Nothing fancy about the implementation, but it does make use of the lambda expressions added to Java 8.