def sum_w(*args)
i = 0
sum = 0
while i < args.length do
sum += args[i]
i += 1
end
sum
end
def sum_e(*args)
sum = 0
args.each { |num|
sum += num
}
sum
end
def sum_r(*args)
return 0 if args.empty?
sum = args.shift + sum_r(*args)
end
def combine(array1, array2)
combined = []
array1.each.with_index { |el, i|
combined.push array1[i]
combined.push array2[i]
}
combined
end
Récursif :
def combine(array1, array2, combined = [])
return combined if array1.empty? && array2.empty?
combined.push(array1.shift, array2.shift)
combine(array1, array2, combined)
end
def fibo
list = [0, 1]
98.times { list.push(list[-2] + list[-1]) }
list
end
Récursif :
def fibo_r(list = [0, 1])
return list if list.length == 100
list.push(list[-1] + list[-2])
fibo_r(list)
end
def big(array)
n = array.length
swapped = true
# bubble sort algorithm adaptation
while swapped do
swapped = false
(n - 1).times do |i|
if "#{array[i]}#{array[i+1]}" < "#{array[i+1]}#{array[i]}"
array[i], array [i+1] = array[i+1], array[i]
swapped = true
end
end
end
array.join.to_i
end
def search_combinations_to_100(array)
@results = []
def combinations_to_100(array, result = 0, string_so_far = "")
@results << "#{string_so_far} = #{result}" if result == 100 && array.empty?
return false if array.empty?
head, *tail = array
operations = ['add', 'sub', 'concat_and_add', 'concat_and_sub']
operations.each { |o|
case o
when 'add'
result += head
string_so_far += "+#{head} "
combinations_to_100(tail, result, string_so_far)
when 'sub'
result, string_so_far = *undo('add', head, result, string_so_far)
result -= head
string_so_far += "-#{head} "
combinations_to_100(tail, result, string_so_far)
when 'concat_and_add' then
result, string_so_far = *undo('sub', head, result, string_so_far)
head = "#{head}#{tail.shift}".to_i
result += head
string_so_far += "+#{head} "
combinations_to_100(tail, result, string_so_far)
when 'concat_and_sub' then
result, string_so_far = *undo('add', head, result, string_so_far)
result += head
string_so_far += "+#{head} "
combinations_to_100(tail, result, string_so_far)
end
}
end
def undo(operation, head, result, string_so_far)
case operation
when 'add'
result -= head
string_so_far.slice!("+#{head} ")
return result, string_so_far
when 'sub'
result += head
string_so_far.slice!("-#{head} ")
return result, string_so_far
end
end
combinations_to_100(array)
@results
end
class ['a] node value next_node = object
val mutable value : 'a = value
val mutable next_node : 'a = next_node
method set_value new_value =
value <- new_value
method set_next new_next =
next_node <- new_next
method get_value =
value
method get_next =
next_node
end;;
class lkdlist = object
val mutable head = new node
end;;
class ['a] lkdlist init = object
val mutable l : 'a list = init
method add e =
l <- e :: l
method get_list =
l
end;;