-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathCoding_Challenges.rb
76 lines (51 loc) · 2.17 KB
/
Coding_Challenges.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#----------------------------------------------------------------Ruby Coding Challenges--------------------------------------------------------
# Ruby Coding Challenges on Numbers
# Write a program in Ruby to -
# 1. Convert decimal numbers to octal numbers.
# 2. Reverse an integer.
# 3. Print the Fibonacci series using the recursive method.
# 4. Return the Nth value from the Fibonacci sequence.
# 5. Find the average of numbers (with explanations).
# 6. Convert Celsius to Fahrenheit.
#----------------------------------------------------------------Solution of Problem:----------------------------------------------------------
# 1. Converting Decimal Numbers to Octal Numbers:
decimal_number = 25
octal_number = []
while decimal_number > 0
octal_number.push(decimal_number % 8)
decimal_number /= 8
end
print "Octal number: "
octal_number.reverse_each { |digit| print digit }
#----------------------------------------------------------------------------------------------------------------------------------------------
# 2. Reversing an Integer:
number = 12345
reversed_number = 0
while number != 0
reversed_number = reversed_number * 10 + number % 10
number /= 10
end
puts reversed_number
#----------------------------------------------------------------------------------------------------------------------------------------------
# 3. Printing the Fibonacci Series using Recursion:
def fibonacci(n)
return n if n <= 1
fibonacci(n - 1) + fibonacci(n - 2)
end
n = 10
print "Fibonacci series: "
(0...n).each { |i| print fibonacci(i).to_s + " " }
#----------------------------------------------------------------------------------------------------------------------------------------------
# 4. Returning the Nth Value from the Fibonacci Sequence:
def fibonacci(n)
return n if n <= 1
fibonacci(n - 1) + fibonacci(n - 2)
end
n = 10
fibonacci_number = fibonacci(n)
puts fibonacci_number
#----------------------------------------------------------------------------------------------------------------------------------------------
# 5. Finding the Average of Numbers:
numbers = [10, 20, 30, 40, 50]
average = numbers.sum.to_f / numbers.length
puts "Average: #{average}"