我需要制作程序,但我无法完成它并陷入混乱的方法。 目的是找到所有元素的总和,并将其添加到最后。我刚开始教授课程和方法。
如何在最终数组中得出所有正元素的总和?
这是我的代码:
class Node
attr_accessor :value, :next_node
def initialize val,next_in_line
@value = val
@next_nodex = next_in_line
puts "Initialized a Node with value: " + value.to_s
end
end
class LinkedList
def initialize val
@head = Node.new(val,nil)
end
def add(value)
current = @head
while current.next_node != nil
current = current.next_node
end
current.next_node = Node.new(value,nil)
self
end
def delete(val)
current = @head
if current.value == val
@head = @head.next_node
else
current = @head
while (current != nil) && (current.next_node != nil) && ((current.next_node).value != val)
current = current.next_node
end
if (current != nil) && (current.next_node != nil)
current.next_node = (current.next_node).next_node
end
end
end
def display
current = @head
full_list = []
while current.next_node != nil
full_list += [current.value.to_s]
current = current.next_node
end
full_list += [current.value.to_s]
puts full_list.join(" ")
end
def sum
end
end
puts "\n"
list = [*-99..99].shuffle
ll = LinkedList.new(list[0])
(1..9).each do |i|
ll.add(list[i])
end
puts "\nDo you want item to add? '1' - yes '0' - no"
adding = gets.to_i
puts "\n"
if adding == 1
ll.add(list[10])
end
puts "\nDisplaying Linked List:"
ll.display
puts "\nDo you want to delete item? '1' - yes '0' - no"
deleting = gets.to_i
if deleting == 1
puts "Type in and delete item and then display the linked list:"
deleteInt = gets.to_i
ll.delete(deleteInt)
end
puts ll.display
puts "\nThe sum of all positive elements"
ll.sum
答案 0 :(得分:2)
首先,我认为Node.initialize
方法中的错误类型 - @next_nodex
应该是@next_node
。其次,最后不要使用puts
2次:puts ll.display
。要添加数组,最好使用<<
符号。
另一件事,我看不出display
和sum
方法之间的任何概念差异,除了一个条件。根据这个,它应该是:
def sum
current = @head
sum = 0
while current.next_node != nil
sum += current.value if current.value > 0
current = current.next_node
end
sum += current.value if current.value > 0
sum
end
或干燥:
def full_list
current = @head
full_list = []
while current.next_node != nil
full_list << current.value
current = current.next_node
end
full_list << current.value
full_list
end
def display
puts full_list.join(' ')
end
def sum
full_list.keep_if { |x| x > 0 }.reduce(:+)
end