recursive game plan function - java

I want to write a simple recursive function for a game plan in java.
I have 2^k teams and want an output like this (e.g. 4 teams):
(team)(day1)(day2)(day3)
1 2 3 4
2 1 4 3
3 4 1 2
4 3 2 1
My idea was to call the function recursive with half of its original size, but I can't figure out how to code it properly. If called with n/2, the output has to go into the upper left corner of the plan, the output PLUS n/2 has to go to the lower left corner and the rest is symmetric to the center.
Thanks
My code so far
public void plan(int size) {
if(size==2){}
else{}
}

make a Set for each day (unique)
then use n(max number)
itterate a loop n times and each itteration
newRandomNumber % n (fetch a random number a limit it to 0 to (n-1)
now add the (generatedValue+1) to the set
if it already exists (do check ) then increment the value till its new value then add to set
note: i dont get ur symetric requirement

Related

Generating all possible Permutation matrices [duplicate]

This question already has answers here:
All possible permutations of a NxN matrix in Java
(2 answers)
Closed 1 year ago.
Permutation matrices are matrices with exactly one 1 on each line and column.
Example:
(1 0 0)
(0 1 0)
(0 0 1)
I am trying to generate all possible permutations of a n-sized matrix but this seems harder to solve than expected. I tried swapping rows at first, but if you only swap rows of one initial matrix, you can't generate all possibilities. So I tried some recursion, but sadly I can't get my head through recursion. Does somebody have some advice?
I think you could make an algorithm based on recursion, with this design:
public Collection<Matrix> permute(int n)
Base case is n=1: It returns a single matrix {1}.
The rest of cases must iterate from i=0 to n-1. On eeach iteration:
Call to permute(n-1) and iterate the returned list. On each iteration:
Convert the n-1 matrix to a n x n matrix, inserting a row at position 0 and a column at position 0 (filled with 0).
Set an 1 in the (0,0) position.
Move the first column to the i position.
I suggest you could also make a battery of unit tests. Each one should check, at least, that the size of the collection returned by permute(n) has n! elements:
1->1
2->2
3->6
4->24

How to track and update a value in a Java 2D array?

I need to develop a program that randomly creates an array (10x10) of int values (either 1 or 0; 1 = wall; 0 = no wall) and have a loop that requires the user to navigate the array in a maze-like fashion. This loop must also test if the user has reached the bottom of the array. At the end, the program must print the array with the user's path, basically any value the user touches is a different number than 1 or 0.
I can create and print the array no problem, and set it to only values of 1 or 0 my confusion is:
How to lower the odds of getting a 1.
How to create a loop to navigate/track the maze and the user's path.
How to change the array's values that the user touches, and print the newly changed array correctly. (preferably using nodes).
Let's say this is a randomly generated 5x5 array:
0 1 0 0 1
0 1 1 1 0
1 0 1 1 0
0 1 0 0 1
1 1 0 1 1
This is what the output window would look like using this array:
Where do you want to go (up, down, left, right):
down
Where do you want to go (up, down, left, right):
right
You hit a wall! Game over!
5 1 0 0 1
5 7 1 1 0
1 0 1 1 0
0 1 0 0 1
1 1 0 1 1
The 0's are open paths that allow the user to pass through them, the 1's are walls that end the game if the user runs into them. 5 represents the path of the user, 7 is the spot the user hit a wall at.
In my situation, the array would be 10x10 and only be printed once, at the end of the program. The user would not see the original array.
I'm not asking anyone to program it for me, just a little push in the right direction. I can't seem to figure it out in my head, logically. Again I'm very new to Java programming and would appreciate any help anyone is willing to offer.
I apologize for the very long question, I just want as much clarity as possible, given that my situation requires context to understand fully. If more info is required, I will respond within a day. I have also added photos of my code, if my explanation makes no sense.
I greatly appreciate any and all help given, Thank you very much! :D
Pic 1 of code
Pic 2 of code
For lower odds of getting 1 see this link.
Keep the current location of the played in an object/variable/class ex:
public static class Location {
public static int x = 0;
public static int y = 0;
}
Every time user moves for example down:
Increase Location.x++.
Check if the new location is a wall or not ex: if(Grid[Location.x][Location.y] == 1) /* do stuff */.
Change the value of the grid cell: Grid[Location.x][Location.y] = '{your value}'.
Use Random instead of secure random, you can get the next random with
Random r = new Random();
iWallChance = r.nextInt(100);
2 and 3. Ali Sharabiani has a good answer for that.

Java permutations of offsets

Had a question regarding generating a list of 10-digit phone numbers on a PhonePad, given a set of possible moves and a starting number.
The PhonePad:
1 2 3
4 5 6
7 8 9
* 0 #
Possible moves:
The same number of moves a Queen in chess can make (so north, south, east, west, north-east, north-west, south-east, south-west... n-spaces per each orientation)
Starting number: 5
So far I have implemented the PhonePad as a 2-dimensional char array, implemented the possible moves a Queen can make in a HashMap (using offsets of x and y), and I can make the Queen move one square using one of the possible moves.
My next step is to figure out an algorithm that would give me all 10-digit permutations (phone numbers), using the possible moves in my HasMap. Repetition of a number is allowed. * and # are not allowed in the list of phone numbers returned.
I would imagine starting out with
- 5555555555, 5555555551, 5555555552... and so on up to 0,
- 5555555515, 5555555155, 5555551555.. 5155555555.. and with the numbers 2 upto 0
- 5555555151, 5555551515, 5555515155.. 5151555555.. and with numbers 2 upto 0
... and so on for a two digit combination
Any suggestions on a systematic approach generating 10-digit combinations? Even a pseudocode algorithm is appreciated! Let me know if further clarification is required.
Thanks in advance! :)
In more detail, the simplest approach would be a recursive method, roughly like:
It accepts a prefix string initially empty, a current digit (initially '5'), and a number of digits to generate (initially 10).
If the number of digits is 1, it will simply output the prefix concatenated with the current digit.
If the number of digits is greater than 1, then it will make a list of all possible next digits and call itself recursively with (prefix + (current digit), next digit, (number of digits)-1 ) as the arguments.
Other approaches, and refinements to this one, are possible of course. The "output" action could be writing to a file, adding to a field in the current class or object, or adding to a local variable collection (List or Set) that will be returned as a result. In that last case, the (ndigits>1) logic would have to combine results from multiple recursive calls to get a single return value.

Courier delivery with A* algorithm

I have to make a program which can calculate the shortest path to finish all deliveries.
The map is represent as x, y coordinate and the path is calculated using Manhattan distance(so go along x and then along y).
Start point is always (0, 0) and the courier can finish on any point. The courier can only bring 1 packet at any given time.
This could be implemented using A* search algorithm, my question is since A* algorithm is an I formed search, it needs to know heuristic value of its statusNode. What is a good heuristic implementation for this problem? Or even an idea for the heuristic value?
I have a sample input:
Job 3 3 to 5 3 # there is a job from (3,3) to (5,3)
Job 1 1 to 9 2 # there is a job from (1,1) to (9,2)
Job 3 5 to 2 7 # there is a job from (3,5) to (2,7)
Job 5 5 to 5 7 # there is a job from (5,5) to (5,7)
ANd the output:
Cost = 31
Move from 0 0 to 1 1
Carry from 1 1 to 9 2
Move from 9 2 to 3 3
Carry from 3 3 to 5 3
Move from 5 3 to 5 5
Carry from 5 5 to 5 7
Move from 5 7 to 3 5
Carry from 3 5 to 2 7
My current method for the search is:
I have list of jobToBeDone and jobDone
Intialise intial value of current position is 0, 0
Check whether all jobs have been done
If not, for all remaining jobs, Calculate the total cost=path to get there + some heuristic value of the job.
Put them in jobsToBeDone and sort with shortest path has lower index (like a priorityQueue in java).
repeat instruction from no 2 by updating current position to the job in the first index.
There are two problems. Shortest path and traveling salesman.
You need to calculate all paths between your points and then order the points to get the final shortest route. For the last part you need an heuristic or brute force for a small amount of points.
Instead of A* use Dijkstra as with dijkstra you can easily calculate several paths at once (as it is one to many)

Create 2 arrays - 1st has random integers, 2nd has unique random integers

I am working on a school homework problem. I need to create 2 int[] arrays. The first array int[10] is filled with random integers. The second array has the same numbers as in the first array, but without any duplicates.
For example, assume my first array is 1,2,2,3,1,5,5,7,9,9. My second array would then be 1,2,3,5,7,9.
Could someone please point me in the right direction to solving this problem.
Put the numbers into a Set. Then retrieve numbers from the Set. Simple! Duplicates will automatically be removed!
I would do the following (assuming that it is homework and you shouldn't be doing anything too complicated)...
Sort the array using java.util.Arrays.sort(myArray); - this will order the numbers, and make sure that all repeating numbers are next to each other.
Loop through the array and keep a count of the number of unique numbers (ie compare the current number to the next number - if they're different, increment the counter by 1)
Create your second int[] array to the correct size (from point 2)
Repeat the same process as point 2, but fill your new array with the unique numbers, rather than incrementing a counter.
This should be enough to get you moving in the right direction. When you have some code, if you still have questions, come back to us and ask.
I recommend using a Set , but here's a way to do it without using a Set. (Note: This will work, but don't ask me about the efficiency of this!)
Have a function like this -
public static boolean isNumberInArray(int[] array, int number)
{
for(int i=0; i<array.length; i++)
{
if(number == array[i])
return true;
}
return false;
}
Now use this function before you make an insert into the new array. I leave you to figure out that part. It's homework after all!
Hints(WATTO explains it better):
a = sorted first array
lastItem = a[0]
append lastItem into new array
for i in 1 to length(a):
if a[i] != lastItem:
append a[i] into new array
lastItem = a[i]
#WATTO Studios has a good approach. Sorting is always useful when duplicates are involved.
I will suggest an alternative method using hash tables:
Create a hashing structure with an integer as key (the number in the original array) and a counter as a value.
Go through the original array and for each number encountered increment it's corresponding counter value in the hash table.
Go through the original array again. For each number check back the hash table. If the counter associated is greater than 1, remove the value and decrement the counter.
Let's see a practical case:
4 5 6 4 1 1 3
First pass will create the following table:
1 -> 2
3 -> 1
4 -> 2
5 -> 1
6 -> 1
Second pass step by step:
4 5 6 4 1 1 3
^
4 has a counter of 2 -> remove and decrement:
1 -> 2
3 -> 1
4 -> 1
5 -> 1
6 -> 1
5 6 4 1 1 3
^
5 has a counter of 1 -> ignore
6 has a counter of 1 -> ignore
4 has a counter of 1 -> ignore
1 has a counter of 2 -> remove and decrement
1 -> 1
3 -> 1
4 -> 1
5 -> 1
6 -> 1
5 6 4 1 3
^
1 has a counter of 1 -> ignore
3 has a counter of 1 -> ignore
Final array:
5 6 4 1 3
There are, of course, more efficient ways to handle the removal (since using an array implies shifting), like inserting the items into a linked list for example. I'll let you decide that. :)
Edit: An even faster approach, requiring a single pass:
Use the same hashing structure as above.
Go through the original array. For each item check the table. If the associated counter is 0, increment it to 1. If it's already 1, remove the item.

Categories