Parking Spot function given parking lot array, and car dimension - dynamic-programming

I was doing the coding challenges on Codefights, sponsored by Uber and there was a problem that I was unable to solve. For the question, you can look here http://codepen.io/ducminhn/pen/JYmrmE.
I believe that this problem is related with Dynamic Programming, so I tagged this problem as Dynamic programming, but I am still learning Java, so please inform me if I am wrong.
This is what I have so far, and I believe that my logic may not be correct inside the nested for loop. If anyone could please review my code and fix it for me.
Thanks in advance,
boolean parkingSpot(int[] carDimensions, int[][] parkingLot, int[] luckySpot) {
int carx = carDimensions[0];
int cary = carDimensions[1];
boolean result = false;
for(int l=0;l<parkingLot.length;l++){
for(int k=0;k<parkingLot.length;k++){
if(l == luckySpot[0]){
for(int i=luckySpot[0];i<carx;i++){
if(k== luckySpot[1]){
for(int j= luckySpot[1];j<cary;j++){
if(parkingLot[i][j] != 0){
result = false;
}
}
}
}
}
}
}
return true;
}

This seems more complicated than what you did... so not too sure if it helps. I just tested it against the given examples but if I'm not completely misunderstanding the problem, you can just use a couple of loops, so there's no obvious use of Dynamic Programming.
static boolean h(int[] luckySpot,int[][] parkingLot){
// check if parking spot given contains a 1
// (check if it's a valid parking spot)
for(int i=luckySpot[0];i<=luckySpot[2];i++){
for(int j=luckySpot[1];j<=luckySpot[3];j++){
if(parkingLot[i][j]==1) return false;
}
}
// check if the car parked vertically
if( Math.abs(luckySpot[0]-luckySpot[2]) >
Math.abs(luckySpot[1]-luckySpot[3])) {
// check for empty path going to the top
outerloop:
for(int i=0;i<luckySpot[0];i++){
for(int j=luckySpot[1];j<=luckySpot[3];j++){
if(parkingLot[i][j]==1) break outerloop;
}
if(i==luckySpot[0]-1) return true;
}
// check for empty path going to the bottom
for(int i=luckySpot[2]+1;i<parkingLot.length;i++){
for(int j=luckySpot[1];j<=luckySpot[3];j++){
if(parkingLot[i][j]==1) return false;
}
if(i==parkingLot.length-1) return true;
}
}
// the car parked horizontally
else{
// check for empty path going to the left
outerloop:
for(int i=luckySpot[0];i<=luckySpot[2];i++){
for(int j=0;j<luckySpot[1];j++){
if(parkingLot[i][j]==1) break outerloop;
}
if(i==luckySpot[2]) return true;
}
// check for empty path going to the right
for(int i=luckySpot[0];i<=luckySpot[2];i++){
for(int j=luckySpot[3]+1;j<parkingLot[0].length;j++){
if(parkingLot[i][j]==1) return false;
}
if(i==luckySpot[2]) return true;
}
}
return false;
}
public static void main(String[] args) {
/*
"for safety reasons, the car can only move in two directions inside
the parking lot -- forwards or backwards along the long side of the car"
i assume this to mean that the direction the car travels is parallel
to the long side of the car
*/
int[] carDimensions = {3, 2};
int [][] parkingLot = {
{1, 0, 1, 0, 1, 0},
{1, 0, 0, 0, 1, 0},
{1, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 1, 1}
};
int[] luckySpot={1, 1, 2, 3};
System.out.println(h(luckySpot,parkingLot));
}

Related

How to have different color brushes using multi touch?

I am trying to make it so each finger on the screen has a different color as it paints its path. I am using pointers to create the path and toyed with assigning the pointer IDs a different color per number but no result. In the code below I am trying to make the first finger blue then when another finger begins drawing it would turn red. Currently the code makes all the paint blue but when 3 fingers are on the screen it all changes red. Any help is appreciated thank you
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(idColor == 1)
mFingerPaint.setColor(Color.BLUE);
if(idColor == 2)
mFingerPaint.setColor(Color.RED);
for (Path completedPath : mCompletedPaths) {
canvas.drawPath(completedPath, mFingerPaint);
}
for (Path fingerPath : mFingerPaths) {
if (fingerPath != null) {
canvas.drawPath(fingerPath, mFingerPaint);
}
}
}
public boolean onTouchEvent(MotionEvent event) {
int pointerCount = event.getPointerCount();
int cappedPointerCount = pointerCount > MAX_FINGERS ? MAX_FINGERS : pointerCount;
// get pointer index from the event object
int actionIndex = event.getActionIndex();
// get masked (not specific to a pointer) action
int action = event.getActionMasked();
// get pointer ID
int id = event.getPointerId(actionIndex);
idColor = id;
if ((action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) && id < MAX_FINGERS)
{
mFingerPaths[id] = new Path();
mFingerPaths[id].moveTo(event.getX(actionIndex), event.getY(actionIndex));
}
else if ((action == MotionEvent.ACTION_POINTER_UP || action == MotionEvent.ACTION_UP) && id < MAX_FINGERS)
{
mFingerPaths[id].setLastPoint(event.getX(actionIndex), event.getY(actionIndex));
mCompletedPaths.add(mFingerPaths[id]);
mFingerPaths[id].computeBounds(mPathBounds, true);
invalidate((int) mPathBounds.left, (int) mPathBounds.top, (int) mPathBounds.right, (int) mPathBounds.bottom);
mFingerPaths[id] = null;
}
for(int i = 0; i < cappedPointerCount; i++) {
if(mFingerPaths[i] != null)
{
int index = event.findPointerIndex(i);
mFingerPaths[i].lineTo(event.getX(index), event.getY(index));
mFingerPaths[i].computeBounds(mPathBounds, true);
invalidate((int) mPathBounds.left, (int) mPathBounds.top, (int) mPathBounds.right, (int) mPathBounds.bottom);
}
}
return true;
}
}

Index out of range exception while reading pixel data

Related post: Stride of the BitmapData is different than the original
dimension.
I have taken the source code from here and modified it.
The code is generating a variety of exceptions in different occasions.
.
Error in BitmapLocker.cs
At the following line in Lock(),
// Copy data from IntegerPointer to _imageData
Marshal.Copy(IntegerPointer, _imageData, 0, _imageData.Length);
The following exception is being generated:
An unhandled exception of type 'System.AccessViolationException'
occurred in mscorlib.dll
Additional information: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
For the following driver code,
double[,] mask = new double[,]
{
{ .11, .11, .11, },
{ .11, .11, .11, },
{ .11, .11, .11, },
};
Bitmap bitmap = ImageDataConverter.ToBitmap(mask);
BitmapLocker locker = new BitmapLocker(bitmap);
locker.Lock();
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
Color c = locker.GetPixel(i, j);
locker.SetPixel(i, j, c);
}
}
locker.Unlock();
At the following line in GetPixel(),
if (i > dataLength)
{
throw new IndexOutOfRangeException();
}
An unhandled exception of type 'System.IndexOutOfRangeException'
occurred in Simple.ImageProcessing.Framework.dll
Additional information: Index was outside the bounds of the array.
.
At the following line in SetPixel(),
if (ColorDepth == 8)
{
_imageData[i] = color.B;
}
An unhandled exception of type 'System.Exception' occurred in
Simple.ImageProcessing.Framework.dll
Additional information: (0, 0), 262144, Index was outside the bounds
of the array., i=262144
.
Error in Driver program
At the line,
Color c = bmp.GetPixel(i, j);
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Drawing.dll
Additional information: Bitmap region is already locked.
Source Code:
public class BitmapLocker : IDisposable
{
//private properties
Bitmap _bitmap = null;
bool _isLocked = false;
BitmapData _bitmapData = null;
private byte[] _imageData = null;
//public properties
public IntPtr IntegerPointer { get; private set; }
public int Width { get { return _bitmap.Width; } }
public int Height { get { return _bitmap.Height; } }
public int Stride { get { return _bitmapData.Stride; } }
public int ColorDepth { get { return Bitmap.GetPixelFormatSize(_bitmap.PixelFormat); } }
public int Channels { get { return ColorDepth / 8; } }
public int PaddingOffset { get { return _bitmapData.Stride - (_bitmap.Width * Channels); } }
public PixelFormat ImagePixelFormat { get { return _bitmap.PixelFormat; } }
public bool IsGrayscale { get { return Grayscale.IsGrayscale(_bitmap); } }
//Constructor
public BitmapLocker(Bitmap source)
{
IntegerPointer = IntPtr.Zero;
this._bitmap = source;
}
/// Lock bitmap
public void Lock()
{
if (_isLocked == false)
{
try
{
// Lock bitmap (so that no movement of data by .NET framework) and return bitmap data
_bitmapData = _bitmap.LockBits(
new Rectangle(0, 0, _bitmap.Width, _bitmap.Height),
ImageLockMode.ReadWrite,
_bitmap.PixelFormat);
// Create byte array to copy pixel values
int noOfBitsNeededForStorage = _bitmapData.Stride * _bitmapData.Height;
int noOfBytesNeededForStorage = noOfBitsNeededForStorage / 8;
_imageData = new byte[noOfBytesNeededForStorage * ColorDepth];//# of bytes needed for storage
IntegerPointer = _bitmapData.Scan0;
// Copy data from IntegerPointer to _imageData
Marshal.Copy(IntegerPointer, _imageData, 0, _imageData.Length);
_isLocked = true;
}
catch (Exception)
{
throw;
}
}
else
{
throw new Exception("Bitmap is already locked.");
}
}
/// Unlock bitmap
public void Unlock()
{
if (_isLocked == true)
{
try
{
// Copy data from _imageData to IntegerPointer
Marshal.Copy(_imageData, 0, IntegerPointer, _imageData.Length);
// Unlock bitmap data
_bitmap.UnlockBits(_bitmapData);
_isLocked = false;
}
catch (Exception)
{
throw;
}
}
else
{
throw new Exception("Bitmap is not locked.");
}
}
public Color GetPixel(int x, int y)
{
Color clr = Color.Empty;
// Get color components count
int channels = ColorDepth / 8;
// Get start index of the specified pixel
int i = (Height - y - 1) * Stride + x * channels;
int dataLength = _imageData.Length - channels;
if (i > dataLength)
{
throw new IndexOutOfRangeException();
}
if (ColorDepth == 32) // For 32 bpp get Red, Green, Blue and Alpha
{
byte b = _imageData[i];
byte g = _imageData[i + 1];
byte r = _imageData[i + 2];
byte a = _imageData[i + 3]; // a
clr = Color.FromArgb(a, r, g, b);
}
if (ColorDepth == 24) // For 24 bpp get Red, Green and Blue
{
byte b = _imageData[i];
byte g = _imageData[i + 1];
byte r = _imageData[i + 2];
clr = Color.FromArgb(r, g, b);
}
if (ColorDepth == 8)
// For 8 bpp get color value (Red, Green and Blue values are the same)
{
byte c = _imageData[i];
clr = Color.FromArgb(c, c, c);
}
return clr;
}
public void SetPixel(int x, int y, Color color)
{
// Get color components count
int cCount = ColorDepth / 8;
// Get start index of the specified pixel
int i = ((Height - y -1) * Stride + x * cCount);
try
{
if (ColorDepth == 32) // For 32 bpp set Red, Green, Blue and Alpha
{
_imageData[i] = color.B;
_imageData[i + 1] = color.G;
_imageData[i + 2] = color.R;
_imageData[i + 3] = color.A;
}
if (ColorDepth == 24) // For 24 bpp set Red, Green and Blue
{
_imageData[i] = color.B;
_imageData[i + 1] = color.G;
_imageData[i + 2] = color.R;
}
if (ColorDepth == 8)
// For 8 bpp set color value (Red, Green and Blue values are the same)
{
_imageData[i] = color.B;
}
}
catch(Exception ex)
{
throw new Exception("("+x+", "+y+"), "+_imageData.Length+", "+ ex.Message+", i=" + i);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
_bitmap = null;
_bitmapData = null;_imageData = null;IntegerPointer = IntPtr.Zero;
}
// free native resources if there are any.
//private properties
//public properties
}
}
.
ImageDataConverter.cs
public static Bitmap ToBitmap(double[,] input)
{
int width = input.GetLength(0);
int height = input.GetLength(1);
Bitmap output = Grayscale.CreateGrayscaleImage(width, height);
BitmapData data = output.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly,
output.PixelFormat);
int pixelSize = System.Drawing.Image.GetPixelFormatSize(PixelFormat.Format8bppIndexed) / 8;
int offset = data.Stride - width * pixelSize;
double Min = 0.0;
double Max = 255.0;
unsafe
{
byte* address = (byte*)data.Scan0.ToPointer();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
double v = 255 * (input[x, y] - Min) / (Max - Min);
byte value = unchecked((byte)v);
for (int c = 0; c < pixelSize; c++, address++)
{
*address = value;
}
}
address += offset;
}
}
output.UnlockBits(data);
return output;
}
Here is the picture I used for the test,
int noOfBitsNeededForStorage = _bitmapData.Stride * _bitmapData.Height;
That is the most essential bug in the code. Stride * Height are the number of bytes needed for storage. So it doesn't make the _imageData array large enough and IndexOutOfRangeException is the expected outcome.
int pixelSize = System.Drawing.Image.GetPixelFormatSize(PixelFormat.Format8bppIndexed) / 8;
Lots of possible mishaps from this statement. It hard-codes the pixel format to 8bpp but that is not the actual pixel format that the LockBits() call used. Which was output.PixelFormat. Notably fatal on the sample image, although it is not clear how it is used in the code, 8bpp is a very awkward pixel format since it requires a palette. The PNG codec will create a 32bpp image in memory, even though the original file uses 8bpp. You must use output.PixelFormat here to get a match with the locked data and adjust the pixel writing code accordingly. Not clear why it is being used at all, the SetPixel() method provided by the library code should already be good enough.
int dataLength = _imageData.Length - channels;
Unclear what that statement tries to do, subtracting the number of channels is not a sensible operation. It will generate a spurious IndexOutOfRangeException. There is no obvious reason to help, the CLR already provides array index checking on the _imageData array. So just delete that code.
Additional information: Bitmap region is already locked.
Exception handling in the code is not confident, a possible reason for this exception. In general it must be noted that the underlying bitmap is completely inaccessible, other than through _imageData, after the Lock() method was called and Unlock() wasn't called yet. Best way to do this is with try/finally with the Unlock() call in the finally block so you can always be sure that the bitmap doesn't remain locked by accident.
byte c = _imageData[i];
This is not correct, except in the corner case of an 8bpp image that has a palette that was explicitly created to handle grayscale images. The default palette for an 8bpp image does not qualify that requirement nor is it something you can blindly rely on when loading images from a file. Indexed pixel formats where a dreadful hack that was necessary in the early 1990s because video adapters where not yet powerful enough. It no longer makes any sense at all today. Note that SetPixel() also doesn't handle a 16-bit pixel formats. And that the PNG codec will never create an 8bpp memory image and cannot encode an 8bpp file. Best advice is to eliminate 8bpp support completely to arrive at more reliable code.
In fact, the point of directly accessing pixel data is to make image manipulation fast. There is only one pixel format that consistently produces fast code, it is Format32bppArgb. The pixels can now be accessed with an int* instead of a byte*, moving pixels ~4 times faster. And no special tweaks are necessary to deal with stride or special-case the code for methods like SetPixel(). So pass that format into LockBits(), the codec will do the work necessary if the actual image format is not 32bpp as well.
I should note that Format32bppPArgb is the fast pixel format for displaying images on the screen since it is compatible with the pixel format used by all modern video adapters. But that isn't the point of this code and dealing with the pre-multiplied alpha is awkward.

j2me, generate random location of food for simple snake game

here is my code for the snake game, the thing i need to do is generate location for the snake food, once the snake touch the snake food, it will regenerate the location of the food~pls, i really need your guys help!!! just kindly have a look
package snake;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class SnakeCanvas extends Canvas{
private int currentX =getWidth()/2;
private int currentY =getHeight()/2;
private boolean condition = false;
private boolean position = false;
Random rand = new Random();
int randomX=rand.nextInt(180) + 20;
int randomY =rand.nextInt(250) + 20;
private final Midlet midlet;
private int score = 0;
Timer t;
public SnakeCanvas(Midlet midlet)
{
this.midlet = midlet;
t = new Timer();
t.schedule(new TimerTask() {
public void run() {
if((condition==false)&&(position==false))
{
currentY -= 5 ;
}
if((condition==false)&&(position==true))
{
currentY += 5 ;
}
if((condition==true)&&(position==false))
{
currentX -= 5 ;
}
if((condition==true)&&(position==true))
{
currentX += 5 ;
}
}
}, 50, 50);
}
public void paint(Graphics g) {
boolean touch=false;
//drawing Background
g.setColor(0x000000);
g.fillRect(0, 0, getWidth(), getHeight());
//drawing snake
g.setColor(0xffffff);
g.fillRoundRect(currentX, currentY, 20, 20, 5, 5);
//snake food
g.setColor(234,41,42);
g.fillRect(randomX,randomY,10,10);
if((currentX-9<=randomX+4&&currentX+9>=randomX-4)&&(currentY-9<=randomY+4&&currentY+9>=randomY-4)){
addScore();
}
//drawing block
g.setColor(82,133,190);
g.fillRect(0, 0, getWidth(), 5);
g.fillRect(0, getHeight()-5, getWidth(), 5);
g.fillRect(0, 0, 5, getHeight());
g.fillRect(getWidth()-5, 0, 5, getHeight());
if((currentX>=getWidth()-10)||(currentX<5)||(currentY>=getHeight()-5)||(currentY<5))
midlet.GameOver();
g.setColor(142,255,17);
g.drawString("Score : "+score, 8, 7, Graphics.TOP|Graphics.LEFT);
repaint();
}
protected void keyPressed(int keyCode) {
System.out.println(keyCode);
switch(keyCode)
{
case -1:
condition = false;
position = false;
break;
case -2:
condition = false;
position = true;
break;
case -3:
condition = true;
position = false;
break;
case -4:
condition = true;
position= true;
break;
}
repaint();
}
private void addScore() {
score=score+1;**strong text**
}
private void food(){
Random rand = new Random();
int randomX=rand.nextInt(150) + 20;
int randomY=rand.nextInt(250) + 20;
}
}
Okay. I don't know if you managed to solve your problem but there seems to be a couple things wrong with your code.
First in this code block in the beginning:
Private int currentX =getWidth()/2;
private int currentY =getHeight()/2;
private boolean condition = false;
private boolean position = false;
Random rand = new Random();
int randomX=rand.nextInt(180) + 20;
int randomY =rand.nextInt(250) + 20;
^I am sure this does not compile, you can't have function calls when declaring header variables.
Second
if((condition==false)&&(position==false))
{
currentY -= 5 ;
}
if((condition==false)&&(position==true))
{
currentY += 5 ;
}
if((condition==true)&&(position==false))
{
currentX -= 5 ;
}
if((condition==true)&&(position==true))
{
currentX += 5 ;
}
}
}, 50, 50);
}
Your block coding style is horrible and hard to read. http://en.wikipedia.org/wiki/Programming_style#Indentation has a good guide on mastering this, read it!
This applies to your switch/case statements too!
Lastly your question:
private void food(){
Random rand = new Random();
int randomX=rand.nextInt(150) + 20;
int randomY=rand.nextInt(250) + 20;
}
^ Just generates random numbers, but doesn't do anything with them. I am guessing you meant:
private void food(){
Random rand = new Random();
randomX=rand.nextInt(150) + 20;
randomY=rand.nextInt(250) + 20;
}
which sets the classes global randomX and randomY to new values.
This doesn't help though since you don't actually call the Food() function anywhere in this class! And considering it is "Private" and can only be used by this class that must be an error.
tl;dr You need to study programming some more, but it is a good effort. I will help you more in the comments if you like. If my answer helped, please accept it.
Fenix

How can I correct the error "Cross-thread operation not valid"?

This following code gives me the error below . I think I need "InvokeRequired" . But I don't understand how can I use?
error:Cross-thread operation not valid: Control 'statusBar1' accessed from a thread other than the thread it was created on.
the code :
public void CalculateGeneration(int nPopulation, int nGeneration)
{
int _previousFitness = 0;
Population TestPopulation = new Population();
for (int i = 0; i < nGeneration; i++)
{
if (_threadFlag)
break;
TestPopulation.NextGeneration();
Genome g = TestPopulation.GetHighestScoreGenome();
if (i % 100 == 0)
{
Console.WriteLine("Generation #{0}", i);
if ( ToPercent(g.CurrentFitness) != _previousFitness)
{
Console.WriteLine(g.ToString());
_gene = g;
statusBar1.Text = String.Format("Current Fitness = {0}", g.CurrentFitness.ToString("0.00"));
this.Text = String.Format("Sudoko Grid - Generation {0}", i);
Invalidate();
_previousFitness = ToPercent(g.CurrentFitness);
}
if (g.CurrentFitness > .9999)
{
Console.WriteLine("Final Solution at Generation {0}", i);
statusBar1.Text = "Finished";
Console.WriteLine(g.ToString());
break;
}
}
}
}
Easiest for reusability is to add a helper function like:
void setstatus(string txt)
{
Action set = () => statusBar1.Text = txt;
statusBar1.Invoke(set);
}
Or with the invokerequired check first:
delegate void settextdelegate(string txt);
void setstatus(string txt)
{
if (statusBar1.InvokeRequired)
statusBar1.Invoke(new settextdelegate(setstatus), txt);
else
statusBar1.Text = txt;
}
Either way the status can then be set like
setstatus("Finished");
For completeness I should add that even better would be to keep your calculating logic separated from your form and raise a status from within your calculating functionality that can be hanled by the form, but that could be completely out of scope here.

How to create multiple checkbox in canvas

I get trouble when I try to create a check box in canvas.
My checkbox works well but I don't know how to store value of each item, that mean when user check row 1 , and then they move to another row check box still check row 1, and when user check row 1 and 2 and move to another row, check box will check row 1 and 2.
But I can't find out solution for this problem
modify your code to use selectTodelete as boolean array instead of int, about like shown below
// ...initialization of DataList
boolean[] selectTodelete = new boolean[2]; // instead of int
{ selectTodelete[0] = selectTodelete[1] = false; } // init array
Command editCommand, backCommand,selectCmd, unselectCmd,selectAll;
//...
protected void paint(Graphics g) {
//...
for(int i =0 ; i<countRow; i++ ){
//draw background
//...
if(selectTodelete[i]){ // was selectTodelete == 1
//draw select dot at location for row 'i'
//...
}
// remove: you don't need that anymore: if(selectTodelete == 2) {
//draw select dot...
//}
// draw a checkbox before each item
// ...
}
}
public void commandAction(Command c, Displayable d) {
//...
if(c == selectCmd){
selectTodelete[selectedItem] = true;
}
if(c== unselectCmd){
selectTodelete[selectedItem] = false;
}
if(c == selectAll){
selectTodelete[0] = selectTodelete[1] = true;
}
repaint();
}
//...
}
update - answer to question in comments
I want to get RCID fit to checked it mean when row was checked I can get this id and when I use delete command it will delete all rows were checked
For that, you can expose selectTodelete for use outside of its class with getter, or, better yet, with method like below...
boolean isSelected(int elementNum) {
return elementNum >= 0 && elementNum < selectTodelete.length
&& selectTodelete[elementNum];
} // modelled after javax.microedition.lcdui.Choice.isSelected
...information exposed like that can be further used anywhere when you need it to deal with RCID, like eg in method below:
Vector useSelection(DataList dataList, DataStore[][] ds) {
Vector result = new Vector();
int count = ds.length;
for(int i = 0; i < count; i++ ) {
if (!dataList.isSelected(i)) {
continue; // skip non selected
}
System.out.println("RCID selected: [" + ds[i][5].cellText + "]");
result.addElement(ds[i][5]);
}
return result;
}

Resources