Calculate Values of Variables Found in an Interval with Java - constraint-programming

I am trying to find the values x and y may take so the following inequalities hold:
1/24 < 1/15*y < 1/10*x < 2/24 < 2/15*y < 3/24
Is there a way to formulate such a problem in Java?
Constraint Programming would probably solve such a problem but is there an alternative way?
If Constraint Programming is the only way, how does this look like?
The following is what I tried with constraint programming using or-tools. How to formulate strict inequalities?
MPSolver solver = new MPSolver(
"SimpleMipProgram", MPSolver.OptimizationProblemType.CBC_MIXED_INTEGER_PROGRAMMING);
// [END solver]
// [START variables]
double infinity = java.lang.Double.POSITIVE_INFINITY;
// x and y are float/double variables.
MPVariable x = solver.makeNumVar(0,1,"x"); //makeIntVar(0.0, infinity, "x");
MPVariable y = solver.makeNumVar(0,1,"y"); //makeIntVar(0.0, infinity, "y");
System.out.println("Number of variables = " + solver.numVariables());
// [END variables]
// [START constraints]
// x + 7 * y <= 17.5.
/*MPConstraint c0 = solver.makeConstraint(-1, 17.5, "c0");
c0.setCoefficient(x, 1);
c0.setCoefficient(y, 7);
// x <= 3.5.
MPConstraint c1 = solver.makeConstraint(-infinity, 3.5, "c1");
c1.setCoefficient(x, 1);
c1.setCoefficient(y, 0);*/
// 1/24 < 1/15*y ---> -1/15 * y < -1/24
MPConstraint c0 = solver.makeConstraint(-1000,-1/24.0,"c0");
c0.setCoefficient(y,-1/15.0);
// 1/15*y < 1/10*x ---> 1/15*y - 1/10*x < 0
MPConstraint c1 = solver.makeConstraint(-1000,0,"c1");
c1.setCoefficient(y,1/15.0);
c1.setCoefficient(x,-1/10.0);
// 1/10*x < 2/24 ---> 1/10*x < 2/24
MPConstraint c2 = solver.makeConstraint(-1000,2/24.0,"c2");
c2.setCoefficient(x,1/10.0);
// 2/24 < 2/15*y ---> -2/15*y < -2/24
MPConstraint c3 = solver.makeConstraint(-1000, -2/24.0);
c3.setCoefficient(y,-2/15.0);
// 2/15*y < 3/24 ---> 2/15*y < 3/24
MPConstraint c4 = solver.makeConstraint(-1000,3/24.0);
c4.setCoefficient(y,2/15.0);

Here is a working code using the integer solver
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model
model = cp_model.CpModel()
scale = 1000
x = model.NewIntVar(0, scale, 'x')
y = model.NewIntVar(0, scale, 'y')
# 1/24 < 1/15*y < 1/10*x < 2/24 < 2/15*y < 3/24
model.Add(5 * scale < 8 * y)
model.Add(8 * y < 12 * x)
model.Add(12 * x < 10 * scale)
model.Add(10 * scale < 16 * y)
model.Add(16 * y < 15 * scale)
solver = cp_model.CpSolver()
solver.parameters.log_search_progress = True
status = solver.Solve(model)
if status == cp_model.FEASIBLE:
print('x =', solver.Value(x) * 1.0 / scale)
print('y =', solver.Value(y) * 1.0 / scale)
With scale = 1000, it outputs:
x = 0.418
y = 0.626
With scale = 100, it outputs:
x = 0.43
y = 0.63
With scale = 10, it outputs
x = 0.5
y = 0.7

I found the solution by writing down a loop that produces random values until all the statements are fulfilled.
Now I am interested in how wolfram alpha solves such problems so quickly.
public class inequalities {
private static double x;
private static double y;
private static double Ratio3 = 1/24.0;
private static double Ratio2 = 1/15.0;
private static double Ratio1 = 1/10.0;
public static void main(String[] args) {
x = Math.random();
y = Math.random();
boolean loop = true;
while (loop) {
loop = calculatingTheInequalities();
if (loop) {
x = Math.random();
y = Math.random();
}
}
System.out.println("x value: " + x);
System.out.println("y value: " + y);
}
public static boolean calculatingTheInequalities() {
if (Ratio3<Ratio2*y && Ratio2*y<Ratio1*x &&
Ratio1*x<2*Ratio3 && 2*Ratio3<2*Ratio2*y &&
2*Ratio2*y<3*Ratio3) {
return false;
} else {
return true;
}
/*if (Ratio3 < Ratio2 *y) {
if (Ratio2 *y < Ratio1 *x) {
if (Ratio1 *x<2* Ratio3) {
if (2* Ratio3 < 2* Ratio2 *y) {
if (2* Ratio2 *y < 3* Ratio3) {
return false;
} else {
return true;
}
} else {
return true;
}
} else {
return true;
}
} else {
return true;
}
} else {
return true;
}*/
}
}

Related

Node isometric tile map render second layer problem

I'm building an isometric map tile image in Node and I'm stuck at the second layer rendering, I can't figure out how to adjust items in the y axis
Here's my code so far:
let i = 0;
for (let layer of map) {
const xTiles = layer.length;
const yTiles = layer[0].length;
for (let Xi = xTiles - 1; Xi >= 0; Xi--) {
for (let Yi = 0; Yi < yTiles; Yi++) {
const imgIndex = layer[Xi][Yi];
if (imgIndex == null || imgIndex == -1) {
continue;
}
const tile = tiles[imgIndex];
const offX = (Xi * tileColOffset / 2 + Yi * tileColOffset / 2 + originX) + (i * ((tileColOffset - tile.width) / 2));
const offY = (Yi * tileRowOffset / 2 - Xi * tileRowOffset / 2 + originY) - (i * ((tileRowOffset / 2)));
ctx.drawImage(tile, offX, offY);
}
}
i++;
}
I can center the sprite on the x axis but not on the y one, probably because sprites have different heights. The code above reproduces this
As you can see the taller sprites are quite centered, but the small ones are not. Any suggestion?
Thanks!
Just found out that I have to calculate the difference between the half height of the ground tile and the height of the sprite:
let i = 0;
for (let layer of map) {
const xTiles = layer.length;
const yTiles = layer[0].length;
for (let Xi = xTiles - 1; Xi >= 0; Xi--) {
for (let Yi = 0; Yi < yTiles; Yi++) {
const imgIndex = layer[Xi][Yi];
if (imgIndex == null || imgIndex == -1) {
continue;
}
const tile = tiles[imgIndex];
let offX, offY
if (i === 0) {
offX = (Xi * tileColOffset / 2 + Yi * tileColOffset / 2 + originX);
offY = (Yi * tileRowOffset / 2 - Xi * tileRowOffset / 2 + originY);
} else {
offX = (Xi * tileColOffset / 2 + Yi * tileColOffset / 2 + originX) + (i * ((tileColOffset - tile.width) / 2));
offY = (Yi * tileRowOffset / 2 - Xi * tileRowOffset / 2 + originY) + ((i * (tileRowOffset / 2 - tile.height)));
}
ctx.drawImage(tile, offX, offY);
}
}
i++;
}

How to make function call other like callback

Heres what I want (image):
Main Idea is:
InputField is a function that calls something if input value changed.
For example: you have text input field in game and you add text to it, when value doesnt change until like 1 second it will call code like g_Engine.ChangeName()
Heres also callback class, but I dont know how to do it still please help
Code:
typedef void (*fn_callback)(void);
class pCallback
{
public:
pCallback(fn_callback callback);
fn_callback callback_void{ nullptr };
};
class CMenu
{
private:
void InputField(int x, int y, char* text, int maxLen, int& out, ...);
};
extern CMenu g_Menu;
void CMenu::InputField(int x, int y, char* text, int maxLen, int& out, ...)
{
unsigned int w = 220;
unsigned int h = 16;
g_pISurface->DrawSetColor(cvar.cheat_global_color_r, cvar.cheat_global_color_g, cvar.cheat_global_color_b, 255);
g_pISurface->DrawOutlinedRect(x - 2, y - 2, x + w + 2, y + h + 2);
bool clicked = false;
static DWORD dwTemporaryBlockTimer = 0;
static std::string value;
if (GetTickCount() - dwPaletteBlockedTime > 200 && GetTickCount() - dwListBlockedTime > 200 && !bCursorInPalette && !bCursorInList && keys[VK_LBUTTON] && !IsDragging && CursorX >= x && CursorX <= x + w && CursorY >= y && CursorY <= y + h)
{
if (GetTickCount() - dwTemporaryBlockTimer > 200)
{
clicked = true;
dwTemporaryBlockTimer = GetTickCount();
}
}
if (clicked || CursorX >= x && CursorX <= x + w && CursorY >= y && CursorY <= y + h)
{
g_pISurface->DrawSetColor(cvar.cheat_global_color_r, cvar.cheat_global_color_g, cvar.cheat_global_color_b, 255);
g_pISurface->DrawOutlinedRect(x - 1, y - 1, x + w + 1, y + h + 1);
}
if (text)
g_Drawing.DrawString(MENU, x + 1, y - 10, 215, 215, 215, 255, FONT_LEFT, text);
if (GetTickCount() - dwInputfieldBlockedTime > 200 && !bCursorInPalette && !bCursorInList && !IsDragging && CursorX >= x && CursorX <= x + w && CursorY >= y && CursorY <= y + h)
{
if (maxLen != 0)
{
if (!(value.length() > maxLen))
value.append(GetPressedNumKeyString());
}
if (keys[VK_BACK])
{
if (!value.empty())
value.erase(std::prev(value.end()));
}
dwInputfieldBlockedTime = GetTickCount();
}
int iVal = std::atoi(value.c_str());
if (out != iVal)
out = iVal;
if (!value.empty())
g_Drawing.DrawString(MENU, x + w / 2, y + (h / 2), 220, 220, 220, 255, FONT_CENTER, value.c_str());
else
g_Drawing.DrawString(MENU, x + w / 2, y + (h / 2), 81, 81, 81, 255, FONT_CENTER, "N/A");
}
I think I did it
void CMenu::InputField(int x, int y, char* text, int maxLen, int& out, std::function<void()>&& Callback)
{
if (out != iVal)
{
out = iVal;
Callback();
}
}
InputField(x + box_indent_x, y + line_y, "SteamID", 31, SID, []() { g_SteamID.Apply(SID); });

CS50 Pset4 Sepia Filter, where is the bug? The code doesn't pass the CS50 tests

So this is the code I have for Pset4 for the Sepia filter...it's heading in the right direction but I've been trying to figure out why it isn't passing the tests. Cannot filter a simple 3 x 3 image or complex 3 x 3 image or the 4 x 4 image. Trying to figure out where the bug is, any tips would be wonderful!
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// get values of each colour in the image
int red = image[i][j].rgbtRed;
int blue = image[i][j].rgbtBlue;
int green = image[i][j].rgbtGreen;
// find average of the pixel RBG colors
float average = (round(red) + round(blue) + round(green)) / 3;
average = round(average);
//puts the value average into the pixel colors
image[i][j].rgbtRed = average;
image[i][j].rgbtBlue = average;
image[i][j].rgbtGreen = average;
}
}
return;
}
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
//gets the values of each color in the image
int red = image[i][j].rgbtRed;
int blue = image[i][j].rgbtBlue;
int green = image[i][j].rgbtGreen;
// gets the sepia value of the pixels
int sepiaRed = round(0.393 * red + 0.769 * green + 0.189 * blue);
int sepiaGreen = round(0.349 * red + 0.686 * green + 0.168 * blue);
int sepiaBlue = round(0.272 * red + 0.534 * green + 0.131 * blue);
if (sepiaRed >= 256)
{
sepiaRed = 255;
}
if (sepiaGreen >= 256)
{
sepiaGreen = 255;
}
if (sepiaBlue >= 256)
{
sepiaBlue= 255;
}
image[i][j].rgbtRed = sepiaRed;
image[i][j].rgbtBlue = sepiaBlue;
image[i][j].rgbtGreen = sepiaGreen;
}
return;
}
}
I'm not sure, without seeing more of the code. But shouldn't these three ifs at the end be placed before you save their values to the image? Like this:
...
if (sepiaRed >= 256)
{
sepiaRed = 255;
}
if (sepiaGreen >= 256)
{
sepiaGreen = 255;
}
if (sepiaBlue >= 256)
{
sepiaBlue = 255;
}
image[i][j].rgbtRed = sepiaRed;
image[i][j].rgbtBlue = sepiaBlue;
image[i][j].rgbtGreen = sepiaGreen;
...
First You check if calculated values are not higher than 255. Then save these values to the image.
Also you should replace 'else if' with 'if' to check all 3 values not up to one. And then edit value of sepiaRed, sepiaBlue, sepiaGreen not red, blue, green.
I'm not sure if I get right what that function suppose to do.
you have to use the math function round(), mine just working fine.
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
//gets the values of each color in the image
int red = image[i][j].rgbtRed;
int blue = image[i][j].rgbtBlue;
int green = image[i][j].rgbtGreen;
// gets the sepia value of the pixels
int sepiaRed = round(0.393 * red + 0.769 * green + 0.189 * blue) ;
int sepiaGreen = round(0.349 * red + 0.686 * green + 0.168 * blue) ;
int sepiaBlue = round(0.272 * red + 0.534 * green + 0.131 * blue) ;
if (sepiaRed >= 256)
{
sepiaRed = 255;
}
if (sepiaGreen >= 256)
{
sepiaGreen = 255;
}
if (sepiaBlue >= 256)
{
sepiaBlue= 255;
}
image[i][j].rgbtRed = sepiaRed;
image[i][j].rgbtBlue = sepiaBlue;
image[i][j].rgbtGreen = sepiaGreen;
}
}

What does the value 0.5 represent here?

This is an implementation of Naive Bayes Classifier Algorithm.
I couldn't understand the line score.Add(results[i].Name, finalScore * 0.5);.
Where does this value 0.5 come from?
Why 0.5? Why not any other value?
public string Classify(double[] obj)
{
Dictionary<string,> score = new Dictionary<string,>();
var results = (from myRow in dataSet.Tables[0].AsEnumerable()
group myRow by myRow.Field<string>(
dataSet.Tables[0].Columns[0].ColumnName) into g
select new { Name = g.Key, Count = g.Count() }).ToList();
for (int i = 0; i < results.Count; i++)
{
List<double> subScoreList = new List<double>();
int a = 1, b = 1;
for (int k = 1; k < dataSet.Tables["Gaussian"].Columns.Count; k = k + 2)
{
double mean = Convert.ToDouble(dataSet.Tables["Gaussian"].Rows[i][a]);
double variance = Convert.ToDouble(dataSet.Tables["Gaussian"].Rows[i][++a]);
double result = Helper.NormalDist(obj[b - 1], mean, Helper.SquareRoot(variance));
subScoreList.Add(result);
a++; b++;
}
double finalScore = 0;
for (int z = 0; z < subScoreList.Count; z++)
{
if (finalScore == 0)
{
finalScore = subScoreList[z];
continue;
}
finalScore = finalScore * subScoreList[z];
}
score.Add(results[i].Name, finalScore * 0.5);
}
double maxOne = score.Max(c => c.Value);
var name = (from c in score
where c.Value == maxOne
select c.Key).First();
return name;
}
I figured it out.
0.5 is the apriori probability.

(computer graphics) radial image distortion

I need to create an effect, that radially distorts a bitmap, by stretching or shrinking its "layers of pixels" radially (as shown on the image):
http://i.stack.imgur.com/V6Voo.png
by colored circles (their thickness) is shown the transform, that is applied to the image
What approach should I take? I have a bitmap (array of pixels) and an another bitmap, that should be the result of such a filter applied (as a result, there should be some kind of a round water ripple on the bitmap).
Where could I read about creating such effects?
Thank you.
Try to look here
http://www.jhlabs.com/ip/blurring.html
Zoom and Spin Blur
it is Java but nevertheless it could be fit to your request.
Well, the most accurate results would come from mapping the euclidean coordinates to a polar matrix. Then you would very easily be able to stretch them out. Then just translate them back to a euclidean representation and save. I'll write and edit with some code in a second.
Alright I got a bit carried away but here's my code. It will take a bitmap, convert it to and from polar coordinates and save it. now, radial based distortion should be a breeze.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define PI 3.141592654
#define C_R 1000
#define C_S 1000
#define C_M 2000
typedef struct{ int r,g,b; } color;
typedef struct{ int t; color* data; int w, h; } bitmap;
typedef struct{ int t; color* data; int r, s, w, h; } r_bitmap;
bitmap* bmp_load_from_file( const char* fname ){
FILE* b = fopen( fname, "rb" );
if( b <= 0 ) return 0;
int num;
fscanf( b, "BM%n", &num );
if( num < 2 ) return 0;
struct{ int size, reserved, offset;
int hsize, wid, hig, planes:16, bpp:16, comp, bmpsize, hres, vres, colors, important; } head;
fread( &head, 13, 4, b );
bitmap* bmp = malloc( sizeof( bitmap ) );
bmp->data = malloc( head.wid * head.hig * sizeof( color ) );
bmp->w = head.wid;
bmp->h = head.hig;
for( int y = head.hig - 1; y >= 0; --y ){
int x;
for( x = 0; x < head.wid; ++x ){
color t;
t.r = fgetc( b );
t.g = fgetc( b );
t.b = fgetc( b );
bmp->data[x+y*bmp->w] = t;
}
x*=3;
while( x%4 != 0 ){
++x;
fgetc( b );
}
}
bmp->t = 0;
fclose( b );
return bmp;
}
void bmp_save( const char* fname, bitmap* bmp ){
FILE* b = fopen( fname, "wb" );
if( b <= 0 ) return 0;
struct{ int size, reserved, offset;
int hsize, wid, hig, planes:16, bpp:16, comp, bmpsize, hres, vres, colors, important; } head;
fprintf( b, "BM" );
head.size = 3 * (bmp->w+4)/4*4 * bmp->h + 54;
head.offset = 54;
head.hsize = 40;
head.wid = bmp->w;
head.hig = bmp->h;
head.planes = 1;
head.bpp = 24;
head.comp = 0;
head.bmpsize = 3 * (bmp->w+4)/4*4 * bmp->h;
head.hres = 72;
head.vres = 72;
head.colors = 0;
head.important = 0;
fwrite( &head, 13, 4, b );
for( int y = bmp->h - 1; y >= 0; --y ){
int x;
for( x = 0; x < bmp->w; ++x ){
fputc( bmp->data[x + y * bmp->w].r, b );
fputc( bmp->data[x + y * bmp->w].g, b );
fputc( bmp->data[x + y * bmp->w].b, b );
}
x*=3;
while( x % 4 != 0 ){
++x;
fputc(0, b);
}
}
fclose( b );
}
color color_mix( color a, color b, int offset ){ /*offset is a value between 0 and 255 to determine the weight. the lower it is the more color a gets*/
//if( offset > 255 || offset < 0)
//printf("%i\t", offset);
a.r += ( b.r - a.r ) * offset / 255;
a.g += ( b.g - a.g ) * offset / 255;
a.b += ( b.b - a.b ) * offset / 255;
return a;
}
r_bitmap* bmp_to_r( bitmap* b ){
r_bitmap* r = malloc( sizeof( r_bitmap ) );
r->t = 1;
int radius = sqrt( b->w * b->w + b->h * b->h ) / 2 * C_R / C_M + 2;
int step = C_S * ( b->w + b->h ) / C_M;
r->data = malloc( radius * step * sizeof( color ) );
r->r = radius;
r->s = step;
r->w = b->w;
r->h = b->h;
color black = {0, 0, 0};
for( double i = 0; i < radius; ++ i ){
for( double j = 0; j < step; ++j ){
double x = i * C_M * cos( 2 * PI * j / step ) / C_R + b->w / 2;
double y = i * C_M * sin( 2 * PI * j / step ) / C_R + b->h / 2;
int ix = x;
int iy = y;
if( x < 0 || x >= b->w || y < 0 || y >= b->h )
r->data[(int)(j + i * step)] = black;
else{
color tmp = b->data[ix + iy * b->w];
if( iy < b->h - 1 ){
int off = 255 * (y - iy);
tmp = color_mix( tmp, b->data[ix + (iy+1) * b->w], off );
}
if( ix < b->w - 1 ){
int off = 255 * ( x - ix );
tmp = color_mix( tmp, b->data[ix +1 + iy * b->w], off );
}
r->data[(int)(j + i * step)] = tmp;
}
}
}
return r;
}
bitmap* bmp_from_r( r_bitmap* r ){
bitmap* b = malloc( sizeof( bitmap ) );
b->t = 0;
b->data = malloc( r->w * r->h * sizeof( color ) );
b->w = r->w;
b->h = r->h;
for( int y = 0; y < b->h; ++y ){
for( int x = 0; x < b->w; ++x ){
int tx = x - b->w/2;
int ty = y - b->h/2;
double rad = sqrt( tx*tx+ty*ty ) * C_R / C_M;
double s = atan2( ty, tx );
if( s < 0 ) s += 2 * PI;
s *= r->s / ( 2 * PI );
int is = s;
int irad = rad;
color tmp = r->data[(int)(is + irad * r->s)];
/*if( x > 0 && x < r->w - 1 && y > 0 && y < r->h - 1 ){
tmp = color_mix(tmp, r->data[((int)(is+1)%r->s + irad * r->s)], abs(255* rad - floor(rad)));
tmp = color_mix(tmp, r->data[(is + (irad + 1) * r->s)], abs(255* s - floor(s)));
}*/
b->data[x+y*b->w] = tmp;
}
}
return b;
}
int main( ) {
bitmap* b = bmp_load_from_file( "foo.bmp" );
r_bitmap* r = bmp_to_r( b );
bitmap* c = bmp_from_r( r );
bmp_save( "lol.bmp", c );
}

Resources