How to try all possible way of traversing Array of integer - java

I'm new in programming and I'd like some help for an assignment, I only need a little clue to help me getting started (no answer, I only want to get a direction of how to do it then work my way).
The rules of the game : on the initial square is a marker that can move to other squares along the row. At each step in the game, you may move the marker the number of squares indicated by the integer in the square it currently occupies. The marker may move either left or right along the row but may not move past either end.
The goal of the game is to move the marker to the cave, the “0” at the far end of the row. In this configuration, you can solve the game by making the following set of moves:
eg: 2 3 1 2 4 0
first: move of 2 (to the right since it's impossible to go to the left) then: either move 1 to the right or 1 to the left then: if we moved left before: move 3 to the right (cannot go 3 to the left) if we moved right before then it's either 2 to the left or 2 to the right. 2 to the right is the right answer since then the next value is 0.
I must write the program that will try all the possibilities (so using a loop or a recursive I guess?) and return TRUE if there's a solution or FALSE if there are no solution. I had to choose the data structure from a few given by the prof for this assignment and decided to use an Array Based List since the get() is O(1) and it's mainly the only method used once the arraylist is created.
My program is only missing the (static?) method that will evaluate if it's possible or not, I dont need help for the rest of the assignment.
Assume that the ArrayBasedList is already given.
Thanks for your help!

I think your idea about using a recursive method makes a lot of sense. I appreciate you don't want the full answer, so this should just give you an idea:
Make a method (that passes in an integer x of the current position and your list) that returns a boolean.
In the method, check the value of list.get(x).
If it's 0, return true.
If it's -1, return false (more on that later).
Otherwise, store the value in a variable n, replace it with a -1, and return method(x+n) || method(x-n).
What the -1 does is it eventually fills everything in the array with a value that will terminate the program. Otherwise, you could end up with an infinite loop (like if you passed in [1, 2, 4, 2, 3]) with the value going back and forth.
A couple of things to keep in mind:
You'd need to make a new copy of the array every time, so you don't keep overwriting the original array.
You'd need to incorporate a try-catch (or equivalent logic) to make sure you are not trying to measure out of bounds.
If you have any further questions, feel free to ask!

Related

Displaying Numbers in Certain Shapes

I just thought of this problem 15 minutes ago and even though it appears insanely easy I'm having a serious problem coming up with an answer.
Basically what I would like to do is based on a number (n) given by the user, I would like to draw a square shape.
Example: let's say the user gives the number 2, the result should be:
12
43
Now, suppose the user gives the number 3, the result should be:
123
894
765
etc..
Please don't give me the solution to this problem, I just want a clue or two to get me going.
I thought about doing it with a simple java class but I'm still struggling to get past the first condition:
public class DrawSquareWithNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your number: ");
int number = scanner.nextInt();
for (int i = 0; i <= number; i++) {
if (i<number)
System.out.print(i);
if (i>=number) {
System.out.println("\n"+i);
}
}
}
}
Any tip? Thanks in advance.
So I think I just put way too much time in this but it's a fun challenge so I thought let's give it a go.
I implented a code version for this solution and it works quite well although it's probably not the cleanest as I approached the whole problem backwards.
Here is my solution to try out online (note it's severely unoptimized and by no ways good Java code. It's a quick and dirty implementation to be honest):
https://ideone.com/97JB7Y
So the idea is quite simple: We first calculate the correct value for each position in a matrix and then we print that matrix out.
Let's go over it in a bit more detail:
We start of by creating the Matrix for our values to print:
With a given size n this is
int[][] values = new int[n][n];
Now we want to calculate the correct value at each point. I chose to tackle it the "wrong way" around by not starting at the first point but at the center of the spiral.
Basically imagine this matrix with n = 3:
[1][2][3]
[8][9][4]
[7][6][5]
Instead of at 1 I just start at 9. Reasoning for this is that it's actually easier to calculate the position spiraling out from a point over spiraling in to a point.
So starting at this center point we spiral out from there in a circular fashion. For the matrix
[1][2]
[4][3]
this means we visit 4 -> 3 -> 2 -> 1. And then just save the correct value in the matrix.
Only problem with my approach is that for a matrix with uneven size (3, 5, 7, etc.) I still visit the points in spiraling order, for 3x3 the order of visiting is e.g. 9 -> 4 -> 3 -> 2 -> 1 -> 8 -> 7 -> 6 -> 5, as visualized in this perfect picture I totally drew in Paint:
This leads to the result matrix being inversed as such:
[5][6][7]
[4][9][8]
[3][2][1]
This small problem is easily fixed though by simply printing the matrix out inversed once more should n%2 != 0.
Hope I could help with maybe a different approach to the problem.
I think you want to make nxn matrix with user entered number. So you can check the input and then you can use loop as for(i=1; i<=n; i++) for rows and similarly for column(for j=0;j<=n;j++) and then you can print your desired shape. Since you have asked to give you idea only so I am not posting any code here. If in case you get stuck somewhere you can refer : https://www.google.com/amp/s/www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/amp/
Ok, let's give this a try. First let's assume you'll have to store the matrix before printing it and that there's no magic formula that allows you to print what you need in a single iteration.
Now, you've the NxN matrix, for example for 3 it'd be 3x3, 9 positions. Instead of solving it with a series of ifs in an ugly way, you could use direction vectors for a cleaner solution. Also assume for now that you've another NxN matrix filled with booleans, all set to false, that will represent the already printed positions in the NxN matrix that you will print in the end. When you write a number in the final NxN matrix, you put the same position's boolean to true in the boolean matrix.
So for example, you want to print the positions of the first row, 1 2 3. You are displacing to the right to print. This'd be the direction (1,0), aka the starting direction vector. You advance through the NxN matrix using this coordinates. When you go outside the matrix (in the example, your x position is 3) you decrease your x position by one and you "spin" your direction vector (this should be done in a separate function). (1,0) would spin to (0,-1). You keep using this vector to iterate your matrix, spinning as necesary. After the first whole circle, you will get to an already printed position before going outside the matrix. So after every print you've to check not only if you go outside the matrix, but also if that position has already a number on it. For this, you use the boolean matrix.
This is how I'd solve it, there are probably many other ways (and better ones). For starters you could use null, or a mark, in the final matrix and save yourself the booleans one.
Create the result matrix beforehand, and declare a variable for the current number, starting value = 1, the current co-ordinates, starting with (0,0), the stepping direction starting with "to the right"
Start loop
Calculate the co-ordinates of next step, and check it
If it is off the matrix, then change direction, and re calculate, re-check
If free, then put the number in the matrix, increment it, and loop
If it is not free, then end loop, print out result matrix

Double Recursion in one method Java

I am pretty sure that I thoroughly understand how the methods with only one recursion work.
Ex) calculating factorial
public int factorial(int n){ //factorial recursion
if(n==0){
return 1;
}
else{
return n*factorial(n-1);
}
}
For these methods, I can even picture what's going on in the stacks and what values are being returned at each stack level.
But Whenever, I encounter methods with Double Recursions, the nightmare begins.
Below is a recursion problem with double recursions from coding bat.
Ex) Given an array of ints, is it possible to choose a group of some of the ints, such that the group sums to the given target? If yes, true. If no, false.
You use 3 parameters; starting index start, An int Array nums, target int value target.
Below is the solution for this problem.
public boolean groupSum(int start, int[] nums, int target) {
if (start >= nums.length) return (target == 0);
if (groupSum(start + 1, nums, target - nums[start])) return true;
if (groupSum(start + 1, nums, target)) return true;
return false;
}
My take to understand this solution is this. Say I was given an array {2,4,8} with starting index = 0, and target value 10. So (0,{2,4,8},10) goes in through the method, the function gets re-called at
if (groupSum(start + 1, nums, target - nums[start])) return true;
so it becomes (1,{2,4,8},8) and it does over and over until start index hits
3. when it hits 3. The stack at the last level(?) goes to the second recursive call. And this is where I start losing track of what's happening.
Can anybody break this down for me? And when people use double recursion,(I know it's very inefficient and in practice, almost no one uses it for its inefficiency. But just in an attempt to understand it.)can they actually visualize what's going to happen? or do they just use it hoping that the base case and recursion would work properly? I think this applies generally to all the ppl who wrote merge sort, tower of hanoi alogrithm etc..
Any help is greatly appreciated..
The idea of a double recursion is to break the problem into two smaller problems. Once you solve the smaller problems, you can either join their solutions (as is done in merge sort) or choose one of them - which is done in your example, which only requires the second smaller problem to be solved if solving the first smaller problem didn't solve the full problem.
Your example tries to determine if there is a subset of the input nums array whose sum is the target sum. start determines which part of the array is considered by the current recursive call (when it's 0, the entire array is considered).
The problem is broken to two, since if such a subset exists, it either contains the first element of the array (in which case the problem is reduced to finding if there's a sub-set of the last n-1 elements of the array whose sum is target minus the value of the first element) or doesn't contain it (in which case the problem is reduced to finding if there's a sub-set of the last n-1 elements of the array whose sum is target).
The first recursion handles the case where the subset contains the first element, which is why it makes a recursive call that would look for the target sum minus the first element in the remaining n-1 elements of the array. If the first recursion returns true, it means that the required subset exists, so the second recursion is never called.
The second recursion handles the case where the subset doesn't contain the first element, which is why it makes a recursive call that would look for the target sum in the remaining n-1 elements of the array (this time the first element is not subtracted from the target sum, since the first element is not included in the sum). Again, if the second recursive call returns true, if means that the required subset exists.
Well if you want to visualize it, usually it's kind of like a tree. You first follow one path through the tree until the end, then step one back and pick a different path (if possible). If there is none or you are happy with your result you just take another step back and so on.
I don't know if this helps you but when I learned recursion, it helped to just think of my method as already working.
So I thought: Great, so basically my method is already working, but I can't call it with the same parameters and have to make sure I return the right value for these exact parameters by using different ones.
If we take that example:
At first we know that if we have no numbers to look at left, then the answer depends on if the target is 0. (first line)
Now what do we do with the rest? Well... we'd need to think about it for a moment.
Just think about the very first number. Under what circumstances is it part of the solution? Well that would be if you could create target-firstnumber with the rest of the numbers. Because then when you add firstnumber, you reach target.
So you try to see if that's possible. If so, it's solvable. (second line)
But if not, it's still possible that the first number just isn't important for the solution. So you have to try again to build the target without that number. (third line)
And that's basically all there is to this.
Of course to think like this you need two things:
1. You need to believe that your method already works for other parameters
2. You need to make sure your recursion terminates. That's the first line in this example but you should always think about if there is any combination of parameters that will just create an endless recursion.
Try to understand it like this: Recursion can be rewritten as a while-loop. where the condition of the while is the negation of the stop-condition of the recursion.
As already said, there is nothing called double recursion.

Given an array of length N, where each element in the array has X possibilities, return all possible arrays

I'm trying to solve the above problem using Java. Thought about using for loops but I can't see how this would work without knowing X and N in advance. I'm trying to solve it with recursion but not sure how it looks. Been trying for a couple hours now. Any help is greatly appreciated.
Example, if N = 4 and x = 3, possible arrays are:
[0,0,0,1]
[2,1,0,0]
[1,2,1,1]
[0,2,2,2]
My algorithem works like counting, you start counting until X (basiclly like counting in Base X) and when you get to X you add 1 to the next position in the Array and reset the last position.
so, as far as i know you can't return few arrays in a normal way so i'll assume you want to print them.
now, this is a "nice" code:
http://pastebin.com/Uqv3fMxg
few notes:
you should not make the function static, i did it from laziness.
this is not perfect, it print twice [1,0], [2,0] and so on. couln't find the problem and it is way too late for me, i'll try to check it again tommorow.
i'm not a guy that comments his code, i did a little but i'll explain everything i can here.
The program starts in the main method where i defined the Array and started the recurtion method.
The stop statement is when i got into the N position (that doesn't exist in the array, only N-1)
The parameters: the array, the position in the array that i am corrently counting and a "mode", is it a run to go to the next position or just to print all of the number in this position.
The alreadyHas variable is ment to not print number 2 times.
if i won't use it, it would print every number atleast 2 times, it will redo any work he has done until he move to this position and every position.
it is hard to explain, you can write 0 instead of it and see what happens.
so, i count until X, every time i print the new Array and to count every number and not skiping any i have to recount the last position with a different number in the last position.
after i have count all of the possible numbers in this possition, i am giving it a value of 0 and going to the next position.
so,to sum it up, you count the number in the first position of the array, when you reach the maximum you add a carry in the next position and reset the corrent position.

Simple algorithm for a sudoku solver java

I've been stuck on this thing for a while, I just can't wrap my head around it. For a homework, I have to produce an algorithm for a sudoku solver that can check what number goes in a blank square in a row, in a column and in a block. It's a regular 9x9 sudoku and I'm assuming that the grid is already printed so I have to produce the part where it solves it.
I've read a ton of stuff on the subject I just get stuck expressing it.
I want the solver to do the following:
If the value is smaller than 9, increase it by 1
If the value is 9, set it to zero and go back 1
If the value is invalid, increase by 1
I've already read about backtracking and such but I'm in the early stage of the class so I'd like to keep it as simple as possible.
I'm more capable of writing in pseudo code but not so much with the algorithm itself and it's the algorithm that is needed for this exercise.
Thanks in advance for your help guys.
Seeing as it's homework, I believe I can point you in the general direction.
To start, keep a two-dimensional array (or a data structure that can represent the grid), and keep track of the values that can go there. Let's say it's a class named "possibilities":
public class Possibilities {
//Keep track of the numbers possible internally, with an accessor
}
The way sudoku works, there will usually be a square with only a single answer (in some cases, this won't be available, which means you need to potentially make a copy of the data and play out a little bit, or have a way to roll back). Simply put, fill in the answer, and then iterate over the adjacent squares to remove the freshly put number as a possibility (And check those squares simultaneously as new potential answers).
I think the easiest algorithm for solving a sudoku puzzle is a complete search. That is, trying every single combination until you find one that works. The easiest way to implement this is recursively. I know you don't want to get involved in backtracking, but I actually think that would be the easiest way for you to write this algorithm.
Assume you already have an algorithm that checks whether n can go in some cell at (i, j) in your board. This means that n does not violate any of the constraints (there can only be one number from 1 .. 9 in each row, column and box). This should not be too hard, you just have to loop through the row, column and box that contains cell (i, j) and make sure that n does not appear yet.
Then, you will have a recursive function called solve() that will return true if it finds a solution, otherwise it will return false. The function will constantly place numbers in empty cells of the sudoku board (only if they don't violate the constraints, which we assume you already write an algorithm for) until it is filled. Once filled, the puzzle is solved. You know that the board is valid because you've been checking the validity of every number you place on the way there. If no number can be placed at any point, it will backtrack by returning false.
The pseudocode for solve will look something like this:
boolean solve()
if the board is filled
return true
for each cell that is not empty
for n = 1 .. 9
if n does not exist in this row, column and box
place n in this cell
if solve()
return true
remove n from this cell
return false

RLE sequence, setting a value

Say I have an arbitrary RLE Sequence. (For those who don't know, RLE compresses an array like [4 4 4 4 4 6 6 1 1] into [(5,4) (2,6) (2,1)]. First comes the number of a particular integer in a run, then the number itself.)
How can I determine an algorithm to set a value at a given index without decompressing the whole thing? For example, if you do set(0,1) the RLE would become [(1,1) (4,4) (2,6) (2,1)]. (In set, the first value is the index, the second is the value)
Also, I've divided this compressed sequence into an ArrayList of Entries. That is, each Entry is one of these: (1,1) where it has an amount and value.
I'm trying to find an efficient way to do this, right now I can just think of methods that have WAY too many if statements to be considered clean. There are so many possible variations: for example, if the given value splits an existing entry, or if it has the same value as an existing entry, etc...
Any help would be much appreciated. I'm working on an algorithm now, here is some of it:
while(i<rleAL.size() && count != index)
{
indexToStop=0;
while(count<index || indexToStop == rleAL.get(i).getAmount())
{
count++;
indexToStop++;
}
if(count != index)
{
i++;
}
}
As you can see this is getting increasingly sloppy...
Thanks!
RLE is generally bad at updates, exactly for the reason stated. Changing ArrayList to LinkedList won't help much, as LinkedList is awfully slow in everything but inserts (and even with inserts you must already hold a reference to a specific location using e.g. ListIterator).
Talking about the original question, though, there's no need to decompress all. All you need is find the right place (summing up the counts), which is linear-time (consider skip list to make it faster) after which you'll have just four options:
You're in a block, and this block is the same as a number you're trying to save.
You're inside a block, and the number is different.
You're in the beginning or the end of the block, the number differs from the block's but same as neighbour has.
You're in the beginning or the end of the block, the number is neither the same as block's nor the one of neighbour's.
The actions are the same, obviously:
Do nothing
Change counter in the block, add two blocks
Change counters in two blocks
Change counter in one block, insert a new one
(Note though if you have skip lists, you must update those as well.)
Update: it gets more interesting if the block to update is of length 1, true. Still, it all stays as trivial: in any case, the changes are limited to maximum of three blocks.

Categories