# Remapping ASCII

### Challenge

Write a program that reorders the ASCII characters!

It should output a single string containing all of the printable ASCII characters exactly once. The first character of this string is assigned the value 1, the second character the value 2, and so on.

If two characters are normally next to each other (the difference between their character codes is 1), they may not appear next to each other in the output.

### Scoring

Your score will be the sum of the values for all of the characters in your source code, as dictated by your program's output.

Please see the Verification section to calculate your score.

Lowest score wins!

### Rules

• "Printable ASCII" is defined to mean character codes 32 - 126, inclusive.

• You may write a full program or a function.

• Your code may only contain printable ASCII characters and newlines.

• Your program may not take any input.

• Newlines will always have the value 1. Your program's output should not include a newline.

### Verification

Use this stack snippet to verify that your code's output is valid, and to calculate your code's score!

var result = document.getElementById("result");document.getElementById("submit").onclick = function() {var code = document.getElementById("code").value;var output = document.getElementById("output").value;var values = [];for (var i = 0; i < output.length; i++) {var c = output[i];var v = c.charCodeAt();if (v < 32 || v > 126) {result.innerHTML = "Invalid output! Reason: " + c + " (code " + v + ") is out of range.";return;}if (values.indexOf(c) >= 0) {result.innerHTML = "Invalid output! Reason: " + c + " (code " + v + ") was repeated.";return;}if (i > 0) {var d = output[i - 1];var w = d.charCodeAt();if (Math.abs(v - w) == 1) {result.innerHTML = "Invalid output! Reason: " + d + " and " + c + " (codes " + w + " and " + v + ") cannot appear next to each other in the output.";return;}}values.push(c);}for (var j = 32; j <= 126; j++) {var c = String.fromCharCode(j);if (values.indexOf(c) < 0) {result.innerHTML = "Invalid output! Reason: " + c + " (code " + j + ") was missing.";return;}}var score = 0;for (var k = 0; k < code.length; k++) {var s = values.indexOf(code[k]) + 1;if (s <= 0) s = 1;score += s}result.innerHTML = "Your score is " + score + "!";}
<textarea id="code" rows=10 cols=50>Enter your code here.</textarea><br/><textarea id="output" rows=1 cols=50>Enter your code's output here.</textarea><br/><button id="submit">Submit</button><br/><p id="result"></p>

Thanks to this post for the leaderboard code!

• Loving the validation snippet. – mınxomaτ Sep 14 '15 at 14:36
• Can you explain briefly how the score is calculated, so we know how to optimize our answers? – Fatalize Sep 14 '15 at 14:38
• @Fatalize Basically, the idea is to write a program whose output assigns low values to the characters that it uses, by putting them towards the beginning of the outputted string. The "value" of each ASCII character is determined by its 1-based index in your code's output. Instead of counting each character in your source as 1, like a code-golf, each character in your source is counted as its value, as described above. – jrich Sep 14 '15 at 14:54
• This seems like a good time to use Whitespace in a programming contest... – C0deH4cker Sep 14 '15 at 16:58
• @C0deH4cker Unfortunately that would require tabs, which are not printable ASCII characters or newlines, so that would be invalid. – jrich Sep 14 '15 at 17:01

# CJam, 3561861681311261119996 94

"_|'~,Y/G>z|"_~

Try it online in the CJam interpreter.

"_|'~,Y/G>z[ \$&(*.02468:<@BDFHJLNPRTVXZ^bdfhjlnprtvx!#%)+-13579;=?ACEIKMOQSUW]acegikmoqsuwy{} ### Idea Using a variation of a technique common in CJam quines, we sort the printable ASCII characters by whether they appear in the source code, and the non-appearing ones – with two exceptions – by their code points' parity bits. With the proper source layout, we also manage to sort the source code characters – with one exception – by their frequencies. Special care has to be taken that two adjacent characters do not appear one after the other for the first time in the source code, as this would invalidate the answer. ### Code " "_~ Push a string, duplicate it and evaluate the copy. _| Perform the set union of the original string with itself. This is just an "excuse" to introduce the underscore.  Inspect the string (surrounds it with double quotes). '~, Push the string of Unicode characters before the tilde. Y/ Divide it into pairs. G> Discard the first 16 pairs (control characters). z Zip. This interleaves the pairs, ordering the characters by their code points' parities.  Inspect the array, i.e., push its string representation. | Perform set union with the string of source code characters. • Wouldn't be surprised to see CJam win this, Pyth doesn't have simple quines nor the ASCII characters in a built-in. – orlp Sep 14 '15 at 15:53 • CJam doesn't have a built-in for ASCII characters either. I'm using a unary range, then discard the control characters. – Dennis Sep 14 '15 at 15:59 ## Brainfuck, 1692826 765 (Still) Unoptimized, I know. I'm working on it (leave opts in the comments). ++[------>+<]>.++.---[-->+++<]>-.[->+++++++++<]>.--[----->+<]>.[-->+++<]>+.++.>+++[<---------->-]<-[-->+<]>-++.>++[>+++<-]>[<<++.>>-]<<++++.++.++.++.++.++.++++>>++++[<++++++++>-]<[<++.>-]<---.++.-->+++[>+++++<-]>-[<<--.>>-]<<---->++++[>+++++<-]>++[<<--.>>-]<<------.--.--.--.--. Output: +->.<[] "$&(*,02468:@BDFHJLNPRTVXZ\^bdfhjlnprtvxz|~{}ywusqomkigeca_YWUSQOMKIGECA?=;97531/)'%#!

I'm already utilizing overflow on 8bit cells to some extent, but I guess you could still optimize it. Though that would decrease the use of cheap chars :).

• I got 576 with a very naive program. Feel free to mix and match my idea. +1. – Level River St Sep 14 '15 at 21:09

# Pyth, 173 170

### Code

-so%CN2rd\~p"p~\dr2NC%os-

p~\dr2NC%os- "$&(*,.0468:<>@BDFHJLPRTVXZ^bfhjlntvxz|!#')+/13579;=?AEGIKMOQSUWY[]_acegikmquwy{} Hardcoding a quine-like string. Conveniently, the " character is very near the start of the generated string. Prints even then odd characters after the "quine". Much thanks to Dennis for saving 3 points, and making the code a palindome! Try it here • Using \~ for the character range improves your score by 3 points. (It also allows you to make your code a palindrome.) – Dennis Sep 14 '15 at 21:10 # Java, 3518 3189 2692 A simple loop that prints even characters, then odds. I tried a few things to optimize earlier ASCIIs, but most ended up making it longer overall, and ended up with a higher score. void A(){for(char A=31;A!=126;System.out.print(A+=2))A=A==125?30:A;} Output is: !#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^bdfhjlnprtvxz|~

Edit: Misunderstood the scoring at first. After flipping it to odd first, then even, it scores a lot better.

# Octave, 628

Code

["" 32:2:126 33:2:125]

Output:

# C,39 bytes, score 1687

main(i){for(;i-96;)i=putchar(32+i%95);}

>:,2+:"~"|
^         <

Output:

"$&(*,.02468:<>@BDFHJLNPRTVXZ\^bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} You can try it here if you want. It works by outputting 32-126 evens, and then 33-125 odds. If anyone wants an explanation, I'd be willing to. I golfed it until I got it better than brainf***, which I deemed to be the lowest I could go. As far as golfing strategies, I generated the ascii characters and then tried to replace costly characters with cheaper ones (like 1 with 2). I found out since g was so expensive, it was better to compute 126 every iteration. I also wrapped around the top since ^ was cheaper than v. 801 -> 797: Recent change was removing extra spaces that was a relic from using g. 797 -> 724: I changed calculating 126 every time to just reading tilde using "~". this also allowed for cutting away whitespace (And i'm beating one of the BF answers again) 724 -> 699: Similar to the last change, " " is an extremely cheap (4 points) way of obtaining 32 699 -> 627: Since I only go through the 2nd row pass once, I just changed it to setting 33 instead of maintaining another value on the stack and adding one. 627 -> 612: Moved as much as I could to string input. I'm pretty sure the design would need to change drastically to golf it any further. This is probably the final iteration, unless one of the non-golfing languages gets a lower solution. # Haskell, 830 ['!','#'..'}']++[' ','\"'..'~'] Evaluates to the string: !#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^bdfhjlnprtvxz|~

Inspired by @Jørgen's answer and completely different from my own.

# Brainfuck, score 576 667

Thinking about it, 576 seemed to good to be true: I did a little estimation and worked out my score to be around 95*6 + 45*2 = 660. Something must have gone wrong the first time I ran the validator. The correct score is closer to my estimate. It's still not a bad score.

+++++++++++++++++++++++++++++++++++++++++++++.--.+++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.++.---.++.----.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.--.---.--.--.--.--.--.--.+++.--.++++.++.++.

Keep it simple.

Basically just walks up and down the ASCII set, printing characters. The three characters used in the program are printed first. Turning round at either end was a little bit tricky.

-+.02468:<>@BDFHJLNPRTVXZ\^bdfhjlnprtvxz|~{}ywusqomkigeca_][YWUSQOMKIGECA?=;97531/,*(&$" #!%') # Ruby 2.2, 1157 eval s='srand 1;([*s.bytes].shuffle|[*33..0x7e].shuffle).map{|c|putc c}' Output: f.p|cahu]xens7*0{)3tbmdy[}l1; r(o@&gN/MjzSVv~>D4IL\KB92=i%PHE?5TQw,W-#6U'^Y!$R"XkO_q+CAGZF<8:J

This is a pretty dumb solution (and I'm not sure srand shouldn't be a standard loophole especially since it drastically reduces portability). Shuffles (most of) the bytes in its own source code and shuffles the rest, then uniques and concatenates the arrays. Uses a random seed picked so that the output is legal (the fact that it's a single digit is pure luck).

• Interesting solution! I'll classify this as legal because it will always produce the same output (if I've understood correctly) given the same seed. Also, having a variety of different approaches is always more interesting. – jrich Sep 14 '15 at 19:05

# CBM BASIC V2, 2553

1FORI=0TO47:PRINTCHR$(32+I*2);:NEXT 2FORI=0TO47:PRINTCHR$(33+I*2);:NEXT

the output (converted in ASCII by a python script on pc):

### Usage

Copy and paste the following to your console
(mawk won't work, because it's too sctrict stricter with printf)

awk 'END{for(rrf=rrr="rf(3)+=;1\"$?:~ptoin[<-EN% ^.|P";fr++<333;$fr=(ff=sprintf("%c",fr))~"[[(]"?f:ff);for(;r++<33+13+1;rrf=f)printf(rrf)(rrr~(rr=$(31+1+r+r))?f:rr)(rrr~(rr=$(133-(3+3+r+r)))?f:rr)}' < /dev/null

The < /dev/null at the end signals the end of input, so the END block will be executed.

I basically interweaved the characters coming from the bottom and coming from the top. Then I analysed, which characters were used the most in the program and printed them first, in order of frequency. Then I had to make sure that no character is printed more than one time. The weaving in opposite directions made it more probable that an already used character wouldn't lead to printing neighbours. But they met in the middle at P, so I had to print that in the beginning too. Then there were some problems with characters which are used in regexps... Then I renamed the variables cheaply and did the whole thing over again. Then I found some characters I could replace in my program, and did the whole thing over again. And so on.. I finally tweaked the string with the preferred characters a little by testing.

I think I'm done :D

During the process I never executed the program from the command line, but constructed a string I executed from inside a script, which would analyse the output for correctness and give me the score and stuff. That score output helped a lot. Of course I rechecked here (you never know) but it got me the same result.

There the program looks like this

p=sprintf("END{"\
"for(rrf=rrr=%c%s%c;fr++<333;$fr=(ff=sprintf(%c%cc%c,fr))~%c[[(]%c?f:ff);"\ "for(;r++<33+13+1;rrf=f)printf"\ "(rrf)(rrr~(rr=$(31+1+r+r))?f:rr)(rrr~(rr=$(133-(3+3+r+r)))?f:rr)}"\ ,34,s=sprintf("rf(3)+=;1%c%c$?:~ptoin[<-EN%c ^.|P",92,34,37),34,34,37,34,34,34)

# Matlab, 763

Of course, it's quite impossible to beat the Octave solution in MATLAB, since it doesn't have " which is 'early' in the ASCII-range. However, I decided to get a bit creative and figured to abuse randperm. I admit that it's a bit hacky and some could consider it cheating, but I guess it's a nice touch. First, the program and output:

rng(1194663);['' randperm(95)+31]

Ouput:

# Java, 15470

class A{public static void main(String[]I) throws Exception{java.lang.reflect.Field C=Character.class.getDeclaredClasses()[0].getDeclaredField("cache");C.setAccessible(true);Character[]E=(Character[])C.get(C);for(char A=31,G=31;A!=126;E[G++]=new Character(A+=2))A=A==125?30:A;for(char A=31;A!=126;A++)System.out.printf("%c", A);}}

Not really optimal at all, but it actually remaps the chars (rather than just printing out a set of modified chars).

Ungolfed:

public class Main {
public static void main(String[] args) throws Exception {
java.lang.reflect.Field feild = Character.class.getDeclaredClasses()[0].getDeclaredField("cache");
feild.setAccessible(true);
Character[] array = (Character[]) feild.get(args); //Since it's a static field, we can supply whatever we want here, and args is cheaper than null.

char i = 31;
for (char c = 31; c != 126; array[i++] = new Character(c += 2)) {
c = c == 125 ? 30 : c;
}

for (char c = 31; c < 126; c++) {
System.out.printf("%c", c);
}
}
}

!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^bdfhjlnprtvxz|~ It orders the chars using the same method as Geobits' answer, and does something similar to this answer to change the chars. # BBC BASIC, 2554 ## Code n=32 s$=""
REPEAT
s$+=CHR$(n)
n+=2
IFn=128THENn=33
UNTILn=127

# Fortran 90, 15231519 1171

This is a nested output loop, similar to other answers. Not too confident that much improvement is possible...

PRINT*,((CHAR(J),J=L,126,2),L=32,33)
END

Output:

"$&(*,.02468:<>@BDFHJLNPRTVXZ\^bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} Edit: Forgot that Fortran 90 is necessary for this code, 77 requires code to start in the 7th column. On the other hand, the language is case insensitive, allowing an easy improvement. The loop counters are J and L because these are the first two letters in the output string implicitly declared as integers by Fortran. # Perl, 1089 922 It turns out that printing the ASCII values in steps of 42 58 gives the lowest score with this approach: print chr$_*58%95+32for 0..94

### Output:

Z5oJ%_:tO*d?yT/iD~Y4nI$^9sN)c>xS.hC}X3mH#]8rM(b=wR-gB|W2lG"\7qL'a<vQ,fA{V1kF![6pK&;uP+e@zU0jE • print chr$_*42%95+32for 0..94 already achieves a score of 925, and 42 is most likely no longer optimal. – Dennis Sep 15 '15 at 22:30
• Thanks @Dennis — I had no idea you could write loops that way. – r3mainer Sep 15 '15 at 22:41
• If you replace the spaces with linefeeds, print chr$_*63%95+32for 31..125 achieves a score of 799. – Dennis Sep 15 '15 at 23:33 # JavaScript, 3169254821442104207118851876 1872 ### Code t='' i=S=95 while(i--)t+=String.fromCharCode(i*2291%S- -32) alert(t) ### Output ti^SH=2'{peZOD9.#wlaVK@5*~sh]RG<1&zodYNC8-"vkUJ?4)}rg\QF;0%yncXMB7,!uj_TI>3(|qf[PE:/$xmbWLA6+
• Is the v+ part of (v,i)=>v+i*3%95+32 necessary? It seems to me that it simply adds 0 every time since the array is filled with 0s.... – jrich Sep 14 '15 at 17:27
• @UndefinedFunction It seems not. Didn't focus too hard on optimizing, since I was working on an alternative method that ended up shorter anyways. Thanks! =) – Mwr247 Sep 14 '15 at 17:36
• for(w=95;w-->0;) can be for(w=95;w--;), because 0 is falsy and 1, 2, 3... are truthy. – jrich Sep 14 '15 at 19:19
• @UndefinedFunction Wow, how did I not think of that! You just shaved 56 points off of my best, bringing it to 2144 now :D Still trying to get it below 2000 though... – Mwr247 Sep 14 '15 at 19:33
• Easy improvement: use newlines instead of semicolons to separate statements. Newlines count as 1. – jrich Sep 14 '15 at 20:09

# Python 2, 72 bytes (3188) 116 bytes (1383)(1306) (1303)

thanks @FryAmTheEggman for the join trick ;)

thanks @nim (Did I misread the text? :P)

thanks @Mathias Ettinger

n='nr i(a)2:]o[c=fh1+t"3egj,p.7'
a=[chr(r)for r in range(32,127)if not chr(r)in n]
print n+"".join(a[::2]+a[1::2])

output:

nr<blank>i(a)2:]o[c=fh1+t"3egj,p.7!$&*/469<?ACEGIKMOQSUWY\_bkmsvxz|~#%'-058;>@BDFHJLNPRTVXZ^dlquwy{} • a=map(chr,range(32,172)) and "".join(a[::2]+a[1::2]) – FryAmTheEggman Sep 14 '15 at 17:49 • I think you can replace some of the ; with newlines, which count as 1 – nimi Sep 14 '15 at 19:24 • You can get 3 points out by starting with n='nr i(a… instead of n=' nri(a… – 301_Moved_Permanently Sep 17 '15 at 12:13 # PHP, 1217 1081 The code: for(;$T!=T;$T=($T+52)%95)echo chr(32+$T); Because the variables are not initialized, it needs to suppress the notices on running (PHP complains but continues execution and uses a default value that is appropriate in the context; 0 in this case):$ php -d error_reporting=0 remapping-ascii.php

Its output:

T)]2f;oDxM"V+_4h=qFzO$X-a6j?sH|Q&Z/c8lAuJ~S(\1e:nCwL!U*^3g<pEyN#W,5i>rG{P%Y.b7k@tI}R'[0d9mBvK Remarks: • the output starts with a white space (chr(32)); • the code prints the white space then each 52th character, wrapping around the range; • the magic number 52 was "discovered" by searching the entire range (1..94) of possible offsets; 1 produces the list of printable chars in the ascending order of their ASCII codes, 94 produces the list in the reverse order, both are bad; the multiples of 5 and 19 (the divisors of 95) produce short cycles and don't cover the entire range of values (also bad); • 52 seems to be magic; it is the best offset for this code; but it is also the best for some variations of the code (that produce slightly bigger scores); the variations I tried: use while() instead of for(), use$f++, $f-- or --$f instead of ++$f, swap the operands around the < and + operators; squeeze the modification of$T into 32+$T; • the names of the variables ($T and $f) are the first letters from the output; • I tried to initialize$T with 4 or 11 but the scores were worse; starting with 4 makes $the first character in the output; it is the most used character in a PHP source code; 11 brings + in front;$ and + are the most used characters in this code.

The code, tests, incremental changes I tried until I reached this solution and the script that tested all possible step values (the authoritative provider for 52 as the best step) can be found on github.

# Fourier, 1236

Basically a conversion of my BBCB program

32~N127(Na^^~N{128}{33~N}N)

Try it online!