Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Ruby: Общие вопросы > массив Ruby


Автор: joker332 24.10.2009, 12:14
вот задание Дан целочисленный массив. Определить количество участков, на которых его 
элементы монотонно возрастают.
Я написал програму, но вот такой вот трабл 
Я нахожу первый елемент цепочки  (if ar[i]<ar[i+1]) потом с помощью while ar[i]<ar[i+1] прохожу эту все цепочку, потом я хочу начинать крутить цикл не с0 второго елемента а с последнего елемента цепочки, но почемуто цикл дальше начинается со второго елемента!
Код
ar = [1, 2, 3, 4 ,5 , 41, 11, 9, 6, 7, 0]
count=0
temp=0
i=0
for i in 0...ar.length-1
print "i(first)=", i
  if ar[i]<ar[i+1]
   #puts " ", ar[i], " ", ar[i+1]
    #i=temp+1;
    #temp=i+1
     count=count+1
      while ar[i]<ar[i+1] 
    #print" ", ar[i]," ",ar[i+1] ;
      i=i+1
      #i=temp;
    end
    print "i(last)=", i
   
  end
end
print("Count = ", count)


Автор: source777 25.10.2009, 23:36
joker332, внутри for нельзя изменить значение i.  smile 

Автор: joker332 26.10.2009, 00:24
а как мне быть???В с++ можно))

Автор: Bose 26.10.2009, 02:26
Цитата(joker332 @  25.10.2009,  23:24 Найти цитируемый пост)
В с++ можно

только в С++ такое наверное и можно.  smile 

Автор: source777 26.10.2009, 20:26
Цитата(joker332 @  26.10.2009,  00:24 Найти цитируемый пост)
а как мне быть?

решать задачу, не трогая счётчик цикла.

Автор: shine 27.10.2009, 15:46
Нашлась пара минут и вот что получилось:

Код

require 'test/unit'

def mono_up input_array
  result = 0

  if input_array.size > 2 # we need at least 3 items in row to find one monoup
    delta_arr = [] #deltas between each element and next element in array
    input_array[0..input_array.size-2].each_with_index do |item, index|
      delta_arr << (input_array[index+1] - item)
    end
    
    delta_arr.each_with_index do |item, index|
      if index == 0
        result += 1 if item == delta_arr[index+1]
      elsif index != delta_arr.size - 1
        result += 1 if (delta_arr[index-1] != item && item == delta_arr[index+1])
      end
    end
  end
  
  result
end

class MonoUp < Test::Unit::TestCase
  def test_for_truth
    test_arr_1, test_res_1 = [1, 2, 3, 4 ,5, 41, 11, 9, 6, 7, 0], 1
    test_arr_2, test_res_2 = [1, 3, 4, 6, 7, 8, 10, 11], 1
    test_arr_3, test_res_3 = [1, 2, 3, 4, 6, 7, 8, 10, 11], 2
    test_arr_4, test_res_4 = [1, 3, 4, 6, 7, 8, 10, 11, 12], 2
    test_arr_5, test_res_5 = [1, 2, 3, 4, 6, 8, 10, 15, 16, 17], 3
    test_arr_6, test_res_6 = [1, 3, 4, 6, 9, 10, 15, 16, 19], 0
    test_arr_7, test_res_7 = [1, 3, 4], 0
    test_arr_8, test_res_8 = [1, 2, 4], 0
    test_arr_9, test_res_9 = [1], 0
    test_arr_10, test_res_10 = [1, 3], 0
    test_arr_11, test_res_11 = [1, 2, 3], 1

    assert defined?(mono_up)
    assert_equal mono_up(test_arr_1), test_res_1
    assert_equal mono_up(test_arr_2), test_res_2
    assert_equal mono_up(test_arr_3), test_res_3
    assert_equal mono_up(test_arr_4), test_res_4
    assert_equal mono_up(test_arr_5), test_res_5
    assert_equal mono_up(test_arr_6), test_res_6
    assert_equal mono_up(test_arr_7), test_res_7
    assert_equal mono_up(test_arr_8), test_res_8
    assert_equal mono_up(test_arr_9), test_res_9
    assert_equal mono_up(test_arr_10), test_res_10
    assert_equal mono_up(test_arr_11), test_res_11
  end
end

Автор: source777 27.10.2009, 16:02
shine, если меня не подводит память на школьный курс алгебры, то монотонное возрастание отнюдь не означает, что разница между соседними элементами должна быть равной. Достаточно чтобы последующий элемент был больше предыдущего.

Автор: shine 27.10.2009, 17:10
Мне бы такую память... Тогда все еще проще:
Код

require 'test/unit'

def mono_up input_arr
  result = 0

  input_arr.each_with_index do |item, index|
    if index == 0
      result += 1 if item < input_arr[index+1]
    elsif index != input_arr.size - 1
      result += 1 if (input_arr[index-1] >= item && item < input_arr[index+1])
    end
  end if input_arr.size > 1 # we need at least 2 items in row to find one monoup
  
  result
end

class MonoUp < Test::Unit::TestCase
  def test_for_truth
    test_arr_1, test_res_1 = [1, 2, 3, 4 ,5, 41, 11, 9, 6, 7, 0], 2
    test_arr_2, test_res_2 = [1, 3, 4, 6, 7, 8, 10, 11], 1
    test_arr_3, test_res_3 = [1, 2, 3, 4, 6, 7, 8, 10, 11], 1
    test_arr_4, test_res_4 = [9, 1, 3, 4, 6, 7, 8, 10, 11, 12, 1, 9, 11], 2
    test_arr_5, test_res_5 = [1, 2, 3, 4, 1, 8, 10, 1, 16, 17], 3
    test_arr_6, test_res_6 = [1, 3, 4, 6, 9, 10, 5, 16, 19], 2
    test_arr_7, test_res_7 = [1, 4, 3], 1
    test_arr_8, test_res_8 = [1, 2, 4], 1
    test_arr_9, test_res_9 = [1], 0
    test_arr_10, test_res_10 = [1, 3], 1
    test_arr_11, test_res_11 = [1, 2, 1, 3], 2

    assert defined?(mono_up)
    assert_equal mono_up(test_arr_1), test_res_1
    assert_equal mono_up(test_arr_2), test_res_2
    assert_equal mono_up(test_arr_3), test_res_3
    assert_equal mono_up(test_arr_4), test_res_4
    assert_equal mono_up(test_arr_5), test_res_5
    assert_equal mono_up(test_arr_6), test_res_6
    assert_equal mono_up(test_arr_7), test_res_7
    assert_equal mono_up(test_arr_8), test_res_8
    assert_equal mono_up(test_arr_9), test_res_9
    assert_equal mono_up(test_arr_10), test_res_10
    assert_equal mono_up(test_arr_11), test_res_11
  end
end

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)