Problem with Random Integer in C Robotics - random

Okay, so basically, I'm trying to have my robot go forwards, until it detects a wall, then reverse, and then turn into a random direction. Problem is, it's only turning right. If anyone can help with this, I will be VERY appreciative, because I've spent about two days on it, and not even my teacher can figure out what's wrong with it. It is more of a robotics thing rather than just a code thing, but you can probably just ignore the motor/servo jargon. Thanks!
#include <PRIZM.h> // include PRIZM library
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RAND_MAX 1
PRIZM prizm; // instantiate a PRIZM object “prizm” so we can use its functions
void setup() {
prizm.PrizmBegin(); //initialize PRIZM
prizm.setServoSpeed(1,50);
prizm.setMotorInvert(1,1); // invert the direction of DC Motor 1
// to harmonize the direction of
// opposite facing drive motors
}
void loop() {
int x;
x = 1;
int r;
while((prizm.readSonicSensorCM(3) > 50)&&(x == 1))
{
prizm.setMotorPowers(40,40); // if distance greater than 25cm, do this
prizm.setServoPosition(1,146.75);
prizm.setServoPosition(2,55.5);
r = rand();
}
if((prizm.readSonicSensorCM(3) <= 50)||(x == 0))
{
x--;
prizm.setServoPosition(1, 54.5);
prizm.setServoPosition(2,145.25);
prizm.setMotorPowers(0,0);
delay(250);
prizm.setMotorPowers(-30,-30);
delay(750);
prizm.setMotorPowers(0,0);
delay(300);
if (r == 0) {
prizm.setMotorPowers(-50,50);
delay(1100);
}
else {
prizm.setMotorPowers(50,-50);
delay(1100);
}
prizm.setMotorPowers(0,0);
delay(200);
x++;
}
}

Note that your redefinition of RAND_MAX has no effect on the output of the rand() function. This is not a parameter for the function, but a constant telling you what the maximum value of the output is.
The best way to get a 50% of probability in your if (r == 0), is to go one side if r is even, the other if it is odd:
if ((r % 2) == 0) {
prizm.setMotorPowers(-50,50);
delay(1100);
}
else {
prizm.setMotorPowers(50,-50);
delay(1100);
}

Related

How to fill a fixed rectangle with square pieces entirely?

Is this knapsack algorithm or bin packing? I couldn't find an exact solution but basically I have a fixed rectangle area that I want to fill with perfect squares that represents my items where each have a different weight which will influence their size relative to others.
They will be sorted from large to smaller from top left to bottom right.
Also even though I need perfect squares, in the end some non-uniform scaling is allowed to fill the entire space as long as they still retain their relative area, and the non-uniform scaling is done with the least possible amount.
What algorithm I can use to achieve this?
There's a fast approximation algorithm due to Hiroshi Nagamochi and Yuusuke Abe. I implemented it in C++, taking care to obtain a worst-case O(n log n)-time implementation with worst-case recursive depth O(log n). If n ≤ 100, these precautions are probably unnecessary.
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
namespace {
struct Rectangle {
double x;
double y;
double width;
double height;
};
Rectangle Slice(Rectangle &r, const double beta) {
const double alpha = 1 - beta;
if (r.width > r.height) {
const double alpha_width = alpha * r.width;
const double beta_width = beta * r.width;
r.width = alpha_width;
return {r.x + alpha_width, r.y, beta_width, r.height};
}
const double alpha_height = alpha * r.height;
const double beta_height = beta * r.height;
r.height = alpha_height;
return {r.x, r.y + alpha_height, r.width, beta_height};
}
void LayoutRecursive(const std::vector<double> &reals, const std::size_t begin,
std::size_t end, double sum, Rectangle rectangle,
std::vector<Rectangle> &dissection) {
while (end - begin > 1) {
double suffix_sum = reals[end - 1];
std::size_t mid = end - 1;
while (mid > begin + 1 && suffix_sum + reals[mid - 1] <= 2 * sum / 3) {
suffix_sum += reals[mid - 1];
mid -= 1;
}
LayoutRecursive(reals, mid, end, suffix_sum,
Slice(rectangle, suffix_sum / sum), dissection);
end = mid;
sum -= suffix_sum;
}
dissection.push_back(rectangle);
}
std::vector<Rectangle> Layout(std::vector<double> reals,
const Rectangle rectangle) {
std::sort(reals.begin(), reals.end());
std::vector<Rectangle> dissection;
dissection.reserve(reals.size());
LayoutRecursive(reals, 0, reals.size(),
std::accumulate(reals.begin(), reals.end(), double{0}),
rectangle, dissection);
return dissection;
}
std::vector<double> RandomReals(const std::size_t n) {
std::vector<double> reals(n);
std::exponential_distribution<> dist;
std::default_random_engine gen;
for (double &real : reals) {
real = dist(gen);
}
return reals;
}
} // namespace
int main() {
const std::vector<Rectangle> dissection =
Layout(RandomReals(100), {72, 72, 6.5 * 72, 9 * 72});
std::cout << "%!PS\n";
for (const Rectangle &r : dissection) {
std::cout << r.x << " " << r.y << " " << r.width << " " << r.height
<< " rectstroke\n";
}
std::cout << "showpage\n";
}
Ok so lets assume integer positions and sizes (no float operations). To evenly divide rectangle into regular square grid (as big squares as possible) the size of the cells will be greatest common divisor GCD of the rectangle sizes.
However you want to have much less squares than that so I would try something like this:
try all square sizes a from 1 to smaller size of rectangle
for each a compute the naive square grid size of the rest of rectangle once a*a square is cut of it
so its simply GCD again on the 2 rectangles that will be created once a*a square is cut of. If the min of all 3 sizes a and GCD for the 2 rectangles is bigger than 1 (ignoring zero area rectangles) then consider a as valid solution so remember it.
after the for loop use last found valida
so simply add a*a square to your output and recursively do this whole again for the 2 rectangles that will remain from your original rectangle after a*a square was cut off.
Here simple C++/VCL/OpenGL example for this:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include "gl_simple.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
class square // simple square
{
public:
int x,y,a; // corner 2D position and size
square(){ x=y=a=0.0; }
square(int _x,int _y,int _a){ x=_x; y=_y; a=_a; }
~square(){}
void draw()
{
glBegin(GL_LINE_LOOP);
glVertex2i(x ,y);
glVertex2i(x+a,y);
glVertex2i(x+a,y+a);
glVertex2i(x ,y+a);
glEnd();
}
};
int rec[4]={20,20,760,560}; // x,y,a,b
const int N=1024; // max square number
int n=0; // number of squares
square s[N]; // squares
//---------------------------------------------------------------------------
int gcd(int a,int b) // slow euclid GCD
{
if(!b) return a;
return gcd(b, a % b);
}
//---------------------------------------------------------------------------
void compute(int x0,int y0,int xs,int ys)
{
if ((xs==0)||(ys==0)) return;
const int x1=x0+xs;
const int y1=y0+ys;
int a,b,i,x,y;
square t;
// try to find biggest square first
for (a=1,b=0;(a<=xs)&&(a<=ys);a++)
{
// sizes for the rest of the rectangle once a*a square is cut of
if (xs==a) x=0; else x=gcd(a,xs-a);
if (ys==a) y=0; else y=gcd(a,ys-a);
// min of all sizes
i=a;
if ((x>0)&&(i>x)) i=x;
if ((y>0)&&(i>y)) i=y;
// if divisible better than by 1 remember it as better solution
if (i>1) b=a;
} a=b;
// bigger square not found so use naive square grid division
if (a<=1)
{
t.a=gcd(xs,ys);
for (t.y=y0;t.y<y1;t.y+=t.a)
for (t.x=x0;t.x<x1;t.x+=t.a)
if (n<N){ s[n]=t; n++; }
}
// bigest square found so add it to result and recursively process the rest
else{
t=square(x0,y0,a);
if (n<N){ s[n]=t; n++; }
compute(x0+a,y0,xs-a,a);
compute(x0,y0+a,xs,ys-a);
}
}
//---------------------------------------------------------------------------
void gl_draw()
{
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glDisable(GL_TEXTURE_2D);
// set view to 2D [pixel] units
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-1.0,-1.0,0.0);
glScalef(2.0/float(xs),2.0/float(ys),1.0);
// render input rectangle
glColor3f(0.2,0.2,0.2);
glBegin(GL_QUADS);
glVertex2i(rec[0] ,rec[1]);
glVertex2i(rec[0]+rec[2],rec[1]);
glVertex2i(rec[0]+rec[2],rec[1]+rec[3]);
glVertex2i(rec[0] ,rec[1]+rec[3]);
glEnd();
// render output squares
glColor3f(0.2,0.5,0.9);
for (int i=0;i<n;i++) s[i].draw();
glFinish();
SwapBuffers(hdc);
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner):TForm(Owner)
{
// Init of program
gl_init(Handle); // init OpenGL
n=0; compute(rec[0],rec[1],rec[2],rec[3]);
Caption=n;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormDestroy(TObject *Sender)
{
// Exit of program
gl_exit();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormPaint(TObject *Sender)
{
// repaint
gl_draw();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormResize(TObject *Sender)
{
// resize
gl_resize(ClientWidth,ClientHeight);
}
//---------------------------------------------------------------------------
And preview for the actually hardcoded rectangle:
The number 8 in Caption of the window is the number of squares produced.
Beware this is just very simple startup example for this problem. I Have not tested it extensively so there is possibility once prime sizes or just unlucky aspect ratios are involved then this might result in really high number of squares... for example if GCD of the rectangle size is 1 (primes) ... In such case you should tweak the initial rectangle size (+/-1 or whatever)
The important thing in the code is just the compute() function and the global variables holding the output squares s[n]... beware the compute() does not clear the list (in order to allow recursion) so you need to set n=0 before its non recursive call.
To keep this simple I avoided to use any libs or dynamic allocations or containers for the compute itself...

why am i getting access violation error c++?

i am getting 0xc0000005 error(access violation error), where am i wrong in this code?
i couldnt debug this error. please help me.
question is this
Formally, given a wall of infinite height, initially unpainted. There occur N operations, and in ith operation, the wall is painted upto height Hi with color Ci. Suppose in jth operation (j>i) wall is painted upto height Hj with color Cj such that Hj >= Hi, the Cith color on the wall is hidden. At the end of N operations, you have to find the number of distinct colors(>=1) visible on the wall.
#include<iostream>
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main()
{
int t;
cin>>t;
for(int tt= 0;tt<t;tt++)
{
int h,c;
int temp = 0;
cin>>h>>c;
int A[h], B[c];
vector<int> fc;
for(int i = 0;i<h;i++)
{
cin>>A[i];
}
for(int j =0;j<h;j++)
{
cin>>B[j];
}
if(is_sorted(A,A+h))
{
return 1;
}
if(count(A,A+h,B[0]) == h)
{
return 1;
}
for(int i = 0;i<h;i++)
{
if(A[i]>=temp)
{
temp = A[i];
}
else
{
if(temp == fc[fc.size()-1])
{
fc[fc.size()-1] = B[i];
}
else
{
fc.push_back(B[i]);
}
}
}
}
}
There are several issues.
When reading values into B, your loop check is j<h. How many elements are in B?
You later look at fc[fc.size()-1]. This is Undefined Behavior if fc is empty, and is the likely source of your problem.
Other issues:
Don't use #include <bits/stdc++.h>
Avoid using namespace std;
Variable declarations like int A[h], where h is a variable, are not standard C++. Some compilers support them as an extension.

OpenCV and Mat::forEach operator not working in full image

I am trying to segment a depth image, so that values of depth between limits (low and high) remain the same, and values outside limits are set to 0.
To accomplish this I am trying to use the forEach method in OpenCV 3, to speed up the operation using all the available cores of the CPU.
Implementing the function this way, it works:
void Filter_Image(cv::Mat &img, int low, int high)
{
for (uint8_t &p : cv::Mat_<uint8_t>(img))
{
if(((p > low) && (p < high)) == false)
p = 0;
}
}
However, when I try to use the lambda expression, I only get correct results in one vertical third of the image (if you splitted the image in 3 columns, I only get the first left column well segmented). The code is as follows:
void Filter_Image(cv::Mat &img, int low, int high)
{
img.forEach<uint8_t>([&](uint8_t &p, const int * position) -> void {
if(((p > low) && (p < high)) == false)
p = 0;
});
}
The functions are called from this piece of code (simplified for testing):
#include "opencv/cv.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include "config_parser.h"
#include "background_substractor.h"
#include "object_tracker.h"
#include "roi_processing.h"
#include "filtering_functions.h"
using namespace cv;
int main(int argc, char **argv)
{
Mat opencv_frame;
namedWindow("Input Video");
//parse config
VIDEO_CONFIG videoConfig;
BACK_SUBS_CONFIG backSubsConfig;
TRACKER_CONFIG trackerConfig;
ROI_CONFIG roiConfig;
FILTERING_DATA filteringData;
Parse_Config("../Config/ConfigDepthImage.json", videoConfig, backSubsConfig, trackerConfig, filteringData, roiConfig);
Display_Config(videoConfig, backSubsConfig, trackerConfig, filteringData, roiConfig);
VideoCapture videoInput(videoConfig.path.c_str());
if (!videoInput.isOpened())
{
std::cout<<"Could not open reference video"<<std::endl;
return -1;
}
while (1)
{
videoInput >> opencv_frame;
if(opencv_frame.empty())
{
std::cout<<"Empty frame"<<std::endl;
destroyWindow("Input Video");
destroyWindow("Filtered Video");
break;
}
Filter_Image(opencv_frame, filteringData.min, filteringData.max);
//show video
imshow("Input Video", opencv_frame);
waitKey((1.0/videoConfig.fps)*1000);
}
return 0;
}
The difference in results can be observed in the displayed images:
This is the good one:
And this is the bad result in the same conditions using forEach:
I cannot see the error or the difference between the two functions. The type of the image is CV_8UC1.
Could anyone provide a clue?
Thank yo all very much in advance.

Sort odd and even numbers separatedly and move all odd numbers in front

For example, if the input array is
832461905
The output is
1357902468
I think this can be done in two steps
1) sort data
012345678
2) move odd numbers in front of even numbers by preserving order
To do so, we can have two pointers
Initially one points to the beginning and the other points to the end
Move the head util even numbers are found
The move the tail until odd numbers are found
Swap data at the pointers
Do the above until the two pointers meet
My question is if we can solve the problem by using one step rather than two
All you need is a little comp-function for sorting:
bool comp(int x, int y)
{
if (x % 2 == y % 2) return x < y;
return x % 2 > y % 2;
}
...
sort(your_array.begin(), your_array.end(), comp);
Yes, it can be done in one step.
Write your own comparison function, and use std::sort in C++:
sort(data.begin(),data.end(),comp);
bool comp(int x,int y)
{
if (x%2==0)
{
if(y%2==0)
{
return x<y; // if both are even
}
else
{
return false; // if only x is even
}
}
else
{
if(y%2==0)
{
return true;
}
else
{
return x<y;
}
}
}
Under the <algorithm> library in C++ you can use sort to order the numbers and then stable_partition to separate by odd and even.
Like so:
auto arr = std::valarray<int>{8,3,2,4,6,1,9,0,5};
std::sort(std::begin(arr), std::end(arr));
std::stable_partition(std::begin(arr), std::end(arr), [](int a){ return a % 2; });
Resulting in a rather succinct solution.
I am considering you are familiar with C++. See my code snippet, and yes it can be done in a step:
#include <iostream>
#include <stdio.h>
#include <algorithm>
bool function(int a, int b) {
if(a%2 != b%2) { /* When one is even and another is odd */
if(a&1) {
return true;
} else {
return false;
}
} else { /* When both are either odd or even */
return (a<b);
}
}
int main() {
int input[10005]; /* Input array */
int n = -1, i;
/* Take the input */
while(scanf("%i", &input[++n]) != EOF);
/* Sort according to desire condition */
std::sort(input, input+n, function);
/* Time to print out the values */
for(i=0; i<n; i++) {
std::cout << input[i] << " ";
}
return 0;
}
Any confusion, comments most welcome.

Optimized way to find if a number is a perfect square

I had a question in my assignment to find whether a number was perfect square or not:
Perfect square is an element of algebraic structure which is equal to
the square of another element.
For example: 4, 9, 16 etc.
What my friends did is, if n is the number, they looped n - 1 times calculating n * n:
// just a general gist
int is_square = 0;
for (int i = 2; i < n; i++)
{
if ((i * i) == n)
{
std::cout << "Yes , it is";
is_square = 1;
break;
}
}
if (is_square == 0)
{
std::cout << "No, it is not";
}
I came up with a solution as shown below:
if (ceil(sqrt(n)) == floor(sqrt(n)))
{
std::cout << "Yes , it is";
}
else
{
std::cout << "no , it is not";
}
And it works properly.
Can it be called as more optimized solution than others?
The tried and true remains:
double sqrt(double x); // from lib
bool is_sqr(long n) {
long root = sqrt(n);
return root * root == n;
}
You would need to know the complexity of the sqrt(x) function on your computer to compare it against other methods. By the way, you are calling sqrt(n) twice ; consider storing it into a variable (even if the compiler probably does this for you).
If using something like Newton's method, the complexity of sqrt(x) is in O(M(d)) where M(d) measures the time required to multiply two d-digits numbers. Wikipedia
Your friend's method does (n - 2) multiplications (worst case scenario), thus its complexity is like O(n * M(x)) where x is a growing number.
Your version only uses sqrt() (ceil and floor can be ignored because of their constant complexity), which makes it O(M(n)).
O(M(n)) < O(n * M(x)) - Your version is more optimized than your friend's, but is not the most efficient. Have a look at interjay's link for a better approach.
#include <iostream>
using namespace std;
void isPerfect(int n){
int ctr=0,i=1;
while(n>0){
n-=i;
i+=2;
ctr++;
}
if(!n)cout<<"\nSquare root = "<<ctr;
else cout<<"\nNot a perfect square";
}
int main() {
isPerfect(3);
isPerfect(2025);
return 0;
}
I don't know what limitations do you have but perfect square number definition is clear
Another way of saying that a (non-negative) number is a square number,
is that its square roots are again integers
in wikipedia
IF SQRT(n) == FLOOR(SQRT(n)) THEN
WRITE "Yes it is"
ELSE
WRITE "No it isn't"
examples sqrt(9) == floor(sqrt(9)), sqrt(10) == floor(sqrt(10))
I'll recommend this one
if(((unsigned long long)sqrt(Number))%1==0) // sqrt() from math library
{
//Code goes Here
}
It works because.... all Integers( & only positive integers ) are positive multiples of 1
and Hence the solution.....
You can also run a benchmark Test like;
I did with following code in MSVC 2012
#include <iostream>
#include <conio.h>
#include <time.h>
#include <math.h>
using namespace std;
void IsPerfect(unsigned long long Number);
void main()
{
clock_t Initial,Final;
unsigned long long Counter=0;
unsigned long long Start=Counter;
Start--;
cout<<Start<<endl;
Initial=clock();
for( Counter=0 ; Counter<=100000000 ; Counter++ )
{
IsPerfect( Counter );
}
Final=clock();
float Time((float)Final-(float)Initial);
cout<<"Calculations Done in "<< Time ;
getch();
}
void IsPerfect( unsigned long long Number)
{
if(ceil(sqrt(Number)) == floor(sqrt(Number)))
//if(((unsigned long long)sqrt(Number))%1==0) // sqrt() from math library
{
}
}
Your code took 13590 time units
Mine just 10049 time units
Moreover I'm using few extra steps that is Type conversion
like
(unsigned long long)sqrt(Number))
Without this it can do still better
I hope it helps .....
Have a nice day....
Your solutions is more optimized, but it may not work. Since sqrt(x) may return the true square root +/- epsilon, 3 different roots must be tested:
bool isPerfect(long x){
double k = round( sqrt(x) );
return (n==(k-1)*(k-1)) || (n==k*k) || (n==(k+1)*(k+1));
}
This is simple python code for finding perfect square r not:
import math
n=(int)(input())
giv=(str)(math.sqrt(n))
if(len(giv.split('.')[1])==1):
print ("yes")
else:
print ("No")

Resources