i would like to know if you can help me with this problem for my game. I'm currently using lots of switch, if-else, etc on my code and i'm not liking it at all.
I would like to generate 2 random arithmethic expressions that have one of the forms like the ones bellow:
1) number
e.g.: 19
2) number operation number
e.g.: 22 * 4
3) (number operation number) operation number
e.g.: (10 * 4) / 5
4) ((number operation number) operation number) operation number
e.g.: ((25 * 2) / 10) - 2
After i have the 2 arithmetic expresions, the game consist in matching them and determine which is larger.
I would like to know how can i randomly choose the numbers and operations for each arithmetic expression in order to have an integer result (not float) and also that both expression have results that are as close as possible. The individual numbers shouldn't be higher than 30.
I mean, i wouldn't like a result to be 1000 and the other 14 because they would be probably too easy to spot which side is larger, so they should be like:
expresion 1: ((25 + 15) / 10) * 4 (which is 16)
expression 2: (( 7 * 2) + 10) / 8 (which is 3)
The results (16 and 3) are integers and close enough to each other.
the posible operations are +, -, * and /
It would be possible to match between two epxressions with different forms, like
(( 7 * 2) + 10) / 8
and
(18 / 3) * 2
I really appreciate all the help that you can give me.
Thanks in advance!!
Best regards.
I think a reasonable way to approach this is to start with a value for the total and recursively construct a random expression tree to reach that total. You can choose how many operators you want in each equation and ensure that all values are integers. Plus, you can choose how close you want the values of two equations, even making them equal if you wish. I'll use your expression 1 above as an example.
((25 + 15) / 10) * 4 = 16
We start with the total 16 and make that the root of our tree:
16
To expand a node (leaf), we select an operator and set that as the value of the node, and create two children containing the operands. In this case, we choose multiplication as our operator.
Multiplication is the only operator that will really give us trouble in trying to keep all of the operands integers. We can satisfy this constraint by constructing a table of divisors of integers in our range [1..30] (or maybe a bit more, as we'll see below). In this case our table would have told us that the divisors of 16 are {2,4,8}. (If the list of divisors for our current value is empty, we can choose a different operator, or a different leaf altogether.)
We choose a random divisor, say 4 and set that as the right child of our node. The left child is obviously value/right, also an integer.
*
/ \
4 4
Now we need to select another leaf to expand. We can randomly choose a leaf, randomly walk the tree until we reach a leaf, randomly walk up and right from our current child node (left) until we reach a leaf, or whatever.
In this case our selection algorithm chooses to expand the left child and the division operator. In the case of division, we generate a random number for the right child (in this case 10), and set left to value*right. (Order is important here! Not so for multiplication.)
*
/ \
÷ 4
/ \
40 10
This demonstrates why I said that the divisor table might need to go beyond our stated range as some of the intermediate values may be a bit larger than 30. You can tweak your code to avoid this, or make sure that large values are further expanded before reaching the final equation.
In the example we do this by selecting the leftmost child to expand with the addition operator. In this case, we can simply select a random integer in the range [1..value-1] for the right child and value-right for the left.
*
/ \
÷ 4
/ \
+ 10
/ \
25 15
You can repeat for as many operations as you want. To reconstruct the final equation, you simply need to perform an in-order traversal of the tree. To parenthesize as in your examples, you would place parentheses around the entire equation when leaving any interior (operator) node during the traversal, except for the root.
Related
I am trying to implement the speck cipher as specified here: Speck Cipher. On page 18 of the document you can find some speck pseudo-code I want to implement.
It seems that I got a problem on understanding the pseudo-code. As you can find there, x and y are plaintext words with length n. l[m-2],...l[0], k[0] are key words (as for words, they have length n right?). When you do the key expansion, we iterate for i from 0 to T-2, where T are the round numbers (for example 34). However I get an IndexOutofBoundsException, because the array with the l's has only m-2 positions and not T-2.
Can someone clarify what the key expansions does and how?
Ah, I get where the confusion lies:
l[m-2],...l[0], k[0]
these are the input key words, in other words, they represent the key. These are not declarations of the size of the arrays, as you might expect if you're a developer.
Then the subkey's in array k should be derived, using array l for intermediate values.
According to the formulas, taking the largest i, i.e. i_max = T - 2 you get a highest index for array l of i_max + m - 1 = T - 2 + m - 1 = T + m - 3 and therefore a size of the array of one more: T + m - 2. The size of a zero-based array is always the index of the last element - plus one, after all.
Similarly, for subkey array k you get a highest index of i_max + 1, which is T - 2 + 1 or T - 1. Again, the size of the array is one more, so there are T elements in k. This makes a lot of sense if you require T round keys :)
Note that it seems possible to simply redo the subkey derivation for each round if you require a minimum of RAM. The entire l array doesn't seem necessary either. For software implementations that doesn't matter a single iota of course.
This problem gives you a positive integer number which is less than or equal to 100000 (10^5). You have to find out the following things for the number:
i. Is the number prime number? If it is a prime number, then print YES.
ii. If the number is not a prime number, then can we express the number as summation of unique prime numbers? If it is possible, then print YES. Here unique means, you can use any prime number only for one time.
If above two conditions fail for any integer number, then print NO. For more clarification please see the input, output section and their explanations.
Input
At first you are given an integer T (T<=100), which is the number of test cases. For each case you will be given a positive integer X which is less than or equal 100000.
Output
For every test case, print only YES or NO.
Sample
Input Output
3
7
6
10 YES
NO
YES
Case – 1 Explanation: 7 is a prime number.
Case – 2 Explanation: 6 is not a prime number. 6 can be expressed as 6 = 3 + 3 or 6 = 2 + 2 + 2. But you can’t use any prime number more than 1 time. Also there is no way to express 6 as two or three unique prime numbers summation.
Case – 3 Explanation: 10 is not prime number but 10 can be expressed as 10 = 3 + 7 or 10 = 2 + 3 + 5. In this two expressions, every prime number is used only for one time.
Without employing any mathematical tricks (not sure if any exist...you'd think as a mathematician I'd have more insight here), you will have to iterate over every possible summation. Hence, you'll definitely need to iterate over every possible prime, so I'd recommend the first step being to find all the primes at most 10^5. A basic (Sieve of Eratosthenes)[https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes] will probably be good enough, though faster sieves exist nowadays. I know your question is language agnostic, but you could consider the following as vectorized pseudocode for such a sieve.
import numpy as np
def sieve(n):
index = np.ones(n+1, dtype=bool)
index[:2] = False
for i in range(2, int(np.sqrt(n))):
if index[i]:
index[i**2::i] = False
return np.where(index)[0]
There are some other easy optimizations, but for simplicity this assumes that we have an array index where the indices correspond exactly to whether the number is prime or not. We start with every number being prime, mark 0 and 1 as not prime, and then for every prime we find we mark every multiple of it as not prime. The np.where() at the end just returns the indices where our index corresponds to True.
From there, we can consider a recursive algorithm for actually solving your problem. Note that you might feasibly have a huge number of distinct primes necessary. The number 26 is the sum of 4 distinct primes. It is also the sum of 3 and 23. Since the checks are more expensive for 4 primes than for 2, I think it's reasonable to start by checking the smallest number possible.
In this case, the way we're going to do that is to define an auxiliary function to find whether a number is the sum of precisely k primes and then sequentially test that auxiliary function for k from 1 to whatever the maximum possible number of addends is.
primes = sieve(10**5)
def sum_of_k_primes(x, k, excludes=()):
if k == 1:
if x not in excludes and x in primes:
return (x,)+excludes
else:
return ()
for p in (p for p in primes if p not in excludes):
if x-p < 2:
break
temp = sum_of_k_primes(x-p, k-1, (p,)+excludes)
if temp:
return temp
return ()
Running through this, first we check the case where k is 1 (this being the base case for our recursion). That's the same as asking if x is prime and isn't in one of the primes we've already found (the tuple excludes, since you need uniqueness). If k is at least 2, the rest of the code executes instead. We check all the primes we might care about, stopping early if we'd get an impossible result (no primes in our list are less than 2). We recursively call the same function for smaller k, and if we succeed we propagate that result up the call stack.
Note that we're actually returning the smallest possible tuple of unique prime addends. This is empty if you want your answer to be "NO" as specified, but otherwise it allows you to easily come up with an explanation for why you answered "YES".
partial = np.cumsum(primes)
def max_primes(x):
return np.argmax(partial > x)
def sum_of_primes(x):
for k in range(1, max_primes(x)+1):
temp = sum_of_k_primes(x, k)
if temp:
return temp
return ()
For the rest of the code, we store the partial sums of all the primes up to a given point (e.g. with primes 2, 3, 5 the partial sums would be 2, 5, 10). This gives us an easy way to check what the maximum possible number of addends is. The function just sequentially checks if x is prime, if it is a sum of 2 primes, 3 primes, etc....
As some example output, we have
>>> sum_of_primes(1001)
(991, 7, 3)
>>> sum_of_primes(26)
(23, 3)
>>> sum_of_primes(27)
(19, 5, 3)
>>> sum_of_primes(6)
()
At a first glance, I thought caching some intermediate values might help, but I'm not convinced that the auxiliary function would ever be called with the same arguments twice. There might be a way to use dynamic programming to do roughly the same thing but in a table with a minimum number of computations to prevent any duplicated efforts with the recursion. I'd have to think more about it.
As far as the exact output your teacher is expecting and the language this needs to be coded in, that'll be up to you. Hopefully this helps on the algorithmic side of things a little.
I am looking for help with pseudo code (unless you are a user of Game Maker 8.0 by Mark Overmars and know the GML equivalent of what I need) for how to generate a list / array of unique combinations of a set of X number of integers which size is variable. It can be 1-5 or 1-1000.
For example:
IntegerList{1,2,3,4}
1,2
1,3
1,4
2,3
2,4
3,4
I feel like the math behind this is simple I just cant seem to wrap my head around it after checking multiple sources on how to do it in languages such as C++ and Java. Thanks everyone.
As there are not many details in the question, I assume:
Your input is a natural number n and the resulting array contains all natural numbers from 1 to n.
The expected output given by the combinations above, resembles a symmetric relation, i. e. in your case [1, 2] is considered the same as [2, 1].
Combinations [x, x] are excluded.
There are only combinations with 2 elements.
There is no List<> datatype or dynamic array, so the array length has to be known before creating the array.
The number of elements in your result is therefore the binomial coefficient m = n over 2 = n! / (2! * (n - 2)!) (which is 4! / (2! * (4 - 2)!) = 24 / 4 = 6 in your example) with ! being the factorial.
First, initializing the array with the first n natural numbers should be quite easy using the array element index. However, the index is a property of the array elements, so you don't need to initialize them in the first place.
You need 2 nested loops processing the array. The outer loop ranges i from 1 to n - 1, the inner loop ranges j from 2 to n. If your indexes start from 0 instead of 1, you have to take this into consideration for the loop limits. Now, you only need to fill your target array with the combinations [i, j]. To find the correct index in your target array, you should use a third counter variable, initialized with the first index and incremented at the end of the inner loop.
I agree, the math behind is not that hard and I think this explanation should suffice to develop the corresponding code yourself.
So in my text book there is this example of a recursive function using f#
let rec gcd = function
| (0,n) -> n
| (m,n) -> gcd(n % m,m);;
with this function my text book gives the example by executing:
gcd(36,116);;
and since the m = 36 and not 0 then it ofcourse goes for the second clause like this:
gcd(116 % 36,36)
gcd(8,36)
gcd(36 % 8,8)
gcd(4,8)
gcd(8 % 4,4)
gcd(0,4)
and now hits the first clause stating this entire thing is = 4.
What i don't get is this (%)percentage sign/operator or whatever it is called in this connection. for an instance i don't get how
116 % 36 = 8
I have turned this so many times in my head now and I can't figure how this can turn into 8?
I know this is probably a silly question for those of you who knows this but I would very much appreciate your help the same.
% is a questionable version of modulo, which is the remainder of an integer division.
In the positive, you can think of % as the remainder of the division. See for example Wikipedia on Euclidean Divison. Consider 9 % 4: 4 fits into 9 twice. But two times four is only eight. Thus, there is a remainder of one.
If there are negative operands, % effectively ignores the signs to calculate the remainder and then uses the sign of the dividend as the sign of the result. This corresponds to the remainder of an integer division that rounds to zero, i.e. -2 / 3 = 0.
This is a mathematically unusual definition of division and remainder that has some bad properties. Normally, when calculating modulo n, adding or subtracting n on the input has no effect. Not so for this operator: 2 % 3 is not equal to (2 - 3) % 3.
I usually have the following defined to get useful remainders when there are negative operands:
/// Euclidean remainder, the proper modulo operation
let inline (%!) a b = (a % b + b) % b
So far, this operator was valid for all cases I have encountered where a modulo was needed, while the raw % repeatedly wasn't. For example:
When filling rows and columns from a single index, you could calculate rowNumber = index / nCols and colNumber = index % nCols. But if index and colNumber can be negative, this mapping becomes invalid, while Euclidean division and remainder remain valid.
If you want to normalize an angle to (0, 2pi), angle %! (2. * System.Math.PI) does the job, while the "normal" % might give you a headache.
Because
116 / 36 = 3
116 - (3*36) = 8
Basically, the % operator, known as the modulo operator will divide a number by other and give the rest if it can't divide any longer. Usually, the first time you would use it to understand it would be if you want to see if a number is even or odd by doing something like this in f#
let firstUsageModulo = 55 %2 =0 // false because leaves 1 not 0
When it leaves 8 the first time means that it divided you 116 with 36 and the closest integer was 8 to give.
Just to help you in future with similar problems: in IDEs such as Xamarin Studio and Visual Studio, if you hover the mouse cursor over an operator such as % you should get a tooltip, thus:
Module operator tool tip
Even if you don't understand the tool tip directly, it'll give you something to google.
Is there any closed form formula to find out maximum possible binary trees with height or depth 'h'. I have seen formula for total number of binary trees for a given number of nodes. But I have not seen any closed form formula for a given fixed height or depth irrespective of number of nodes.
Let's employ a recurrence relation in order to find a formula. Let n[h] be the number of binary trees with height h. Then we know that
n[0] = 1 //An empty tree
n[1] = 1 //A single leaf
A binary tree of height i can be built as follows: Either we use a tree of height i - 1 as the left child. Then we can choose any tree with height from 0 through i - 1 as the right child. Or we choose a tree of height i - 1 as the right child. Then we can choose any tree with height from 0 through i-2 as the left child (note the -2 in the last term to avoid counting the same trees twice). Hence,
n[h + 1] = Sum{i from 0 to h}[n[h]*n[i]] + Sum{i from 0 to h-1}[n[h]*n[i]]
We can calculate the first few elements:
1
1
3
21
651
457653
210065930571
44127887745696109598901
1947270476915296449559659317606103024276803403
If we search for this sequence in OEIS, we find this sequence. There are some formulas at the bottom and none of them looks to have a closed form. But that doesn't seem necessary. The sequence grows so fast that the numbers exceed fixed length data types very soon. Hence, it is very easy to calculate these few numbers that can be represented with your desired data type via dynamic programming or even pre-calculate the numbers and use them as constants.
This is similar to Nico's answer (which seems to be counting the number of trees where all non-leaf nodes have exactly two children) but counts the number of trees where each node has at most two children.
Here is a Python script for calculating this number by a recurrence relation:
def b(n):
if n == 0:
return 1
else:
return b(n-1) + b(n-1)**2 + 2*sum(b(k)*b(n-1) for k in range(n-1))
Output for the first few values is: 1, 2, 10, 170, 33490, 1133870930. The sequence can be found in OEIS here