Move History

Rooted by: rot13 in Elixir
Fork Selected
  • Encoding
    Algorithms
    Logic
    Description

    Nice profile picture. Regex, modulo alternative solution.

    Code
    defmodule Rot13 do
      def encode(str) do
        Regex.replace(
          ~r/[A-Z]/i,
          str,
          fn x ->
            # from https://elixirforum.com/t/get-ascii-value-of-a-character/16619/3
            <<x::utf8>> = x
            if x < 97 do
              rem(x, 26) + 65
            else
              rem(x - 6, 26) + 97
            end
          end
        )
      end
    end
    Test Cases
    # TODO: Replace examples and use TDD by writing your own tests
    
    defmodule TestSolution do
      use ExUnit.Case
      import Rot13, only: [encode: 1]
    
      test "some test description" do
        assert encode("NOWHERE abjurer") == "ABJURER nowhere"
        assert encode("  stuff ") == "  fghss "
        assert encode("123 mirë u pafshim абв") == "123 zveë h cnsfuvz абв"
        assert encode("rknzcyrf") == "examples"
        assert encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") == "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
      end
    end
    
  • Code
    • defmodule Rot13 do
    • def rotate({k, v}) do
    • cond do
    • v in ?A..?M ->
    • k + 13
    • v in ?N..?Z ->
    • k - 13
    • true ->
    • k
    • end
    • end
    • def encode(str) do
    • List.zip([
    • str
    • |> String.to_charlist(),
    • str
    • |> String.upcase()
    • |> String.to_charlist()
    • ])
    • |> Enum.map(&rotate/1)
    • |> List.to_string()
    • Regex.replace(
    • ~r/[A-Z]/i,
    • str,
    • fn x ->
    • # from https://elixirforum.com/t/get-ascii-value-of-a-character/16619/3
    • <<x::utf8>> = x
    • if x < 97 do
    • rem(x, 26) + 65
    • else
    • rem(x - 6, 26) + 97
    • end
    • end
    • )
    • end
    • end
    Test Cases
    • # TODO: Replace examples and use TDD by writing your own tests
    • defmodule TestSolution do
    • use ExUnit.Case
    • import Rot13, only: [encode: 1]
    • test "some test description" do
    • assert encode("NOWHERE abjurer") == "ABJURER nowhere"
    • assert encode(" stuff ") == " fghss "
    • assert encode("123 mirë u pafshim абв") == "123 zveë h cnsfuvz абв"
    • assert encode("rknzcyrf") == "examples"
    • assert encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") == "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
    • end
    • end