26
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 1. Does it have to be a function? 2. According to your reference code, n would be the first character that is not printed. \$\endgroup\$ – Dennis Oct 28 '14 at 12:49
  • 2
    \$\begingroup\$ Actually the reference code prints nothing. It just returns a list of the characters and lets the REPL do whatever it wants with the result. \$\endgroup\$ – manatwork Oct 28 '14 at 12:50
  • 1
    \$\begingroup\$ Can somebody please explain the downvote? I am sorry if my english isn't that good. If there's something unclear within the question please tell me. \$\endgroup\$ – oopbase Oct 28 '14 at 12:57
  • 1
    \$\begingroup\$ for x in range(input()):print chr(x) Would actually print the characters, if you want to edit your example. \$\endgroup\$ – FryAmTheEggman Oct 28 '14 at 12:59
  • 2
    \$\begingroup\$ nota [i for i in range(n)] is quite similar to range(n) \$\endgroup\$ – njzk2 Oct 28 '14 at 19:22

88 Answers 88

19
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Do you have to specify some input? The online runner just outputs the code itself. \$\endgroup\$ – manatwork Oct 28 '14 at 12:52
  • 11
    \$\begingroup\$ @manatwork: Just a sec. You have to hurry when you post these... ;) \$\endgroup\$ – Dennis Oct 28 '14 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 Oct 28 '14 at 18:03
  • 1
    \$\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 Oct 28 '14 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 Oct 29 '14 at 15:28
6
\$\begingroup\$

APL,5

⎕UCS⍳

Example usage:

⎕UCS⍳256
\$\endgroup\$
  • 1
    \$\begingroup\$ You don't have to make a dfn. Just ⎕UCS⍳ would work fine. So 5 chars \$\endgroup\$ – Moris Zucca Oct 28 '14 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 Feb 7 '16 at 21:43
3
\$\begingroup\$

CJam, 3

,:c

I assumed the argument to be the top stack element.

Example usage:

256,:c

ri,:c
\$\endgroup\$
12
\$\begingroup\$

Pyth, 4 bytes

VQCN

Basically a translation of the Python 3 program:

for N in range(eval(input())):print(chr(N))
\$\endgroup\$
2
\$\begingroup\$

Golfscript - 5

Thanks to @Dennis

~,''+
\$\endgroup\$
  • 1
    \$\begingroup\$ ~,""+ is shorter and correctly processes input from STDIN. \$\endgroup\$ – Dennis Oct 28 '14 at 14:04
  • \$\begingroup\$ @Dennis That doesn't produce any output for me... \$\endgroup\$ – Beta Decay Oct 28 '14 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 Oct 28 '14 at 14:17
  • 1
    \$\begingroup\$ @Dennis Oh thanks that works now! \$\endgroup\$ – Beta Decay Oct 28 '14 at 14:25
1
\$\begingroup\$

Ruby - 35 33 bytes

Please note that I can't Ruby at all:

$*[0].to_i.times{|i|puts i.chr()}
\$\endgroup\$
  • 1
    \$\begingroup\$ As far as I know there is an alias for "puts" that is simply "p". So -3 bytes if that's correct? \$\endgroup\$ – oopbase Oct 28 '14 at 13:28
  • 2
    \$\begingroup\$ @Forlan07, not really an alias. p is equivalent to puts whatever.inspect. \$\endgroup\$ – manatwork Oct 28 '14 at 13:36
  • \$\begingroup\$ @manatwork OK, nice to know :-) \$\endgroup\$ – oopbase Oct 28 '14 at 13:39
  • \$\begingroup\$ This prints every character on a separate line. Shouldn't it be print? \$\endgroup\$ – nyuszika7h Oct 29 '14 at 13:48
  • \$\begingroup\$ Fixed and 3 bytes shorter: puts (0..$*[0]).map(&:chr)*'' \$\endgroup\$ – nyuszika7h Oct 29 '14 at 13:51
1
\$\begingroup\$

Lua - 43 41 Bytes

for i=1,arg[1]do print(string.char(i))end
\$\endgroup\$
  • \$\begingroup\$ You can shorten this by a byte a=""for i=1,arg[1]do print(a.char(i))end \$\endgroup\$ – Digital Veer Oct 31 '15 at 15:21
  • \$\begingroup\$ You can shorten this by 2 bytes for i=1,arg[1]do print(("").char(i))end \$\endgroup\$ – manatwork Jul 22 '16 at 9:25
1
\$\begingroup\$

PowerShell - 20

%{0..$_|%{[char]$_}}

Usage:
56 | %{0..$_|%{[char]$_}}
\$\endgroup\$
  • \$\begingroup\$ A bit debatable to call a piece of syntax that isn't even valid a program or function ;-) (you cannot use ForEach-Object standalone like that). The function part of that is the script block, but it won't ever work as a function, because the context ($_) is provided by ForEach-Object. You can shorten it a bit by casting the range to an array, by the way. \$\endgroup\$ – Joey Oct 30 '14 at 7:32
3
\$\begingroup\$

Ruby, 30 characters

puts (0..$*[0].to_i).map &:chr
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Notice that the alphabet is not exactly ASCII. \$\endgroup\$ – FUZxxl Jun 30 '15 at 13:10
  • \$\begingroup\$ Up to {.&a. 127, it is no? \$\endgroup\$ – jpjacobs Jul 1 '15 at 6:44
  • \$\begingroup\$ No because J has box drawing characters instead of some of the control characters. \$\endgroup\$ – FUZxxl Jul 1 '15 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 Jul 1 '15 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 Jul 1 '15 at 7:16
6
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ This doesn't really handle neither parameter nor input. \$\endgroup\$ – manatwork Oct 28 '14 at 14:14
  • \$\begingroup\$ Just change the 70 to a different number; that's the input. \$\endgroup\$ – Scimonster Oct 28 '14 at 14:17
  • \$\begingroup\$ Okay, i updated it to take input, at the cost of 6 bytes. \$\endgroup\$ – Scimonster Oct 28 '14 at 14:25
  • 3
    \$\begingroup\$ -2: f=n=>[...Array(n)].map((v,i)=>String.fromCharCode(i)) \$\endgroup\$ – edc65 Oct 28 '14 at 18:13
  • 2
    \$\begingroup\$ 44 Characters! f=n=>String.fromCharCode(...Array(n).keys()) \$\endgroup\$ – Swivel Jul 21 '16 at 20:57
3
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ alias no='yes no' \$\endgroup\$ – nyuszika7h Oct 29 '14 at 15:25
  • \$\begingroup\$ ...but then I'd have to count the chars of that alias definition too... :-( \$\endgroup\$ – yeti Oct 29 '14 at 15:49
11
\$\begingroup\$

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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        }

        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>

\$\endgroup\$
  • \$\begingroup\$ I hope you don't mind that I used an inline interpreter from here :) \$\endgroup\$ – Ingo Bürk Oct 29 '14 at 19:36
  • \$\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 Oct 29 '14 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 Oct 29 '14 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 Oct 30 '14 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 Oct 30 '14 at 8:58
25
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Nice! Definitely +1 for the effort :-) \$\endgroup\$ – oopbase Oct 28 '14 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 Oct 28 '14 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 Oct 29 '14 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 Oct 29 '14 at 13:09
  • 1
    \$\begingroup\$ Also, your second answer is valid. \$\endgroup\$ – Esolanging Fruit Feb 13 '17 at 0:18
8
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ You can save some chars by declaring the int while opening the scanner: int i,n=new Scanner(... and changing the loop to for(;++i<n;). Also, you don't need to invoke Character.toString. You can just feed System.out a char value and it will happily output it. \$\endgroup\$ – Shujal Oct 28 '14 at 16:03
  • 1
    \$\begingroup\$ The challenge allows the use of your a as input. And I think you can shorten the for 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 Oct 29 '14 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 Oct 29 '14 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 Oct 29 '14 at 21:01
  • 1
    \$\begingroup\$ So we come down to void f(int n){int i=0;for(;++i<=n;System.out.print((char)i));} which is 62 bytes. At least I don't see more to golf now. :) \$\endgroup\$ – Ingo Bürk Oct 30 '14 at 6:53
1
\$\begingroup\$

Java, 125 bytes

class M{public static void main(String[]a){p(256);}static void p(int l){int i=-1;for(;i++<l;){System.out.println((char)i);}}}

Simply puts in the number of characters to print from the ascii table @ p(n) where n is the number of characters.

\$\endgroup\$
2
\$\begingroup\$

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                                               ;
\$\endgroup\$
1
\$\begingroup\$

Befunge-98, 26 20

0&;1-::0`j;;,$>:#,_@

It's longer than the other Befunge-98 answer, but it's not self-modifying and only uses one line. (Also, the pointer only moves to the right until it gets to the print loop.)

This is shorter now. Also, it's still not self-modifying. Hooray, jumping trickery!

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ For the loop, you can save 5 or so characters converting the WHILE to a GOTO with label. For the query, maybe specify msdb.sys.objects to guarantee enough objects. Also, it doesn't output CHAR(0). However, as consolation you can ORDER BY @. \$\endgroup\$ – Muqo Oct 29 '14 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 Jul 11 '16 at 14:26
  • \$\begingroup\$ @t-clausen.dk not sure how I let that one through. Thanks for that. \$\endgroup\$ – MickyT Jul 11 '16 at 18:37
1
\$\begingroup\$

Rebol - 35 34

for n 0 do input 1[prin to-char n]
\$\endgroup\$
6
\$\begingroup\$

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'..])!!)
\$\endgroup\$
  • \$\begingroup\$ This doesn't actually print the result. \$\endgroup\$ – nyuszika7h Oct 29 '14 at 15:22
  • \$\begingroup\$ @nyuszika7h now it does \$\endgroup\$ – John Dvorak Oct 29 '14 at 16:00
  • \$\begingroup\$ (`take`['\0'..]) saves a byte. \$\endgroup\$ – Laikoni Aug 16 '17 at 7:13
1
\$\begingroup\$

If I'm allowed to have another answer in a different language, here goes...

Pascal: 91 bytes

PROGRAM A;VAR i,n:Integer;BEGIN
n:=0;readln(n);FOR i:=0 TO n DO
Write(chr(i));readln;END.

(just for kicks, really, I haven't messed in Pascal in ages)

\$\endgroup\$
  • 7
    \$\begingroup\$ Posting multiple answers is perfectly fine. \$\endgroup\$ – Dennis Oct 28 '14 at 20:55
  • \$\begingroup\$ @Dennis is well aware of this. Just check all the questions he's answered \$\endgroup\$ – caird coinheringaahing Mar 15 '17 at 22:00
1
\$\begingroup\$

Python 3 — 51 bytes

lambda n:sys.stdout.buffer.write(bytes(range(n+1)))

This is a variation of a line I keep in my shell history for when I need to refer to the ASCII table.

It first calls range(), passing n + 1 as the sole argument. When used like this, range() returns an iterable of integers between 0 (inclusive) and the argument (exclusive—hence the need for the +1). The iterable is then passed to bytes(), which returns a bytestring, interpreting each integer as one byte. The bytestring is then written directly to the buffer for stdout (passing it to sys.stdout.write() or print() would result in an exception; those accept strings, not bytestrings).

Note that n must not be greater than 255. If it is, bytes() will raise an exception, because values greater than 255 do not fit in a single byte.

Also note that this doesn't bind the function to a name. I'm assuming that's acceptable, given that it does still create the function.

\$\endgroup\$
  • \$\begingroup\$ 1. There's no need for all of that: lambda n:print(str(bytes(range(n+1)))) is just 38 characters. 2. If you go with your current method, you need to include import sys. \$\endgroup\$ – Beta Decay Oct 29 '14 at 15:18
  • \$\begingroup\$ Actually, just lambda n:print(bytes(range(n+1))) works perfectly well. \$\endgroup\$ – Beta Decay Oct 29 '14 at 15:20
1
\$\begingroup\$

PHP - 47 bytes

<?=join(array_map('chr',range(0,$argv[1])));

Usage:

php ascii.php n
\$\endgroup\$
  • \$\begingroup\$ join does the same as implode and is 3 bytes shorter. \$\endgroup\$ – Titus Dec 14 '16 at 13:20
  • \$\begingroup\$ @Titus good catch, updated! \$\endgroup\$ – zamnuts Dec 15 '16 at 7:21
2
\$\begingroup\$

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.
\$\endgroup\$
4
\$\begingroup\$

Bash+BSD common utilities, 9 bytes

jot -c $1

GNU dc, 20 bytes

?sc_1[1+dPdlc>m]dsmx
\$\endgroup\$
2
\$\begingroup\$

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:

  1. Get upper limit of range
  2. Generate a range of the table.
  3. Map the range to chr function ( takes int, returns ascii ).
  4. 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.

\$\endgroup\$
  • \$\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 do f=lambda i:map(chr,range(i)) \$\endgroup\$ – Justin Oct 29 '14 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 Oct 29 '14 at 6:27
0
\$\begingroup\$

Haskell - 16 22 characters

(`take`['\0'..])

Edit

Now printing the result

print.(`take`['\0'..])
\$\endgroup\$
  • \$\begingroup\$ nice trick to get rid of a character \$\endgroup\$ – John Dvorak Oct 29 '14 at 9:32
  • \$\begingroup\$ This doesn't actually print the result. \$\endgroup\$ – nyuszika7h Oct 29 '14 at 15:20
  • \$\begingroup\$ @JanDvorak he pretty much removed the space, as (``) does the same thing as flip here, in just as many characters... \$\endgroup\$ – archaephyrryx Oct 29 '14 at 15:57
2
\$\begingroup\$

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

\$\endgroup\$
  • 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 Oct 29 '14 at 16:00
  • \$\begingroup\$ Quite possibly, I've only used Delphi. But someone edited that out of the title. \$\endgroup\$ – Mark K Cowan Jun 4 '18 at 15:26
2
\$\begingroup\$

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
\$\endgroup\$
  • 2
    \$\begingroup\$ (I should have put a F00F exploit in there, it's not like anyone will run it anyway) \$\endgroup\$ – Mark K Cowan Oct 29 '14 at 13:09
  • 7
    \$\begingroup\$ I was going to run this. I'm not going to run this now. \$\endgroup\$ – Aearnus Oct 30 '14 at 2:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.