2017-12-16 9 views
0

Codility質問はここにある:今https://codility.com/programmers/lessons/15-caterpillar_method/count_distinct_slices/コーディング:CountDistinctSlices。私は何が欠けていますか?

、私の解決策は以下の通りです:

def solution(m, a) 

    end_idx = 0 
    hash_of_elements = {} 
    last_idx = a.size - 1 
    slice_right_now = [] 

    slice_counter = 0 

    while last_idx >= end_idx 

    el_to_add = a[end_idx] 

    while !hash_of_elements[el_to_add].nil? 
     element_to_remove = slice_right_now.shift 
     hash_of_elements.delete element_to_remove 
     #puts "removing #{element_to_remove} from the slice. the new slice is #{slice_right_now}. Hash is #{hash_of_elements.inspect}" 
     puts "#{slice_right_now.inspect}" if slice_right_now.size > 1 
     if slice_right_now.size > 1 
     slice_counter += 1 
     return 1000000000 if slice_counter > 1000000000 
     end 
    end 

    #puts "Adding #{el_to_add} to the list!" 
    hash_of_elements[el_to_add] = true 
    slice_right_now << el_to_add 
    puts "#{slice_right_now.inspect}" if slice_right_now.size > 1 
    if slice_right_now.size > 1 
     slice_counter += 1 
     return 1000000000 if slice_counter > 1000000000 
    end 
    end_idx += 1 

    end 

    puts "Number of slices other than indivisual elments are #{slice_counter}" 

    slice_counter += a.size 

end 

それはRubyのソリューションです。入力の場合:これに加えて

[1, 3] 
[1, 3, 4] 
[3, 4] 
[3, 4, 1] 
[3, 4, 1, 2] 
[4, 1, 2] 
[1, 2] 
[2, 1] 
[2, 1, 3] 
[1, 3] 
[1, 3, 2] 
[3, 2] 
[3, 2, 1] 

、の各要素:6、[1、3、4、1、2、1、3、2、1]

これは、次のスライスを取得します配列もスライスです。

答えは間違っていますが明らかです。

私の入力は24です。鉱山は22です。紛失したものは分かりません。

+0

後でこの問題を遭遇する可能性のある人は、アレイのサイズが1の場合は1スライスになります。サイズが2の場合は2 + 1スライスが可能です。 3の場合は3 + 2 + 1となります。したがって、スライスを列挙する必要はありません。配列の長さが変わると、スライスを数えるだけです。 –

答えて

1

24あなたは簡単にすべて以上のスライスを行くブルートフォースソリューションをチェックして、明確なものを数えることができるよう、正しいです:

(1..a.size).sum { |k| a.each_cons(k).count { |s| !s.uniq! } } 
=> 24 

(1..a.size).sum { |k| a.each_cons(k).reject(&:uniq!).count } 
=> 24 

(0...a.size).sum { |i| (i...a.size).count { |j| !a[i..j].uniq! } } 
=> 24 

(0...a.size).to_a.repeated_combination(2).count { |i, j| !a[i..j].uniq! } 
=> 24 

(0..a.size).to_a.combination(2).count { |i, j| !a[i...j].uniq! } 
=> 24 

あなたがいないだけでcountが、印刷を行う場合はそれらを、 [4, 1]と最後に[2, 1]で構成されるスライスが欠けていることがわかります。

釣りのレッスンは:問題のある場合は、あなたがそれを簡単なブルートフォースで解決できるほど小さい場合は、それを行い、あなたのより巧妙な試みの結果とその結果を比較してください。

+0

ありがとう!それは多くの意味があります。 –

関連する問題