The task is to display n characters of the ASCII table.
You may write a function (or a program that takes the argument as a parameter, STDIN is allowed as well) that takes a parameter n, which will be the index of the last character to print.
The task is quite simple, so as an example here's a possible implementation in Python 2.7:
(lambda n:map(chr, range(n)))(256)
As I said it's a simple task. So this is code-golf and the shortest codes wins!
EDIT
As some of you pointed out this code doesn't print the result. It's just an example since I might struggle explaining the problem in english ;-).
EDIT2
Feel free to post the answer in any programming language, even if it's not the shortest code. Maybe there are some interesting implementations out there!
EDIT3
Fixed the example so it prints the result.
101 Answers 101
brainfuck - (削除) 169 (削除ここまで) (削除) 146 (削除ここまで) 142 bytes
-[+>+[+<]>+]>+>>,[>,]<[<]<[->>[->]<[<]<]>>>[[<[-<+<+<+>>>]+++++++++[<[-<+>]<<[-<+>>>+<<]<[->+<]>>>>-]]<,<<,>[->>>+<<<]>>>---------->]<-[->.+<]
Limitations:
- EOF must be 0
- Requires 8-bit wrapping cells
- Because of ^, mods input by 256
Not the shortest answer here, but hey, brainfuck! This would be a really, really good brainfuck challenge, except for the fact that it requires human readable input without guaranteeing the number of digits. I could have required input to have leading zeroes to make it 3 characters long, but what fun is that? :D One major problem with taking input this way is that brainfuck's only branching or looping structure checks if the current cell is zero or not. When the input can contain zeroes, it can cause your code to take branches it shouldn't be taking. To solve this problem, I store each digit of input plus 1, then subtract the excess at the last possible second. That way, I always know where my zeroes are.
I did say that this would have been a great brainfuck challenge without having to parse input. Why is that? Well, let's pretend that we don't take a numeric input. We'll say the challenge is "Given a byte of input, output all ASCII characters below that byte". Here's what my answer would be:
brainfuck - 8 bytes
,[->.+<]
It's quite a difference! The real program uses 135 instructions to collect the input (over 95% of the program!), just because it's a human typing it. Store the number as a byte and give that to me, and it only takes one.
(Fun fact: If you understood the hypothetical program, then congratulations! You understand brainfuck in its entirety. The whole language has only eight commands, and that program happens to use each one exactly once.)
Explanation
-[+>+[+<]>+]>+ abuse 8 bit wrapping to put 47 in cell 4
>>,[>,] starting in cell 6; get each character of input
<[<]<[->>[->]<[<]<] subtract the value of cell 4 from each input character
'0' has an ascii value of 47 so subtracting 47 from each
digit gives you that digit's value plus 1
>>>[ if the number is in more than one cell
(when the program first starts this means "if the input has
more than one digit")
[<[-<+<+<+>>>] copy first input cell to 3 new cells
+++++++++[<[-<+>]<< do some fancy addition magic to multiply that value by 10
[-<+>>>+<<]<[->+<]>>>>-]]
<,<<,> clean up a bit (abusing comma to set cells to 0)
[->>>+<<<]>>> add the value to the next cell of input
---------- because we multiplied (the digit plus 1) by 10; the answer
is 10 too high; so subtract 10
>] if the input is still in multiple cells; do the song and
dance again (multiply by 10; add to next cell; subtract 10)
<- we never got a chance to fix the final digit; so it's still 1
too high
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; we have now finished processing input ;;
;; the tape is empty except for the current cell ;;
;; the current cell contains the number that was input ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
[ while the cell containing input != 0
- subtract 1 from it
>.+ go a cell to the right; output that cell; then add 1
<] repeat
-
\$\begingroup\$ Nice! Definitely +1 for the effort :-) \$\endgroup\$oopbase– oopbase2014年10月28日 15:24:37 +00:00Commented Oct 28, 2014 at 15:24
-
1\$\begingroup\$ You could save some bytes on the outputting part:
>[-]<[->.+<]
Set cell next to current cell to 0, then count down the current cell while increasing the cell next to it and simultaneously printing the value. \$\endgroup\$Shujal– Shujal2014年10月28日 15:59:52 +00:00Commented Oct 28, 2014 at 15:59 -
\$\begingroup\$ @shu That's an excellent point! I didn't think of that at all. In addition to being shorter, it fixes the problem I had with choking on large inputs and it's probably faster! Thanks :) \$\endgroup\$undergroundmonorail– undergroundmonorail2014年10月29日 12:59:31 +00:00Commented Oct 29, 2014 at 12:59
-
\$\begingroup\$ Yeah, it's much, much faster now. I also didn't need the
>[-]<
part because I was already next to an empty cell. :) \$\endgroup\$undergroundmonorail– undergroundmonorail2014年10月29日 13:09:24 +00:00Commented Oct 29, 2014 at 13:09 -
2\$\begingroup\$ Also, your second answer is valid. \$\endgroup\$Esolanging Fruit– Esolanging Fruit2017年02月13日 00:18:19 +00:00Commented Feb 13, 2017 at 0:18
CJam, 4 bytes
ric,
Full program that reads from STDIN (input field in the online interpreter).
This simply executes range(chr(int(input())))
, taking advantage of the fact that ,
gives a return an array of characters if its argument is a character.
I call dibs on c,
(2 bytes), just in case that assuming the input is already on the stack turns out to be allowed.
-
\$\begingroup\$ Do you have to specify some input? The online runner just outputs the code itself. \$\endgroup\$manatwork– manatwork2014年10月28日 12:52:34 +00:00Commented Oct 28, 2014 at 12:52
-
14\$\begingroup\$ @manatwork: Just a sec. You have to hurry when you post these... ;) \$\endgroup\$Dennis– Dennis2014年10月28日 12:53:47 +00:00Commented Oct 28, 2014 at 12:53
-
\$\begingroup\$ I am a little confused by this. The character at 0 ( aka 0c )prevents anything else from being printed after it. ric,( seems to work fine. This means the code doesn't work. \$\endgroup\$kaine– kaine2014年10月28日 18:03:45 +00:00Commented Oct 28, 2014 at 18:03
-
2\$\begingroup\$ @kaine: Internet Explorer is written in C++, which does not use null-terminated strings. According to this, null characters are parse errors in HTML 5; the browser must replace it with a � or abort processing the document. \$\endgroup\$Dennis– Dennis2014年10月28日 18:55:34 +00:00Commented Oct 28, 2014 at 18:55
-
4\$\begingroup\$ Keep in mind that you have to enter a sufficiently large
n
, because the first few dozen of ASCII characters are non-printable characters. Fun fact: this program also outputs the Unicode table, for example n=9999 \$\endgroup\$Sanchises– Sanchises2014年10月29日 15:28:10 +00:00Commented Oct 29, 2014 at 15:28
Befunge 93 - (削除) 23 (削除ここまで) 21
&> :#v_,>:#,_@
^-1:<
Befunge 93 - (削除) 15 (削除ここまで) 13 (by Ingo Bürk)
This one prints the list in reverse, but OP only said we need to print the first n
characters, not that it has to be in order.
&>::>v
@^-1,_
Might not be golfable any further without moving on to Befunge98 (for the ";" operator, see @Kasran's answer)
Try it here:
function BefungeBoard(source, constraints) {
constraints = constraints || {
width: 80,
height: 25
};
this.constraints = constraints;
this.grid = source.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/).map(function (line) {
return (line + String.repeat(' ', constraints.width - line.length)).split('');
});
for (var i = this.grid.length; i < constraints.height; i++) {
this.grid[i] = String.repeat(' ', constraints.width).split('');
}
this.pointer = {
x: 0,
y: 0
};
this.direction = Direction.RIGHT;
}
BefungeBoard.prototype.nextPosition = function () {
var vector = this.direction.toVector(),
nextPosition = {
x: this.pointer.x + vector[0],
y: this.pointer.y + vector[1]
};
nextPosition.x = nextPosition.x < 0 ? this.constraints.width - 1 : nextPosition.x;
nextPosition.y = nextPosition.y < 0 ? this.constraints.height - 1 : nextPosition.y;
nextPosition.x = nextPosition.x >= this.constraints.width ? 0 : nextPosition.x;
nextPosition.y = nextPosition.y >= this.constraints.height ? 0 : nextPosition.y;
return nextPosition;
};
BefungeBoard.prototype.advance = function () {
this.pointer = this.nextPosition();
if (this.onAdvance) {
this.onAdvance.call(null, this.pointer);
}
};
BefungeBoard.prototype.currentToken = function () {
return this.grid[this.pointer.y][this.pointer.x];
};
BefungeBoard.prototype.nextToken = function () {
var nextPosition = this.nextPosition();
return this.grid[nextPosition.y][nextPosition.x];
};
var Direction = (function () {
var vectors = [
[1, 0],
[-1, 0],
[0, -1],
[0, 1]
];
function Direction(value) {
this.value = value;
}
Direction.prototype.toVector = function () {
return vectors[this.value];
};
return {
UP: new Direction(2),
DOWN: new Direction(3),
RIGHT: new Direction(0),
LEFT: new Direction(1)
};
})();
function BefungeStack() {
this.stack = [];
}
BefungeStack.prototype.pushAscii = function (item) {
this.pushNumber(item.charCodeAt());
};
BefungeStack.prototype.pushNumber = function (item) {
if (isNaN(+item)) {
throw new Error(typeof item + " | " + item + " is not a number");
}
this.stack.push(+item);
};
BefungeStack.prototype.popAscii = function () {
return String.fromCharCode(this.popNumber());
};
BefungeStack.prototype.popNumber = function () {
return this.stack.length === 0 ? 0 : this.stack.pop();
};
function Befunge(source, constraints) {
this.board = new BefungeBoard(source, constraints);
this.stack = new BefungeStack();
this.stringMode = false;
this.terminated = false;
this.digits = "0123456789".split('');
}
Befunge.prototype.run = function () {
for (var i = 1; i <= (this.stepsPerTick || 10); i++) {
this.step();
if (this.terminated) {
return;
}
}
requestAnimationFrame(this.run.bind(this));
};
Befunge.prototype.step = function () {
this.processCurrentToken();
this.board.advance();
};
Befunge.prototype.processCurrentToken = function () {
var token = this.board.currentToken();
if (this.stringMode && token !== '"') {
return this.stack.pushAscii(token);
}
if (this.digits.indexOf(token) !== -1) {
return this.stack.pushNumber(token);
}
switch (token) {
case ' ':
while ((token = this.board.nextToken()) == ' ') {
this.board.advance();
}
return;
case '+':
return this.stack.pushNumber(this.stack.popNumber() + this.stack.popNumber());
case '-':
return this.stack.pushNumber(-this.stack.popNumber() + this.stack.popNumber());
case '*':
return this.stack.pushNumber(this.stack.popNumber() * this.stack.popNumber());
case '/':
var denominator = this.stack.popNumber(),
numerator = this.stack.popNumber(),
result;
if (denominator === 0) {
result = +prompt("Illegal division by zero. Please enter the result to use:");
} else {
result = Math.floor(numerator / denominator);
}
return this.stack.pushNumber(result);
case '%':
var modulus = this.stack.popNumber(),
numerator = this.stack.popNumber(),
result;
if (modulus === 0) {
result = +prompt("Illegal division by zero. Please enter the result to use:");
} else {
result = Math.floor(numerator / modulus);
}
return this.stack.pushNumber(result);
case '!':
return this.stack.pushNumber(this.stack.popNumber() === 0 ? 1 : 0);
case '`':
return this.stack.pushNumber(this.stack.popNumber() < this.stack.popNumber() ? 1 : 0);
case '>':
this.board.direction = Direction.RIGHT;
return;
case '<':
this.board.direction = Direction.LEFT;
return;
case '^':
this.board.direction = Direction.UP;
return;
case 'v':
this.board.direction = Direction.DOWN;
return;
case '?':
this.board.direction = [Direction.RIGHT, Direction.UP, Direction.LEFT, Direction.DOWN][Math.floor(4 * Math.random())];
return;
case '_':
this.board.direction = this.stack.popNumber() === 0 ? Direction.RIGHT : Direction.LEFT;
return;
case '|':
this.board.direction = this.stack.popNumber() === 0 ? Direction.DOWN : Direction.UP;
return;
case '"':
this.stringMode = !this.stringMode;
return;
case ':':
var top = this.stack.popNumber();
this.stack.pushNumber(top);
return this.stack.pushNumber(top);
case '\\':
var first = this.stack.popNumber(),
second = this.stack.popNumber();
this.stack.pushNumber(first);
return this.stack.pushNumber(second);
case '$':
return this.stack.popNumber();
case '#':
return this.board.advance();
case 'p':
return this.board.grid[this.stack.popNumber()][this.stack.popNumber()] = this.stack.popAscii();
case 'g':
return this.stack.pushAscii(this.board.grid[this.stack.popNumber()][this.stack.popNumber()]);
case '&':
return this.stack.pushNumber(+prompt("Please enter a number:"));
case '~':
return this.stack.pushAscii(prompt("Please enter a character:")[0]);
case '.':
return this.print(this.stack.popNumber());
case ',':
return this.print(this.stack.popAscii());
case '@':
this.terminated = true;
return;
}
};
Befunge.prototype.withStdout = function (printer) {
this.print = printer;
return this;
};
Befunge.prototype.withOnAdvance = function (onAdvance) {
this.board.onAdvance = onAdvance;
return this;
};
String.repeat = function (str, count) {
var repeated = "";
for (var i = 1; i <= count; i++) {
repeated += str;
}
return repeated;
};
window['requestAnimationFrame'] = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
(function () {
var currentInstance = null;
function resetInstance() {
currentInstance = null;
}
function getOrCreateInstance() {
if (currentInstance !== null && currentInstance.terminated) {
resetInstance();
}
if (currentInstance === null) {
var boardSize = Editor.getBoardSize();
currentInstance = new Befunge(Editor.getSource(), {
width: boardSize.width,
height: boardSize.height
});
currentInstance.stepsPerTick = Editor.getStepsPerTick();
currentInstance.withStdout(Editor.append);
currentInstance.withOnAdvance(function (position) {
Editor.highlight(currentInstance.board.grid, position.x, position.y);
});
}
return currentInstance;
}
var Editor = (function (onExecute, onStep, onReset) {
var source = document.getElementById('source'),
sourceDisplay = document.getElementById('source-display'),
sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
stdout = document.getElementById('stdout');
var execute = document.getElementById('execute'),
step = document.getElementById('step'),
reset = document.getElementById('reset');
var boardWidth = document.getElementById('board-width'),
boardHeight = document.getElementById('board-height'),
stepsPerTick = document.getElementById('steps-per-tick');
function showEditor() {
source.style.display = "block";
sourceDisplayWrapper.style.display = "none";
source.focus();
}
function hideEditor() {
source.style.display = "none";
sourceDisplayWrapper.style.display = "block";
var computedHeight = getComputedStyle(source).height;
sourceDisplayWrapper.style.minHeight = computedHeight;
sourceDisplayWrapper.style.maxHeight = computedHeight;
sourceDisplay.textContent = source.value;
}
function resetOutput() {
stdout.value = null;
}
function escapeEntities(input) {
return input.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
sourceDisplayWrapper.onclick = function () {
resetOutput();
showEditor();
onReset && onReset.call(null);
};
execute.onclick = function () {
resetOutput();
hideEditor();
onExecute && onExecute.call(null);
};
step.onclick = function () {
hideEditor();
onStep && onStep.call(null);
};
reset.onclick = function () {
resetOutput();
showEditor();
onReset && onReset.call(null);
};
return {
getSource: function () {
return source.value;
},
append: function (content) {
stdout.value = stdout.value + content;
},
highlight: function (grid, x, y) {
var highlighted = [];
for (var row = 0; row < grid.length; row++) {
highlighted[row] = [];
for (var column = 0; column < grid[row].length; column++) {
highlighted[row][column] = escapeEntities(grid[row][column]);
}
}
highlighted[y][x] = '<span class="activeToken">' + highlighted[y][x] + '</span>';
sourceDisplay.innerHTML = highlighted.map(function (lineTokens) {
return lineTokens.join('');
}).join('\n');
},
getBoardSize: function () {
return {
width: +boardWidth.innerHTML,
height: +boardHeight.innerHTML
};
},
getStepsPerTick: function () {
return +stepsPerTick.innerHTML;
}
};
})(function () {
getOrCreateInstance().run();
}, function () {
getOrCreateInstance().step();
}, resetInstance);
})();
.container {
width: 100%;
}
.so-box {
font-family:'Helvetica Neue', Arial, sans-serif;
font-weight: bold;
color: #fff;
text-align: center;
padding: .3em .7em;
font-size: 1em;
line-height: 1.1;
border: 1px solid #c47b07;
-webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
background: #f88912;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
display: inline-block;
border-radius: 6px;
float: left;
margin-right: 25px;
cursor: pointer;
}
.option {
padding: 10px 20px;
margin-right: 25px;
float: left;
}
input, textarea {
box-sizing: border-box;
}
textarea {
display: block;
white-space: pre;
overflow: auto;
height: 75px;
width: 100%;
max-width: 100%;
min-height: 25px;
}
span[contenteditable] {
padding: 2px 6px;
background: #cc7801;
color: #fff;
}
#controls-container, #options-container {
height: auto;
padding: 6px 0;
}
#stdout {
height: 50px;
}
#reset {
float: right;
}
#source-display-wrapper {
display: none;
width: 100%;
height: 100%;
overflow: auto;
border: 1px solid black;
box-sizing: border-box;
}
#source-display {
font-family: monospace;
white-space: pre;
padding: 2px;
}
.activeToken {
background: #f88912;
}
.clearfix:after {
content:".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {
display: inline-block;
}
* html .clearfix {
height: 1%;
}
.clearfix {
display: block;
}
<div class="container">
<textarea id="source" placeholder="Enter your Befunge-93 program here" wrap="off">&> :#v_,>:#,_@
^-1:<</textarea>
<div id="source-display-wrapper">
<div id="source-display"></div>
</div>
</div>
<div id="controls-container" class="container clearfix">
<input type="button" id="execute" class="control so-box" value="► Execute" />
<input type="button" id="step" class="control so-box" value="Step" />
<input type="button" id="reset" class="control so-box" value="Reset" />
</div>
<div id="stdout-container" class="container">
<textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea>
</div>
<div id="options-container" class="container">
<div class="option so-box">Steps per Tick: <span id="steps-per-tick" contenteditable>500</span>
</div>
<div class="option so-box">Board Size: <span id="board-width" contenteditable>80</span> x <span id="board-height" contenteditable>25</span>
</div>
</div>
-
-
\$\begingroup\$ The question doesn't state that we must print it in any order, so this is five byte shorter:
&> #- #1:# :#,_@
(it just prints it in reverse) \$\endgroup\$Ingo Bürk– Ingo Bürk2014年10月29日 19:55:43 +00:00Commented Oct 29, 2014 at 19:55 -
\$\begingroup\$ I shaved off another bytes for a total of 15. Because of newlines I will edit it into your post. \$\endgroup\$Ingo Bürk– Ingo Bürk2014年10月29日 19:57:28 +00:00Commented Oct 29, 2014 at 19:57
-
\$\begingroup\$ Well played on the extra golfing :) As for the inline interpreter, I wasn't aware there was one. It's great, thanks :) \$\endgroup\$karhell– karhell2014年10月30日 08:47:54 +00:00Commented Oct 30, 2014 at 8:47
-
\$\begingroup\$ The interpreter is new from the linked challenge. I just thought I'd actually use it when I saw your answer. :) \$\endgroup\$Ingo Bürk– Ingo Bürk2014年10月30日 08:58:17 +00:00Commented Oct 30, 2014 at 8:58
Java, (削除) 151 (削除ここまで) (削除) 128 (削除ここまで) (削除) 77 (削除ここまで) (削除) 62 (削除ここまで) 56 bytes
First try at code-golfing.
void f(int n){for(char i=0;++i<=n;System.out.print(i));}
Usage:
import java.util.Scanner;
class A {
public static void main(String[] a) {
int num = new Scanner(System.in).nextInt();
new A().f(num);
}
void f(int n) {
for (char i = 0; ++i <= n; System.out.print(i));
}
}
Thanks to @Shujal, @flawr, @Ingo Bürk and @Loovjo for the serious byte reduction.
-
1\$\begingroup\$ You can save some chars by declaring the int while opening the scanner:
int i,n=new Scanner(...
and changing the loop tofor(;++i<n;)
. Also, you don't need to invokeCharacter.toString
. You can just feed System.out a char value and it will happily output it. \$\endgroup\$Shujal– Shujal2014年10月28日 16:03:52 +00:00Commented Oct 28, 2014 at 16:03 -
1\$\begingroup\$ @Shujal I have much to learn yet. Thanks! \$\endgroup\$Rodolfo Dias– Rodolfo Dias2014年10月28日 19:21:39 +00:00Commented Oct 28, 2014 at 19:21
-
1\$\begingroup\$ The challenge allows the use of your
a
as input. And I think you can shorten thefor
loop by abusing the increment place as loop body:for(;++i<n;System.out.print((char)i));
(but you might have to change the initialization or end value by +- 1) \$\endgroup\$flawr– flawr2014年10月29日 19:11:57 +00:00Commented Oct 29, 2014 at 19:11 -
1\$\begingroup\$ You are allowed to write a function, so no need for an entire class and everything. \$\endgroup\$Ingo Bürk– Ingo Bürk2014年10月29日 19:33:24 +00:00Commented Oct 29, 2014 at 19:33
-
1\$\begingroup\$ @RodolfoDias Are you sure? Obviously,
++i<n+1
should be equivalent to++i<=n
. Note the=
in there, however! It just saves one byte. It works for me. \$\endgroup\$Ingo Bürk– Ingo Bürk2014年10月29日 21:01:47 +00:00Commented Oct 29, 2014 at 21:01
APL,5
⎕UCS⍳
Example usage:
⎕UCS⍳256
-
1\$\begingroup\$ You don't have to make a dfn. Just ⎕UCS⍳ would work fine. So 5 chars \$\endgroup\$Moris Zucca– Moris Zucca2014年10月28日 13:34:27 +00:00Commented Oct 28, 2014 at 13:34
-
1\$\begingroup\$ You don't have to support code points over 127. Just ↑⎕AV would work fine. So 4 chars \$\endgroup\$Adám– Adám2016年02月07日 21:43:50 +00:00Commented Feb 7, 2016 at 21:43
JavaScript, ES6 - (削除) 52 (削除ここまで) (削除) 58 (削除ここまで) (削除) 56 (削除ここまで) (削除) 53 (削除ここまで) (削除) 44 (削除ここまで) 42 bytes
n=>String.fromCharCode(...Array(n).keys())
Paste this into the Firefox console. Run as f(NUM)
.
(削除) Had to make it longer because the first didn't properly accept input. (削除ここまで)
Down 3, thanks edc65! Down to 44 thanks to Swivel!
-
1\$\begingroup\$ This doesn't really handle neither parameter nor input. \$\endgroup\$manatwork– manatwork2014年10月28日 14:14:25 +00:00Commented Oct 28, 2014 at 14:14
-
\$\begingroup\$ Just change the 70 to a different number; that's the input. \$\endgroup\$Scimonster– Scimonster2014年10月28日 14:17:13 +00:00Commented Oct 28, 2014 at 14:17
-
\$\begingroup\$ Okay, i updated it to take input, at the cost of 6 bytes. \$\endgroup\$Scimonster– Scimonster2014年10月28日 14:25:50 +00:00Commented Oct 28, 2014 at 14:25
-
3\$\begingroup\$ -2: f=n=>[...Array(n)].map((v,i)=>String.fromCharCode(i)) \$\endgroup\$edc65– edc652014年10月28日 18:13:12 +00:00Commented Oct 28, 2014 at 18:13
-
2\$\begingroup\$ 44 Characters!
f=n=>String.fromCharCode(...Array(n).keys())
\$\endgroup\$Swivel– Swivel2016年07月21日 20:57:12 +00:00Commented Jul 21, 2016 at 20:57
Haskell, (削除) 17 (削除ここまで) 23 bytes
flip take['0円'..]
Not sure if it is possible to do any better without imports.
Edit
My first solution didn't actually print the result, so allow 6 more chars for that:
print.flip take['0円'..]
Also, not shorter (25 chars with printing, 19 without), but an interesting alternate approach (it requires 'Data.List', though):
print.((inits['0円'..])!!)
-
\$\begingroup\$ This doesn't actually print the result. \$\endgroup\$user344– user3442014年10月29日 15:22:15 +00:00Commented Oct 29, 2014 at 15:22
-
\$\begingroup\$ @nyuszika7h now it does \$\endgroup\$John Dvorak– John Dvorak2014年10月29日 16:00:20 +00:00Commented Oct 29, 2014 at 16:00
-
\$\begingroup\$
(`take`['0円'..])
saves a byte. \$\endgroup\$Laikoni– Laikoni2017年08月16日 07:13:33 +00:00Commented Aug 16, 2017 at 7:13
Perl, 17 bytes
say chr for 0..$_
-
1\$\begingroup\$ Too many parenthesis.
print chr for 0..$ARGV[0]
\$\endgroup\$manatwork– manatwork2014年10月29日 15:29:43 +00:00Commented Oct 29, 2014 at 15:29 -
\$\begingroup\$ You're right! It has been a while since I used perl \$\endgroup\$Demnogonis– Demnogonis2014年10月29日 15:46:20 +00:00Commented Oct 29, 2014 at 15:46
-
1\$\begingroup\$ You can use
shift
instead of$ARGV[0]
to save 2 bytes. \$\endgroup\$user344– user3442014年10月29日 16:32:14 +00:00Commented Oct 29, 2014 at 16:32 -
\$\begingroup\$ If you are allowed to print the characters on different lines, you can use
say
. Also, the character count is shorter if you do it as a one-liner with-n
.echo "90" | perl -nE'say chr for 0..$_'
would count as18
characters.17
forsay chr for 0..$_
plus1
for then
. \$\endgroup\$hmatt1– hmatt12014年10月29日 17:26:43 +00:00Commented Oct 29, 2014 at 17:26 -
\$\begingroup\$ You're right. But
say
won't work with every version of perl. \$\endgroup\$Demnogonis– Demnogonis2014年10月30日 08:32:55 +00:00Commented Oct 30, 2014 at 8:32
awk - 27
{while(i<0ドル)printf"%c",i++}
To give the parameter on stdin run it like:
awk '{while(i<0ドル)printf"%c",i++}' <<<96
Just for fun: The "think positive version" starting with a definitive yes
:
yes|head -96|awk '{printf"%c",NR-1}'
NR-1
is needed to print (char)0
for NR==1
. :-(
And why don't we have a no
command? That's kinda mean!
-
1\$\begingroup\$
alias no='yes no'
\$\endgroup\$user344– user3442014年10月29日 15:25:13 +00:00Commented Oct 29, 2014 at 15:25 -
\$\begingroup\$ ...but then I'd have to count the chars of that alias definition too... :-( \$\endgroup\$user19214– user192142014年10月29日 15:49:21 +00:00Commented Oct 29, 2014 at 15:49
-
\$\begingroup\$ This made my day. @nyuszika7h. My gosh XD thanks for this \$\endgroup\$Jane– Jane2021年02月16日 22:01:59 +00:00Commented Feb 16, 2021 at 22:01
Bash+BSD common utilities, 9 bytes
jot -c 1ドル
GNU dc, 20 bytes
?sc_1[1+dPdlc>m]dsmx
C, (削除) 31 (削除ここまで) (削除) 30 (削除ここまで) (削除) 28 (削除ここまで) 27
k;f(n){putch(k++)<n&&f(n);}
Since putch is nonstandard, here's the fully compliant version:
k;f(n){putchar(k++)<n&&f(n);}
Must be called from main:
main(){f(255);}
EDIT: Improved by taking advantage of putchar return value
EDIT 2: Reduced by another character through recursion
-
1\$\begingroup\$ putch is a non-standard function. Also, may I ask why this answer was downvoted? \$\endgroup\$Stuntddude– Stuntddude2015年06月12日 00:37:44 +00:00Commented Jun 12, 2015 at 0:37
-
\$\begingroup\$ @Stuntddude I'll add an alternatve version that uses putchar, and no idea why this is downvoted. After all, it is one of the shorter ones. \$\endgroup\$takra– takra2015年06月12日 00:39:45 +00:00Commented Jun 12, 2015 at 0:39
CJam, 3
,:c
I assumed the argument to be the top stack element.
Example usage:
256,:c
ri,:c
Ruby, 30 characters
puts (0..$*[0].to_i).map &:chr
J - 5 bytes
{.&a.
{.
is Head, a.
is Alphabet ( a list of all chars) and &
Bonds them, generating a monadic verb called like:
{.&a. 100 NB. first 100 characters
Note: It seems this does not work interactively: Jconsole and jQt seems to set up a translation, outputting box characters instead of some control characters. In a script or from the commandline, it does work though:
ijconsole <<< '127 {. a.' | hd
-
\$\begingroup\$ Notice that the alphabet is not exactly ASCII. \$\endgroup\$FUZxxl– FUZxxl2015年06月30日 13:10:26 +00:00Commented Jun 30, 2015 at 13:10
-
\$\begingroup\$ Up to
{.&a. 127
, it is no? \$\endgroup\$jpjacobs– jpjacobs2015年07月01日 06:44:36 +00:00Commented Jul 1, 2015 at 6:44 -
\$\begingroup\$ No because J has box drawing characters instead of some of the control characters. \$\endgroup\$FUZxxl– FUZxxl2015年07月01日 06:46:14 +00:00Commented Jul 1, 2015 at 6:46
-
\$\begingroup\$ Actually, writing this to a file and inspecting it with a hex viewer tells me that J outputs the correct values (0x00 0x01, ...) . it's only the J interpreter/ IDE interpretting those values as boxdrawing characters instead of control characters. It does exactly the same as all other languages using
char
or equivalents do. \$\endgroup\$jpjacobs– jpjacobs2015年07月01日 07:07:07 +00:00Commented Jul 1, 2015 at 7:07 -
\$\begingroup\$ That's weird because I tested it on my UNIX box and it did indeed output Unicode characters for some of the code-points. \$\endgroup\$FUZxxl– FUZxxl2015年07月01日 07:16:44 +00:00Commented Jul 1, 2015 at 7:16
gs2, 2 bytes
V.
This should be competing, I think! It would’ve worked even in the early days of gs2. Try it here.
-
1\$\begingroup\$ Successfully tested with this version, which predates the challenge by a month. \$\endgroup\$Dennis– Dennis2016年02月05日 18:02:46 +00:00Commented Feb 5, 2016 at 18:02
Brainfuck, 44 bytes
, [ <[>++++++++++<-] -[>-<-----] >+++>, ] <[>.+<-]
Expects a decimal string without a trailing newline.
Reading integers in the range [0, max_cell_size]
in brainfuck is not difficult. I encourage you to invent a clean method on your own. I consider this a beginner level exercise. (The reverse operation of printing a cell's numeric value is more involved, and could be considered an intermediate level task.)
Here's a 58-byte version that can handle 256
on 8-bit implementations:
, [ <[<+>>++++++++++<-] -[>-<-----] >+++>, ] <[>] -<<[>.]>[>+.<-]
-
\$\begingroup\$ Why haven't I thought of this??? This is ingenious!!! \$\endgroup\$FinW– FinW2017年02月25日 19:03:00 +00:00Commented Feb 25, 2017 at 19:03
-
\$\begingroup\$ Can I borrow this to use on future answers? \$\endgroup\$FinW– FinW2017年02月25日 19:11:39 +00:00Commented Feb 25, 2017 at 19:11
-
1\$\begingroup\$ @FinW I'm guessing you don't know about this meta post. \$\endgroup\$Mitch Schwartz– Mitch Schwartz2017年02月26日 02:37:04 +00:00Commented Feb 26, 2017 at 2:37
√ å ı \ ® Ï Ø ¿ , 3 bytes
Note: Language post-dates challenge
IrW
Explanation
I › Take input from command line, evaluate and push to stack
r › Push the range from 0 to top value + 1
W › Output the whole stack as Unicode characters
Alternate Solution
As pointed out by @FlipTack in his Java answer, it is not clear if the OP wants us to print up to and including the input or excluding the input.
If the second is true, the solution below is the correct answer.
IrPW
Explanation
I › Take input from command line, evaluate and push to stack
r › Push the range from 0 to top value + 1
P › Pop the top value from the stack
W › Output the whole stack as Unicode characters
-
\$\begingroup\$ Link to language? \$\endgroup\$user– user2021年08月06日 19:18:05 +00:00Commented Aug 6, 2021 at 19:18
-
\$\begingroup\$ @user Added: github.com/cairdcoinheringaahing/UnprintableName \$\endgroup\$2021年08月06日 19:21:36 +00:00Commented Aug 6, 2021 at 19:21
Golfscript - 5
Thanks to @Dennis
~,''+
-
1\$\begingroup\$
~,""+
is shorter and correctly processes input from STDIN. \$\endgroup\$Dennis– Dennis2014年10月28日 14:04:10 +00:00Commented Oct 28, 2014 at 14:04 -
\$\begingroup\$ @Dennis That doesn't produce any output for me... \$\endgroup\$Beta Decay– Beta Decay2014年10月28日 14:15:46 +00:00Commented Oct 28, 2014 at 14:15
-
1\$\begingroup\$ Are you using the online interpeter? To correctly simulate input from STDIN, you have to use, e.g.,
;"65"
, since the input from STDIN will always be a string. \$\endgroup\$Dennis– Dennis2014年10月28日 14:17:25 +00:00Commented Oct 28, 2014 at 14:17
Lua - (削除) 43 (削除ここまで) 41 Bytes
for i=1,arg[1]do print(string.char(i))end
-
\$\begingroup\$ You can shorten this by a byte
a=""for i=1,arg[1]do print(a.char(i))end
\$\endgroup\$Veer Singh– Veer Singh2015年10月31日 15:21:54 +00:00Commented Oct 31, 2015 at 15:21 -
\$\begingroup\$ You can shorten this by 2 bytes
for i=1,arg[1]do print(("").char(i))end
\$\endgroup\$manatwork– manatwork2016年07月22日 09:25:26 +00:00Commented Jul 22, 2016 at 9:25
Befunge 98, 22
&:00pv>0gk,@
0::-1<^j`
Kind of sad that this is so long.
&:00p ; gets numerical input, stores a copy at cell (0,0) ;
v ; IP goes down ;
< ; IP goes left, so I execute 1-::0`j^ ;
::-1 ; (1-::) subtract one from our number and duplicate it twice ;
0 ` ; (0`) compare the number with 0, push 1 if greater else 0 ;
<^j ; if the result was 0, go up, otherwise continue going left ;
>0gk, ; get the value at cell (0,0), print that many numbers from stack ;
@ ; terminate program ;
Python 3.4 - 36 bytes / 43 bytes
print(*map(chr,range(int(input()))))
print(*map(chr,range(int(input()))),sep='')
255 input()
How this works is:
- Get upper limit of range
- Generate a range of the table.
- Map the range to chr function ( takes int, returns ascii ).
- Consume the map via splat argument expansion ( number -> character -> print! )
The second one just removes the space separating each character in exchange for 7 bytes.
-
\$\begingroup\$ You could very much make this into a lambda, as the question states this, and in Python 2,
map
returns a list, so you could just dof=lambda i:map(chr,range(i))
\$\endgroup\$Justin– Justin2014年10月29日 06:14:20 +00:00Commented Oct 29, 2014 at 6:14 -
\$\begingroup\$ That's true, and my initial solution was similar but I didn't want to use a lambda so that I could immediately print output. I wish map kept the trend of returning a list instead of an iterator, even if it is more pythonic that way. \$\endgroup\$Full Metal– Full Metal2014年10月29日 06:27:09 +00:00Commented Oct 29, 2014 at 6:27
Pascal 87
program _;var c:char;n:byte;begin n:=0;readln(n);for c:=chr(0)to chr(n)do write(c);end.
Pascal 73
program _;var c,n:byte;begin readln(n);for c:=0to n do write(chr(c));end.
Builds and runs fine from http://www.onlinecompiler.net/pascal
-
1\$\begingroup\$ FreePascal (and if I remember correctly, Turbo Pascal too) only needs 60 of those characters:
var c,n:byte;begin read(n);for c:=0to n do write(chr(c))end.
pastebin.com/aFLVTuvh \$\endgroup\$manatwork– manatwork2014年10月29日 16:00:52 +00:00Commented Oct 29, 2014 at 16:00 -
\$\begingroup\$ Quite possibly, I've only used Delphi. But someone edited that out of the title. \$\endgroup\$Mark K Cowan– Mark K Cowan2018年06月04日 15:26:39 +00:00Commented Jun 4, 2018 at 15:26
x86 ASM (Linux) (many many bytes unless you compile it)
Written as a function, assumes parameter is passed in AX (I forget the number for the read syscall) Also doesn't preserve [SP] or BX.
test ax,ax
jz @Done
mov [sp],ax
@Loop:
mov ax,4
mov bx,1
mov cx,sp
mov dx,1
int 0x80
sub [sp],1 ; Can I do this? Or do I need to load/sub/store separately?
jnz @Loop
@Done:
ret
-
2\$\begingroup\$ (I should have put a F00F exploit in there, it's not like anyone will run it anyway) \$\endgroup\$Mark K Cowan– Mark K Cowan2014年10月29日 13:09:11 +00:00Commented Oct 29, 2014 at 13:09
-
7\$\begingroup\$ I was going to run this. I'm not going to run this now. \$\endgroup\$Aearnus– Aearnus2014年10月30日 02:43:11 +00:00Commented Oct 30, 2014 at 2:43
Perl - 29
sub f{print map{chr}0..shift}
Ruby, 23
f=->n{puts *?0円..n.chr}
Explanation
- Input is taken as the argument to a lambda. It expects an Integer.
- The "destructuring operator" (
*
) invokes#to_ary
on the Range to print every character on its own line.
Julia: 20 characters (REPL)
This is close to the question's example: just generates the characters and let the REPL to do whatever it wants with them.
f(n)=map(char,[0:n])
Julia: 33 characters
Prints each character in a separate line.
print(map(char,[0:int(ARGS[1])]))
M (MUMPS) - 21
R n F i=1:1:n W $C(i)
In expanded form: READ n FOR i=1:1:n WRITE $CHAR(i)
T-SQL: (削除) 68 (削除ここまで) 63
As a print loop
DECLARE @i INT=64,@ INT=0A:PRINT CHAR(@)SET @+=1IF @<=@i GOTO A
T-SQL: (削除) 95 (削除ここまで) 86
As a query
DECLARE @ INT=64SELECT TOP(@+1)CHAR(ROW_NUMBER()OVER(ORDER BY 0/0)-1)FROM sys.messages
Edit: Made changes and fixes pointed out by Muqo. Thanks. Fixes and golfing suggested by @t-clausen.dk
-
\$\begingroup\$ For the loop, you can save 5 or so characters converting the WHILE to a
GOTO
with label. For the query, maybe specifymsdb.sys.objects
to guarantee enough objects. Also, it doesn't output CHAR(0). However, as consolation you canORDER BY @
. \$\endgroup\$Muqo– Muqo2014年10月29日 02:41:23 +00:00Commented Oct 29, 2014 at 2:41 -
\$\begingroup\$ Second answer is invalid. You can rewrite it this way and golf 9 characters: DECLARE @ INT=64SELECT TOP(@+1)CHAR(ROW_NUMBER()OVER(ORDER BY 0/0)-1)FROM sys.messages \$\endgroup\$t-clausen.dk– t-clausen.dk2016年07月11日 14:26:36 +00:00Commented Jul 11, 2016 at 14:26
-
\$\begingroup\$ @t-clausen.dk not sure how I let that one through. Thanks for that. \$\endgroup\$MickyT– MickyT2016年07月11日 18:37:05 +00:00Commented Jul 11, 2016 at 18:37
BrainFuck - (削除) 140 (削除ここまで) 112 Bytes
,>,>,>-[>+<-----]>---[<+>-]<[<<<->->->-]<[>+<-]<[>>++++++++++<<-]<[>>>>++++++++++[<++++++++++>-]<<<<-]>>>[>.+<-]
Saved 28 bytes by changing [<<<->>>->+<]>[<<<->>>->+<]>[<<<->>>-]
to [<<<->->->-]
.
What it does
,>,>,> Takes three inputs
in three separate cells
-[>+<-----]>---[<+>-]<[<<<->->->-]< Takes 48 off of each to
convert them to decimal
[>+<-]<[>>++++++++++<<-]<[>>>>++++++++++[<++++++++++>-]<<<<-]>>> Combines them into a
three digit number by
multiplying the first
by 100, the second by
10 and then adding all
three
[>.+<-] Repeatedly prints the
value of the adjacent
cell and then adds one
to it until it reaches
the input value.
for x in range(input()):print chr(x)
Would actually print the characters, if you want to edit your example. \$\endgroup\$[i for i in range(n)]
is quite similar torange(n)
\$\endgroup\$