Если этот код не является шуткой, как же он работает?

Вы можете использовать массив со смещениями для массива для подсчета.

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

var array = [[0, 0, 0, 0, 0, 0], [5, 5, 5, 0, 0, 0], [10, 10, 10, 0, 0, 0], [0, 0, 0, 0, 0, 0], [5, 5, 5, 0, 0, 0], [10, 10, 10, 0, 0, 0]],
    hourglass = [[-1, -1], [-1, 0], [-1, 1], [0, 0], [1, -1], [1, 0], [1, 1]],
    totals = array.map(a => a.map(_ => 0)), // get an array with all zero values
    i, j, k;

for (i = 1; i < array.length - 1; i++) {
    for (j = 1; j < array[i].length - 1; j++) {
       totals[i][j] = 0;
       for (k = 0; k < hourglass.length; k++) {
           totals[i][j] += array[i + hourglass[k][0]][j + hourglass[k][1]];
       }
    }
}

totals.forEach(a => console.log(...a));

6
задан Community 23 May 2017 в 12:26
поделиться

4 ответа

Править: Человек, который отправил исходный запутываемый пример, дал фактический исходный код в своем ответе. Он также отправил исправленную версию запутываемого кода, потому что, поскольку я отметил, часть его не имела смысла, даже когда Вы удалили броский синтаксис.

Это - некоторый приятно запутываемый код. Как с наиболее запутываемым кодом, это - главным образом много тернарных операторов и упрямого отказа вставить пробел, где нормальный человек был бы. Вот в основном то же самое, записанное больше обычно:

class Tree
  def initialize(*d)
    @d,  = d # the comma is for multiple return values,
             # but since there's nothing after it,
             # all but the first are discarded.
  end
  def to_s
    @l || @r ? ",>" : @d
  end
  def total
    total = @d.is_a?(Numeric) ? @d : 0
    total += @l.total if @l
    total += @r.total if @r
  end
  def insert(arg)
    if @d
      if @l
        @l.insert(arg)
      else
        @l = Tree.new(arg)
      end
    else
      @d = arg
    end
  end
end

Метод вставки не синтаксически действителен (он пропускает имя метода в одной части), но это по существу, что он делает насколько я могу сказать. Путаница в том методе является довольно толстой:

  1. Вместо просто выполнения @l = whatever, это использует instance_variable_get() и instance_variable_set(). Еще хуже, это искажает instance_variable_get() просто быть g().

  2. Это переносит большую часть функциональности в функцию лямбды, которой это передает название @l. Затем это вызывает эту функцию с менее известным синтаксисом func[arg1, arg2], который эквивалентен func.call(arg1, arg2).

15
ответ дан 8 December 2019 в 02:27
поделиться

Это, кажется, реализация двоичного дерева в очень немногих строках. Я приношу извинения, если мое понимание рубинового синтаксиса ограничено:

class Tree                    // defining the class Tree

    def initialize *d;        // defines the initializer
        @d = d;               // sets the node value
    end

    def to_s;                 // defines the to_s(tring) function
        @l || @r ? ",>" : @d; // conditional operator. Can't tell exactly what this 
                              // function is intending. Would think it should make a
                              // recursive call or two if it's trying to do to_string
    end

    def total;                // defines the total (summation of all nodes) function
        @d.is_a ? (Numeric)   // conditional operator.  Returns
            ? @d              // @d if the data is numeric
            : 0               // or zero
        + (@l ? @l.total : 0) // plus the total for the left branch
        + (@r ? @r.total : 0) // plus the total for the right branch
    end

    def insert d              // defines an insert function
        ??                    // but I'm not going to try to parse it...yuck
    end

Надежда, которая помогает некоторым...:/

9
ответ дан 8 December 2019 в 02:27
поделиться

Это началось как это:

class Tree
  include Comparable

  attr_reader :data

  # Create a new node with one initial data element
  def initialize(data=nil)
    @data = data
  end

  # Spaceship operator. Comparable uses this to generate
  #   <, <=, ==, =>, >, and between?
  def <=>(other)
    @data.to_s <=> other.data.to_s
  end

  # Insert an object into the subtree including and under this Node.
  # First choose whether to insert into the left or right subtree,
  # then either create a new node or insert into the existing node at
  # the head of that subtree.
  def insert(data)
    if !@data
      @data = data
    else
      node = (data.to_s < @data.to_s) ? :@left : :@right
      create_or_insert_node(node, data)
    end
  end

  # Sum all the numerical values in this tree. If this data object is a
  # descendant of Numeric, add @data to the sum, then descend into both subtrees.
  def total
    sum = 0
    sum += @data if (@data.is_a? Numeric)
    sum += [@left, @right].map{|e| e.total rescue 0}.inject(0){|a,v|a+v}
    sum
  end

  # Convert this subtree to a String.
  # Format is: <tt>\<data,left_subtree,right_subtree></tt>.
  # Non-existant Nodes are printed as <tt>\<></tt>.
  def to_s
    subtree = lambda do |tree|
      tree.to_s.empty? ? "<>" : tree
    end
    "<#{@data},#{subtree[@left]},#{subtree[@right]}>"
  end

  private ############################################################
  # Given a variable-as-symbol, insert data into the subtree incl. and under this node.
  def create_or_insert_node(nodename, data)
    if instance_variable_get(nodename).nil?
      instance_variable_set(nodename, Tree.new(data))
    else
      instance_variable_get(nodename).insert(data)
    end
  end

end

Я думаю, что на самом деле повредил его, когда я сокращал его вниз. Версия с девятью строками не вполне работает. Я весело провел время независимо.:P

Это было моей любимой частью:

def initialize*d;@d,=d;end

Это acutally использует параллельное присвоение для сохранения пары символов. Вы могли развернуть эту строку до:

def initialize(*d)
  @d = d[0]
end
7
ответ дан 8 December 2019 в 02:27
поделиться

Я отправил исходный код. Извините, но я не потрудился проверять, что я даже сделал его правильно, и набор материала был разделен из-за меньше, чем знаков.

class Tree
  def initialize*d;@d,=d;end
  def to_s;@l||@r?"<#{@d},<#{@l}>,<#{@r}>>":@d;end
  def total;(@d.is_a?(Numeric)?@d:0)+(@l?@l.total: 0)+(@r?@r.total: 0);end
  def insert d
    alias g instance_variable_get
    p=lambda{|s,o|d.to_s.send(o,@d.to_s)&&
      (g(s).nil??instance_variable_set(s,Tree.new(d)):g(s).insert(d))}
    @d?p[:@l,:<]||p[:@r,:>]:@d=d
  end
end

Это - то, на что это должно быть похожим.

6
ответ дан 8 December 2019 в 02:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: