Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active November 21, 2015 22:12
Show Gist options
  • Save henrik/f7a58f2bc02cd4b20099 to your computer and use it in GitHub Desktop.
Save henrik/f7a58f2bc02cd4b20099 to your computer and use it in GitHub Desktop.
# Char count: 124
[n,s]=String.split IO.gets(""),",";IO.write Regex.replace~r/\S/,s,fn<<c>>->q=c-rem String.to_integer(n),26;q<?a&&26+q||q;end
# If we combine "my" Regex.replace with Greg Vaughn's smarter maths, we get to 121 together:
[n,s]=String.split IO.gets(""),",";IO.write Regex.replace~r/\S/,s,fn<<c>>->?a+rem c-71-rem(String.to_integer(n),26),26end
# Just for fun: Using Stream.cycle as suggested by Martin Svalin:
[n,s]=String.split IO.gets(""),",";IO.write Regex.replace~r/\S/,s,fn<<c>>->Enum.at Stream.cycle(?z..?a),?z-c+String.to_integer(n)end
# Just for fun: Using Code.eval_string to convert to int and char list at the same time… (The "do" block contents are borrowed from Greg Vaughn)
{s,n: n}=Code.eval_string String.replace(IO.gets(""),~r/(.+),(.*)\n/,"n=\\1;'\\2'");IO.puts for c<-s,do: c<97&&c||97+rem c-71-rem(n,26),26
# Just for fun: if we limit to single digits we can do:
<<n,?,,s::bits>>=IO.gets"";IO.write Regex.replace~r/\S/,s,fn<<c>>->97+rem c-71-n+?0,26end
# or even
<<n,?,,s::bits>>=IO.gets"";IO.write Regex.replace~r/\S/,s,fn<<c>>->97+rem c-n-23,26end
# If you don't need to "wrap" (so you can do d->a but not a->x).
# `import String; … split … to_integer` is the exact same char count as not importing.
import String;[n,s]=split IO.gets(""),",";IO.write Regex.replace~r/\S/,s,fn<<c>>->c-to_integer(n)end
  • ?a is the ASCII code (97) of "a".
  • The magic number 26 is the count of letters a..z.
  • The magic number 71 is ?a - 26.
  • Handles any-size positive numbers (i.e. also values over 26). If we don't have to, another ~7 chars can be shaved off.
  • Does not handle negative numbers.
  • If extra newlines are acceptable, save one char with write -> puts.
  • If outputting is not required (and an extra newline is OK), remove IO.write :p
  • In the single-digits one, n is the ASCII code for the digit, so we need to subtract the ASCII code for 0.
  • If there had been a String.replace that accepted a function, an import String would have meant some savings.

See Greg's solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment