Skip to content

Instantly share code, notes, and snippets.

@raydive
Created January 3, 2015 17:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raydive/be48edab1b249f27a6d7 to your computer and use it in GitHub Desktop.
Save raydive/be48edab1b249f27a6d7 to your computer and use it in GitHub Desktop.
# coding: utf-8
# タクシー数の4乗バージョン ruby
test = []
(1..300).each {|i| (1..300).each {|j| test << [i, j].sort }}
test.uniq!
by = test.group_by {|i,j| i**4 + j**4 }.select {|key, value| value.count > 1 }
p by # => {3262811042=>[[7, 239], [157, 227]], 635318657=>[[59, 158], [133, 134]], 8657437697=>[[193, 292], [256, 257]]}
@tdtds
Copy link

tdtds commented Jan 7, 2015

同じアルゴリズムでワンライナー:

(1..300).map{|i|(1..300).map{|j|[i,j]}}.flatten(1).map(&:sort).uniq.group_by{|i,j|i**4 + j**4}.select{|k,v|v.count>1}

@Echos
Copy link

Echos commented Jan 7, 2015

別アプローチ!
(1..300).to_a.product((1..300).to_a).map(&:sort).uniq.group_by{|i,j|i4+j4}.select{|k,v|v.count>1}

@Echos
Copy link

Echos commented Jan 7, 2015

短くしてみた。
(1..300).to_a.combination(2).group_by{|i,j|i4+j4}.select{|k,v|v.count>1}

@tdtds
Copy link

tdtds commented Jan 7, 2015

Array#combinationだったか(あったはずだと思ったがリファレンスを引くのがめんどかったw)

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