I am unable to write the part of the code that counts by a multiple of 6 - for-loop

Write a program using the for-loop. The program should:
Take a positive integer as input.
Return a list of all the integers between 0 to the input (including the input number) which are the multiple of 6.
I am unable to write the part of the code that counts by a multiple of 6

Iterate from 0 to the number. Check if the number can be divided by 6. If it is divisible add to the list.
num = int(input("Enter a number"))
list = []
for i in range(0,num+1):
if(i%6==0):
list.append(i)
print(list)

Related

Generate random but always different numbers within a range with CSPRNG

I have a CSPRNG that I'm using to generate 5 numbers between 0 and 20. The problem is, there could be cases where it generates the same number again. So say it generates 5 but running again, it could come out to be 5. If not, then the third or 4th number could be 5.
I want a way to do this where I'm 100% sure the 5 numbers are never the same, even if they do come up as same, I want to re-generate that number in a way that none of the numbers clash.
I thought of using a while loop for each number, to regenerate the number while it's same as the other 4 numbers but that obviously is not optimal and may cause to get stuck in long loops.
Is there a better way?
so as far as I understand that question you want a way to find N unique random numbers from your CSPRNG within the specified range and an execution time that's independant from the numbers generated from the underlying CSPRNG
make an array with your number range (here 0 to 20 => 21 elements)
run a loop for all array elements:
let idx = array index of current element
let jdx = CSPRNG(within range -1; here between 0 and 19 inclusive)
if jdx >= idx add 1 to jdx // idx and jdx are now 2 distinct array index positions
swap array elements idx and jdx
your N uniqe random numbers are the N first/last elements of the array

Random number generator with varies conditions. 3 digits

Hi i am working on a random number generator which i faced a road block. I have done my program but i'm quite lost on how to do a loop for the C++ program to keep on looping. following below is the conditions for program:
The program prompts the user to enter a number.
This number determines the number of times the loop will repeat. The number ranges from 0 to 100. Validate this range.
The program uses a random number to generate a number from 0 to 9999 and then
checks if the generated number contains the digit 1, digit 2 or digit 3.
Please advise on how do i require to do a switch or while loop for point 3.
your inputs is greatly appreciated.
Easiest way to check would be to use the mod operation and division to extract every digit.
A loop would be something like
int randInt = randomFunction();
while(randInt > 0){
//Get Last Digit
int lastDigit = randInt % 10;
switch(lastDigit){
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
}
/*
Divide the number by 10 to remove the last digit.
Integers will automatically truncate remainders.
i.e int a = 21/10, a will = 2
*/
randInt /= 10;
}

random matrix with special order in matlab

this is my simple code: A=randi([0,1],[500,500])
this code gives me matrix A(500*500) that all elements are 0 or 1.
is it any way that I can order that the number of 1 in this element be 7000.
Is it possible to guide me please?
If I understand your question correctly, I don't think the randi function is the way to start here.
I would suggest the following procedure:
Start with a list with 500*500 elements, with 7000 elements set to 1 and the rest to 0
Randomize the order of elements in the list
Make an 500*500 array whose elements are the elements of the list
For instance, the following code would work:
A_init(1:7000) = 1; A_init(7001:500*500) = 0 % step 1
A = A_init(randperm(length(A_init))) % step 2
A = reshape(A,[500,500]) % step 3
The key is the use of randperm, which generates a random permutation of the indices.
To verify that A has the correct number of elements:
num_ones = length(find(A==1))

Scope of variables and the digits function

My question is twofold:
1) As far as I understand, constructs like for loops introduce scope blocks, however I'm having some trouble with a variable that is define outside of said construct. The following code depicts an attempt to extract digits from a number and place them in an array.
n = 654068
l = length(n)
a = Int64[]
for i in 1:(l-1)
temp = n/10^(l-i)
if temp < 1 # ith digit is 0
a = push!(a,0)
else # ith digit is != 0
push!(a,floor(temp))
# update n
n = n - a[i]*10^(l-i)
end
end
# last digit
push!(a,n)
The code executes fine, but when I look at the a array I get this result
julia> a
0-element Array{Int64,1}
I thought that anything that goes on inside the for loop is invisible to the outside, unless I'm operating on variables defined outside the for loop. Moreover, I thought that by using the ! syntax I would operate directly on a, this does not seem to be the case. Would be grateful if anyone can explain to me how this works :)
2) Second question is about syntex used when explaining functions. There is apparently a function called digits that extracts digits from a number and puts them in an array, using the help function I get
julia> help(digits)
Base.digits(n[, base][, pad])
Returns an array of the digits of "n" in the given base,
optionally padded with zeros to a specified size. More significant
digits are at higher indexes, such that "n ==
sum([digits[k]*base^(k-1) for k=1:length(digits)])".
Can anyone explain to me how to interpret the information given about functions in Julia. How am I to interpret digits(n[, base][, pad])? How does one correctly call the digits function? I can't be like this: digits(40125[, 10])?
I'm unable to reproduce you result, running your code gives me
julia> a
1-element Array{Int64,1}:
654068
There's a few mistakes and inefficiencies in the code:
length(n) doesn't give the number of digits in n, but always returns 1 (currently, numbers are iterable, and return a sequence that only contain one number; itself). So the for loop is never run.
/ between integers does floating point division. For extracting digits, you´re better off with div(x,y), which does integer division.
There's no reason to write a = push!(a,x), since push! modifies a in place. So it will be equivalent to writing push!(a,x); a = a.
There's no reason to digits that are zero specially, they are handled just fine by the general case.
Your description of scoping in Julia seems to be correct, I think that it is the above which is giving you trouble.
You could use something like
n = 654068
a = Int64[]
while n != 0
push!(a, n % 10)
n = div(n, 10)
end
reverse!(a)
This loop extracts the digits in opposite order to avoid having to figure out the number of digits in advance, and uses the modulus operator % to extract the least significant digit. It then uses reverse! to get them in the order you wanted, which should be pretty efficient.
About the documentation for digits, [, base] just means that base is an optional parameter. The description should probably be digits(n[, base[, pad]]), since it's not possible to specify pad unless you specify base. Also note that digits will return the least significant digit first, what we get if we remove the reverse! from the code above.
Is this cheating?:
n = 654068
nstr = string(n)
a = map((x) -> x |> string |> int , collect(nstr))
outputs:
6-element Array{Int64,1}:
6
5
4
0
6
8

Random number generator that fills an interval

How would you implement a random number generator that, given an interval, (randomly) generates all numbers in that interval, without any repetition?
It should consume as little time and memory as possible.
Example in a just-invented C#-ruby-ish pseudocode:
interval = new Interval(0,9)
rg = new RandomGenerator(interval);
count = interval.Count // equals 10
count.times.do{
print rg.GetNext() + " "
}
This should output something like :
1 4 3 2 7 5 0 9 8 6
Fill an array with the interval, and then shuffle it.
The standard way to shuffle an array of N elements is to pick a random number between 0 and N-1 (say R), and swap item[R] with item[N]. Then subtract one from N, and repeat until you reach N =1.
This has come up before. Try using a linear feedback shift register.
One suggestion, but it's memory intensive:
The generator builds a list of all numbers in the interval, then shuffles it.
A very efficient way to shuffle an array of numbers where each index is unique comes from image processing and is used when applying techniques like pixel-dissolve.
Basically you start with an ordered 2D array and then shift columns and rows. Those permutations are by the way easy to implement, you can even have one exact method that will yield the resulting value at x,y after n permutations.
The basic technique, described on a 3x3 grid:
1) Start with an ordered list, each number may exist only once
0 1 2
3 4 5
6 7 8
2) Pick a row/column you want to shuffle, advance it one step. In this case, i am shifting the second row one to the right.
0 1 2
5 3 4
6 7 8
3) Pick a row/column you want to shuffle... I suffle the second column one down.
0 7 2
5 1 4
6 3 8
4) Pick ... For instance, first row, one to the left.
2 0 7
5 1 4
6 3 8
You can repeat those steps as often as you want. You can always do this kind of transformation also on a 1D array. So your result would be now [2, 0, 7, 5, 1, 4, 6, 3, 8].
An occasionally useful alternative to the shuffle approach is to use a subscriptable set container. At each step, choose a random number 0 <= n < count. Extract the nth item from the set.
The main problem is that typical containers can't handle this efficiently. I have used it with bit-vectors, but it only works well if the largest possible member is reasonably small, due to the linear scanning of the bitvector needed to find the nth set bit.
99% of the time, the best approach is to shuffle as others have suggested.
EDIT
I missed the fact that a simple array is a good "set" data structure - don't ask me why, I've used it before. The "trick" is that you don't care whether the items in the array are sorted or not. At each step, you choose one randomly and extract it. To fill the empty slot (without having to shift an average half of your items one step down) you just move the current end item into the empty slot in constant time, then reduce the size of the array by one.
For example...
class remaining_items_queue
{
private:
std::vector<int> m_Items;
public:
...
bool Extract (int &p_Item); // return false if items already exhausted
};
bool remaining_items_queue::Extract (int &p_Item)
{
if (m_Items.size () == 0) return false;
int l_Random = Random_Num (m_Items.size ());
// Random_Num written to give 0 <= result < parameter
p_Item = m_Items [l_Random];
m_Items [l_Random] = m_Items.back ();
m_Items.pop_back ();
}
The trick is to get a random number generator that gives (with a reasonably even distribution) numbers in the range 0 to n-1 where n is potentially different each time. Most standard random generators give a fixed range. Although the following DOESN'T give an even distribution, it is often good enough...
int Random_Num (int p)
{
return (std::rand () % p);
}
std::rand returns random values in the range 0 <= x < RAND_MAX, where RAND_MAX is implementation defined.
Take all numbers in the interval, put them to list/array
Shuffle the list/array
Loop over the list/array
One way is to generate an ordered list (0-9) in your example.
Then use the random function to select an item from the list. Remove the item from the original list and add it to the tail of new one.
The process is finished when the original list is empty.
Output the new list.
You can use a linear congruential generator with parameters chosen randomly but so that it generates the full period. You need to be careful, because the quality of the random numbers may be bad, depending on the parameters.

Resources