How would i create an array in RubyMotion and then display a total of every number in the array.
For example - Array[1..20] I want to display a total of 1+2+3+4+5+6....up to and including 20. So the total in this case would be 210.
I'm sure this is fairly straight forward but I am relatively new to RubyMotion and arrays bend my minuscule brain.
Cheers for any help
(1..20).to_a create an array of [1, 2, 3, ...., 19, 20] and you can use Enumerable#inject for calculation.
(1..20).to_a.inject(&:+)
You can use this way for Ruby too.
With a loop:
numberArray = [1, 2, 3, 4]
total = 0
numberArray.each do |number|
total += number
end
Where the += operator means:
x += y
is equal to
x = x + y
Edit :
def getSum(my_array)
total = 0
my_array.each do |number|
total += number
end
total
end
numberArr = [1,2,3,4]
total = getSum(numberArr)
label.text = "#{total}"
I cannot test right now, but it should work.
Related
I am trying to draw the flowchart for this question and stuck.
Given a list A of n numbers, count the number of times 0 occurs in the list.It might be an easy question but I am a beginner and don't have much idea about most questions. Please help me draw that!
You need to iterate through the list A and for each value, check if the value is equal to zero. If it is, add 1 to a running total.
In pseudo code:
total = 0
listA = [1, 5, 0, 2, 0, ...]
for i = 0 to len(listA):
if listA[i] == 0:
total = total + 1
next i
I am given this algorithmic problem, and need to find a way to return the count in a list S and another list L that is between some variable x and some variable y, inclusive, that runs in O(1) time:
I've issued a challenge against Jack. He will submit a list of his favorite years (from 0 to 2020). If Jack really likes a year,
he may list it multiple times. Since Jack comes up with this list on the fly, it is in no
particular order. Specifically, the list is not sorted, nor do years that appear in the list
multiple times appear next to each other in the list.
I will also submit such a list of years.
I then will ask Jack to pick a random year between 0 and 2020. Suppose Jack picks the year x.
At the same time, I will also then pick a random year between 0 and 2020. Suppose I
pick the year y. Without loss of generality, suppose that x ≤ y.
Once x and y are picked, Jack and I get a very short amount of time (perhaps 5
seconds) to decide if we want to re-do the process of selecting x and y.
If no one asks for a re-do, then we count the number of entries in Jack's list that are
between x and y inclusively and the number of entries in my list that are between x and
y inclusively.
More technically, here is the situation. You are given lists S and L of m and n integers,
respectively, in the range [0, k], representing the collections of years selected by Jack and
I. You may preprocess S and L in O(m+n+k) time. You must then give an algorithm
that runs in O(1) time – so that I can decide if I need to ask for a re-do – that solves the
following problem:
Input: Two integers, x as a member of [0,k] and y as a member of [0,k]
Output: the number of entries in S in the range [x, y], and the number of entries in L in [x, y].
For example, suppose S = {3, 1, 9, 2, 2, 3, 4}. Given x = 2 and y = 3, the returned count
would be 4.
I would prefer pseudocode; it helps me understand the problem a bit easier.
Implementing the approach of user3386109 taking care of edge case of x = 0.
user3386109 : Make a histogram, and then compute the accumulated sum for each entry in the histogram. Suppose S={3,1,9,2,2,3,4} and k is 9. The histogram is H={0,1,2,2,1,0,0,0,0,1}. After accumulating, H={0,1,3,5,6,6,6,6,6,7}. Given x=2 and y=3, the count is H[y] - H[x-1] = H[3] - H[1] = 5 - 1 = 4. Of course, x=0 is a corner case that has to be handled.
# INPUT
S = [3, 1, 9, 2, 2, 3, 4]
L = [2, 9, 4, 6, 8, 5, 3]
k = 9
x = 2
y = 3
# Histogram for S
S_hist = [0]*(k+1)
for element in S:
S_hist[element] = S_hist[element] + 1
# Storing prefix sum in S_hist
sum = S_hist[0]
for index in range(1,k+1):
sum = sum + S_hist[index]
S_hist[index] = sum
# Similar approach for L
# Histogram for L
L_hist = [0] * (k+1)
for element in L:
L_hist[element] = L_hist[element] + 1
# Stroing prefix sum in L_hist
sum = L_hist[0]
for index in range(1,k+1):
sum = sum + L_hist[index]
L_hist[index] = sum
# Finding number of elements between x and y (inclusive) in S
print("number of elements between x and y (inclusive) in S:")
if(x == 0):
print(S_hist[y])
else:
print(S_hist[y] - S_hist[x-1])
# Finding number of elements between x and y (inclusive) in S
print("number of elements between x and y (inclusive) in L:")
if(x == 0):
print(L_hist[y])
else:
print(L_hist[y] - L_hist[x-1])
A given list is n=[3,1,5,9,6,14] , replace 5 with 3+1 and 14 with 9+6. The output will look like [3,1,4,9,6,15]
My approach was using a range and assign value
i+ [i+1]==[i+2]
I tried 2 ways but in both cases I am getting out of bound exception
#Approach 1
for idx,item in enumerate(n):
if (idx + (idx+1))!=(idx+2):
n[idx+2]=(idx + (idx+1))
#Approach2
for i in range(len(n)):
if n[i]+n[i+1]!=n[i+2]:
n[i + 2]==n[i]+n[i+1]
print(n)
Even doing a len(n)-1 does not solve the problem. Some directions will be helpful. Thank You.
You could use the mod (%) operator to check for every third item:
items = [3, 1, 5, 9, 6, 14]
for i, item in enumerate(items):
if ((i+1) % 3 == 0):
items[i] = items[i-1] + items[i-2]
print(items)
Or to be more efficient, use range as mentioned in the comments:
for i in range(2, len(items), 3):
items[i] = items[i-1] + items[i-2]
print(items)
I'm trying to find, for a list of numbers from 1 to 50, what numbers within that range are the sums of two other specific numbers from another list. The other list is 1, 2, 4, 6, 18, 26.
I'm basically trying to run a "for x in range(1,50):" type program that then lists all the numbers from 1 to 50 and next to them says "TRUE" if they are the sum of any two of the numbers in that list (e.g. 1 + 1, 1 + 4, 1 + 26, 4 + 18, 18 + 26 etc etc).
Any ideas??
Thank you!!
Matt
Iterate over all possible pairs of numbers:
sums = []
for n1 in numbers:
for n2 in numbers:
# Add them together and store the result in `sums`
And then check to see if every number from range(50) is in your list of sums:
for n in range(50):
if n in sums:
# `n` is the sum of two numbers from your list
def solveMeFirst(a,b):
# Hint: Type return a+b below
return a+b
num1 = int(input())
num2 = int(input())
res = solveMeFirst(num1,num2)
print(res)
With given permutation 1...n for example 5 3 4 1 2
how to find all ascending subsequences of length 3 in linear time ?
Is it possible to find other ascending subsequences of length X ? X
I don't have idea how to solve it in linear time.
Do you need the actual ascending sequences? Or just the number of ascending subsequences?
It isn't possible to generate them all in less than the time it takes to list them. Which, as has been pointed out, is O(NX / (X-1)!). (There is a possibly unexpected factor of X because it takes time O(X) to list a data structure of size X.) The obvious recursive search for them scales not far from that.
However counting them can be done in time O(X * N2) if you use dynamic programming. Here is Python for that.
counts = []
answer = 0
for i in range(len(perm)):
inner_counts = [0 for k in range(X)]
inner_counts[0] = 1
for j in range(i):
if perm[j] < perm[i]:
for k in range(1, X):
inner_counts[k] += counts[j][k-1]
counts.add(inner_counts)
answer += inner_counts[-1]
For your example 3 5 1 2 4 6 and X = 3 you will wind up with:
counts = [
[1, 0, 0],
[1, 1, 0],
[1, 0, 0],
[1, 1, 0],
[1, 3, 1],
[1, 5, 5]
]
answer = 6
(You only found 5 above, the missing one is 2 4 6.)
It isn't hard to extend this answer to create a data structure that makes it easy to list them directly, to find a random one, etc.
You can't find all ascending subsequences on linear time because there may be much more subsequences than that.
For instance in a sorted original sequence all subsets are increasing subsequences, so a sorted sequence of of length N (1,2,...,N) has N choose k = n!/(n-k)!k! increasing subsequences of length k.