12
\$\begingroup\$

Challenge

You have one string of input bytes, output the last byte in it.

Rules

Your submission may be a program or function outputting the last byte in the input which

  • is either a string, stdin or command-line arguments, and
  • is non-empty.

I was trying to solve this with brainfuck, however all languages are allowed to participate. This is .

Examples

"?" -> "?"
"29845812674" -> "4"

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](https://esolangs.org/wiki/Fish), 121 bytes

/* Configuration */

var QUESTION_ID = 181627; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();
    
    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
  • 4
    \$\begingroup\$ Welcome, I changed your question to fit our format more properly (note this is what the sandbox is for, usually). However in its current state the challenge is very easy (also in bf), so not sure about that. \$\endgroup\$ – ბიმო Mar 17 '19 at 19:11
  • 10
    \$\begingroup\$ I vote against closing; it may be trivial, but that doesn't make it offtopic \$\endgroup\$ – MilkyWay90 Mar 17 '19 at 22:30
  • 1
    \$\begingroup\$ @MillyWay I think most of the close votes were before the extensive edit by ბიმო \$\endgroup\$ – Sanchises Mar 18 '19 at 6:47
  • 9
    \$\begingroup\$ @ბიმო We have a consensus not to edit off-topic questions to make them on-topic which I think would have applied here. \$\endgroup\$ – Laikoni Mar 18 '19 at 7:19
  • 2
    \$\begingroup\$ What kind of string? Is it guaranteed to be ASCII only? Or should we handle UTF-8 (and how?) for example? \$\endgroup\$ – FireCubez Mar 18 '19 at 18:28

71 Answers 71

1
\$\begingroup\$

Caboose, 1514 bytes

Caboose hates me, because it does. There isn't any convenient string-indexing instruction in Caboose!

var a=input();print(a.endsWith(' ')and' 'or a.endsWith('!')and'!'or a.endsWith('"')and'"'or a.endsWith('#')and'#'or a.endsWith('$')and'$'or a.endsWith('%')and'%'or a.endsWith('&')and'&'or a.endsWith("'")and"'"or a.endsWith('(')and'('or a.endsWith(')')and')'or a.endsWith('*')and'*'or a.endsWith('+')and'+'or a.endsWith(',')and','or a.endsWith('-')and'-'or a.endsWith('.')and'.'or a.endsWith('/')and'/'or a.endsWith('0')and'0'or a.endsWith('1')and'1'or a.endsWith('2')and'2'or a.endsWith('3')and'3'or a.endsWith('4')and'4'or a.endsWith('5')and'5'or a.endsWith('6')and'6'or a.endsWith('7')and'7'or a.endsWith('8')and'8'or a.endsWith('9')and'9'or a.endsWith(':')and':'or a.endsWith(';')and';'or a.endsWith('<')and'<'or a.endsWith('=')and'='or a.endsWith('>')and'>'or a.endsWith('?')and'?'or a.endsWith('@')and'@'or a.endsWith('A')and'A'or a.endsWith('B')and'B'or a.endsWith('C')and'C'or a.endsWith('D')and'D'or a.endsWith('E')and'E'or a.endsWith('F')and'F'or a.endsWith('G')and'G'or a.endsWith('H')and'H'or a.endsWith('I')and'I'or a.endsWith('J')and'J'or a.endsWith('K')and'K'or a.endsWith('L')and'L'or a.endsWith('M')and'M'or a.endsWith('N')and'N'or a.endsWith('O')and'O'or a.endsWith('P')and'P'or a.endsWith('Q')and'Q'or a.endsWith('R')and'R'or a.endsWith('S')and'S'or a.endsWith('T')and'T'or a.endsWith('U')and'U'or a.endsWith('V')and'V'or a.endsWith('W')and'W'or a.endsWith('X')and'X'or a.endsWith('Y')and'Y'or a.endsWith('Z')and'Z'or a.endsWith('[')and'['or a.endsWith('\\')and'\\'or a.endsWith(']')and']'or'~');

If I add more constants, then Caboose will say that there are too many constants in the chunk. Fortunately it passes all test cases given. Basically it (tries to) check the last character against all characters in printable ASCII.

TIO

\$\endgroup\$
0
\$\begingroup\$

Python 3, 16 bytes

This is a pretty basic answer, but I think that it is the lowest Python 3 can go...

x=lambda a:a[-1]

TIO

\$\endgroup\$
  • 1
    \$\begingroup\$ you don't need the x= here \$\endgroup\$ – ASCII-only Mar 31 '19 at 10:57
0
\$\begingroup\$

Pepe, 13 bytes

REEeREEEeReEe

Try it online! Disable "Separated by" check box below the input text box.

Explanation:

REEe  # Input as string (stack R)
REEEe # Goto last char (stack R)
ReEe  # Output char (stack R)
\$\endgroup\$
0
\$\begingroup\$

Triangular, 10 bytes

(#~p../)?<

Try it online!

Pretty straight-forward; reads characters until it gets a null read, then prints the top of the stack.

Ungolfed:

   ( 
  # ~ 
 p . . 
/ ) ? <
--------------------------------------------
(            Set a point to jump back to
 ~.<         Read a character, change directions ("." is a no-op)
    ?)/      If ToS <= 0, skip next instruction and change directions; otherwise, jump back to "("
       p#    Pop the top value from the stack (the null input), then pop again and print that value
\$\endgroup\$
0
\$\begingroup\$

Commodore 8-bit BASIC (CBM/PET, VIC-20, C64/TheC64Mini, C128, C16/+4) - byte count later

 0inputa$:iflen(a$)thenprintright$(a$,1)

Simplified (without the sanity check):

 0inputa$:?right$(a$,1)

There is a small limitation in that Commodore 8-bit BASIC the maximum length of a string is 255 characters, so any entry above that will cause an error.

\$\endgroup\$
0
\$\begingroup\$

T-SQL, 23 bytes

SELECT RIGHT(v,1)FROM i

Didn't see a SQL solution yet.

Input is via a pre-existing table \$i\$ with varchar field \$v\$, per our IO rules.

\$\endgroup\$
0
\$\begingroup\$

Zsh, 11 bytes

try it online!!

<<<${1: -1}

clone of the bash answer, 2 bytes shorter

\$\endgroup\$
0
\$\begingroup\$

Perl 5, 7 bytes

$_=chop

This must be executed using the -pe flags.

Example

$ echo -n "abcd" | perl -pe '$_=chop'
d

Explanation

The -p flag wraps code inside a block that appears as: while (<>) { ... ; print } whereas the '...' would include the code provided. The entire script would expand to:

while (<>) { $_ = chop ; print }

What I did here was set the context variable $_ to the return value of chop, which returns the last character of a string. Shortly after, print with no statements on its own will display the previously assigned context variable.

\$\endgroup\$
0
\$\begingroup\$

Brain-Flak-cr, (6 bytes code + 3 bytes command line) = 9 bytes

({}<>)

Try it online!

Code:

The command line argument "-cr" means "use ASCII input and output" and "reverse the stack", so when you pop a value, the last byte of the input is popped, and when you push a value, it is pushed to the end.

 {}     pop a character
(    )  and push it
   <>   on the other stack
        implicitly output the current stack
\$\endgroup\$
0
\$\begingroup\$

GolfScript, 3 bytes

The GolfScript = yields a decimal. That's pretty weird ... However, (luckily enough,) GolfScript supports slicing over a string, which allows me to slice the last item of the string.

-1>

Try it online!

Explanation

-1  # The last item
  > # Choose everything in the string
    # after the last item, including the last item
    # this (obviously) yields the last item
\$\endgroup\$
0
\$\begingroup\$

Pushy, 1 byte

'

Try it online!

Print the top of stack as a character!

\$\endgroup\$

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.