Codility:CountDistinctSlices。我错过了什么?

问题描述 投票:0回答:1

Codility问题在这里:https://codility.com/programmers/lessons/15-caterpillar_method/count_distinct_slices/

现在,我的解决方案如下:

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解决方案。输入:6,[1,3,4,1,2,1,3,2,1]

它得到以下切片:

[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]

除此之外,数组的每个元素也是一个切片。

答案显然是错误的。

输入的答案应该是24.我的是22.我不明白我错过了什么。

ruby algorithm
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]组成的切片。

钓鱼课程是:如果有问题的案例足够小,你可以用琐碎的蛮力来解决它,那么这样做并将其发现与你更聪明的尝试结果进行比较。

© www.soinside.com 2019 - 2024. All rights reserved.