Skip to content

Instantly share code, notes, and snippets.

@syntacticsugar
Created December 29, 2013 01:52
Show Gist options
  • Save syntacticsugar/8166585 to your computer and use it in GitHub Desktop.
Save syntacticsugar/8166585 to your computer and use it in GitHub Desktop.
project euler #36, first pass.
class String
def palindrome?
self == self.reverse
end
end
class Integer
def palindrome?(b=10)
self.to_s(b).palindrome?
end
end
(1...1000000).select { |x| x.palindrome? }.select { |x| x.palindrome?(2) }.inject(:+)
@syntacticsugar
Copy link
Author

with self constructed Ruby method to convert to binary:

class Integer
  @@digit_table = { 1   => "1",
                    2   => "2",
                    3   => "3",
                    4   => "4",
                    5   => "5",
                    6   => "6",
                    7   => "7",
                    8   => "8",
                    9   => "9",
                    0   => "0",
                    10  => "A", # for hexadecimal stuff
                    11  => "B",
                    12  => "C",
                    13  => "D",
                    14  => "E",
                    15  => "F", }

  def basify base
    # base case
    if self/base < 1
      @@digit_table[self]
    else
      r = self.modulo(base)
      m = (self-r) / base
      m.basify(base) + @@digit_table[r]
    end
  end
end

@bil-bas
Copy link

bil-bas commented Dec 29, 2013

class Integer
  def to_b
     a, r = self.divmod 2
     if a > 0 
       a.to_b << r.to_s 
     else
       r.to_s
     end
  end

  def to_x(base)
    a, r = self.divmod base
    if a > 0 
      a.to_b << r.to_s 
    else
      r.to_s
    end
  end
end

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