brewersfan1976

construct_square.rb

Oct 3rd, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.06 KB | None | 0 0
  1. def constructSquare(s)
  2.     letter_count = Array.new(26)
  3.     x = 0
  4.    
  5.     while (x < 26)
  6.           letter_count[x] = 0
  7.           x = x + 1
  8.     end
  9.    
  10.     x = 0
  11.    
  12.     while (x < s.length)
  13.           letter_count[s[x].ord - 'a'.ord] = letter_count[s[x].ord - 'a'.ord] + 1
  14.           x = x + 1
  15.     end
  16.    
  17.     letter_count = letter_count.sort
  18.     best = -1
  19.     min_number = 10 ** (s.length - 1)
  20.     x = Math.sqrt(min_number).to_i
  21.    
  22.     while (x <= 10 ** ((s.length + 1) / 2))
  23.           n = x * x
  24.           digit_count = Array.new(26)
  25.           z = 0
  26.            
  27.           while (z < 26)
  28.                 digit_count[z] = 0
  29.                 z = z + 1
  30.           end
  31.          
  32.           while (n > 0)
  33.                 digit_count[n % 10] = digit_count[n % 10] + 1
  34.                 n = n / 10              
  35.           end
  36.        
  37.           digit_count = digit_count.sort
  38.          
  39.           if letter_count == digit_count then
  40.              best = x * x
  41.           end
  42.              
  43.           x = x + 1
  44.     end
  45.        
  46.     return best
  47. end
Advertisement
Add Comment
Please, Sign In to add comment