How to get random blocks(black & white) in board using JavaFX?
using:
Random ran = new Random()
here is a method, you can adapt it to your need :
private void ColoreBlock(Pane p){
Random random = new Random();
int randomNum = random.nextInt((1 - 0) + 1) + 0; // range (1-0) white/black
switch (randomNum) {
case 0:
p.setStyle("-fx-background-color:white;"); // -fx-fill for shape
break;
case 1:
p.setStyle("-fx-background-color:black;"); // -fx-fill for shape
break;
}
}
Related
I am drawing a Pythagoras Tree using L-system and 2 production rules. I managed to use the first rule called “F-rule” to draw the right handside of the tree. I tried using the second rule “H-rule” to draw the left handside. NO matter what I change in the H-rule, it messes up the result of the right handside. Any idea how I can create the leftside similar to the right ? Many thanks.
int SZ = 800;
Tree tree;
void settings() {
size(SZ,SZ);
}
void setup() {
int d = 100;
int x = SZ/2;
int y = SZ/2;
float branchAngle = radians(180);
float branchAngle_Left = radians(-45);
float branchAngle_Right = radians(45);
float initOrientation = PI;
String state = "F"; // initiator
float scaleFactor = 0.8;
String F_rule = "F[+sH]s+F";
String H_rule = "";
String f_rule = "";
int numIterations = 6;
background(255);
noLoop();
tree = new Tree(d, x, y, branchAngle, branchAngle_Right, branchAngle_Left, initOrientation, state, scaleFactor, F_rule, H_rule, f_rule, numIterations);
}
void draw() {
tree.draw();
}
class Tree {
int m_lineLength; // turtle line length
int m_x; // initial x position
int m_y; // initial y position
float m_branchAngle_Right; // turtle rotation at branch
float m_branchAngle_Left; // turtle rotation at branch
float m_branchAngle;
float m_initOrientation; // initial orientation
String m_state; // initial state
float m_scaleFactor; // branch scale factor
String m_F_rule; // F-rule substitution
String m_H_rule; // H-rule substitution
String m_f_rule; // f-rule substitution
int m_numIterations; // number of times to substitute
// constructor
// (d = line length, x & y = start position of drawing)
Tree(int d, int x, int y, float branchAngle, float branchAngle_Right, float branchAngle_Left, float initOrientation, String state, float scaleFactor,
String F_rule, String H_rule, String f_rule, int numIterations) {
m_lineLength = d;
m_x = x;
m_y = y;
m_branchAngle= branchAngle;
m_branchAngle_Right = branchAngle_Right;
m_branchAngle_Left = branchAngle_Left;
m_initOrientation = initOrientation;
m_state = state;
m_scaleFactor = scaleFactor;
m_F_rule = F_rule;
m_H_rule = H_rule;
m_f_rule = f_rule;
m_numIterations = numIterations;
// Perform L rounds of substitutions on the initial state
for (int k=0; k < m_numIterations; k++) {
m_state = substitute(m_state);
}
}
void draw() {
pushMatrix();
pushStyle();
stroke(0);
translate(m_x, m_y); // initial position
rotate(m_initOrientation); // initial rotation
for (int i=0; i < m_state.length(); i++) {
turtle(m_state.charAt(i));
}
popStyle();
popMatrix();
}
void turtle(char c) {
switch(c) {
case 'F': // drop through to next case
case 'H':
//line (0, 0, 0, m_lineLength);
rect(0, 0, m_lineLength, m_lineLength);
translate(0, m_lineLength);
break;
case 'f':
translate(0, m_lineLength);
break;
case 't':
translate(0, -m_lineLength);
break;
case 's':
scale(m_scaleFactor);
break;
case '&':
rotate(m_branchAngle);
break;
case '-':
rotate(m_branchAngle_Left);
break;
case '+':
rotate(m_branchAngle_Right);
break;
case '[':
pushMatrix();
break;
case ']':
popMatrix();
break;
default:
println("Bad character: " + c);
exit();
}
}
// apply substitution rules to string s and return the resulting string
String substitute(String s) {
String newState = new String();
for (int j=0; j < s.length(); j++) {
switch (s.charAt(j)) {
case 'F':
newState += m_F_rule;
break;
case 'H':
newState += m_H_rule;
break;
case 'f':
newState += m_f_rule;
break;
default:
newState += s.charAt(j);
}
}
return newState;
}
}
After a bit of research (1, 2, 3, 4, 5) I have arrived to a few conclusions. However, I haven't been able to find the H and F rules anywhere.
First of all I wouldn't recomend you setting two different angles since they are dependant as they form a right triangle. branchAngle_Right = 90 - branchAngle_Left
Moreover, for 45º, the fact that the scale factor is √2/2 (and not 0,8) is not arbitrary. It's due to trygonometric consequences. If we wanted to generalize it would be something like this: m_scaleFactor_Right = cos(m_branchAngle_Right), and the same for left.
Finally, i would try to redo, the tree generation as it seems to me that it has been overcomplicated. The fourth and the fith (in the coments) references atached at the begining are example codes. See how, in the fith one, it is being calculated the position of the new square and not translating from the previous square, which may be the cause of your problems when doing the left side backwards.
However, i do thing your code could work, but the efford you would put into it would be much larger than doing it from the begining and not overcomplicating.
If you still want to continue that way, please attach some information about those rules you were saying so we can help you.
I'm trying to learn concept about cuckoo search algorithm. Honestly, i'm learning cuckoo search using java source code. we know that cuckoo search using levy distribution for random walk. I have java source code impelements cuckoo search optimation , but i'm doubt that source code using levy distribution. Can anyone help me to inspect wheteher my source code using levy distribution or not?.
this is method that implements random walk..
public CSSolution randomWalk (OptimizationProblem prob, String distribution) {
int n = prob.getNumVar(); //2
// creates a neighborhood of size 1 times the scaling factor
double distanceSquared = Math.pow(rand.nextDouble() *
prob.getScalingFactor(),2);
System.out.println("distance Squared : "+distanceSquared);
// creates an ArrayList from 0 to n-1 (for indexing purposes only)
ArrayList<Integer> varIndices = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++) {
varIndices.add(i, i);
}
ArrayList<Double> vars = this.getVars();
CSSolution newSol = new CSSolution(this.numVars);
newSol.initializeWithNull();
ArrayList<Double> newVars = newSol.getVars();
for (int i = 0; i < n; i++) {
/* Chooses a random variable index from the indices
* of the remaining/unwalked variables. */
int index = rand.nextInt(varIndices.size());
// Finds the variable value that this index corresponds to.
int varIndex = varIndices.get(index);
// System.out.println("varIndicesSize:"+varIndices.size()+" index: "+index+" varIndex: "+varIndex);
double curVar = vars.get(varIndex);
// use correct distribution to generate random double [0,1)
double r;
if (distribution == "weibull"){
r = weibull.random(1.5, 1, new uniform());
}
else if(distribution == "levy"){
r = 0.0;
}
else
r = rand.nextDouble();
// alters this variable coefficient by adding a random step between (-distance,distance)
double distance = Math.sqrt(distanceSquared);
System.out.println("distance : "+distance+" distance Squared : "+distanceSquared);
double varStep = r*distance*2-distance;
double newVar = curVar + varStep;
// System.out.println("x"+varIndex+" : "+curVar+" to "+newVar);
newVars.set(varIndex, newVar);
// removes the variable that has already been visited
varIndices.remove(index);
// updates distance for next for loop
distanceSquared -= Math.pow(varStep, 2);
}
// System.out.println("");
return newSol;
}
source code : https://github.com/cloudrave/Optimizer
I have extracted raster data of a geotiff image using RasterIO of the GDAL library. Since the image shown by OpenGL needs to have width and height both a multiple of 4, I have used this code after extracting the data.
the first switch block evaluates the rest of RasterXSize(width) divided by 4 and for example if it is 1, it means that we should add 3 columns meaning that we should add 3 zeros at the end of each row. This is done by the code:
for ( int i = 1; i <= RasterYSize; i++)
pRasterData.insert(pRasterData.begin()+i*RasterXSize*depthOfPixel+(i-1)*3,3,0);
and the second switch block evaluates the rest of RasterYSize(height) divided by 4 and for example if it is 1, it means that we should easily add 3 rows to the end of the data which is done by this code:
pRasterData.insert(pRasterData.end(),3*RasterXSize,0);
This is the whole code that I have used for extracting the data and preparing it to be displayed by OpenGL:
void FilesWorkFlow::ReadRasterData(GDALDataset* poDataset)
{
RasterXSize = poDataset -> GetRasterXSize();
RasterYSize = poDataset -> GetRasterYSize();
RasterCount = poDataset -> GetRasterCount();
CPLErr error = CE_None;
GDALRasterBand *poRasterBand;
poRasterBand = poDataset -> GetRasterBand(1);
eType = poRasterBand -> GetRasterDataType();
BytesPerPixel = GDALGetDataTypeSize(eType) / 8;
depthOfPixel = RasterCount * BytesPerPixel;
pRasterData.resize(RasterXSize * RasterYSize * RasterCount * BytesPerPixel);
error = poDataset -> RasterIO(GF_Read,0,0,RasterXSize,RasterYSize,&pRasterData[0],RasterXSize,RasterYSize,eType,RasterCount,0,0,0,0);
int modRasterXSize = RasterXSize % 4;
switch (modRasterXSize)
{
case 1:
{
for ( int i = 1; i <= RasterYSize; i++)
pRasterData.insert(pRasterData.begin()+i*RasterXSize*depthOfPixel+(i-1)*3,3,0);
RasterXSize = RasterXSize+3;
break;
}
case 2:
{
for ( int i = 1; i <= RasterYSize; i++)
pRasterData.insert(pRasterData.begin()+i*RasterXSize*depthOfPixel+(i-1)*2,2,0);
RasterXSize = RasterXSize+2;
break;
}
case 3:
{
for ( int i = 1; i <= RasterYSize; i++)
pRasterData.insert(pRasterData.begin()+i*RasterXSize*depthOfPixel+(i-1)*1,1,0);
RasterXSize = RasterXSize+1;
break;
}
}
int modRasterYSize = RasterYSize % 4;
switch (modRasterYSize)
{
case 1:
{
pRasterData.insert(pRasterData.end(),3*RasterXSize,0);
RasterYSize = RasterYSize+3;
break;
}
case 2:
{
pRasterData.insert(pRasterData.end(),2*RasterXSize,0);
RasterYSize = RasterYSize+2;
break;
}
case 3:
{
pRasterData.insert(pRasterData.end(),1*RasterXSize,0);
RasterYSize = RasterYSize+1;
break;
}
}
}
the first switch block is where my code gets slow and because I am working with a 16997*15931 image it takes a lot of time for the program to run through the for loop.
Note that pRasterData is a member variable of the class FilesWorkFlow and because of the problems I had in sending this variable to the COpenGLControl class written by Brett Fowle in codeguru and used by me in the project with some slight changes, decided to use vector<unsigned char> instead of unsighned char*.
Now I am wondering is there anyway to implement these part of code faster using vectors?
Is there anyway to insert zero in certain parts of vector without using for loops and wasting too much time?
something like std::transform? I don't know!
Remember that I'm using MFC in Visual Studio 2010 and it's better for me to use STL but if you have another suggestions besides using vectors or STL, I'd be glad to hear that?
The reason it is slow is because the members of the vector are getting moved multiple times. Think about the members in the last row of your image. They all have to be moved once for every row of the image. It would be faster to create a whole new image, copying just the pixels you need from the original image and adding zeros where appropriate.
Here's an example:
void
padColumns(
std::vector<unsigned char> &old_image,
size_t old_width,
size_t new_width
)
{
size_t height = image.size() / old_width;
assert(image.size() == old_width*height);
std::vector<unsigned char> new_image(new_width * height);
for (size_t row=0; row!=height; ++row) {
std::copy(
old_image.begin() + row*old_width,
old_image.begin() + row*old_width + old_width,
new_image.begin() + row*new_width
);
std::fill(
new_image.begin() + row*new_width + old_width,
new_image.begin() + row*new_width + new_width,
0
);
}
old_image = new_image;
}
I am developing an XNA game that is using Kinect. The player seen on the screen is the real image of the person who is playing in front of Kinect sensor. For eliminating the background and getting only the player's image I am doing these operations in kinect.AllFramesReady:
using (ColorImageFrame colorVideoFrame = imageFrames.OpenColorImageFrame())
{
if (colorVideoFrame != null)
{
//Getting the image of the colorVideoFrame to a Texture2D named colorVideo
}
//And setting its information on a Color array named colors with GetData
colorVideo.GetData(colors);
}
using (DepthImageFrame depthVideoFrame = imageFrames.OpenDepthImageFrame())
{
if (depthVideoFrame != null){
//Copying the the image to a DepthImagePixel array
//Using only the pixels with PlayerIndex > 0 to create a Color array
//And then setting the colors of this array from the 'colors' array by using MapDepthPointToColorPoint method, provided by Kinect SDK
//Finally I use SetData function in order to set the colors to a Texture2D I created before
}
}
But the performance is very low unsurprisingly. Because I have to use GetData for a color array with 640*480 = 307200 length (because of the ColorImageFormat) and SetData for another color array with 320*480 = 76800 length (because of the DepthImageFormat) in every frame!
I wonder if there is any other solutions for this problem, any alternatives for SetData and GetData maybe. Because I know that these functions moving data between the GPU and CPU and that is an expensive operation for big data. Thanks for any help.
The Kinect for Windows Toolbox comes with a "GreenScreen-WPF" example, which should provide some insight into processing the information. Because you are working in XNA there may be some differences, but the overall concepts should work between the two examples.
The example works by extracting multiple players. Here is the business end of the processing function:
private void SensorAllFramesReady(object sender, AllFramesReadyEventArgs e)
{
// in the middle of shutting down, so nothing to do
if (null == this.sensor)
{
return;
}
bool depthReceived = false;
bool colorReceived = false;
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (null != depthFrame)
{
// Copy the pixel data from the image to a temporary array
depthFrame.CopyDepthImagePixelDataTo(this.depthPixels);
depthReceived = true;
}
}
using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
{
if (null != colorFrame)
{
// Copy the pixel data from the image to a temporary array
colorFrame.CopyPixelDataTo(this.colorPixels);
colorReceived = true;
}
}
// do our processing outside of the using block
// so that we return resources to the kinect as soon as possible
if (true == depthReceived)
{
this.sensor.CoordinateMapper.MapDepthFrameToColorFrame(
DepthFormat,
this.depthPixels,
ColorFormat,
this.colorCoordinates);
Array.Clear(this.greenScreenPixelData, 0, this.greenScreenPixelData.Length);
// loop over each row and column of the depth
for (int y = 0; y < this.depthHeight; ++y)
{
for (int x = 0; x < this.depthWidth; ++x)
{
// calculate index into depth array
int depthIndex = x + (y * this.depthWidth);
DepthImagePixel depthPixel = this.depthPixels[depthIndex];
int player = depthPixel.PlayerIndex;
// if we're tracking a player for the current pixel, do green screen
if (player > 0)
{
// retrieve the depth to color mapping for the current depth pixel
ColorImagePoint colorImagePoint = this.colorCoordinates[depthIndex];
// scale color coordinates to depth resolution
int colorInDepthX = colorImagePoint.X / this.colorToDepthDivisor;
int colorInDepthY = colorImagePoint.Y / this.colorToDepthDivisor;
// make sure the depth pixel maps to a valid point in color space
// check y > 0 and y < depthHeight to make sure we don't write outside of the array
// check x > 0 instead of >= 0 since to fill gaps we set opaque current pixel plus the one to the left
// because of how the sensor works it is more correct to do it this way than to set to the right
if (colorInDepthX > 0 && colorInDepthX < this.depthWidth && colorInDepthY >= 0 && colorInDepthY < this.depthHeight)
{
// calculate index into the green screen pixel array
int greenScreenIndex = colorInDepthX + (colorInDepthY * this.depthWidth);
// set opaque
this.greenScreenPixelData[greenScreenIndex] = opaquePixelValue;
// compensate for depth/color not corresponding exactly by setting the pixel
// to the left to opaque as well
this.greenScreenPixelData[greenScreenIndex - 1] = opaquePixelValue;
}
}
}
}
}
// do our processing outside of the using block
// so that we return resources to the kinect as soon as possible
if (true == colorReceived)
{
// Write the pixel data into our bitmap
this.colorBitmap.WritePixels(
new Int32Rect(0, 0, this.colorBitmap.PixelWidth, this.colorBitmap.PixelHeight),
this.colorPixels,
this.colorBitmap.PixelWidth * sizeof(int),
0);
if (this.playerOpacityMaskImage == null)
{
this.playerOpacityMaskImage = new WriteableBitmap(
this.depthWidth,
this.depthHeight,
96,
96,
PixelFormats.Bgra32,
null);
MaskedColor.OpacityMask = new ImageBrush { ImageSource = this.playerOpacityMaskImage };
}
this.playerOpacityMaskImage.WritePixels(
new Int32Rect(0, 0, this.depthWidth, this.depthHeight),
this.greenScreenPixelData,
this.depthWidth * ((this.playerOpacityMaskImage.Format.BitsPerPixel + 7) / 8),
0);
}
}
If you are interested in only a single player, you could look into using the player mask to more quickly extract the appropriate pixel set. You'd fi
using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
{
if (skeletonFrame != null && skeletonFrame.SkeletonArrayLength > 0)
{
if (_skeletons == null || _skeletons.Length != skeletonFrame.SkeletonArrayLength)
{
_skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
}
skeletonFrame.CopySkeletonDataTo(_skeletons);
// grab the tracked skeleton and set the playerIndex for use pulling
// the depth data out for the silhouette.
this.playerIndex = -1;
for (int i = 0; i < _skeletons.Length; i++)
{
if (_skeletons[i].TrackingState != SkeletonTrackingState.NotTracked)
{
this.playerIndex = i+1;
}
}
}
}
You can then step through the depth data to extract the appropriate bits:
depthFrame.CopyPixelDataTo(this.pixelData);
for (int i16 = 0, i32 = 0; i16 < pixelData.Length && i32 < depthFrame32.Length; i16++, i32 += 4)
{
int player = pixelData[i16] & DepthImageFrame.PlayerIndexBitmask;
if (player == this.playerIndex)
{
// the player we are tracking
}
else if (player > 0)
{
// a player, but not the one we want.
}
else
{
// background or something else we don't care about
}
}
I'm pulling this code from a control I use to produce a silhouette, so it does not deal with the color stream. However, making a call to MapDepthFrameToColorFrame at the appropriate time should allow you to deal with the color stream data and extract the corresponding pixels to the player's mask.
hi i am using Random class for getting random numbers but my requirement is once it generate one no that should not be repeate again pls help me.
Keep a list of the generated numbers and check this list before returning the next random.
Since you have not specified a language, I'll use C#
List<int> generated = new List<int>;
public int Next()
{
int r;
do { r = Random.Next() } while generated.Contains(r);
generated.Add(r);
return r;
}
The following C# code shows how to obtain 7 random cards with no duplicates. It is the most efficient method to use when your random number range is between 1 and 64 and are integers:
ulong Card, SevenCardHand;
int CardLoop;
const int CardsInDeck = 52;
Random RandObj = new Random(Seed);
for (CardLoop = 0; CardLoop < 7; CardLoop++)
{
do
{
Card = (1UL << RandObj.Next(CardsInDeck));
} while ((SevenCardHand & Card) != 0);
SevenCardHand |= Card;
}
If the random number range is greater than 64, then the next most efficient way to get random numbers without any duplicates is as follows from this C# code:
const int MaxNums = 1000;
int[] OutBuf = new int[MaxNums];
int MaxInt = 250000; // Reps the largest random number that should be returned.
int Loop, Val;
// Init the OutBuf with random numbers between 1 and MaxInt, which is 250,000.
BitArray BA = new BitArray(MaxInt + 1);
for (Loop = 0; Loop < MaxNums; Loop++)
{
// Avoid duplicate numbers.
for (; ; )
{
Val = RandObj.Next(MaxInt + 1);
if (BA.Get(Val))
continue;
OutBuf[Loop] = Val;
BA.Set(Val, true);
break;
}
}
The drawback with this technique is that it tends to use more memory, but it should be significantly faster than other approaches since it does not have to look through a large container each time a random number is obtained.