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>
Antworten:
CJam,
356186168131126111999694Probieren Sie es online im CJam-Interpreter aus .
Ausgabe
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
quelle
Brainfuck,
1692826765(Noch) nicht optimiert, ich weiß. Ich arbeite daran (lass das in den Kommentaren).
Ausgabe:
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 :).
quelle
Pyth,
173170Code
Output
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
quelle
r
should return a list of strings when used in this mode.\~
for the character range improves your score by 3 points. (It also allows you to make your code a palindrome.)~
into the "quine" part instead of needing to add it to the range somehow... :dJava,
3518 31892692A 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.
Output is:
Edit: Misunderstood the scoring at first. After flipping it to odd first, then even, it scores a lot better.
quelle
Octave, 628
Code
Output:
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.
quelle
C,42 bytes, score 1539
C,39 bytes, score 1687
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.
quelle
i;main(){for(;i<3990;i+=42)putchar(i%95+32);}
scores 1472, I thinka
as the variable name rather thani
in both cases.Befunge-93,
801797724699627612Code:
Output:
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 thanv
.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.
quelle
Haskell, 830
Evaluates to the string:
Inspired by @Jørgen's answer and completely different from my own.
quelle
Brainfuck, score
576667Thinking 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.
quelle
Ruby 2.2, 1157
Output:
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).
quelle
CBM BASIC V2, 2553
the output (converted in ASCII by a python script on pc):
quelle
gawk,
278219881821Output
Usage
Copy and paste the following to your console
(mawk won't work, because it's
too sctrictstricter with printf)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
quelle
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 abuserandperm
. 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:Ouput:
For calculating an appropriate seed, I used the following program, which I ran until seed=4648029 (i.e., until the dishes were done)
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.... ;)
quelle
randperm
wasn't such a long function name.Haskell,
16601376Defines the function
a
which returns the string:quelle
Java, 15470
Not really optimal at all, but it actually remaps the chars (rather than just printing out a set of modified chars).
Ungolfed:
Output
It orders the chars using the same method as Geobits' answer, and does something similar to this answer to change the chars.
quelle
BBC BASIC, 2554
Code
Output
quelle
Fortran 90,
152315191171This is a nested output loop, similar to other answers. Not too confident that much improvement is possible...
Output:
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
andL
because these are the first two letters in the output string implicitly declared as integers by Fortran.quelle
Perl,
1089922It turns out that printing the ASCII values in steps of
4258 gives the lowest score with this approach:Output:
quelle
print chr$_*42%95+32for 0..94
already achieves a score of 925, and 42 is most likely no longer optimal.print chr$_*63%95+32for 31..125
achieves a score of 799.JavaScript,
31692548214421042071188518761872Code
Output
quelle
v+
part of(v,i)=>v+i*3%95+32
necessary? It seems to me that it simply adds0
every time since the array is filled with0
s....for(w=95;w-->0;)
can befor(w=95;w--;)
, because0
is falsy and1, 2, 3...
are truthy.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
output:
quelle
a=map(chr,range(32,172))
and"".join(a[::2]+a[1::2])
;
with newlines, which count as 1n='nr i(a…
instead ofn=' nri(a…
PHP,
12171081The code:
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):Its output:
Remarks:
chr(32)
);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: usewhile()
instead offor()
, use$f++
,$f--
or--$f
instead of++$f
, swap the operands around the<
and+
operators; squeeze the modification of$T
into32+$T
;$T
and$f
) are the first letters from the output;$T
with4
or11
but the scores were worse; starting with4
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.quelle
Fourier, 1236
Basically a conversion of my BBCB program
Output
quelle
AWK, 49 bytes, Score: 1755
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.quelle
Perl 5, 1069
Try it online!
quelle