15
\$\begingroup\$

There exists a very simple cipher that replaces a letter with it's position in the alphabet. For example, abc would become 1 2 3 in this cipher.

This challenge is an alternative take on this cipher.


The Challenge

Create a program that takes an input of ASCII characters, and outputs a space-separated string of:

  • integers -26 through 26

  • letters a through j

The output should come through STDOUT or your language's closest alternative.


Specifications

  • Capital letters should be negated. A capital D for example would be -4, while a lowercase d would be 4.

  • Digits should be changed to their alpha counterparts. 1 being a, and so on. Any zeroes in the input will be j.

  • All non-alphanumeric characters (except spaces) should be ignored.

  • Spaces are 0.

  • Adjacent spaces in the output should be reduced to a single space.

    Input: You + Me
    Correct Output: -25 15 21 0 -13 5
    Incorrect Output: -25 15 21 0 0 0 -13 5
    
  • A single trailing space or newline is allowed.


Examples

Input: programming puzzles
Output: 16 18 15 7 18 1 13 13 9 14 7 0 16 21 26 26 12 5 19

Input: Code Golf
Output: -3 15 4 5 0 -7 15 12 6

Input: Programming Puzzles & Code Golf
Output: -16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 15 4 5 0 -7 15 12 6

Input: C0d3 G0lf
Output: -3 j 4 c 0 -7 j 12 6

Input: abc_ABC
Output: 1 2 3 -1 -2 -3

Scoreboard

For your score to appear on the board, it should be in this format:

# Language, Bytes

Strikethroughs shouldn't cause a problem.

function getURL(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:getURL(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58107,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;
body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 10px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table>

\$\endgroup\$
  • 1
    \$\begingroup\$ Related: codegolf.stackexchange.com/q/12253/4372 \$\endgroup\$ – daniero Sep 16 '15 at 20:26
  • \$\begingroup\$ Can the output have a trailing space? \$\endgroup\$ – Dennis Sep 16 '15 at 22:35
  • \$\begingroup\$ Yes. A single trailing space or newline is allowed. @Dennis \$\endgroup\$ – Zach Gates Sep 16 '15 at 22:37
  • \$\begingroup\$ Is a function returning/printing a string a valid answer? Also can you add a test case like "abc_ABC" to rule out all the [^\w] and [\W] regex? \$\endgroup\$ – Max Sep 17 '15 at 7:46
  • \$\begingroup\$ I wasn't entirely sure what you were asking, but I've added that test case. I hope that's what you were looking for; if not, let me know. @Max \$\endgroup\$ – Zach Gates Sep 17 '15 at 12:11

16 Answers 16

10
\$\begingroup\$

CJam, 58 57 54 51 50 49 bytes

Just when I wrote up the explanation, I noticed that one of the alternative 50 byte versions can be shortened by a byte...

q_el_eu&S-A,s--S%S*{i_32md\2*5-*48md@)A%'a+\?}%S*

Test it here.

50 byte solutions:

q_el_eu&S-A,s--S%S*{_A,s&\i_)A%'a+\32md\2*5-*?}%S*
q_el_eu&S-A,s--S%'`*{i32md:D;(_(2*(D*D3+A%'a+?}%S*
q_el_eu&S-A,s--S%'`*{i32md\(_@_@(2*(*\3+A%'a+?}%S*
q_el_eu&S-A,s--S%'`*{i32md\(_(2*(g@*_z3+A%'a+?}%S*

Explanation

q         e# Read input.
_el_eu&   e# Intersect a lower-case version with an upper-case version to remove
          e# all letters.
S-        e# Remove spaces from that string.
A,s-      e# Remove digit characters from that string. It now contains all the
          e# the characters from the input we should ignore.
-         e# Remove these characters from the input.
S%S*      e# Split on runs of spaces and join by spaces, collapsing multiple into one.
{         e# Map this block onto each character...
  i_      e#   Convert to character code and make a copy.
  32md    e#   Get divmod 32. Note that digits have character codes 32 + something,
          e#   the upper case letters have character codes 64 + n (where n is the 
          e#   absolute value we want), while lower case letters have codes 96 + n. 
          e#   So the div gives 2 or 3 to distinguish capitalisation (and 1 for digits) 
          e#   and the mod gives the correct absolute value for letters.
          e#   As it happens, the mod also gives 0 for spaces.
  \2*5-   e#   Pull up the div, duplicate, subtract 5. Turns 2 into -1 and 3 into 1. 
          e#   It also turns 1 (digits) into -3.
  *       e#   Multiply the mod by this sign.
          e#   We now have the correct result for everything but digits. Note that
          e#   the absolute value for digits is more than 26, and for everything
          e#   else it's less than 27.
  48md    e#   Get divmod 48. This gives div 0 and mod n for all correct results n.
          e#   For digits it gives div -1 and we don't care about the mod. We'll
          e#   use the div as a truthy/falsy value to select the right result.
  @)A%    e#   Pull up the other copy of the character code, increment 
          e#   (range 49..58), take modulo 10.
          e#   This gives 9 for 0 and n-1 for any other digit n.
  'a+     e#   Add to the character a.
  \?      e#   Select the correct result based on the div 48.
}%
S*        e# Join the resulting values by spaces.

This must be the first time, that CJam's modulo behaviour for negative values was useful for me.

\$\endgroup\$
6
\$\begingroup\$

JavaScript (ES6), 110 107 133 120 bytes

Take that, old me!

a=>[...a.replace(/[\W_]*?( ?)[\W_]*/g,'$1')].map(x=>(c=x.charCodeAt())<40?0:c<60?'jabcdefghi'[x]:c<91?64-c:c-96).join` `

There's potentially a lot more room for golfing, especially in the regexes nope, got that one down pretty well. Ungolfed version:

function f(a) {
  // Replaces each run of bad chars and spaces with
  // a space if it contained one, nothing otherwise:
  a = a.replace(/[\W_]*?( ?)[\W_]*/g, '$1');

  var b = a.split('');
  b = b.map(function(x) {
    var c = x.charCodeAt();
    if (c == 32)     // space
      return 0;
    else if (c < 60) // numbers
      return 'jabcdefghi'.charAt(x);
    else if (c < 91)
      return 64 - c; // uppercase
    else
      return c - 96; // lowercase
  });
  b = b.join(' ');
  return b;
}

Suggestions welcome!

\$\endgroup\$
  • \$\begingroup\$ Test '123___abc'. Hint: you need to handle underscores \$\endgroup\$ – edc65 Sep 17 '15 at 5:25
  • \$\begingroup\$ Another problem:All non-alphanumeric characters should be ignored.. Test: 'A$b' should be -1 2 \$\endgroup\$ – edc65 Sep 17 '15 at 5:50
  • \$\begingroup\$ @edc65 Aw, man, I thought I had it done... But thanks for letting me know! \$\endgroup\$ – ETHproductions Sep 17 '15 at 15:30
4
\$\begingroup\$

Pyth, 50 49 bytes

jdm?>d26C+70ddm-xZd26:-z-z=Zs[_rG1dGjk.<UT1)" +"d

Try it out here.

Edit: restructured string sanitisation to ensure underscores are handled correctly. It even saved a byte too, yay!

This program creates a lookup string, which is used to sanitise the input. This is then mapped to the corresponding index in that string. Finally, any index greater than 26 is converted to the correct ASCII character.

                                                     Implicit: z=input(), d=' ', ,
                                                       k='', G=[a-z]
                              _rG1                   Reversed, capitalised alphabet
                                  d                  Single space
                                   G                 Lower case alphabet
                                    jk.<UT1          '1234567890'
                            s[             )         Concatenate the 4 previous statements
                          =Z                         Store in Z
                        -z                           Setwise difference of input and above
                                                       (to get all illegal characters)
                      -z                             Setwise difference of input and illegal chars
                     :                      " +"d    Regex replace to lose multiple spaces
              m                                      Map the above over d:
                xZd                                    Get index of d in Z
               -   26                                  Subtract 26
  m                                                  Map the above over d:
   ?>d26                                               If d > 26
        C+70d                                            Convert (d+70) to ASCII
             d                                         Otherwise, select d
jd                                                   Join on spaces and print

Previous version, which made use of \W regex, at 50 bytes:

jdm?>d26C+70ddm-xs[_rG1\ Gjk.<UT1)d26::z"\W"d" +"d
\$\endgroup\$
3
\$\begingroup\$

Julia, 145 136 bytes

r=replace;print(join([47<x<58?x+58-10(x>48):x==32?0:cmp(x,96)*(lowercase(x)-96)for x=r(r(readline(),r"[^a-z0-9 ]"i,""),r" +"," ")]," "))

Ungolfed:

# Read a string from STDIN
input = readline()

# Remove non-alphanumeric characters and replace duplicated spaces
r = replace(replace(input, r"[^a-z0-9 ]"i, ""), r" +", " ")

# Construct an array using comprehension over the replaced input string
A = [47 < x < 58 ? x + 58 - 10(x > 48) : x == 32 ? 0 : cmp(x, 96) * (lowercase(x) - 96) for x = r]

# Join the array elements with spaces
j = join(A, " ")

# Print to STDOUT
print(j)

To get the digits as letters we add 58 to the ASCII value and subtract 10 if the current character isn't 0. That ensures that 0 maps to j and the other digits map to a-i.

Negating uppercase letters is done using cmp. This will return -1 for uppercase letters and 1 for lowercase.

Try it online

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

Perl 5, 120 116 113 105 Bytes

First cleans up the unwanted characters & extra spaces.
Then climbs down the ascii table for each character.

$_=pop;s/[^\w ]|_//g;s/ +/ /g;map{$n=ord;say$".($n>96?$n-96:$n>64?64-$n:$n>48?chr$n+48:$n>47?j:0)}split//

Test

$ perl -M5.01 numbers4letters.pl "zZaA _ 190"
 26 -26 1 -1 0 a i j
$ perl -M5.01 numbers4letters.pl "PrOgr4mm1n9 Puz2l3s & C0d3_G0lf!"
-16 18 -15 7 18 d 13 13 a 14 i 0 -16 21 26 b 12 c 19 0 -3 j 4 c -7 j 12 6
\$\endgroup\$
  • 2
    \$\begingroup\$ You can golf one character with a single space in regex in place of \s and the second regex can be golfed with s/ +/ /g, the first regex is wrong because \w matches the underscore character \$\endgroup\$ – Max Sep 17 '15 at 0:49
  • 2
    \$\begingroup\$ Another two characters out with s/[^\w ]|_//g \$\endgroup\$ – Max Sep 17 '15 at 8:32
  • \$\begingroup\$ Nice, even better than with the ignore case flag. \$\endgroup\$ – LukStorms Sep 17 '15 at 8:49
  • \$\begingroup\$ @Max nice hint. 2 bytes saved in my answer, thank you. \$\endgroup\$ – edc65 Sep 17 '15 at 21:42
2
\$\begingroup\$

C, 142 138 135

c,d;main(s){while(c=getchar()+1)d=c|32,c=d-98<26u?s=(d-97)*(c/32*2-5),0:c-48<11u?s='a'+c%10,4:c==33&&s?s=0,0:3,printf("%d \0%c "+c,s);}

Ungolfed a bit:

int c,d;
int main(int s)                     // s initially non-zero, meaning spaces are allowed
{
    while(c=getchar()+1)            // getchar until EOF (-1) encountered
    {
        d=c|32;                     // d becomes lowercase c (both incremented by 1)
        if (d-98<26u)               // check for letter
        {
            s=(d-97)*(c/32*2-5);    // print this number and allow subsequent spaces
            c=0;                    // format string will be "%d "
        }
        else if (c-48<11u)          // check for digit
        {
            s='a'+c%10;             // print this letter and allow subsequent spaces
            c=4;                    // format string will be "%c "
        }
        else if (c==33&&s)          // else if space and allowed to output spaces
        {
            s=0;                    // print 0 and disallow subsequent spaces
            c=0;                    // format string will be "%c "
        }
        else
        {
            c=3;                    // format string will be "", prints nothing
        }
        printf("%d \0%c "+c,s);     // final c is treated as index into string literal
    }
}

Passes the given tests in GCC 4.9.3 & Clang 3.5.2.

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

><> (fish), 219 209 bytes

>i:84*=?v:86*1-)?!^:f4*2-(?v:88*)?!v:a9*1+(?v:c8*)?!^:ca*3+  (?v~
>4*(?vov>~86*$:@=?v86*00.  >:86*=?v77*1-+00.>88*-::-$-00.01-*8c<
 >.! ! ! 00~v?( 0:\00. >.!00+6*aa~<>~    92*2!.<2*29<
^7:;?=0:<r0~<
*o73.>n>84

Try it out here

This is my first code golf answer! Finally been able to use the language I wanted to use for a code golf challenge, and this seemed like the perfect one given that characters are automatically converted to decimals.

I expected my result to be way shorter, but apparently not. Though, I haven't golfed this one too much. There are a few places the code could be cleaner/make more sense, but won't save any bytes since they're in places where whitespace is needed anyway. There might be a way to save some bytes on the last bit on the second line, making it go the opposite direction and mashing up with the 00 already there, I'll have to play with it more later

Basically, this checks to see whether the current char is a space, number, uppercase letter, or lowercase letter, by checking if it's in range of the highest/lowest values of that group. If it isn't any of those, it gets discarded. If it is in one of those, it gets converted to a number if it's a letter, and a letter if it's a number (or rather, a number from 97-106 which are the values for letters a-j). Then it checks if the top value is less than 28, in which case it's a number and outputs a number, otherwise it's a letter and outputs the letter that number represents, outputs a space, then loops until the stack is empty.

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

JavaScript (ES6), 108 122 124

Edit Using the regexp from @Max's comment
Edit2 14 bytes saved thanks ETHProductions

EcmaScript 6 just for the arrow functions, so it should work in Firefox and latest Chrome.

Test running the snippet below

F=
t=>t[R='replace'](/[^\w ]|_/g,'')[R](/ +|./g,c=>((v=parseInt(c,36))>9?c>'Z'?v-9:9-v:'jabcdefghi'[v]||0)+' ')

// Less golfed
U=t=>
  t.replace(/[^\w ]|_/g,'') // remove invalid characters
  .replace(/ +/g,' ') // collapse spaces
  .replace(/./g, c => ( // valid character replacing
    v = parseInt(c,36), // '0'..'9'-> 0..9, 'a'..'z' -> 10..25, ' ' -> NaN
    (
      v > 9 
      ? c > 'Z' ? v-9 : 9-v // manage upper vs lower
      : 'jabcdefghi'[v] || 0 // digits, NaN as an index gives undefined, substituted with 0
    ) + ' ' // separator space
  ))


// TEST
out=x=>O.textContent=x+'\n'+O.textContent;

function go() { out(I.value + ' --> ' + F(I.value) +'\n')}

// test cases, a trailing blank added to the expected output as ...
// "A single trailing space or newline is allowed."

;[
  ['A$b','-1 2 ']
, ['123___abc', 'a b c 1 2 3 ']
, ['You + Me','-25 15 21 0 -13 5 ']
, ['programming puzzles', '16 18 15 7 18 1 13 13 9 14 7 0 16 21 26 26 12 5 19 ']
, ['Code Golf', '-3 15 4 5 0 -7 15 12 6 ']
, ['Programming Puzzles & Code Golf', '-16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 15 4 5 0 -7 15 12 6 ']
, ['C0d3 G0lf', '-3 j 4 c 0 -7 j 12 6 ']
].forEach(t=>{ 
  k=t[1],r=F(t[0]), 
  out('Test '+(k==r?'OK':'Fail')+'\nInput:  '+t[0]+'\nResult: '+r+'\nCheck:  '+k+'\n')
})
Custom test: <input id=I><button onclick='go()'>-></button>
<pre id=O></pre>

\$\endgroup\$
  • \$\begingroup\$ I may be mistaken, but I think you can save a whole bunch by changing [R](/ +/g,' ')[R](/./g, to [R](/ +|./g,. (Sorry for bringing up an old post, btw) \$\endgroup\$ – ETHproductions Apr 25 '17 at 16:41
  • \$\begingroup\$ @ETHproductions seems good. Thanks \$\endgroup\$ – edc65 Apr 25 '17 at 18:40
1
\$\begingroup\$

Pyth, 57 bytes

:jdm@s[r_26Zr1 27Zc<GT1"")xs[_rG1G\ jkr1TZ)dz"0[0 ]+""0 "

Live demo and test cases.

\$\endgroup\$
1
\$\begingroup\$

CJam, 52 bytes

'{,97>:L_eu+A,s(++S+l{1$&},S%S*\26,:)_Wf*+LA<+0+erS*

Try it online

The key part with the solution is that it uses the CJam er (transliteration) operator. As arguments to the operator, it needs the list of all characters, and a list of the corresponding values.

As a pre-processing step on the input, it removes characters that are not part of the translation table (special characters), and reduces repeated spaces to a single space.

Explanation:

'{,97>  Build list of all lower case letters.
:L      Save it in variable L for later reuse.
_eu+    Add list of upper case letters.
A,s     Build digits "0123456789".
(+      Pop off first digit and append it at the end, to get "1234567890".
+       Add digits to list of characters.
S+      Add a space. List of characters that have values is now complete.
l       Get input.
{1$&},  Filter out all input characters that are not in list.
S%      Split input at spaces.
S*      And re-assemble it with spaces. This reduces multiple spaces to one space.
\       Swap input and character list.
26,     Start building list of values. Start with [0 ... 25].
:)      Use "smilie operator" to increment all values, to get [1 ... 26].
        These are the values for the lower case letters.
_Wf*    Copy the list and negate the values to get [-1 ... -26] for upper case.
+       Concatenate the two lists.
L       Retrieve the list of lower case letters we saved away earlier.
A<      Keep the first 10, which are the values for the digits.
+       Concatenate to list of values.
0+      Add 0 to list, as value for space.
er      Transliterate input string to corresponding values.
S*      Join with spaces for output.
\$\endgroup\$
1
\$\begingroup\$

Python 2, 191 179 177 173 172 168 160 bytes

import re
print" ".join([[[chr(x+48),"j"][x<49],[`[x-96,-x+64][x<96]`,"0"][x<65]][x>57or x<33]for x in map(ord,re.sub(" +"," ",re.sub("[^\w ]|_","",input())))])

Test

"programming puzzles"
16 18 15 7 18 1 13 13 9 14 7 0 16 21 26 26 12 5 19

"Code Golf"
-3 15 4 5 0 -7 15 12 6

"Programming Puzzles & Code Golf"
-16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 15 4 5 0 -7 15 12 6

"C0d3 G0lf"
-3 j 4 c 0 -7 j 12 6

"You + Me"
-25 15 21 0 -13 5
\$\endgroup\$
1
\$\begingroup\$

PHP, 116 bytes

while($c=ord(preg_replace(["#[^\w ]|_#","# +#"],["","@"],$argn))[$i++])echo$c<96?jabcdefghi[$c-48]?:64-$c:$c-96," ";

takes input from STDIN; run with -nR.

breakdown

while($c=ord(preg_replace(["#[^\w ]|_#","# +#"],["","@"],$argn) # sanitize input
    [$i++]))echo            # loop through string and print ...
    $c<96                       # if not lowercase:
        ?jabcdefghi[$c-48]          # digit -> letter
        ?:                          # if that turned out falsy (=empty):
        64-$c                       # uppercase (or former spaces) -> negative (or 0)
    :$c-96                      # else -> positive
," ";                           # append space

You can replace the @ with a backtick to handle spaces in the lowercase part.
With jabcdefghi0 for the digits, you could also use :.

\$\endgroup\$
  • \$\begingroup\$ I believe that you must change the order "#_|[^\w ]#" instead of "#[^\w ]|_#" . \$\endgroup\$ – Jörg Hülsermann Apr 25 '17 at 14:33
0
\$\begingroup\$

Hassium, 1156 Bytes

func main() {s = input();c="";for(x=0;x<s.length;x++){c=s[Convert.toNumber(Convert.toString(x))].toString();if (c.toLower()!=c)print(r(c.toLower())*-1);else if(r(c)=="")continue;else print(r(c));print(" ");}}func r(c) {if(c=="a")return 1;else if(c=="b")return 2;else if(c=="c")return 3;else if(c=="d")return 4;else if(c=="e")return 5;else if(c=="f")return 6;else if(c=="g")return 7;else if(c=="h")return 8;else if(c=="i")return 9;else if(c=="j")return 10;else if(c=="k")return 11;else if(c=="l")return 12;else if(c=="m")return 13;else if(c=="n")return 14;else if(c=="o")return 15;else if(c=="p")return 16;else if(c=="q")return 17;else if(c=="r")return 18;else if(c=="s")return 19;else if(c=="t")return 20;else if(c=="u")return 21;else if(c=="v")return 22;else if(c=="w")return 23;else if(c=="x")return 24;else if(c=="y")return 25;else if(c=="z")return 26;else if(c==" ")return 0;else if(c=="1")return "a";else if(c=="2")return "b";else if(c=="3")return "c";else if(c=="4")return "d";else if(c=="5")return "e";else if(c=="6")return "f";else if(c=="7")return "g";else if(c=="8")return "h";else if(c=="9")return "i";else if(c=="0")return "j";else return"";}

Very long answer

\$\endgroup\$
  • 1
    \$\begingroup\$ Collapsing spaces doesn't quite seem to work. You + Me produces the output -25 15 21 0 0 -13 5. \$\endgroup\$ – Dennis Sep 16 '15 at 22:36
  • 1
    \$\begingroup\$ Interesting language, sort of like C/Java/[another language I can't remember the name of]. Is there an easier way to convert each character into a number, i.e. a function to retrieve a char code? (Scroll down to the table and look at the Dec column.) \$\endgroup\$ – ETHproductions Sep 16 '15 at 22:39
0
\$\begingroup\$

Jelly, 32 bytes, language postdates challenge

⁶ØB;µ³fi@€
Øaḣ⁵ṙ9
26RµN;;0¢;ị@ÑK

Try it online!

Explanation

Helper function 1Ŀ (translates each alphanumeric/space in the input into a number)

⁶ØB;µ³fi@€
⁶           space
 ØB;        append all digits, uppercase and lowercase letters (in that order)
    µ       set as the new default for missing arguments
     ³      first command-line argument
      f     delete all characters not in {space + alphanumerics}
       i@€  take index of each element within {space + alphanumerics}

Helper function (returns the constant string “jabcdefghi”)

Øaḣ⁵ṙ9
Øa      lowercase alphabet
  ḣ⁵    take first 10 elements
    ṙ9  rotate 9 elements to the left

Main program

26RµN;;0¢;ị@ÑK
26R             Range from 1 to 26
   µ            set as default for missing arguments
    N           Minus {each element of the range from 1 to 26}
     ;          with {the range from 1 to 26} appended
      ;0        with a 0 appended
        ¢;      with the result of 2£ prepended
          ị@    index into this using
            Ñ   the result of 1Ŀ
             K  separate by spaces
\$\endgroup\$
0
\$\begingroup\$

Retina, 74 70 bytes (non-competing)

Note the leading space on line 3, the trailing space on line 6, and the empty second line.

[^\w ]|_

 +
~
.
$+ 
[A-Z]
-$+
T`L`l
[j-s]
a$+
[t-z]
b$+
T`~ld`dd0-6jl

Try it Online!

Although the language was made before the challenge, I think some of the language features I used postdate the challenge, so I have marked this as non-competing.

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

Java 7, 257 254 bytes

class M{public static void main(String[]a){String r="",x;for(int c:a[0].getBytes()){x=(c>96&c<123?c-96:c>64&c<91?"-"+(c-64):c>48&c<58?(char)(c+48):c==48?"j":c<33?0:"")+"";r+=!x.isEmpty()&&!(r.endsWith("0 ")&x.equals("0"))?x+" ":"";}System.out.print(r);}}

Try it here.

Explanation:

class M{                               // Class
  public static void main(String[]a){  //  Required main-method
    String r="",                       //   Result-String
      x;                               //   Temp String
    for(int c:a[0].getBytes()){        //   Loop over the characters of the input-String
      x=(                              //    Set the temp String to:
        c>96&c<123?                    //     If it's a lowercase letter:
          c-96                         //      Set `x` to the 1-indexed alphabetic index
        :c>64&c<91?                    //     Else-if it's a uppercase letter:
          "-"+(c-64)                   //      Set `x` to the 1-indexed alphabetic index as negative
        :c>48&c<58?                    //     Else-if it's a digit 1-9:
          (char)(c+48)                 //      Set `x` to the 1-indexed alphabetic character
        :c==48?                        //     Else if it's a zero:
          "j"                          //      Set `x` to "j"
        :c<33?                         //     Else if it's a space:
          0                            //      Set `x` to "0"
        :                              //     Else:
          ""                           //      Set `x` to an empty String
       )+"";                           //     Required `+""` because `(char)` and `0` aren't Strings
      r+=                              //    Append the result-String with:
        !x.isEmpty()                   //     If `x` has a value
        &&!(r.endsWith("0 ")&x.equals("0"))?
                                       //     and it's not "0" with the previous value also being a zero
          x+" "                        //      Append the value of `x`, plus a space
        :                              //     Else:
          "";                          //      Append nothing
    }                                  //   End of loop
    System.out.print(r);               //   Print the result to STDOUT
  }                                    //  End of main-method
}                                      // End of class

Example input & output:

Input:
Programming Puzzles & C0d3 G0lf

Output:
-16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 j 4 c 0 -7 j 12 6 
\$\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.