Neuzuordnung von ASCII


36

Herausforderung

Schreiben Sie ein Programm, das die ASCII-Zeichen neu anordnet!

Es sollte eine einzelne Zeichenfolge ausgegeben werden, die alle druckbaren ASCII-Zeichen genau einmal enthält. Dem ersten Zeichen dieser Zeichenfolge wird der Wert 1, dem zweiten Zeichen der Wert 2 usw. zugewiesen.

Wenn zwei Zeichen normalerweise nebeneinander stehen (der Unterschied zwischen ihren Zeichencodes ist 1), werden sie in der Ausgabe möglicherweise nicht nebeneinander angezeigt.

Wertung

Ihre Punktzahl ist die Summe der Werte für alle Zeichen in Ihrem Quellcode, wie von der Ausgabe Ihres Programms vorgegeben.

Bitte lesen Sie den Abschnitt Überprüfung , um Ihre Punktzahl zu berechnen.

Die niedrigste Punktzahl gewinnt!

Regeln

  • "Druckbares ASCII" bedeutet die Zeichencodes 32 bis einschließlich 126.

  • Sie können ein vollständiges Programm oder eine Funktion schreiben.

  • Ihr Code darf nur druckbare ASCII-Zeichen und Zeilenumbrüche enthalten.

  • Ihr Programm nimmt möglicherweise keine Eingabe entgegen.

  • Zeilenumbrüche haben immer den Wert 1. Die Ausgabe Ihres Programms sollte keinen Zeilenumbruch enthalten.

Nachprüfung

Verwenden Sie dieses Stack-Snippet, um zu überprüfen, ob die Ausgabe Ihres Codes gültig ist, und um die Punktzahl Ihres Codes zu berechnen!


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>

Bestenliste

Vielen Dank an diesen Beitrag für den Leaderboard-Code!


var QUESTION_ID=57914,OVERRIDE_USER=42844;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>


12
Ich liebe das Validierungs-Snippet.
Mittwoch,

2
Können Sie kurz erläutern, wie die Punktzahl berechnet wird, damit wir wissen, wie wir unsere Antworten optimieren können?
Fatalize

@Fatalize Grundsätzlich besteht die Idee darin, ein Programm zu schreiben, dessen Ausgabe den verwendeten Zeichen niedrige Werte zuweist, indem sie an den Anfang der ausgegebenen Zeichenfolge gesetzt werden. Der "Wert" jedes ASCII-Zeichens wird durch seinen 1-basierten Index in der Ausgabe Ihres Codes bestimmt. Anstatt jedes Zeichen in Ihrer Quelle wie bei einem Code-Golf als 1 zu zählen, wird jedes Zeichen in Ihrer Quelle wie oben beschrieben als sein Wert gezählt.
jrich

4
Dies scheint eine gute Zeit zu sein, um Whitespace in einem Programmierwettbewerb zu verwenden ...
C0deH4cker

3
@ C0deH4cker Das würde leider Tabulatoren erfordern, die keine druckbaren ASCII-Zeichen oder Zeilenumbrüche sind, damit das ungültig wäre.
jrich

Antworten:


21

CJam, 356 186 168 131 126 111 99 96 94

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

Probieren Sie es online im CJam-Interpreter aus .

Ausgabe

"_|`'~,Y/G>z[ \$&(*.02468:<@BDFHJLNPRTVXZ^bdfhjlnprtvx!#%)+-13579;=?ACEIKMOQSUW]acegikmoqsuwy{}

Idee

Mit einer Variante einer in CJam-Quines üblichen Technik sortieren wir die druckbaren ASCII-Zeichen danach, ob sie im Quellcode vorkommen, und die nicht vorkommenden - mit zwei Ausnahmen - nach den Paritätsbits ihrer Codepunkte.

Mit dem richtigen Quellcode-Layout können wir die Quellcode-Zeichen - mit einer Ausnahme - auch nach ihrer Häufigkeit sortieren.

Es ist besonders darauf zu achten, dass zwei benachbarte Zeichen im Quellcode nicht zum ersten Mal hintereinander erscheinen, da dies die Antwort ungültig machen würde.

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.

Es wäre nicht verwunderlich, wenn CJam dies gewinnen würde. Pyth hat weder einfache Quines noch die ASCII-Zeichen in einem eingebauten Code.
Orlp

1
In CJam ist auch kein ASCII-Zeichensatz integriert. Ich verwende einen unären Bereich und verwerfe dann die Steuerzeichen.
Dennis

14

Brainfuck, 1692 826 765

(Noch) nicht optimiert, ich weiß. Ich arbeite daran (lass das in den Kommentaren).

++[------>+<]>.++.---[-->+++<]>-.[->+++++++++<]>.--[----->+<]>.[-->+++<]>+.++.>+++[<---------->-]<-[-->+<]>-++.>++[>+++<-]>[<<++.>>-]<<++++.++.++.++.++.++.++++>>++++[<++++++++>-]<[<++.>-]<---.++.-->+++[>+++++<-]>-[<<--.>>-]<<---->++++[>+++++<-]>++[<<--.>>-]<<------.--.--.--.--.

Ausgabe:

+->.<[] "$&(*,02468:@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~{}ywusqomkigeca_YWUSQOMKIGECA?=;97531/)'%#!

Ich nutze bereits einen Überlauf auf 8-Bit-Zellen, aber ich denke, Sie könnten ihn noch optimieren. Dies würde jedoch die Verwendung billiger Zeichen verringern :).


2
I got 576 with a very naive program. Feel free to mix and match my idea. +1.
Level River St

12

Pyth, 173 170

Code

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

Output

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


As a side-note, I don't think Pyth's r should return a list of strings when used in this mode.
FryAmTheEggman

1
Using \~ for the character range improves your score by 3 points. (It also allows you to make your code a palindrome.)
Dennis

@Dennis Thanks! It took me way too long to realize I could just write the ~ into the "quine" part instead of needing to add it to the range somehow... :d
FryAmTheEggman

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.


10

Octave, 628

Code

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

Output:

 "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

Two ranges implicitly converted to string. Not sure if returning as Ans is acceptable, also gives a warning about the implicit conversion. Tried some other range vectors, but could not find anything more efficient.


Returning an answer is acceptable, nice job!
jrich

8

C,42 bytes, score 1539

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

!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~

C,39 bytes, score 1687

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

!Aa"Bb#Cc$Dd%Ee&Ff'Gg(Hh)Ii*Jj+Kk,Ll-Mm.Nn/Oo0Pp1Qq2Rr3Ss4Tt5Uu6Vv7Ww8Xx9Yy:Zz;[{<\|=]}>^~?_ @`

In both cases, i is initialised to the number of strings on the commandline (as no arguments are given, this is 1.)

The first version does things the obvious way, incrementing by 2, taking modulo 95 and thefore printing all the odds then all the evens.

The second version takes advantage of the fact that putchar returns the character printed. As 32 is coprime to 95, we can cycle through the characters. As C contains a lot of lowercase characters I hoped that this, besides being shorter, would have a lower score but unfortunately this is not the case.


i;main(){for(;i<3990;i+=42)putchar(i%95+32);} scores 1472, I think
squeamish ossifrage

@squeamishossifrage well spotted, it does indeed! How long did it take to find that one? I got bored of C, my brainfuck answer is much better.
Level River St

Just noodling around with the Perl script I used to generate this answer :-)
squeamish ossifrage

you can lower your score using a as the variable name rather than i in both cases.
409_Conflict

8

Befunge-93, 801 797 724 699 627 612

Code:

"!  "     ^
v     _@#$<
>:,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.


7

Haskell, 830

['!','#'..'}']++[' ','\"'..'~']

Evaluates to the string:

!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~

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


7

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/,*(&$" #!%')

6

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~>D4I`L\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).


1
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

5

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):

<blank>"$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

5

gawk, 2782 1988 1821

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)}

Output

rf(3)+=;1"$?:~ptoin[<-EN% ^.|P}{&yw*u,sq02m4k68gec>a@_B]DFYHWJULSQORMTKVIXGZ\CA`bd9h7j5l/vx'z#!

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)

5

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:

p2)[]913r~jZe:'Xf +b(Atd@LHT*7&xmN>6!?CJgwsaSh|/McO4_EkK=$5VP-%D<"Gz#Yq08n};WB`{.l\Quy^vR,IFoiU

For calculating an appropriate seed, I used the following program, which I ran until seed=4648029 (i.e., until the dishes were done)

minscore=Inf;
for(seed=1:1e9)
    rng(seed)
    p=randperm(95)+31;
    if(any(abs(diff(p))==1))
        continue
    end
    codestring=sprintf('rng(%d);['''' randperm(95)+31]',seed);
    score=0;
    for(i=1:length(codestring))
        score=score + find(codestring(i)==p,1);
    end
    if(score<minscore)
        minscore=score;
        bestseed=seed;
    end
end

Perhaps one way to improve the program is to try out floating point seeds as well, e.g., 2.3e4 increase the number of seeds without having a longer seed length. If anyone feels like making a program to calculate all n-character numbers representable by Matlab.... ;)


I think this is an excellent solution. However, ['' 32:2:126 33:2:125] (with single quotes) is valid, and shorter at 728 points :-)
Jørgen

@Jørgen I know, but I wanted to try a different approach ;). I guess it would have yielded more interesting results if randperm wasn't such a long function name.
Sanchises

4

Haskell, 1660 1376

""!_="O"
(a:b)!(c:d)=a:c:b!d
a=[' '..'N']!['P'..]

Defines the function a which returns the string:

 P!Q"R#S$T%U&V'W(X)Y*Z+[,\-].^/_0`1a2b3c4d5e6f7g8h9i:j;k<l=m>n?o@pAqBrCsDtEuFvGwHxIyJzK{L|M}N~O

4

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);
        }
    }
}

Output

!#%')+-/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.


3

BBC BASIC, 2554

Code

n=32
s$=""
REPEAT
  s$+=CHR$(n)
  n+=2
  IFn=128THENn=33
UNTILn=127
PRINTs$

Output

 "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

3

Fortran 90, 1523 1519 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.


3

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

1
print chr$_*42%95+32for 0..94 already achieves a score of 925, and 42 is most likely no longer optimal.
Dennis

Thanks @Dennis — I had no idea you could write loops that way.
squeamish ossifrage

If you replace the spaces with linefeeds, print chr$_*63%95+32for 31..125 achieves a score of 799.
Dennis

3

JavaScript, 3169 2548 2144 2104 2071 1885 1876 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-"vk`UJ?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

@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

for(w=95;w-->0;) can be for(w=95;w--;), because 0 is falsy and 1, 2, 3... are truthy.
jrich

@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

Easy improvement: use newlines instead of semicolons to separate statements. Newlines count as 1.
jrich

3

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{}

4
a=map(chr,range(32,172)) and "".join(a[::2]+a[1::2])
FryAmTheEggman

1
I think you can replace some of the ; with newlines, which count as 1
nimi

1
You can get 3 points out by starting with n='nr i(a… instead of n=' nri(a…
409_Conflict

3

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.


2

Fourier, 1236

Basically a conversion of my BBCB program

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

Output

 "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~!#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{}

0

AWK, 49 bytes, Score: 1755

BEGIN{for(f=82;++f<178;)printf"%c",(2*f-1)%95+32}

Try it online!

Simply prints every other character then starts over filling in the blanks. First character printed is an f. I attempted printing in reverse order, but that greatly increased the score. Other patterns are possible by simply changing the multiplier and the loop criteria.


Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.