If I have a fixed size array , how do I write a constraint so that each multi-bit element of the array after randomization is an odd number - uvm

I need to generate odd numbers after randomizing elements of an array in UVM sequence .

Let's say you have the following class with an array variable:
class some_class;
rand int array[10];
endclass
If you want to constrain each element of the array, you can use the foreach construct. To get all even numbers in the array, you can constrain each element of the array to be odd. A number is odd if the remainder of division by 2 isn't 0:
class some_class;
// ...
constraint all_array_elems_odd {
foreach (array[i])
array[i] % 2 != 0;
}
endclass
You can check that it works with the following example:
module test;
initial begin
automatic some_class obj = new();
if (!obj.randomize())
$fatal(0, "Randomization error");
$display("%p", obj);
end
endmodule
Note that I didn't use compare the remainder of division against 1. This is because some programming languages (SystemVerilog included) use % for the remainder operation and not the modulus operation. The remainder can be negative (whereas the modulus is always positive). Negative odd numbers will have a remainder of -1, so forcing the remainder to be 1 will force the numbers to be positive.

Related

What is the most efficient (speed) way to get a digit from a larger number?

I plan to use this inside a game loop to draw the score using custom bitmap font.
Here is what I have. Now I know that I have used the modulus, division and power operators a bunch of times. I understand that using this in a game loop is not a good thing to do. Any suggestions?
// Get digit n, where n is digit starting from the units place and moving left
int getDigit(int number, int position)
{
return (number % (int)pow(10, position)) / pow(10, (position - 1));
}
If int is 32 bits, then:
static const int table[] =
{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
return number / table[position-1] % 10;
is a reasonable implementation:
It does not invoke pow or use floating-point arithmetic.
It uses one table look-up, one division by a variable, and one remainder operation with a constant (which a compiler can optimize to a multiplication and some shifts and adds).
(Note that position is adjusted in the table lookup to be one-based to match the code in the question, but common practice would be to call the units position position 0 instead of position 1.)
If digits are to be extracted for multiple positions or the whole number, then other implementations should be considered.
You said that you extract a digit in order to display the game score; so I assume you will use the whole original number.
You can extract all the digits in a loop this way:
int number = 1234; // this variable will be consumed
while (number) {
rightmostdigit = number % 10;
// do something with the extracted digit
number /= 10; // discard the rightmost at go to the next
}
The above routine extracts digits from the right, so the score shall be drawn from right to left. Warning that if the number is zero, the loop is never executed...
If you want to extract from left, and supposing a fixed-length score (like "00123"), you can store the single digits in an array, then read them back in the inverse direction: it should be faster than trying to extract the digits from left to right.

inverse ring index to get the greatest index as the first of the first index on C

I'm not sure about how to get an inverse index , index%size it's ok to a straight ring index but what I need it's if tou are in 0 index get the last index as the previous of 0.
[0][1][2][3] // the previous index of 0 should be 3
In the language C the remainder operator can be used as follows to get a true (positive) modulo result:
(index+n-1)%n
where n is the length of your array.
if I understood you correctly, then you could just say prev(index) = (index-1) % len(array) given that % returns the modulus and not the remainder (depending on the language, the mod operation might have slightly different behavior with negative integers)
int m(int a,int b){
return (a % b + b) % b;
}
so you would just define prev(n) = m(n-1,len(array))

Division of 2 numbers and saving the result in array

I have been working on some code, but it looks like my logic is not right.
I am trying to make a program that divides number (a) into equal parts (b) (if that is possible) and then save those results, along with the initial dividing number, into an array. Something like this:
20/2=10 [10][10]
20/3=6 [8][6][6]
So I here is my code:
for (i=0; i<b; i++)
{
if (a%b)
{
array[i]=a/b;
}
else
{
array[0]=(a/b)+(a%b);
array[i+1]=a/b;
}
printf("\n\nIn range %d there are %d\n\n",i,Sub_arr_len[i]);
}
It looks like the first case is working, but the second is not and I don't know why. Any ideas?
In the line
array[0]=(a/b)+(a%b);
Your first array element is the integer division, plus the remainder. For any division with a remainder, your program will not work. It instead stores the integer division in all of the elements apart from the first, where it is summed with the remainder.
To combat this I would write most of the code into an if statement testing if the modulus is 0 or not. I assume you don't want to save any array if your division doesn't result in equal parts, so you should only do what you are currently doing if a%b = 0.

Finding the maximum element of the array is a divisor of another element

Given an array of non-zero integers of length N. Write a function that returns the maximum element of the array, which is a divisor of some other element of the same array. If this number is not present, then return 0. I know how to solve in O(n^2). Is it possible to do it faster?
First, note that you are assuming that testing if integer A divides integer B can be completed in O(1). I guess you're also assuming that no pre-computation (e.g. building a divisibility graph) is allowed.
Since integer factorization (for which no polynomial algorithm is known) is not an option, you can't do faster then O(n^2) (worst case).
For example, given the input {11,127, 16139} (all integers are primes, each integer squared is less than the next one), you can't avoid checking all pairs.
I have been playing with your problem for a while and found a sometimes-better than brute-force solution.
It is based in to ideas:
We can perform the search in an order such that bigger divisor candidates are tested first. That way we can terminate the search as soon as we find a divisor.
One way to test if some candidate divw is a divisor for number w, is to calculate r = floor(w / divw) and then check that r * divw == w. The interesting thing, is that when it fails, we can calculate a top limit for the next divisor candidate of w as topw = floor(w / (r + 1)). So we can discard anything between divw and topw.
A sample for that second point: Imagine we are testing if divw = 10 is a divisor of w = 12, we calculate r = floor(12 / 10) = 1, and topw = floor(w / 2) = 6. So, we don't need to check if numbers in the set between 7 and 9, inclusive, are divisors for 12.
In order to implement this algorithm I have used a heap to keep the numbers in the set using as key the next divisor candidate that has to be tested.
So...
Initialize the heap pushing every element which its predecessor as its bigger potential divisor.
Pop the first element from the heap (w) and check if the potential divisor candidate (divw) is actually a divisor.
If it is, return it as the biggest divisor
Calculate topw for w, divw; search the next element in the set divw' that is equal or lesser than topw (using binary-search); if found, push w,divw' again in the queue.
unless the queue is empty, goto 2.
An implementation in Common Lisp is available here!
I guess calculating the theoretical computational cost for this algorithm would be challenging, specially for the average case, so I am not going to do it!
After running it a dozen times, it seems to behave better than the brute force approach when N is high and the numbers are dispersed (which means that the probability of one number being a divisor of other is low). On the other hand, brute-force seems to be faster when N is low or when the numbers are densely distributed in a small range (which means that the probability of a number being a divisor of other is high).
I did it so
int f(int* a, int size)
{
int max = 0;
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
if (a[i] > a[j] && a[i] % a[j] == 0 && a[j] > max)
max = a[j];
return max;
}

Find missing element

I saw the following question:
Given an array A of integers, find an integer k that is not present in A. Assume that the integers are 32-bit signed integers.
How to solve it?
Thank you
//// update -- This is the provided solution - but I don't think it is correct ////
Consider a very simple hash function F(x)=x mod (n+1). we can build a bit-vector of length
n+1 that is initialized to 0 and for every element in A, we set bit F(A[i]) to 1.Since there are only n elements in the array, we can find the missing element easily.
I think the above solution is wrong.
For example,
A [ 2, 100, 4 ], then both 4 and 100 will match to the same place.
If I'm interpreting the question correctly, (find any integer not in A) and n is the number of elements in A, then the answer is correct as given.
The fact that the hash function can have collisions doesn't really matter; By the pigeonhole principle in reverse, there will be some bit in the bit vector that is not set - because it has more bits than there are elements in A. The corresponding value is an integer not in A. In the case where the hash function has collisions, there will actually be more than one bit not set, which works in favor of the algorithm's correctness rather than against it.
To illustrate, here's how your example would work out:
A = [2, 100, 4]
n = length(A) = 3
f(x) = x mod 4
map(f,A) = [2, 0, 0]
so the final bit vector will be:
[1,0,1,0]
From there, we can arbitrarily choose any integer corresponding to any 0 bit, which in this case is any odd number.
max (items) + 1
springs to mind. Of course it would fail if one of the elements was 2^31-1 and another was -(2^32).
Failing that, sort them and look for an interval.
Since there appear to be no upperbounds or other constraints:
for (int i = int.MinValue; i <= int.MaxValue; i++)
{
if (! A.Contains(i))
{
// found it !
break;
}
}

Resources