count the number of times 0 occurs - flowchart

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

Related

How can I write this algorithm that returns the count between x and y in a list?

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])

How do I get "The numbers" Only at the end?

Here is what I want to get:
$ python ex33.py
At the top i is 0
Numbers now: [0]
At the bottom i is 1
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5
This was a while loop:
1 i = 0
2 numbers = []
3
4 while i < 6:
5 print "At the top i is %d" % i
6 numbers.append(i)
7
8 i = i + 1
9 print "Numbers now: ", numbers
10 print "At the bottom i is %d" % i
11
12
13 print "The numbers: "
14
15 for num in numbers:
16 print num
Now Mr Shaw asks me to build this into a function. His exact question is: Convert this while- loop to a function that you can call, and replace 6 in the test (i < 6) with a variable. I am not sure I have build a function (since those mostly start with a def? Or do they always start with a def?)
I am not sure if I understand completely what he is asking, but this is what I did:
i = 0
numbers = []
for i in range (0, 6):
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
Which actually makes me kind of proud for how for I have gotten with this:
At the top i is 0
Numbers now: [0]
At the bottom i is 1
The numbers:
0
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
The numbers:
0
1
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
The numbers:
0
1
2
At the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
The numbers:
0
1
2
3
At the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
The numbers:
0
1
2
3
4
At the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5
Where I am stuck is that "The numbers" is something I only need to get at the end. And that, I can't get my head around. What am I missing (except amazing coding skills and a well functioning brain)?
You have not made a function. While it's not always necessary to use def to make a function, that's the usual way. And I think you've misunderstood what your teacher wanted you to change in your while loop. He wanted you to replace the 6 in the condition i < 6 with a variable (a parameter of the function). You've replaced the while with a for, but still kept the 6 as a constant. Using for loops instead of while loops is often a good idea, but in this case it's now what was being asked for.
As for why your numbers output is being repeated, I suspect it's because that code is inside your main loop now, while it wasn't before. This is not entirely clear though, since you seem to have lost the indentation of the original code when you copied it into Stack Overflow. Since indentation is significant in Python, this makes it hard to know exactly the old code ran.
what you are missing is that in python block of code are defined by the indentation level, you put the part that print the whole list inside the for that fill the list so each time that you put a number in the list also print if afterward. To put that outside reduce the indentation level of that part like this
i = 0
numbers = []
for i in range (0, 6):
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
#this part is now outside the for-loop
print "The numbers: "
for num in numbers:
print num
About your other question, yes functions are defined by the key world def you can check the documentation about the details, but in your case you can transform you code into a function very easy like this
def my_function():
i = 0
numbers = []
for i in range (0, 6):
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
that is, declare that you are creating a new function with the def key world, give it a name, in this case I called my_function, and put your previous code inside it by just give it a extra indentation level as show above.
Functions have the property that they can take a number of arguments and operate according to that, that let you define some behavior and make it more general.
For example: say that you want to print the number 0 to 9 you can do
for num in range(0,10):
print num
Now say that you want to print the number 0-5, 0-20, and 10-20 you can write a similar code for all of them:
for num in range(0,6):
print num
for num in range(0,21):
print num
for num in range(10,21):
print num
but wait there is pattern here all have the same exact code in every case save for the arguments of range, here is when a function come to play, we can define a function that take as arguments 2 numbers and our function do the job of print all the number in between; that is something like this
def my_function(star,stop):
for num in range(star,stop+1): # the +1 is to include the stop number
print num
(this is fun_test.py in the example below)
then we can call our function like this
my_function(0,5)
my_function(0,20)
my_function(10,20)
or if we open the file in a python interpreter or in interactive mode (that is $ python -i ex33.py) we can call with any pair of numbers of our desire
$ python -i fun_test.py
>>> my_function(8,17)
8
9
10
11
12
13
14
15
16
17
>>> my_function(0,5)
0
1
2
3
4
5
>>>
as you can see a function let us re-use a piece of code as many times as we want. The arguments of a function is the part of it that is variable while its code is the behavior we want according to the variable part (if any).
With this little explanation I think that you can modify your function to the requirements that your teacher (?) ask you

Create a total of an array of numbers in RubyMotion

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.

Calculating Hamming Sequence in C++ (a sequence of numbers that has only 2, 3, and 5 as dividers) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating a sequence using prime numbers 2, 3, and 5 only, and then displaying an nth term (C++)
I've been brainstorming over this forever, and I just can't figure this out. I need to solve the following problem:
Generate the following sequence and display the nth term in the
sequence
2,3,4,5,6,8,9,10,12,15, etc..... Sequence only has Prime numbers
2,3,5
I need to use basic C++, such as while, for, if, etc. Nothing fancy. I can't use arrays simply because I don't know much about them yet, and I want to understand the code for the solution.
I'm not asking for a complete solution, but I am asking for guidance to get through this... please.
My problem is that I can't figure out how to check if the number if the number in the sequence is divisible by any other prime numbers other than 2, 3, and 5.
Also let's say I'm checking the number like this:
for(int i=2; i<n; i++){
if(i%2==0){
cout<<i<<", ";
}else if(i%3==0){
cout<<i<<", ";
}else if(i%5==0){
cout<<i<<", ";
}
It doesn't work simply due to the fact that it'll produce numbers such as 14, which can be divided by prime number 7. So I need to figure out how to ensure that that sequence is only divisible by 2, 3, and 5..... I've found lots of material online with solutions for the problem, but the solutions they have are far too advance, and I can't use them (also most of them are in other languages... not C++). I'm sure there's a simpler way.
The problem with your code is that you just check one of the prime factors, not all of them.
Take your example of 14. Your code only checks if 2,3 or 5 is a factor of 14, which is not exactly what you need. Indeed, you find that 2 is a factor of 14, but the other factor is 7, as you said. What you are missing is to further check if 7 has as only factors 2,3 and 5 (which is not the case). What you need to do is to eliminate all the factors 2,3 and 5 and see what is remaining.
Let's take two examples: 60 and 42
For 60
Start with factors 2
60 % 2 = 0, so now check 60 / 2 = 30.
30 % 2 = 0, so now check 30 / 2 = 15.
15 % 2 = 1, so no more factors of 2.
Go on with factors 3
15 % 3 = 0, so now check 15 / 3 = 5.
5 % 3 = 2, so no more factors of 3.
Finish with factors 5
5 % 5 = 0, so now check 5 / 5 = 1
1 % 5 = 1, so no more factors of 5.
We end up with 1, so this number is part of the sequence.
For 42
Again, start with factors 2
42 % 2 = 0, so now check 42 / 2 = 21.
21 % 2 = 1, so no more factors of 2.
Go on with factors 3
21 % 3 = 0, so now check 21 / 3 = 7.
7 % 3 = 1, so no more factors of 3.
Finish with factors 5
7 % 5 = 2, so no more factors of 5.
We end up with 7 (something different from 1), so this number is NOT part of the sequence.
So in your implementation, you should probably nest 3 while loops in your for loop to reflect this reasoning.
Store the next i value in temporary variable and then divide it by 2 as long as you can (eg. as long as i%2 == 0). Then divide by 3 as long as you can. Then by 5. And then check, what is left.
What about this?
bool try_hamming(int n)
{
while(n%2 == 0)
{
n = n/2;
}
while(n%3 == 0)
{
n = n/3;
}
while(n%5 == 0)
{
n = n/5;
}
return n==1;
}
This should return true when n is a hamming nummer and false other wise. So the main function could look something like this
#include<iostream>
using namespace std;
main()
{
for(int i=2;i<100;++i)
{
if(try_hamming(i) )
cout<< i <<",";
}
cout<<end;
}
this schould print out all Hamming numbers less then 100

Ascending subsequences in permutation

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.