Summation constraint writing with std::randomize - constraints

I have two queues; they have the same size and have been assigned value. I want to randomize en_q, but I have no idea about how to write it efficiently.
function void rand ()
int val_q[$];
bit en_q[$];
std::randomize(en_q[i]) with {
// pseudo-code
sum(val_q[i]*en_q[i]) < 100;
// I'm wondering how to convert the above condition into system verilog language?
// I know en_q.sum() < 100; but with multiply summation, I have no any idea.
}
endfunction

You may need to re-structure your queues into a single queue. You could copy them as needed to seperate them. The following worked for me.
module top;
typedef struct {
int val;
rand bit en;
} field_t;
field_t q[$];
initial begin
q = '{ '{1,0},'{2,0},'{3,0},'{4,0},'{5,0},'{6,0},'{7,0},'{8,0},'{9,0} };
repeat (10) begin
if (!std::randomize(q) with {
q.sum(x) with (x.val*x.en) <10;
}) $error("randomize failed");
$display("%p",q);
end
end
endmodule

Related

Exception in thread "main" java.lang.StackOverflowError at Solution.recur(File.java:58)

class Solution{
ArrayList subsetSums(ArrayList arr, int N){
int sum=0;
ArrayList<Integer> temparr = new ArrayList<>();
for(int i=1;i<=arr.size();i++)
{
for(int j = 0; i < arr.size()-i+1 ; j++)
temparr.add(recur(arr,i,j,sum));
}
return temparr;
}
int recur(ArrayList<Integer> arr,int i,int j,int sum)
{
int index = j;
int len = i;
int Sum = sum;
if(len==0)
{
return Sum;
}
Sum += arr.get(index);
return recur(arr,len--,index++,Sum);
}
}
,,,
I'm getting stack overflow error in 'return recur(arr,len--,index++,Sum);'
'''
I think, the main problem here (see comments for potential other problems) is the way you are trying to pass changed arguments to the recursive invocation:
recur(arr,len--,index++,Sum)
Actually this will call recur with the unchanged values of len and index because the operators ++ and -- (when written on the right side of a variable) are defined to return the original value of the variable and then update the variable's value.
Use (I would prefer this)
recur(arr, len-1, index+1, Sum)
or (okay, but the assignment is not needed)
recur(arr, --len, ++index, Sum)
to actually pass the modified value to the function.
Java has a recursion limit. The way to fix this is replace the recursion with a loop. (Or change the function so it does not recur as much. Infinite loops are a problem just as infinite recursion is).
A few tips for the future:
Google the documentation for errors
State the language with a tag in posts
Don't use formatting of line 1
Debug with print statements

Why is this code correct while it should clearly run into an infinite loop?

I have been having a problem with this code for a while. The placement of recursive call of the function does not seem right.
i tried running the code and yes it does run into a infinite loop.
// I DEFINE HEAP STRUCTURE AS :
struct heap_array
{
int *array; // heap implementation using arrays(note : heap is atype of a tree).
int capacity; // how much the heap can hold.
int size; //how much size is currently occupied.
void MaxHeapify(struct heap_array *h,int loc) // note : loc is the location of element to be PERCOLATED DOWN.
{
int left,right,max_loc=loc;
left=left_loc_child(h,loc);
right=right_loc_child(h,loc);
if(left !=-1 && h->array[left]>h->array[loc])
{
max_loc=left;
}
if(right!=-1 && h->array[right]>h->array[max_loc])
{
max_loc=right;
}
if(max_loc!=loc) //i.e. if changes were made:
{
//swap the element at max_loc and loc
int temp=h->array[max_loc];
h->array[max_loc]=h->array[loc];
h->array[loc]=temp;
}
MaxHeapify(h,max_loc); // <-- i feel that this recursive call is misplaced. I have seen the exact same code in almost all the online videos and some books i referred to. ALSO I THINK THAT THE CALL SHOULD BE MADE WITHIN THE SCOPE OF condition if(max_loc!=loc).
//if no changes made, end the func right there.
}
In your current implementation, it looks like you don't have a base case for recursion to stop.
Remember that you need a base case in a recursive function (in this case, your MaxHeapify function), and it doesn't look like there is one.
Here is an example of MaxHeap which may be resourceful to look at
// A recursive function to max heapify the given
// subtree. This function assumes that the left and
// right subtrees are already heapified, we only need
// to fix the root.
private void maxHeapify(int pos)
{
if (isLeaf(pos))
return;
if (Heap[pos] < Heap[leftChild(pos)] ||
Heap[pos] < Heap[rightChild(pos)]) {
if (Heap[leftChild(pos)] > Heap[rightChild(pos)]) {
swap(pos, leftChild(pos));
maxHeapify(leftChild(pos));
}
else {
swap(pos, rightChild(pos));
maxHeapify(rightChild(pos));
}
}
}
Here, you can see the basecase of:
if (isLeaf(pos))
return;
You need to add a base case to your recursive function.

My GML shuffling array function is alway returning the same result

I'm trying to make a shuffling array function in GML. Here's what I tried, with argument0 being the array to shuffle and argument1 being the size of this array:
///Shuffling array function
//argument0: the array to shuffle
//argument1: the size of the array
var i;
var j;
show_debug_message("----------");
show_debug_message("Original array: ");
show_debug_message(argument0);
show_debug_message("Size: ");
show_debug_message(argument1);
for (i = 0; i < argument1; i++)
{
j = irandom_range(i, argument1 - 1);
if (i != j)
{
k = argument0[i];
argument0[i] = argument0[j];
argument0[j] = k;
}
}
show_debug_message("Result array: ");
show_debug_message(argument0);
show_debug_message("----------");
return argument0;
When I execute this function, I alway got the same result:
----------
Original array:
{ { 1,2,3,4,5 }, }
Size:
5
Result array:
{ { 5,3,1,4,2 }, }
----------
Have you used the function randomize() anywhere in your game? Randomize will set the seed to a random value each time your game is run — without it, random functions will always return the same result because they're always working with the same seed value.
NOTE: [Random functions] will return the same value every time the game is run afresh due to the fact that GameMaker: Studio generates the same initial random seed every time to make debugging code a far easier task. To avoid this behaviour use randomize at the start of your game.
Documentation on randomize(): https://docs.yoyogames.com/source/dadiospice/002_reference/maths/real%20valued%20functions/randomize.html

Rcpp keeps running for a seemingly simple task

I've been thinking about it all day and still cannot figure out why this happens. My objective is simple: STEP1, generate a function S(h,p); STEP2, numerically integrate S(h,p) with respect to p by trapezoidal rule and obtain a new function SS(h). I wrote the code and source it by sourceCpp, and it successfully generated two functions S(h,p) and SS(h) in R. But when I tried to test it by calculating SS(1), R just kept running and never gave the result, which is weird because the calculation amount is not that big. Any idea why this would happen?
My code is here:
#include <Rcpp.h>
using namespace Rcpp;
//generate the first function that gives S(h,p)
// [[Rcpp::export]]
double S(double h, double p){
double out=2*(h+p+h*p);
return out;
}
//generate the second function that gives the numerically integreation of S(h,p) w.r.t p
//[[Rcpp::export]]
double SS(double h){
double out1=0;
double sum=0;
for (int i=0;i<1;i=i+0.01){
sum=sum+S(h,i);
}
out1=0.01/2*(2*sum-S(h,0)-S(h,1));
return out1;
}
The problem is that you are treating i as if it were not an int in this statement:
for (int i=0;i<1;i=i+0.01){
sum=sum+S(h,i);
}
After each iteration you are attempting to add 0.01 to an integer, which is of course immediately truncated towards 0, meaning that i is always equal to zero, and you have an infinite loop. A minimal example highlighting the problem, with a couple of possible solutions:
#include <Rcpp.h>
// [[Rcpp::export]]
void bad_loop() {
for (int i = 0; i < 1; i += 0.01) {
std::printf("i = %d\n", i);
Rcpp::checkUserInterrupt();
}
}
// [[Rcpp::export]]
void good_loop() {
for (int i = 0; i < 100; i++) {
std::printf("i = %d\n", i);
Rcpp::checkUserInterrupt();
}
}
// [[Rcpp::export]]
void good_loop2() {
for (double j = 0.0; j < 1.0; j += 0.01) {
std::printf("j = %.2f\n", j);
Rcpp::checkUserInterrupt();
}
}
The first alternative (good_loop) is to scale your step size appropriately -- looping from 0 through 99 by 1 takes the same number of iterations as looping from 0 to 0.99 by 0.01. Additionally, you could just use a double instead of an int, as in good_loop2. At any rate, the main takeaway here is that you need to be more careful about choosing your variable types in C++. Unlike R, when you declare i to be an int it will be treated like an int, not a floating point number.
As #nrussell pointed out very expertly, there is an issue with treating i as an int when the type held is a double. The goal of posting this answer is to stress the need to avoid using a double or float as a loop incrementer. I've opted to post it as an answer instead of a comment for readability.
Please note, the loop increment should not ever be given as a double or a float due to precision issues. e.g. it is hard to get i = .99 since i = 0.981111111 et cetera...
Instead, I would opt to have the loop be processed as an int and convert it to a double / float as soon as possible, e.g.
for (int i=0; i < 100; i++){
// Make sure to use double division
// (e.g. either numerator or denominator is a floating / double)
sum += S(h, i/100.0);
}
Further notes:
RcppArmadillo and C++ division issue
Using float / double as a loop variable

A Boolean recursive function to tell if a digit appears in an integer an even number of times

The function gets an integer and a digit, and should return true
if the digit appears an even number of times in the integer, or false if not.
For example:
If digit=1 and num=1125
the function should return true.
If digit=1 and num=1234
the function should return false.
bool isEven(int num, int dig)
{
bool even;
if (num < 10)
even = false;
else
{
even = isEven(num/10,dig);
This is what I've got so far, and I'm stuck...
This is homework so please don't write the answer but hint me and help me get to it by myself.
To set up recursion, you need to figure out two things:
The base case. What is are the easy cases that you can handle outright? For example, can you handle single-digit numbers easily?
The rule(s) that reduce all other cases towards the base case. For example, can you chop off the last digit and somehow transform the solution for the remaning partial number into the solution for the full number?
I can see from your code that you've made some progress on both of these points. However, both are incomplete. For one thing, you are never using the target digit in your code.
The expression num%10 will give you the last digit of a number, which should help.
Your base case is incorrect because a single digit can have an even number of matches (zero is an even number). Your recursive case also needs work because you need to invert the answer for each match.
This funtion isEven() takes a single integer and returns the true if the number of occurence of numberToCheck is even.
You can change the base as well as the numberToCheck which are defined globally.
#include <iostream>
using std::cout;
using std::endl;
// using 10 due to decimal [change it to respective base]
const int base = 10;
const int numberToCheck = 5;
//Checks if the number of occurence of "numberToCheck" are even or odd
bool isEven(int n)
{
if (n == 0)
return 1;
bool hasNumber = false;
int currentDigit = n % base;
n /= base;
if (currentDigit == numberToCheck)
hasNumber = true;
bool flag = isEven(n);
// XOR GATE
return ((!hasNumber) && (flag) || (hasNumber) && (!flag));
};
int main(void)
{
// This is the input to the funtion IsEven()
int n = 51515;
if (isEven(n))
cout << "Even";
else
cout << "Odd";
return 0;
}
Using XOR Logic to integrate all returns
// XOR GATE
return ((!hasNumber) && (flag) || (hasNumber) && (!flag));

Resources