Related
numbers = [1, 2, 3, 4, 5]
for num in numbers
puts "insert q "
qanswer1 = gets.chomp.to_i
puts "insert 2nd q"
qanswer2 = gets.chomp.to_i
end
This code will repeat the questions 5 times. How do I retrieve the user-inputted data? I'm trying to calculate the total sum of all 10 responses and the index in which the sum of each pair was the highest.
nbr_pairs = 5
def ask(str)
print "#{str}: "
gets.to_i
end
arr = nbr_pairs.times.map { [ask("insert q"), ask("insert 2nd q")] }
#=> [[7, 3], [8, 6], [2, 9], [4, 6], [8, 3]]
Sum of all 10 replies
arr.flatten.sum
#=> 56
Index of largest sum of pairs
nbr_pairs.times.max_by { |i| arr[i].sum }
#=> 1 (8+6 = 14)
See Integer#times, Array#flatten, Enumerable#max_by and Array#sum.
I tried to make a solution as close as possible to yours while still producing the desired results :
numbers = [0,1,2,3,4]
pairs = Array.new(numbers.size, [])
numbers.each do |number|
pairs[number] = []
puts "q 1:"
pairs[number] << gets.to_i
puts "q 2:"
pairs[number] << gets.to_i
end
To get the pair with the max value:
max_value = pairs.max_by(&:sum)
To get the sum of all pairs:
sum_of_all_responses = pairs.flatten.sum
To get the index of the pair with the highest value:
pairs.index(max_value)
If you don't need to store all the data, you could just do calculations on the fly.
First move the input request to a method which returns the pair of value n an array:
def ask
puts "insert q "
qanswer1 = gets.to_i
puts "insert 2nd q"
qanswer2 = gets.to_i
[qanswer1, qanswer2]
end
Then set up variables
big_sum = 0
best_input = 0
best_input_q_number = nil
Finally loop as you did doing the math:
numbers = [1,2,3,4,5]
for n in numbers
# (1..5).each do |n| # this is more Ruby-ish
p qanswers = ask # p for debug
qanswers_sum = qanswers.sum
big_sum += qanswers_sum
if qanswers_sum > best_input
best_input = qanswers_sum # or qanswers if you want to keep the pairs
best_input_q_number = n
end
end
I'm trying to solve a problem called five_sort that accepts an array of integers as the argument and places all the fives at the end of the array and leaves all of the other numbers unsorted. For example, [1,2,5,3,2,5,5,7] would be sorted as [1,2,3,2,7,5,5,5].The rules for the problem state that only a while loops can be used and no other methods can be called on the array except [] and []=. Here is my current code:
def five_sort(array)
sorted = false
while sorted == false
idx = 0
while idx < array.length
if array[idx] == 5
array[idx], array[idx + 1] = array[idx + 1], array[idx]
end
idx += 1
end
sorted = true
end
array
end
When running it, it is just in a continuous loop but I can't find out how to fix it. I know that if I just run the second while loop without the while sorted loop, the array would only run once and the fives would only switch places once and the loop would be over. But I don't know how to run the second while loop and stop it once all the fives are at the end.
Can anyone help me figure this one out?
Just a simple O(n) time and O(1) space solution, using a write-index and a read-index.
w = r = 0
while array[w]
r += 1 while array[r] == 5
array[w] = array[r] || 5
w += 1
r += 1
end
While a couple of people have posted alternative approaches, which are all good, I wanted to post something based on your own code to reassure you that you had got pretty close to a solution.
I've added comments to explain the changes I've made:
def five_sort(array)
sorted = false
while sorted == false
idx = 0
# use did_swap to keep track of if we've needed to swap any numbers
did_swap = false
# check if next element is nil as alternative to using Array#length
while array[idx + 1] != nil
# it's only really a swap if the other entry is not also a 5
if array[idx] == 5 and array[idx + 1] != 5
array[idx], array[idx + 1] = array[idx + 1], array[idx]
did_swap = true
end
idx += 1
end
# if we've been through the array without needing to make any swaps
# then the list is sorted
if !did_swap
sorted = true
end
end
array
end
Your array is becoming longer at each loop:
array = [1,2]
array[1], array[2] = array[2], array[1]
puts array.length
Outputs 3.
What you need is to not swap if idx = array.length - 1
if (array[idx] == 5)
array[idx], array[idx+1] = array[idx+1], array[idx] if idx != array.length - 1
end
def five_sort(arr)
i = 0
cnt = 0
while arr[i]
if arr[i] == 5 && arr[i+1]
arr[i..i] = []
cnt += 1
else
i += 1
end
end
cnt.times { arr[-1,2] = [arr[-1],5] }
arr
end
arr = [1,5,3,5,6]
five_sort arr
#=> [1, 3, 6, 5, 5]
arr
#=> [1, 3, 6, 5, 5] # confirms arr is mutated
five_sort [5,5,5,3,6]
#=> [3, 6, 5, 5, 5]
five_sort [5,5,5,5,5]
#=> [5, 5, 5, 5, 5]
five_sort [1,2,3,4,6]
#=> [1, 2, 3, 4, 6]
five_sort []
#=> []
Notes:
As required by the spec, the only methods invoked on arr are [] and []= and no other arrays are created.
if i indexes the last element of the array, arr[i+1] equals nil.
arr[i..i] = [] removes the elementarr[i] from arr.
arr[-1,2] = [arr[-1],5] appends a 5 to arr.
So
#[11,13,17,23] => [13,17,19,29]
if the number isn't prime, then the function is just returning the number
#[11,8,2,24] => [13,8,3,24]
I'm having so much trouble with the very last number (29), for some reason, it's going into an infinite loop. I feel like there is such a simple solution, but it's just escaping me..
def next_prime(arr)
new_arr = []
arr.each do |num|
#puts num
if prime?(num)
p = false
i = num + 2
while !p
p = prime?(i)
i += 2
end
new_arr << i
else
new_arr << num
end
end
new_arr
end
EDIT: here is the prime function
def prime?(num)
if num ==1
return false
elsif num < 3
return true
elsif num % 2 == 0 || num % 3 == 0
return false
end
i = 5
while i*i <= num
if num % i == 0 || num % (i + 2) == 0
return false
end
i += 6
end
return true
end
The first array works decently for me, even the 29, except for the fact that everything is 2 higher than it should be, because you add 2 after you check if you have a prime which can be fixed by a slight alteration to the code:
if prime?(num)
p = false
i = num
while !p
i += 2
p = prime?(i)
end
new_arr << i
The only infinite loop I encounter is when you hit 2 in the second array, because to check for primes, you just keep incrementing by 2, and so you end up checking every multiple of 2 to see if it's prime. Naturally you never find a prime multiple of 2. To fix this, instead of incrementing by 2 before checking for the next prime, if you increment by 1 would work, you just need to check twice as many numbers:
if prime?(num)
p = false
i = num
while !p
i += 1
p = prime?(i)
end
new_arr << i
your last problem is that your prime? function returns false for 3, which can be fixed by changing:
elsif num <= 3
return true
and now your 2 samples yield:
[11, 13, 17, 23] => [13, 17, 19, 29]
[11, 8, 2, 24] => [13, 8, 3, 24]
Similar to #Cary Swoveland answer, but more idiomatic Ruby IMHO.
require 'prime'
def next_primes(ary)
ary.map { |candidate| candidate.prime? ? next_prime(candidate) : candidate }
end
def next_prime(previous_prime)
all_primes = Prime.each
all_primes.find { |prime| prime > previous_prime }
end
next_primes([11,8,2,24]) # => [13, 8, 3, 24]
next_primes([11,13,17,23]) # => [13, 17, 19, 29]
I've assumed the array arr is sorted. If it isn't, save the original indices of the sorted values, which are then used to reorder the elements of the array of values containing prime and non-prime numbers. For example, if
arr = [57, 13, 28, 6]
then
indices = arr.each_with_index.sort.map(&:last)
#=> [3, 1, 2 0]
The steps of the the main method are as follows.
Step 1: create an empty array a that will be returned by the method.
Step 2: create an enumerator, enum, that generates an infinite sequence of prime numbers (2, 3, 5, 7,..). Generate the first prime m = enum.next #=> 2.
Step 3: create an enumerator, earr, that generate the elements of the given array arr.
Step 4: consider the next element of the array, x = earr.next, which is initially the first element of the array. When there are no more elements of the array, break from the loop and return the array a.
Step 5: if x is not prime save it to an array a (a << x) and repeat step 4; else go to Step 6.
Step 6: (x is prime) if x < m, save m to the array a and go to
Step 4; else (i.e., m <= x), obtain the next prime (m = enum.next) and repeat this step.
require 'prime"
def next_primes(arr)
enum = Prime.each
m = enum.next
earr = arr.to_enum
x = earr.next
a = []
loop do
if x.prime?
if x < m
a << m
x = earr.next
else
m = enum.next
end
else
a << x
x = earr.next
end
end
a
end
next_primes([2, 6, 7, 23, 100])
#=> [3, 6, 11, 29, 100]
next_primes([2, 6, 7, 7, 100])
#=> [3, 6, 11, 11, 100]
Solution to find the next prime number if it is a prime number if not return the same number:
def is_prime(num)
if num<2
return false
end
(2...num).each do |i|
if num%i == 0
return false
end
end
return true
end
def next_prime(arr)
new_arr = []
arr.each do |num|
if is_prime(num)
p = false
i = num
while !p
i += 1
p = is_prime(i)
end
new_arr<<i
else
new_arr<<num
end
end
return new_arr
end
print next_prime([2,3,4,5])
puts
print next_prime([2, 6, 7, 23, 100]) #[3, 6, 11, 29, 100]
I'm iterating over permutations of a list (18 items) like this:
List = [item0..item18] # (unpredictable)
Permutation_size = 7
Start_at = 200_000_000
for item, i in List.repeated_permutation(Permutation_size).each_with_index
next if i < Start_at
# do stuff
end
Start_at is used to resume from a previously saved state so it's always different but it takes almost 200s to reach 200 million so I'm wondering if there is a faster way to skip multiple iterations or start at iteration n (converting the enumerator to an array takes even longer). If not, a way to create a custom repeated_permutation(n).each_with_index (that yields results in the same order) would also be appreciated.
Feel free to redirect me to an existing answer (I haven't found any)
PS. (what I had come up with)
class Array
def rep_per_with_index len, start_at = 0
b = size
raise 'btl' if b > 36
counter = [0]*len
# counter = (start_at.to_s b).split('').map {|i| '0123456789'.include?(i) ? i.to_i : (i.ord - 87)} #this is weird, your way is way faster
start_at.to_s(b).chars.map {|i| i.to_i b}
counter.unshift *[0]*(len - counter.length)
counter.reverse!
i = start_at
Enumerator.new do |y|
loop do
y << [counter.reverse.map {|i| self[i]}, i]
i += 1
counter[0] += 1
counter.each_with_index do |v, i|
if v >= b
if i == len - 1
raise StopIteration
else
counter[i] = 0
counter[i + 1] += 1
end
else
break
end
end
end
end
end
end
I first construct a helper method, change_base, with three arguments:
off, the base-10 offset into the sequence of repeated permutations of the given array arr,
m, a number system base; and
p, the permutation size.
The method performs three steps to construct an array off_m:
converts off to base m (radix m);
separates the digits of the base m value into an array; and
if necessary, pads the array with leading 0s to make it of size p.
By setting m = arr.size, each digit of off_m is an offset into arr, so off_m maps the base-10 offset to a unique permutation of size p.
def change_base(m, p, off)
arr = off.to_s(m).chars.map { |c| c.to_i(m) }
arr.unshift(*[0]*(p-arr.size))
end
Some examples:
change_base(16, 2, 32)
#=> [2, 0]
change_base(16, 3, 255)
#=> [0, 15, 15]
change_base(36, 4, 859243)
#=> [18, 14, 35, 31]
18*36**3 + 14*36**2 + 35*36**1 + 31
#=> 859243
This implementation of change_base requires that m <= 36. I assume that will be sufficient, but algorithms are available to convert base-10 numbers to numbers with arbitrarily-large bases.
We now construct a method which accepts the given array, arr, the size of each permutation, p and a given base-10 offset into the sequence of permutations. The method returns a permutation, namely, an array of size p whose elements are elements of arr.
def offset_to_perm(arr, p, off)
arr.values_at(*change_base(arr.size, p, off))
end
We can now try this with an example.
arr = (0..3).to_a
p = 2
(arr.size**p).times do |off|
print "perm for off = "
print " " if off < 10
print "#{off}: "
p offset_to_perm(arr, p, off)
end
perm for off = 0: [0, 0]
perm for off = 1: [0, 1]
perm for off = 2: [0, 2]
perm for off = 3: [0, 3]
perm for off = 4: [0, 1]
perm for off = 5: [1, 1]
perm for off = 6: [2, 1]
perm for off = 7: [3, 1]
perm for off = 8: [0, 2]
perm for off = 9: [1, 2]
perm for off = 10: [2, 2]
perm for off = 11: [3, 2]
perm for off = 12: [0, 3]
perm for off = 13: [1, 3]
perm for off = 14: [2, 3]
perm for off = 15: [3, 3]
If we wish to begin at, say, offset 5, we can write:
i = 5
p offset_to_perm(arr, p, i)
[1, 1]
i = i.next #=> 6
p offset_to_perm(arr, p, i)
[2, 1]
...
How can I find the second smallest number and return its index?
Another approach :
>> a = [1,3,5,6,2,4]
=> [1, 3, 5, 6, 2, 4]
>> a.index(a.sort[1])
=> 4
>>
I can see two options from the top of my head:
Delete the current min, so the new min will be the previous second min
arr = num.delete(num.min)
min_bis = arr.min
Loop through the array, using 2 variables to store the 2 lowest values.
This might be a little trickier but the complexity would only be O(n).
I don't know why you don't want to sort the array, but if it's a performance issue, it's probably one of the best options (to sort it) especially if the array is small.
(Below, Enumerable is a superset of Array, Hash and Range etc.)
Enumerable#sort returns a fresh array containing all the elements of the original object in a sorted order, so you can write a = num.sort[1] (provided that l > 1) to find the second smallest number, without modfying the original input nums.
Then you can feed it to Enumerable#find_index.
http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-sort
http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-find_index
By the way
while (index <l)
nums - gets.to_i
num[index] = nums
index +=1
end
can be written as
nums = (0...l).map{ gets.to_i }
I understand you don't want to sort the array before finding the second-lowest number. But are you willing to use a sorted clone/copy of that array?
If
nums = [1, 5, 1, 9, 3, 8]
Then:
# grab a sorted copy of nums
b = nums.sort
# b = [1, 1, 3, 5, 8, 9]
# delete the lowest number
b.delete(b.min)
# now b = [3, 5, 8, 9]
# so get the index from the original array
nums.index(b.first)
which should return 4 because nums[4] = 3. (You could also use nums.index(b[0]) since b is already sorted.)
If you don't mind being destructive to the original array:
a.delete(a.min)
a.index(a.min)
Here's an approach that does not use sort:
arr = [3,1,2,5,1]
If second_smallest(arr) => 2 is desired:
def second_smallest(arr)
return nil if arr.uniq.size < 2
mn, mx = arr.min, arr.max
arr.map! { |e| e == mn ? mx : e }
arr.index(arr.min)
end
If second_smallest(arr) => 4 is desired:
def second_smallest(arr)
return nil if arr.uniq.size < 2
i1 = arr.index(arr.min)
arr.delete_at(i1)
i2 = arr.index(arr.min)
i2 >= i1 ? i2 + 1 : i2
end
You don't want to use sort as it's O(nlogn). You want to iterate through the array only once (after getting the max):
arr = [123,35,12,34,5,32]
This is a straight forward way of solving the problem:
def second_min_index(arr)
max = arr.max
min, min_index, second_min, second_min_index = max, 0, max, 0
arr.each_with_index do |e, i|
# if something is less than min, second min should become what used to be min
if (e <= min)
second_min, second_min_index, min, min_index = min, min_index, e, i
# if something is less than second min (but not less than min)
# it becomes the second min
elsif (e < second_min)
second_min, second_min_index = e, i
end
end
second_min_index
end
second_min_index(arr)
=> 2
A better and more reusable way of doing this would be via a transform and conquer solution (just in case you get asked for the 3rd smallest number):
def min_index(arr)
min, min_index = arr[0], 0
arr.each_with_index { |e,i| min, min_index = e,i if e < min }
min_index
end
def min_index_excluding(arr, exclude_indexes)
min, min_index = arr[0], 0
arr.each_with_index { |e,i| min, min_index = e,i if (e < min && !exclude_indexes.include?(i)) }
min_index
end
def second_min_index(arr)
min_index_excluding(arr, [min_index(arr)])
end
second_min_index(arr)
=> 2
a_sorted = a.sort
second_min = a_sorted[1]
a.index(second_min)