32
\$\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\$
14
  • \$\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
    Commented Oct 28, 2014 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
    Commented Oct 28, 2014 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
    Commented Oct 28, 2014 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\$ Commented Oct 28, 2014 at 12:59
  • 2
    \$\begingroup\$ nota [i for i in range(n)] is quite similar to range(n) \$\endgroup\$
    – njzk2
    Commented Oct 28, 2014 at 19:22

101 Answers 101

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\$
7
  • \$\begingroup\$ Nice! Definitely +1 for the effort :-) \$\endgroup\$
    – oopbase
    Commented 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
    Commented 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\$ Commented 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\$ Commented Oct 29, 2014 at 13:09
  • 2
    \$\begingroup\$ Also, your second answer is valid. \$\endgroup\$ Commented Feb 13, 2017 at 0:18
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\$
7
  • \$\begingroup\$ Do you have to specify some input? The online runner just outputs the code itself. \$\endgroup\$
    – manatwork
    Commented Oct 28, 2014 at 12:52
  • 14
    \$\begingroup\$ @manatwork: Just a sec. You have to hurry when you post these... ;) \$\endgroup\$
    – Dennis
    Commented 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
    Commented 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
    Commented 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
    Commented Oct 29, 2014 at 15:28
12
\$\begingroup\$

Pyth, 4 bytes

VQCN

Basically a translation of the Python 3 program:

for N in range(eval(input())):print(chr(N))
\$\endgroup\$
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\$
6
  • \$\begingroup\$ I hope you don't mind that I used an inline interpreter from here :) \$\endgroup\$
    – Ingo Bürk
    Commented Oct 29, 2014 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
    Commented 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
    Commented 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
    Commented 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
    Commented Oct 30, 2014 at 8:58
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\$
13
  • 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
    Commented Oct 28, 2014 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
    Commented 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
    Commented 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
    Commented Oct 29, 2014 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
    Commented Oct 30, 2014 at 6:53
7
\$\begingroup\$

APL,5

⎕UCS⍳

Example usage:

⎕UCS⍳256
\$\endgroup\$
2
  • 1
    \$\begingroup\$ You don't have to make a dfn. Just ⎕UCS⍳ would work fine. So 5 chars \$\endgroup\$ Commented 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
    Commented Feb 7, 2016 at 21:43
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\$
12
  • 1
    \$\begingroup\$ This doesn't really handle neither parameter nor input. \$\endgroup\$
    – manatwork
    Commented Oct 28, 2014 at 14:14
  • \$\begingroup\$ Just change the 70 to a different number; that's the input. \$\endgroup\$
    – Scimonster
    Commented Oct 28, 2014 at 14:17
  • \$\begingroup\$ Okay, i updated it to take input, at the cost of 6 bytes. \$\endgroup\$
    – Scimonster
    Commented Oct 28, 2014 at 14:25
  • 3
    \$\begingroup\$ -2: f=n=>[...Array(n)].map((v,i)=>String.fromCharCode(i)) \$\endgroup\$
    – edc65
    Commented Oct 28, 2014 at 18:13
  • 2
    \$\begingroup\$ 44 Characters! f=n=>String.fromCharCode(...Array(n).keys()) \$\endgroup\$
    – Swivel
    Commented Jul 21, 2016 at 20:57
5
\$\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\$
3
  • \$\begingroup\$ This doesn't actually print the result. \$\endgroup\$
    – user344
    Commented Oct 29, 2014 at 15:22
  • \$\begingroup\$ @nyuszika7h now it does \$\endgroup\$ Commented Oct 29, 2014 at 16:00
  • \$\begingroup\$ (`take`['\0'..]) saves a byte. \$\endgroup\$
    – Laikoni
    Commented Aug 16, 2017 at 7:13
5
\$\begingroup\$

Perl, 17 bytes

say chr for 0..$_
\$\endgroup\$
9
  • 1
    \$\begingroup\$ Too many parenthesis. print chr for 0..$ARGV[0] \$\endgroup\$
    – manatwork
    Commented Oct 29, 2014 at 15:29
  • \$\begingroup\$ You're right! It has been a while since I used perl \$\endgroup\$
    – Demnogonis
    Commented Oct 29, 2014 at 15:46
  • 1
    \$\begingroup\$ You can use shift instead of $ARGV[0] to save 2 bytes. \$\endgroup\$
    – user344
    Commented 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 as 18 characters. 17 for say chr for 0..$_ plus 1 for the n. \$\endgroup\$
    – hmatt1
    Commented Oct 29, 2014 at 17:26
  • \$\begingroup\$ You're right. But say won't work with every version of perl. \$\endgroup\$
    – Demnogonis
    Commented Oct 30, 2014 at 8:32
4
\$\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\$
3
  • 1
    \$\begingroup\$ alias no='yes no' \$\endgroup\$
    – user344
    Commented Oct 29, 2014 at 15:25
  • \$\begingroup\$ ...but then I'd have to count the chars of that alias definition too... :-( \$\endgroup\$
    – user19214
    Commented Oct 29, 2014 at 15:49
  • \$\begingroup\$ This made my day. @nyuszika7h. My gosh XD thanks for this \$\endgroup\$ Commented Feb 16, 2021 at 22:01
4
\$\begingroup\$

Bash+BSD common utilities, 9 bytes

jot -c $1

GNU dc, 20 bytes

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

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

\$\endgroup\$
2
  • 1
    \$\begingroup\$ putch is a non-standard function. Also, may I ask why this answer was downvoted? \$\endgroup\$
    – Stuntddude
    Commented 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
    Commented Jun 12, 2015 at 0:39
3
\$\begingroup\$

CJam, 3

,:c

I assumed the argument to be the top stack element.

Example usage:

256,:c

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

gs2, 2 bytes

V.

This should be competing, I think! It would’ve worked even in the early days of gs2. Try it here.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Successfully tested with this version, which predates the challenge by a month. \$\endgroup\$
    – Dennis
    Commented Feb 5, 2016 at 18:02
3
\$\begingroup\$

Brainfuck, 44 bytes

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

Expects a decimal string without a trailing newline.

Try it online.

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:

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

\$\endgroup\$
3
  • \$\begingroup\$ Why haven't I thought of this??? This is ingenious!!! \$\endgroup\$
    – FinW
    Commented Feb 25, 2017 at 19:03
  • \$\begingroup\$ Can I borrow this to use on future answers? \$\endgroup\$
    – FinW
    Commented Feb 25, 2017 at 19:11
  • 1
    \$\begingroup\$ @FinW I'm guessing you don't know about this meta post. \$\endgroup\$ Commented Feb 26, 2017 at 2:37
3
\$\begingroup\$

√ å ı ¥ ® Ï Ø ¿ , 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
\$\endgroup\$
2
2
\$\begingroup\$

Golfscript - 5

Thanks to @Dennis

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

Lua - 43 41 Bytes

for i=1,arg[1]do print(string.char(i))end
\$\endgroup\$
2
  • \$\begingroup\$ You can shorten this by a byte a=""for i=1,arg[1]do print(a.char(i))end \$\endgroup\$
    – Veer Singh
    Commented 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
    Commented Jul 22, 2016 at 9:25
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\$
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\$
2
  • \$\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
    Commented 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
    Commented Oct 29, 2014 at 6:27
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\$
2
  • 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
    Commented Oct 29, 2014 at 16:00
  • \$\begingroup\$ Quite possibly, I've only used Delphi. But someone edited that out of the title. \$\endgroup\$ Commented Jun 4, 2018 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
  • 2
    \$\begingroup\$ (I should have put a F00F exploit in there, it's not like anyone will run it anyway) \$\endgroup\$ Commented Oct 29, 2014 at 13:09
  • 7
    \$\begingroup\$ I was going to run this. I'm not going to run this now. \$\endgroup\$
    – Aearnus
    Commented Oct 30, 2014 at 2:43
2
\$\begingroup\$

Perl - 29

sub f{print map{chr}0..shift}
\$\endgroup\$
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\$
2
\$\begingroup\$

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])]))
\$\endgroup\$
2
\$\begingroup\$

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)

\$\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\$
3
  • \$\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
    Commented 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\$ Commented Jul 11, 2016 at 14:26
  • \$\begingroup\$ @t-clausen.dk not sure how I let that one through. Thanks for that. \$\endgroup\$
    – MickyT
    Commented Jul 11, 2016 at 18:37
2
\$\begingroup\$

BrainFuck - 140 112 Bytes

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

Try It Here!

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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