I am attempting to make a random maze generator using Java and the recursive backtracking algorithm. I am getting stack overflow when I try to run this code. I know some about stack, I don't think this is infinite recursion. My guess is that I have a big logic error. Do I have to allocate more memory?
The stack trace:
Exception in thread "main" java.lang.StackOverflowError
at java.base/java.util.Vector.elementAt(Vector.java:499)
at java.base/java.util.Stack.peek(Stack.java:103)
at java.base/java.util.Stack.pop(Stack.java:84)
at mazeMaker.Maze.generateMaze(Maze.java:115)
at mazeMaker.Maze.generateMaze(Maze.java:115)
...
at mazeMaker.Maze.generateMaze(Maze.java:115)
at mazeMaker.Maze.generateMaze(Maze.java:115)
Main.java
package mazeMaker;
public class Main
{
public static void main(String[] args)
{
Maze mainMaze = new Maze(20, 30);
}
}
Maze.java
package mazeMaker;
import java.util.Random;
import java.util.Stack;
public class Maze
{
public int xSize = 0;
public int ySize = 0;
public int totalDimensions = 0;
Random randomGenerator = new Random();
public Cell[][] cellData;
public Stack<Cell> cellStack = new Stack<Cell>();
Cell tempCell; // Temporary variable used for maze generation
public Maze(int xSize, int ySize)
{
cellData = new Cell[xSize][ySize];
this.xSize = xSize;
this.ySize = ySize;
this.totalDimensions = this.xSize * this.ySize;
// Initialize array objects
for (int i = 0; i < this.xSize; i++)
{
for (int j = 0; j < this.ySize; j++)
{
cellData[i][j] = new Cell();
}
}
// Assign x and y positions
for (int i = 0; i < this.xSize; i++)
{
for (int j = 0; j < this.ySize; j++)
{
cellData[i][j].xPos = i;
cellData[i][j].yPos = j;
}
}
initBoundries();
generateMaze();
}
private void initBoundries()
{
// Initialize the border cells as visited so we don't go out of bounds
int m = this.xSize;
int n = this.ySize;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (i == 0 || j == 0 || i == n - 1 || j == n - 1)
cellData[i][j].hasBeenVisited = true;
}
}
}
private void generateMaze(int x, int y)
{
// Set current cell as visited
cellData[x][y].hasBeenVisited = true;
// While there are unvisited neighbors
while (!cellData[x][y+1].hasBeenVisited || !cellData[x+1][y].hasBeenVisited || !cellData[x][y-1].hasBeenVisited || !cellData[x-1][y].hasBeenVisited)
{
// Select a random neighbor
while (true)
{
int r = randomGenerator.nextInt(4);
if (r == 0 && !cellData[x][y+1].hasBeenVisited)
{
cellStack.push(cellData[x][y]);
cellData[x][y].hasNorthWall = false;
cellData[x][y+1].hasSouthWall = false;
generateMaze(x, y + 1);
break;
}
else if (r == 1 && !cellData[x+1][y].hasBeenVisited)
{
cellStack.push(cellData[x][y]);
cellData[x][y].hasEastWall = false;
cellData[x+1][y].hasWestWall = false;
generateMaze(x+1, y);
break;
}
else if (r == 2 && !cellData[x][y-1].hasBeenVisited)
{
cellStack.push(cellData[x][y]);
cellData[x][y].hasSouthWall = false;
cellData[x][y-1].hasNorthWall = false;
generateMaze(x, y-1);
break;
}
else if (r == 3 && !cellData[x-1][y].hasBeenVisited)
{
cellStack.push(cellData[x][y]);
cellData[x][y].hasWestWall = false;
cellData[x-1][y].hasEastWall = false;
generateMaze(x-1, y);
break;
}
}
}
// There are no unvisited neighbors
tempCell = cellStack.pop();
generateMaze(tempCell.xPos, tempCell.yPos);
}
// Begin generating maze at top left corner
private void generateMaze()
{
generateMaze(1,1);
}
}
Cell.java
package mazeMaker;
public class Cell
{
public boolean isCurrentCell;
public boolean hasBeenVisited;
public boolean hasNorthWall;
public boolean hasSouthWall;
public boolean hasEastWall;
public boolean hasWestWall;
public int xPos;
public int yPos;
}
The method generateMaze can never terminate not even by chance for some simple reason:
For terminating the generateMaze method would need to finish it's execution - it has to return.
There are no return statements in this method, therefore it has to pass the while loops and then continue until the execution reaches and finishes the last statement of the method.
However the last statement is generateMaze(tempCell.xPos, tempCell.yPos); which starts a new recursion, therefore your code can never ever terminate!
I tried to run your project on my own environment but unfortunately, I was not able to reproduce your issue.
However, I was facing an IndexOutOfBound exception in the method generateMaze. While I was solving this, I figured out that there was an issue in the initBoudaries method.
Indeed, when you set the boolean hasBeenVisited to true, you do not use the right variable in the IF clause. Here is the version I tried instead :
private void initBoundries()
{
// Initialize the border cells as visited so we don't go out of bounds
for (int i = 0; i < this.xSize; i++)
{
for (int j = 0; j < ySize; j++)
{
if (i == 0 || j == 0 || i == xSize - 1 || j == ySize - 1)
cellData[i][j].hasBeenVisited = true;
}
}
}
Now about the emptyStackException, I think that if this stack is empty, this means that there is no more cell to handle (as you mentioned in your comment) and the program must end. If I am right, just make sure to test if your stack is empty before call the method pop() on it like this :
// There are no unvisited neighbors
if (!cellStack.isEmpty()) {
tempCell = cellStack.pop();
generateMaze(tempCell.xPos, tempCell.yPos);
}
Hope it will help.
I'm currently trying to learn how to program, and I have started with Java. I would like to create a calendar, but I can't even seem to return any statements. When I run my code, nothing shows up. I realize my code may be very inefficient to anyone with experience, and I would appreciate any help.
import java.util.ArrayList;
public class CalendarSource {
public ArrayList<String> calendarString = new ArrayList<String>(30);
public ArrayList<Integer> calendarDay = new ArrayList<Integer>(30);
public ArrayList<Integer> calendarMonth = new ArrayList<Integer>(12);
public CalendarSource () {
for (int x = 0; x < calendarMonth.size(); x++) {
calendarMonth.add(x);
}
for (int x = 0; x < calendarString.size(); x++) {
if (calendarString.indexOf(x) == 0 || x%7 == 0) {
calendarString.add("Monday");
}
if (calendarString.indexOf(x) == 1 || x%7 == 1) {
calendarString.add("Tuesday");
}
if (calendarString.indexOf(x) == 2 || x%7 == 2) {
calendarString.add("Wednesday");
}
if (calendarString.indexOf(x) == 3 || x%7 == 3) {
calendarString.add("Thursday");
}
if (calendarString.indexOf(x) == 4 || x%7 == 4) {
calendarString.add("Friday");
}
if (calendarString.indexOf(x) == 5 || x%7 == 5) {
calendarString.add("Saturday");
}
if (calendarString.indexOf(x) == 6 || x%7 == 6) {
calendarString.add("Sunday");
}
}
int x;
}
public String getInfo() {
int r;
int c;
for (int x = 0; x<calendarMonth.size(); x++)
for (r = 0; r < 5; r++) {
for (c = 0; c < 7; c++) {
System.out.println(("placeholder " + calendarString.get(c) + calendarMonth.get(x) + calendarDay.get(c)) );
}
System.lineSeparator();
}
return "testing text if nothing else returns";
}
}
Here is the code I am using to test it, and I can't even get "testing text" to print out.
public class CalendarClass {
public static void main(String[] args) {
CalendarSource some= new CalendarSource();
some.getInfo();
}
}
you have a problem with the constructor.
The size of the array will always give you 0, unless you have a object inside, when you do like new ArrayList (12), you are no giving a size() to the arrayList.
istead of using the .size(0 in the constructor, you could use the number you used to create the arraylist.
Actually, your code has a lot of issues :
ArrayList(12) does not mean the ArrayList of size 12, but the Array List which will be able to accommodate 12 elements. So for all below ArrayLists size is still 0.
public ArrayList<String> calendarString = new ArrayList<String>(30);
public ArrayList<Integer> calendarDay = new ArrayList<Integer>(30);
public ArrayList<Integer> calendarMonth = new ArrayList<Integer>(12);
you can try it by using
public String getInfo() {
int r;
int c;
System.out.println(calendarMonth.size());
for (int x = 0; x < calendarMonth.size(); x++) {
System.out.println("In Loop");
for (r = 0; r < 5; r++) {
for (c = 0; c < 7; c++) {
System.out.println(("placeholder " + calendarString.get(c) + calendarMonth.get(x) + calendarDay.get(c)));
}
System.lineSeparator();
}
}
return "testing text if nothing else returns";
}
This question already has answers here:
Find elements surrounding an element in an array
(8 answers)
Closed 6 years ago.
I have a series of if statements, as shown below:
if (board[x+1][y]==true) {
ar+=1;
}
if (board[x][y+1]==true) {
ar+=1;
}
if (board[x-1][y]==true) {
ar+=1;
}
if (board[x][y-1]==true) {
ar+=1;
}
if (board[x+1][y+1]==true) {
ar+=1;
}
if (board[x+1][y-1]==true) {
ar+=1;
}
if (board[x-1][y+1]==true) {
ar+=1;
}
if (board[x-1][y-1]==true) {
ar+=1;
}
Is there a way to simplify/condense these statements with Java?
Simply loop around the position that you care about. Skipping the center of the "box".
Tip: You access a 2D array by row then column, or [y][x] (at least, that's how you'd translate the board from looking at the code).
// int x, y; // position to look around
for (int xDiff = -1; xDiff <= 1; xDiff++) {
for (int yDiff = -1; yDiff <= 1; yDiff++) {
if (xDiff == 0 && yDiff == 0) continue;
if (board[y+yDiff][x+xDiff]) {
ar += 1;
}
}
}
Beware - Out of bounds exception is not handled
The following would be a more visual equivalent, easily extensible to other shapes of the area of interest. Note ternary operators, ?: which are necessary in Java to convert bools to ints.
ar += (board[x-1][y-1]?1:0) + (board[x-1][y]?1:0) + (board[x-1][y+1]?1:0);
ar += (board[x+0][y-1]?1:0) + (board[x+0][y+1]?1:0);
ar += (board[x+1][y-1]?1:0) + (board[x+1][y]?1:0) + (board[x+1][y+1]?1:0);
In addition to the answers you already have, you can also use enhanced for loops (and re-use the range as it is the same for both).
int[] range = { -1, 0, 1 };
for (int i : range) {
for (int j : range) {
if ((i != 0 || j != 0) && board[i][j]) {
ar++;
}
}
}
This code should give the same result (probably you want to check that you are always in the bounds of the matrix
for(int i=-1; i<=1; i++) {
for(int j=-1; j<=1; j++) {
if((i != 0 || j != 0) && board[x+i][y+j]) {
ar++;
}
}
}
You can simplify as follows as well :
for(int i = x-1;i<=x+1;i++) {
for(int j=y-1;j<=y+1;j++) {
if(i==x && j==y) continue;
if (board[i][j]) {
ar+=1;
}
}
}
Looks like you're testing surrounding squares apart from (x, y) itself. I'd use a loop to maintain a counter, with extra step to exclude the (x, y) centre cell.
for (int xTest = x - 1; xTest <= x + 1; xTest++) {
for (int yTest = y - 1; yTest <= y + 1; yTest++) {
if (xTest == x && yTest == y) {
continue;
}
if (board[xTest][yTest]) {
ar += 1;
}
}
}
Also, note the == true is unnecessary. Boolean statements are first class citizens in Java.
I'm facing a problem and I'd like to know some ideas on how to solve it. I have a matrix of two dimensions and given a point on that matrix I need to look for ten cells up, down right, left and with diagonal movements (see the following image).
What I'm doing is selecting the values of i and j as the values to be multiplied by the position coordinates and give the direction that I want in each case. For example:
Diagonal A : i=1 j=-1 since i increases and j decreases
Diagonal B : i=1 j=1 since both increase
And for the vertical and horizontal movements i and j will take values 1 or 0.
Having these two values I can take the center and add a value to it starting this value to 1 and increasing it until I get to the limit (10). If the center is (2,4) and I'm in diagonal A I will add the value that is starting in one multiplied by i and j for each coordinate having the following results:
(3,3) (4,2) (5,1) (6,0)
Right now I am interested in computing i and j so that they take all the needed values for the diagonals and the axis. My java code that goes inside a loop is the following:
GS.r++;
if (GS.r > 10) {
GS.r = 0;
if (GS.iteration) {
int i = 0, j = 0;
if (GS.i == 1) {
i = -1;
} else if (GS.i == -1) {
i = 0;
j = 1;
}
if (GS.j == 1) {
j = -1;
} else if (GS.j == -1) {
j = 0;
i = 1;
}
GS.i = i;
GS.j = j;
if (GS.i == 1 && GS.j == 0) {
GS.iteration = false;
GS.i = -1;
GS.j = -1;
}
} else {
if (GS.i == 1 && GS.j == 1) {
GS.iteration = true;
GS.i = 1;
GS.j = 0;
} else {
if (GS.i == 1)
GS.j *= -1;
GS.i *= -1;
}
}
}
GS.i and GS.j are initialised as -1. And with this code I get first the diagonals since the values for GS.i and GS.j would be (-1,-1) (1, -1) (-1, 1) (1, 1) and then the axis having these values: (-1, 0) (1, 0) (0, -1) (0, 1).
I was wondering if there is a better way of generating i and j since my code is not that clean.
Thank you!
What I would do is create an enum for all the four directions you can move in that is Diagonal right up,Diagonal right down,Diagonal left up and Diagonal left down.
Sample code :
public enum Direction {
DIAGONAL_RIGHT_UP(1,1),
DIAGONAL_RIGHT_DOWN(1,-1),
DIAGONAL_LEFT_UP(-1,1),
DIAGONAL_LEFT_DOWN(-1,-1);
public int x;
public int y;
private Direction(int xCoordinateChange,int yCoordinateChange) {
x=xCoordinateChange;
y=yCoordinateChange;
}
}
Then use this to traverse.
public class CartesianCoordinate {
private long xCoordinate;
private long yCoordinate;
public CartesianCoordinate(long xCoordinate,long yCoordinate) {
this.xCoordinate=xCoordinate;
this.yCoordinate=yCoordinate;
}
public long getXCoordinate() {
return xCoordinate;
}
public long getYCoordinate() {
return yCoordinate;
}
public void moveCoordinateByStepSize(Direction direction,long stepSize) {
xCoordinate+=direction.x*stepSize;
yCoordinate+=direction.y*stepSize;
}
#Override
public int hashCode() {
int hashCode=0;
hashCode += (int)(xCoordinate-yCoordinate)*31;
hashCode += (int)(yCoordinate+xCoordinate)*17;
return hashCode;
}
#Override
public boolean equals(Object object) {
if(object == null || !(object instanceof CartesianCoordinate)) {
return false;
}
if( this == object) {
return true;
}
CartesianCoordinate cartesianCoordinateObject = (CartesianCoordinate)object;
if(xCoordinate == cartesianCoordinateObject.getXCoordinate() && yCoordinate == cartesianCoordinateObject.getYCoordinate()) {
return true;
}
return false;
}
#Override
public String toString() {
return "["+xCoordinate+","+yCoordinate+"]";
}
public CartesianCoordinate getAClone() {
return new CartesianCoordinate(xCoordinate,yCoordinate);
}
}
Now say you have a point (1,3) as a starting point. what you can do is for 100 iterations in a particular line.
CartesianCoordinate startingPoint = new CartesianCoordinate(1,3);
CartesianCoordinate rightUpDiag = startingPoint.getAClone(),leftUpDiag = startingPoint.getAClone(),rightDownDiag = startingPoint.getAClone(),leftDownDiag = startingPoint.getAClone();
for(int counter = 0 ;counter < 100; counter ++) {
System.out.println(rightUpDiag.moveCoordinateByStepSize(Direction.DIAGONAL_RIGHT_UP,1));
System.out.println(leftUpDiag.moveCoordinateByStepSize(Direction.DIAGONAL_LEFT_UP,1));
System.out.println(rightDownDiag.moveCoordinateByStepSize(Direction.DIAGONAL_RIGHT_DOWN,1));
System.out.println(leftDownDiag.moveCoordinateByStepSize(Direction.DIAGONAL_LEFT_DOWN,1));
}
I have been trying to solve a Java exercise on a Codility web page.
Below is the link to the mentioned exercise and my solution.
https://codility.com/demo/results/demoH5GMV3-PV8
Can anyone tell what can I correct in my code in order to improve the score?
Just in case here is the task description:
A small frog wants to get to the other side of a river. The frog is currently located at position 0, and wants to get to position X. Leaves fall from a tree onto the surface of the river.
You are given a non-empty zero-indexed array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in minutes.
The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X.
For example, you are given integer X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
In minute 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.
Write a function:
class Solution { public int solution(int X, int[] A); }
that, given a non-empty zero-indexed array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river.
If the frog is never able to jump to the other side of the river, the function should return −1.
For example, given X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
the function should return 6, as explained above. Assume that:
N and X are integers within the range [1..100,000];
each element of array A is an integer within the range [1..X].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(X), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
And here is my solution:
import java.util.ArrayList;
import java.util.List;
class Solution {
public int solution(int X, int[] A) {
int list[] = A;
int sum = 0;
int searchedValue = X;
List<Integer> arrayList = new ArrayList<Integer>();
for (int iii = 0; iii < list.length; iii++) {
if (list[iii] <= searchedValue && !arrayList.contains(list[iii])) {
sum += list[iii];
arrayList.add(list[iii]);
}
if (list[iii] == searchedValue) {
if (sum == searchedValue * (searchedValue + 1) / 2) {
return iii;
}
}
}
return -1;
}
}
You are using arrayList.contains inside a loop, which will traverse the whole list unnecessarily.
Here is my solution (I wrote it some time ago, but I believe it scores 100/100):
public int frog(int X, int[] A) {
int steps = X;
boolean[] bitmap = new boolean[steps+1];
for(int i = 0; i < A.length; i++){
if(!bitmap[A[i]]){
bitmap[A[i]] = true;
steps--;
if(steps == 0) return i;
}
}
return -1;
}
Here is my solution. It got me 100/100:
public int solution(int X, int[] A)
{
int[] B = A.Distinct().ToArray();
return (B.Length != X) ? -1 : Array.IndexOf<int>(A, B[B.Length - 1]);
}
100/100
public static int solution (int X, int[] A){
int[]counter = new int[X+1];
int ans = -1;
int x = 0;
for (int i=0; i<A.length; i++){
if (counter[A[i]] == 0){
counter[A[i]] = A[i];
x += 1;
if (x == X){
return i;
}
}
}
return ans;
}
A Java solution using Sets (Collections Framework) Got a 100%
import java.util.Set;
import java.util.TreeSet;
public class Froggy {
public static int solution(int X, int[] A){
int steps=-1;
Set<Integer> values = new TreeSet<Integer>();
for(int i=0; i<A.length;i++){
if(A[i]<=X){
values.add(A[i]);
}
if(values.size()==X){
steps=i;
break;
}
}
return steps;
}
Better approach would be to use Set, because it only adds unique values to the list. Just add values to the Set and decrement X every time a new value is added, (Set#add() returns true if value is added, false otherwise);
have a look,
public static int solution(int X, int[] A) {
Set<Integer> values = new HashSet<Integer>();
for (int i = 0; i < A.length; i++) {
if (values.add(A[i])) X--;
if (X == 0) return i;
}
return -1;
}
do not forget to import,
import java.util.HashSet;
import java.util.Set;
Here's my solution, scored 100/100:
import java.util.HashSet;
class Solution {
public int solution(int X, int[] A) {
HashSet<Integer> hset = new HashSet<Integer>();
for (int i = 0 ; i < A.length; i++) {
if (A[i] <= X)
hset.add(A[i]);
if (hset.size() == X)
return i;
}
return -1;
}
}
Simple solution 100%
public int solution(final int X, final int[] A) {
Set<Integer> emptyPosition = new HashSet<Integer>();
for (int i = 1; i <= X; i++) {
emptyPosition.add(i);
}
// Once all the numbers are covered for position, that would be the
// moment when the frog will jump
for (int i = 0; i < A.length; i++) {
emptyPosition.remove(A[i]);
if (emptyPosition.size() == 0) {
return i;
}
}
return -1;
}
Here's my solution.
It isn't perfect, but it's good enough to score 100/100.
(I think that it shouldn't have passed a test with a big A and small X)
Anyway, it fills a new counter array with each leaf that falls
counter has the size of X because I don't care for leafs that fall farther than X, therefore the try-catch block.
AFTER X leafs fell (because it's the minimum amount of leafs) I begin checking whether I have a complete way - I'm checking that every int in count is greater than 0.
If so, I return i, else I break and try again.
public static int solution(int X, int[] A){
int[] count = new int[X];
for (int i = 0; i < A.length; i++){
try{
count[A[i]-1]++;
} catch (ArrayIndexOutOfBoundsException e){ }
if (i >= X - 1){
for (int j = 0; j< count.length; j++){
if (count[j] == 0){
break;
}
if (j == count.length - 1){
return i;
}
}
}
}
return -1;
}
Here's my solution with 100 / 100.
public int solution(int X, int[] A) {
int len = A.length;
if (X > len) {
return -1;
}
int[] isFilled = new int[X];
int jumped = 0;
Arrays.fill(isFilled, 0);
for (int i = 0; i < len; i++) {
int x = A[i];
if (x <= X) {
if (isFilled[x - 1] == 0) {
isFilled[x - 1] = 1;
jumped += 1;
if (jumped == X) {
return i;
}
}
}
}
return -1;
}
Here's what I have in C#. It can probably still be refactored.
We throw away numbers greater than X, which is where we want to stop, and then we add numbers to an array if they haven't already been added.
When the count of the list has reached the expected number, X, then return the result. 100%
var tempArray = new int[X+1];
var totalNumbers = 0;
for (int i = 0; i < A.Length; i++)
{
if (A[i] > X || tempArray.ElementAt(A[i]) != 0)
continue;
tempArray[A[i]] = A[i];
totalNumbers++;
if (totalNumbers == X)
return i;
}
return -1;
below is my solution. I basically created a set which allows uniques only and then go through the array and add every element to set and keep a counter to get the sum of the set and then using the sum formula of consecutive numbers then I got 100% . Note : if you add up the set using java 8 stream api the solution is becoming quadratic and you get %56 .
public static int solution2(int X, int[] A) {
long sum = X * (X + 1) / 2;
Set<Integer> set = new HashSet<Integer>();
int setSum = 0;
for (int i = 0; i < A.length; i++) {
if (set.add(A[i]))
setSum += A[i];
if (setSum == sum) {
return i;
}
}
return -1;
}
My JavaScript solution that got 100 across the board. Since the numbers are assumed to be in the range of the river width, simply storing booleans in a temporary array that can be checked against duplicates will do. Then, once you have amassed as many numbers as the quantity X, you know you have all the leaves necessary to cross.
function solution(X, A) {
covered = 0;
tempArray = [];
for (let i = 0; i < A.length; i++) {
if (!tempArray[A[i]]) {
tempArray[A[i]] = true;
covered++
if(covered === X) return i;
}
}
return -1;
}
Here is my answer in Python:
def solution(X, A):
# write your code in Python 3.6
values = set()
for i in range (len(A)):
if A[i]<=X :
values.add(A[i])
if len(values)==X:
return i
return -1
Just tried this problem as well and here is my solution. Basically, I just declared an array whose size is equal to position X. Then, I declared a counter to monitor if the necessary leaves have fallen at the particular spots. The loop exits when these leaves have been met and if not, returns -1 as instructed.
class Solution {
public int solution(int X, int[] A) {
int size = A.length;
int[] check = new int[X];
int cmp = 0;
int time = -1;
for (int x = 0; x < size; x++) {
int temp = A[x];
if (temp <= X) {
if (check[temp-1] > 0) {
continue;
}
check[temp - 1]++;
cmp++;
}
if ( cmp == X) {
time = x;
break;
}
}
return time;
}
}
It got a 100/100 on the evaluation but I'm not too sure of its performance. I am still a beginner when it comes to programming so if anybody can critique the code, I would be grateful.
Maybe it is not perfect but its straightforward. Just made a counter Array to track the needed "leaves" and verified on each iteration if the path was complete. Got me 100/100 and O(N).
public static int frogRiver(int X, int[] A)
{
int leaves = A.Length;
int[] counter = new int[X + 1];
int stepsAvailForTravel = 0;
for(int i = 0; i < leaves; i++)
{
//we won't get to that leaf anyway so we shouldnt count it,
if (A[i] > X)
{
continue;
}
else
{
//first hit!, keep a count of the available leaves to jump
if (counter[A[i]] == 0)
stepsAvailForTravel++;
counter[A[i]]++;
}
//We did it!!
if (stepsAvailForTravel == X)
{
return i;
}
}
return -1;
}
This is my solution. I think it's very simple. It gets 100/100 on codibility.
set.contains() let me eliminate duplicate position from table.
The result of first loop get us expected sum. In the second loop we get sum of input values.
class Solution {
public int solution(int X, int[] A) {
Set<Integer> set = new HashSet<Integer>();
int sum1 = 0, sum2 = 0;
for (int i = 0; i <= X; i++){
sum1 += i;
}
for (int i = 0; i < A.length; i++){
if (set.contains(A[i])) continue;
set.add(A[i]);
sum2 += A[i];
if (sum1 == sum2) return i;
}
return -1;
}
}
Your algorithm is perfect except below code
Your code returns value only if list[iii] matches with searchedValue.
The algorithm must be corrected in such a way that, it returns the value if sum == n * ( n + 1) / 2.
import java.util.ArrayList;
import java.util.List;
class Solution {
public int solution(int X, int[] A) {
int list[] = A;
int sum = 0;
int searchedValue = X;
int sumV = searchedValue * (searchedValue + 1) / 2;
List<Integer> arrayList = new ArrayList<Integer>();
for (int iii = 0; iii < list.length; iii++) {
if (list[iii] <= searchedValue && !arrayList.contains(list[iii])) {
sum += list[iii];
if (sum == sumV) {
return iii;
}
arrayList.add(list[iii]);
}
}
return -1;
}
}
I think you need to check the performance as well. I just ensured the output only
This solution I've posted today gave 100% on codility, but respectivly #rafalio 's answer it requires K times less memory
public class Solution {
private static final int ARRAY_SIZE_LOWER = 1;
private static final int ARRAY_SIZE_UPPER = 100000;
private static final int NUMBER_LOWER = ARRAY_SIZE_LOWER;
private static final int NUMBER_UPPER = ARRAY_SIZE_UPPER;
public static class Set {
final long[] buckets;
public Set(int size) {
this.buckets = new long[(size % 64 == 0 ? (size/64) : (size/64) + 1)];
}
/**
* number should be greater than zero
* #param number
*/
public void put(int number) {
buckets[getBucketindex(number)] |= getFlag(number);
}
public boolean contains(int number) {
long flag = getFlag(number);
// check if flag is stored
return (buckets[getBucketindex(number)] & flag) == flag;
}
private int getBucketindex(int number) {
if (number <= 64) {
return 0;
} else if (number <= 128) {
return 1;
} else if (number <= 192) {
return 2;
} else if (number <= 256) {
return 3;
} else if (number <= 320) {
return 4;
} else if (number <= 384) {
return 5;
} else
return (number % 64 == 0 ? (number/64) : (number/64) + 1) - 1;
}
private long getFlag(int number) {
if (number <= 64) {
return 1L << number;
} else
return 1L << (number % 64);
}
}
public static final int solution(final int X, final int[] A) {
if (A.length < ARRAY_SIZE_LOWER || A.length > ARRAY_SIZE_UPPER) {
throw new RuntimeException("Array size out of bounds");
}
Set set = new Set(X);
int ai;
int counter = X;
final int NUMBER_REAL_UPPER = min(NUMBER_UPPER, X);
for (int i = 0 ; i < A.length; i++) {
if ((ai = A[i]) < NUMBER_LOWER || ai > NUMBER_REAL_UPPER) {
throw new RuntimeException("Number out of bounds");
} else if (ai <= X && !set.contains(ai)) {
counter--;
if (counter == 0) {
return i;
}
set.put(ai);
}
}
return -1;
}
private static int min(int x, int y) {
return (x < y ? x : y);
}
}
This is my solution it got me 100/100 and O(N).
public int solution(int X, int[] A) {
Map<Integer, Integer> leaves = new HashMap<>();
for (int i = A.length - 1; i >= 0 ; i--)
{
leaves.put(A[i] - 1, i);
}
return leaves.size() != X ? -1 : Collections.max(leaves.values());
}
This is my solution
public func FrogRiverOne(_ X : Int, _ A : inout [Int]) -> Int {
var B = [Int](repeating: 0, count: X+1)
for i in 0..<A.count {
if B[A[i]] == 0 {
B[A[i]] = i+1
}
}
var time = 0
for i in 1...X {
if( B[i] == 0 ) {
return -1
} else {
time = max(time, B[i])
}
}
return time-1
}
A = [1,2,1,4,2,3,5,4]
print("FrogRiverOne: ", FrogRiverOne(5, &A))
Actually I re-wrote this exercise without seeing my last answer and came up with another solution 100/100 and O(N).
public int solution(int X, int[] A) {
Set<Integer> leaves = new HashSet<>();
for(int i=0; i < A.length; i++) {
leaves.add(A[i]);
if (leaves.contains(X) && leaves.size() == X) return i;
}
return -1;
}
I like this one better because it is even simpler.
This one works good on codality 100% out of 100%. It's very similar to the marker array above but uses a map:
public int solution(int X, int[] A) {
int index = -1;
Map<Integer, Integer> map = new HashMap();
for (int i = 0; i < A.length; i++) {
if (!map.containsKey(A[i])) {
map.put(A[i], A[i]);
X--;
if (X == 0) {index = i;break;}
}
}
return index;
}
%100 with js
function solution(X, A) {
let leafSet = new Set();
for (let i = 0; i < A.length; i += 1) {
if(A[i] <= 0)
continue;
if (A[i] <= X )
leafSet.add(A[i]);
if (leafSet.size == X)
return i;
}
return -1;
}
With JavaScript following solution got 100/100.
Detected time complexity: O(N)
function solution(X, A) {
let leaves = new Set();
for (let i = 0; i < A.length; i++) {
if (A[i] <= X) {
leaves.add(A[i])
if (leaves.size == X) {
return i;
}
}
}
return -1;
}
100% Solution using Javascript.
function solution(X, A) {
if (A.length === 0) return -1
if (A.length < X) return -1
let steps = X
const leaves = {}
for (let i = 0; i < A.length; i++) {
if (!leaves[A[i]]) {
leaves[A[i]] = true
steps--
}
if (steps === 0) {
return i
}
}
return -1
}
C# Solution with 100% score:
using System;
using System.Collections.Generic;
class Solution {
public int solution(int X, int[] A) {
// go through the array
// fill a hashset, until the size of hashset is X
var set = new HashSet<int>();
int i = 0;
foreach (var a in A)
{
if (a <= X)
{
set.Add(a);
}
if (set.Count == X)
{
return i;
}
i++;
}
return -1;
}
}
https://app.codility.com/demo/results/trainingXE7QFJ-TZ7/
I have a very simple solution (100% / 100%) using HashSet. Lots of people check unnecessarily whether the Value is less than or equal to X. This task cannot be otherwise.
public static int solution(int X, int[] A) {
Set<Integer> availableFields = new HashSet<>();
for (int i = 0; i < A.length; i++) {
availableFields.add(A[i]);
if (availableFields.size() == X){
return i;
}
}
return -1;
}
public static int solutions(int X, int[] A) {
Set<Integer> values = new HashSet<Integer>();
for (int i = 0; i < A.length; i++) {
if (values.add(A[i])) {
X--;
}
if (X == 0) {
return i;
}
}
return -1;
}
This is my solution. It uses 3 loops but is constant time and gets 100/100 on codibility.
class FrogLeap
{
internal int solution(int X, int[] A)
{
int result = -1;
long max = -1;
var B = new int[X + 1];
//initialize all entries in B array with -1
for (int i = 0; i <= X; i++)
{
B[i] = -1;
}
//Go through A and update B with the location where that value appeared
for (int i = 0; i < A.Length; i++)
{
if( B[A[i]] ==-1)//only update if still -1
B[A[i]] = i;
}
//start from 1 because 0 is not valid
for (int i = 1; i <= X; i++)
{
if (B[i] == -1)
return -1;
//The maxValue here is the earliest time we can jump over
if (max < B[i])
max = B[i];
}
result = (int)max;
return result;
}
}
Short and sweet C++ code. Gets perfect 100%... Drum roll ...
#include <set>
int solution(int X, vector<int> &A) {
set<int> final;
for(unsigned int i =0; i< A.size(); i++){
final.insert(A[i]);
if(final.size() == X) return i;
}
return -1;
}