Related
We have an NxM grid, grid have one element named Bob. Bob can travel diagonally blocks only. The grid has some blocked blocks on which Bob can not travel. Write a function that returns on how many possible positions Bob can move. Solve this problem using BFS and submit the executable code in any programming language. In the following image example, Bob's positioning is at 9,3, and it can visit the places where Y is marked; hence your method should return 30.
Anybody any pseudocode or approach on how to solve this using BFS
Following solution is modified version of solution given by ( https://stackoverflow.com/users/10987431/dominicm00 ) on problem ( Using BFS to find number of possible paths for an object on a grid )
Map.java:
import java.awt.*;
public class Map {
public final int width;
public final int height;
private final Cell[][] cells;
private final Move[] moves;
private Point startPoint;
public Map(int[][] mapData) {
this.width = mapData[0].length;
this.height = mapData.length;
cells = new Cell[height][width];
// define valid movements
moves = new Move[]{
new Move(1, 1),
new Move(-1, 1),
new Move(1, -1),
new Move(-1, -1)
};
generateCells(mapData);
}
public Point getStartPoint() {
return startPoint;
}
public void setStartPoint(Point p) {
if (!isValidLocation(p)) throw new IllegalArgumentException("Invalid point");
startPoint.setLocation(p);
}
public Cell getStartCell() {
return getCellAtPoint(getStartPoint());
}
public Cell getCellAtPoint(Point p) {
if (!isValidLocation(p)) throw new IllegalArgumentException("Invalid point");
return cells[p.y][p.x];
}
private void generateCells(int[][] mapData) {
boolean foundStart = false;
for (int i = 0; i < mapData.length; i++) {
for (int j = 0; j < mapData[i].length; j++) {
/*
0 = empty space
1 = wall
2 = starting point
*/
if (mapData[i][j] == 2) {
if (foundStart) throw new IllegalArgumentException("Cannot have more than one start position");
foundStart = true;
startPoint = new Point(j, i);
} else if (mapData[i][j] != 0 && mapData[i][j] != 1) {
throw new IllegalArgumentException("Map input data must contain only 0, 1, 2");
}
cells[i][j] = new Cell(j, i, mapData[i][j] == 1);
}
}
if (!foundStart) throw new IllegalArgumentException("No start point in map data");
// Add all cells adjacencies based on up, down, left, right movement
generateAdj();
}
private void generateAdj() {
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
for (Move move : moves) {
Point p2 = new Point(j + move.getX(), i + move.getY());
if (isValidLocation(p2)) {
cells[i][j].addAdjCell(cells[p2.y][p2.x]);
}
}
}
}
}
private boolean isValidLocation(Point p) {
if (p == null) throw new IllegalArgumentException("Point cannot be null");
return (p.x >= 0 && p.y >= 0) && (p.y < cells.length && p.x < cells[p.y].length);
}
private class Move {
private int x;
private int y;
public Move(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}}
Cell.java:
import java.util.LinkedList;
public class Cell {
public final int x;
public final int y;
public final boolean isWall;
private final LinkedList<Cell> adjCells;
public Cell(int x, int y, boolean isWall) {
if (x < 0 || y < 0) throw new IllegalArgumentException("x, y must be greater than 0");
this.x = x;
this.y = y;
this.isWall = isWall;
adjCells = new LinkedList<>();
}
public void addAdjCell(Cell c) {
if (c == null) throw new IllegalArgumentException("Cell cannot be null");
adjCells.add(c);
}
public LinkedList<Cell> getAdjCells() {
return adjCells;
}}
MapHelper.java:
class MapHelper {
public static int countReachableCells(Map map) {
if (map == null) throw new IllegalArgumentException("Arguments cannot be null");
boolean[][] visited = new boolean[map.height][map.width];
// subtract one to exclude starting point
return dfs(map.getStartCell(), visited) - 1;
}
private static int dfs(Cell currentCell, boolean[][] visited) {
visited[currentCell.y][currentCell.x] = true;
int touchedCells = 0;
for (Cell adjCell : currentCell.getAdjCells()) {
if (!adjCell.isWall && !visited[adjCell.y][adjCell.x]) {
touchedCells += dfs(adjCell, visited);
}
}
return ++touchedCells;
}}
Grid.java:
public class Grid{
public static void main(String args[]){
int[][] gridData = {
{0,0,0,0,0,0,0,0},
{0,1,0,0,0,1,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,1,0,0,1,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,1,0},
{0,0,1,0,0,1,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,2,1,0,0,0}}; //2 is bobs position, 1 is blocked, 0 can be visited
Map grid = new Map(gridData);
MapHelper solution = new MapHelper();
System.out.println(solution.countReachableCells(grid));
}}
For original answer of similar problem visit (Using BFS to find number of possible paths for an object on a grid) for original answer.
I am new into using moa and I am having a hard time trying to decode how the clustering algorithms have to be used. The documentation lacks of sample code for common usages, and the implementation is not well explained with comments ... have not found any tutorial either.
So, here is my code:
import com.yahoo.labs.samoa.instances.DenseInstance;
import moa.cluster.Clustering;
import moa.clusterers.denstream.WithDBSCAN;
public class TestingDenstream {
static DenseInstance randomInstance(int size) {
DenseInstance instance = new DenseInstance(size);
for (int idx = 0; idx < size; idx++) {
instance.setValue(idx, Math.random());
}
return instance;
}
public static void main(String[] args) {
WithDBSCAN withDBSCAN = new WithDBSCAN();
withDBSCAN.resetLearningImpl();
for (int i = 0; i < 10; i++) {
DenseInstance d = randomInstance(2);
withDBSCAN.trainOnInstanceImpl(d);
}
Clustering clusteringResult = withDBSCAN.getClusteringResult();
Clustering microClusteringResult = withDBSCAN.getMicroClusteringResult();
System.out.println(clusteringResult);
}
}
And here is the error I get:
Any insights into how the algorithm has to be used will be appreciated. Thanks!
I have updated the code.
It is working as I mentioned in the github, you have to assign header to your instance. See the github discussion
here is the updated code:
static DenseInstance randomInstance(int size) {
// generates the name of the features which is called as InstanceHeader
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
for (int i = 0; i < size; i++) {
attributes.add(new Attribute("feature_" + i));
}
// create instance header with generated feature name
InstancesHeader streamHeader = new InstancesHeader(
new Instances("Mustafa Çelik Instance",attributes, size));
// generates random data
double[] data = new double[2];
Random random = new Random();
for (int i = 0; i < 2; i++) {
data[i] = random.nextDouble();
}
// creates an instance and assigns the data
DenseInstance inst = new DenseInstance(1.0, data);
// assigns the instanceHeader(feature name)
inst.setDataset(streamHeader);
return inst;
}
public static void main(String[] args) {
WithDBSCAN withDBSCAN = new WithDBSCAN();
withDBSCAN.resetLearningImpl();
withDBSCAN.initialDBScan();
for (int i = 0; i < 1500; i++) {
DenseInstance d = randomInstance(5);
withDBSCAN.trainOnInstanceImpl(d);
}
Clustering clusteringResult = withDBSCAN.getClusteringResult();
Clustering microClusteringResult = withDBSCAN.getMicroClusteringResult();
System.out.println(clusteringResult);
}
here is the screenshot of debug process, as you see the clustering result is generated:
image link is broken, you can find it on github github entry link
This is a program that prints out all the even numbers between any given integer.
import java.util.*;
public class Question1
{
private int i;
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Give me a number!");
int i = scanner.nextInt();
if ((i % 2) != 0)
{
i = i - 1;
do
{
System.out.println(i);
i = i - 2;
} while (i != -2);
}
}
}
So, if I give the number 11, it will print out 10, 8, 6, 4, 2. Why won't it print 0 as well, since my while statement contains i!= -2 and 0 counts as an even number?
Because after scanner.nextInt(); you must put scanner.nextLine(); else, the last element the scanner gets from nextInt(); will be ignored.
Even so, your algorithm is extremely dizzy. why not try:
Scanner in = new Scanner( System.in );
int number = in.nextInt(); in.nextLine();
for( int i = 0; i <= number; i += 2 ) {
System.out.println( i );
}
?
Can someone please explain how could I solve a maze using breadth first search? I need to use breadth first search to find shortest path through a maze, but I am so confused.
This is the pseudo code from my book:
void breadth_first_search(tree T) {
queue!;
node u, v;
initialize(Q);
v = root of T;
visit v;
enqueue(Q, v);
while (!empty(Q)) {
dequeue(Q, v);
for (each child u of v) {
visit u;
enqueue(Q, u);
}
}
}
So if I have a maze that is stored in a 2D matrix, is the "root" (i.e. the starting point), going to be in maze[x][y]?
Here's a full BFS Maze solver. It returns a full shortest path to the end point if found. In the maze array arr: 0 denotes unexplored spaces, 5 is a wall space, and 9 is the goal space. Spaces are marked with a -1 after they have been visited.
import java.util.*;
public class Maze {
public static int[][] arr = new int[][] {
{0,0,0,0,0,0,0,0,0},
{5,5,5,0,0,0,0,0,0},
{0,0,0,5,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,9},
};
private static class Point {
int x;
int y;
Point parent;
public Point(int x, int y, Point parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
public Point getParent() {
return this.parent;
}
public String toString() {
return "x = " + x + " y = " + y;
}
}
public static Queue<Point> q = new LinkedList<Point>();
public static Point getPathBFS(int x, int y) {
q.add(new Point(x,y, null));
while(!q.isEmpty()) {
Point p = q.remove();
if (arr[p.x][p.y] == 9) {
System.out.println("Exit is reached!");
return p;
}
if(isFree(p.x+1,p.y)) {
arr[p.x][p.y] = -1;
Point nextP = new Point(p.x+1,p.y, p);
q.add(nextP);
}
if(isFree(p.x-1,p.y)) {
arr[p.x][p.y] = -1;
Point nextP = new Point(p.x-1,p.y, p);
q.add(nextP);
}
if(isFree(p.x,p.y+1)) {
arr[p.x][p.y] = -1;
Point nextP = new Point(p.x,p.y+1, p);
q.add(nextP);
}
if(isFree(p.x,p.y-1)) {
arr[p.x][p.y] = -1;
Point nextP = new Point(p.x,p.y-1, p);
q.add(nextP);
}
}
return null;
}
public static boolean isFree(int x, int y) {
if((x >= 0 && x < arr.length) && (y >= 0 && y < arr[x].length) && (arr[x][y] == 0 || arr[x][y] == 9)) {
return true;
}
return false;
}
public static void main(String[] args) {
Point p = getPathBFS(0,0);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
while(p.getParent() != null) {
System.out.println(p);
p = p.getParent();
}
}
}
Short answer: yes
Explanation:
That pseudo code is representing the path through the maze as a path to the leaf of a tree. Each spot in the maze is a node on the tree and each new spot you can go to from there is a child of that node.
In order to do breadth first search, an algorithm first has to consider all paths through the tree of length one, then length two, etc. until it reaches the end, which will cause the algorithm to stop since the end has no children, resulting in an empty queue.
The code keeps track of the nodes it needs to visit by using a queue (Q). It first sets the start of the maze to the root of the tree, visits it (checks if it is the end), then removes the root from the queue and repeats the process with each child. In this way, it visits the nodes in post-order i.e. root, (each child of root), (each child of first child), (each child of second child), etc. until it gets to the end.
edit: As it stands, the algorithm may not terminate when it reaches the end because of other nodes after it in the queue. You will have to wright the condition for termination yourself.
I'm looking for digital low pass filter code/library/class for a .net windows forms project, preferably written in c, c++ or c#. I probably need to set the number of poles, coefficients, windowing, that sort of thing. I can't use any of the gpl'd code that's available, and don't know what else is out there. Any suggestions appreciated.
Here is a Butterworth Low Pass filter I wrote for a recent project.
It has some magic numbers as constants that was given to me. If you can figure out how to create the magic numbers with your poles, coefficients, etc, then this might be helpful.
using System;
using System.Collections.Generic;
using System.Text;
namespace Filter
{
public class ButterworthLowPassFilter
{
//filter fc = 2hz, fs = 10hz
private const int LowPassOrder = 4;
private double[] inputValueModifier;
private double[] outputValueModifier;
private double[] inputValue;
private double[] outputValue;
private int valuePosition;
public ButterworthLowPassFilter()
{
inputValueModifier = new double[LowPassOrder];
inputValueModifier[0] = 0.098531160923927;
inputValueModifier[1] = 0.295593482771781;
inputValueModifier[2] = 0.295593482771781;
inputValueModifier[3] = 0.098531160923927;
outputValueModifier = new double[LowPassOrder];
outputValueModifier[0] = 1.0;
outputValueModifier[1] = -0.577240524806303;
outputValueModifier[2] = 0.421787048689562;
outputValueModifier[3] = -0.0562972364918427;
}
public double Filter(double inputValue)
{
if (this.inputValue == null && this.outputValue == null)
{
this.inputValue = new double[LowPassOrder];
this.outputValue = new double[LowPassOrder];
valuePosition = -1;
for (int i=0; i < LowPassOrder; i++)
{
this.inputValue[i] = inputValue;
this.outputValue[i] = inputValue;
}
return inputValue;
}
else if (this.inputValue != null && this.outputValue != null)
{
valuePosition = IncrementLowOrderPosition(valuePosition);
this.inputValue[valuePosition] = inputValue;
this.outputValue[valuePosition] = 0;
int j = valuePosition;
for (int i = 0; i < LowPassOrder; i++)
{
this.outputValue[valuePosition] += inputValueModifier[i] * this.inputValue[j] -
outputValueModifier[i] * this.outputValue[j];
j = DecrementLowOrderPosition(j);
}
return this.outputValue[valuePosition];
}
else
{
throw new Exception("Both inputValue and outputValue should either be null or not null. This should never be thrown.");
}
}
private int DecrementLowOrderPosition(int j)
{
if (--j < 0)
{
j += LowPassOrder;
}
return j;
}
private int IncrementLowOrderPosition(int position)
{
return ((position + 1) % LowPassOrder);
}
}
}
Keith
Ok, I found out how to get the coefficients you used. I downloaded Octave for windows and ran the butter command (as in MatLab) like this:
[b,a] = butter(3, .4, 'low')
Now I can use this code with other fs and fc parameters.