代码之家  ›  专栏  ›  技术社区  ›  Nifriz

如何从文件中读取二维数组中元素的出现次数?

  •  2
  • Nifriz  · 技术社区  · 7 年前

    我从一个我以前存储过的文件中加载二维数组,类似这样:

    [[1, 1, 1, 1, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, 2, 2, 1, 1, 1], [1, 4, 4, 5, 1, 2, 2, 1, 1, 1], [1, 4, 4, 5, 1, 2, 2, 1, 1, 1], [1, 4, 4, 1, 2, 2, 1, 1, 1, 1], [1, 4, 4, 1, 0, 0, 1, 1, 1, 1]]
    

    我做了一个叫做“地图”的课程:

    require 'json'
    class Maps 
    
      def initialize(filename)
        @map = JSON.parse(File.read(filename))
      end
    
      def isCorrupted?
        @map.count(0) > 1 ? true : false
      end
    
    end
    

    当我尝试使用我的类方法时被破坏了?结果总是假的。

    require_relative 'classes/maps'
    
    current_map = Maps.new("test.txt")
    puts current_map.isCorrupted?
    

    0 错误的 .

    我还尝试修改该方法以获取计数出现次数,如下所示:

    @map.count(0)
    

    但结果总是 0 .

    2 回复  |  直到 7 年前
        1
  •  0
  •   potashin    7 年前

    0 数组集合中的元素(不是整数)。

    如果您需要知道所有子阵列中是否总共有两个以上的零:

    @map.flatten.count(0) > 1
    

    如果您想知道是否存在包含一个或多个零的子阵列,则应使用另一种方法:

    @map.any? { |collection| collection.count(0) > 1 }
    
        2
  •  3
  •   Tom Lord    7 年前

    flatten

    优化 ,如果要求只是检查 0 存在于嵌套数组中。但这不是你在这里要做的,你想检查一下吗 不止一个 出现在任何数组中。

    例如,您希望将以下内容视为非腐败,但poashin的答案将其视为腐败:

    [[0, 1], [1, 0]]
    

    require 'json'
    
    class Maps 
      def initialize(filename)
        @map = JSON.parse(File.read(filename))
      end
    
      def is_corrupted?
        @map.any? { |row| row.count(0) > 1 }
      end
    end
    

    (小结:我遵循了 ruby style guide conventions here snake_case 方法名,而不是 camelCase .)