Comparing Two 1 column 2d Arrays - java

I have a 2d array
0 1 0
0 * 0
0 * 0
0 2 0
0 * 0
That I altered to be this
0 * 0
0 * 0
0 * 0
0 1 0
0 2 0
By doing this
Dot[][] tempDot = dotArray;
ArrayList<Descriptor> movedList = new ArrayList<Descriptor>();
for(int j=0; j<this.getHeight(); j++){
for (int i=this.getHeight()-1; i>0; i--){
if(dotArray[i][col] == null){
dotArray[i][col] = dotArray[i-1][col];
dotArray[i-1][col] = null;
}
}
}
Now I'm trying to figure out how compare the second column in the first one to the second column in the second one. I have to return a "Descriptor" object which contains the original location any non-null that moved down. I have tried doing nesting for loops to check the first value in each loop and then finding the first value in the second loop but that wasn't working. Any help would be great!

If Descriptor is defined like this,
private class Descriptor {
Descriptor(int from, int to, Dot[] dots) {
this.from = from;
this.to = to;
this.dots = dots;
}
public int from;
public int to;
public Dot[] dots;
}
you can do this way.
// Store original location(index) of each row.
Map<Dot[], Integer> originLocMap = new HashMap<Dot[], Integer>();
for (int i = 0; i < tempDot.length; i++) {
originLocMap.put(tempDot[i], i);
}
// Sort rows by second column (dot[*][1])
for (int i = tempDot.length - 1; i > 0; i--) {
if (tempDot[i][1] != null) {
continue;
}
for (int j = i - 1; j >= 0; j--) {
if (tempDot[j][1] != null) {
Dot[] temp = tempDot[i];
tempDot[i] = tempDot[j];
tempDot[j] = temp;
break;
}
}
}
// Collect location change data
ArrayList<Descriptor> movedList = new ArrayList<Descriptor>();
for (int i = tempDot.length - 1; i >= 0; i--) {
if (tempDot[i][1] == null) {
break;
}
Dot[] dots = tempDot[i];
int from = originLocMap.get(dots);
Descriptor descriptor = new Descriptor(from, i, dots);
movedList.add(descriptor);
}
Iterator<Descriptor> it = movedList.iterator();
while (it.hasNext()) {
Descriptor d = it.next();
System.out.println(d.from + " ==> " + d.to);
}

Related

Is there a simpler way to move objects in an array so they are adjacent?

I'm working on a problem that gives an array of objects (4 objects) in an array with a size of 7, so there are 3 null values. The array is scrambled. I need to consolidate the elements so they are in the 0,1,2,3 spaces of the array, in the same order. the null values have to be put at the end of the array on spaces 4,5,6.
Here is what I have so far:
//a car object has a name and top speed
public void consolidate() {
int numCars = 0;
for (int i = 1; i < cars.length; i++) {
if (cars[i] != null)
numCars++;
}
for (int k = 0; k < numCars; k++) {
for (int i = 1; i < cars.length; i++) {
if (cars[i - 1] == null) {
cars[i - 1] = cars[i];
cars[i] = null;
}
}
}
}
If you are okay with creating a separate array of the same length but null values at the end, you can do it very simply as shown below:
int j=0;
Car[] newCars = new Car[cars.length];
for(int i=0; i<cars.length; i++) {
if(cars[i] != null)
newCars[j++] = cars[i];
}
1. Have two variables i = 0, j = last element of array
2. Repeat
Move i till you get a null object
Move j till you get a non null object
swap value of i and j
If i <= j then break
Hope it helps.
To maintain the same order
1. Have two variables i = 0, j = 0
2. Repeat
Move i till you get a null object
j = i+1
Move j till you get a non null object
swap value of i and j
Either i or j reaches end of the element then break
1 null 2 3 null
i => null at index = 1
j = at index = 2
===
1 2 null 3 null
i finds null at index =2 as it was at index=1
j finds 3
1 2 3 null null
Alternativley you could use Arrays#sort like below:
Arrays.sort(cars, new Comparator<Car>() {
#Override
public int compare(Car c1, Car c2) {
if (c1 == null && c2 == null) {
return 0;
}
if (c1 == null) {
return 1;
}
if (c2 == null) {
return -1;
}
return Arrays.asList(cars).indexOf(c1)-Arrays.asList(cars).indexOf(c2);
}
});
This seems to work:
Integer[] cars = {null, null, 1, null, 2, 3, 4};
int nums = 4;
for (int i = 0; i < nums; i++) {
if (cars[i] != null) {
continue;
}
int j = i + 1;
while(j < cars.length - 1 && cars[j] == null) {
j++;
}
cars[i] = cars[j];
cars[j] = null;
}

Java Removing Redundant Items in Array

For this particular problem I am attempting to remove redundant elements in an sorted array and replace them all with 0s at the end of the array. For example, if I had an array consisting of the int elements
1,3,3,4,4,5,6,6,7
My output array should be
1,3,4,5,6,7,0,0,0
My first attempt at the problem was to create a swapper in order to push all the 0s to the end of the list after removing the elements, but it won't seem to push the zeros to the end of the list. Here is my code.
public void implode(int[] ary)
{
int swapper = -1;
int[] newARY = new int[ary.length];
int current = -1;
for (int i = 0; i < ary.length; i++)
{
if (current != ary[i])
{
newARY[i] = ary[i];
current = ary[i];
}
}
for (int i = 0; i < ary.length; i++)
{
if (ary[i] == 0)
{
if (ary[i + 1] != 0)
{
swapper = ary[i + 1];
ary[i] = swapper;
ary[i + 1] = 0;
}
}
}
ary = newARY;
for (int i = 0; i < newARY.length; i++)
{
System.out.print(newARY[i] + " ");
}
}
The array im testing it with is,
int[] aryIn2 = {1, 1, 2, 3, 4, 4, 5, 6};
However, when outputting the imploded array, I receive this one.
1 0 2 3 4 0 5 6
Is there something I am missing?
Thanks in advance.
not an answer to your problem, but using (if possible) java streams can shorten your way:
int[] arr = {1,3,3,4,4,5,6,6,7};
// distinct
List<Integer> list = Arrays.stream(arr).distinct().boxed().collect(Collectors.toList());
// pad with zero's
while(list.size() < arr.length) {
list.add(0);
}
// display
System.out.println(list.stream().map(String::valueOf).collect(Collectors.joining(",")));
will output
1,3,4,5,6,7,0,0,0
Two issue with you code that I observed.
1) Your swapper logic is performing swapping on a different array than the one in which you had done modification earlier
2) You need to have this logic in a bubble-sort way, i.e. loop inside a loop
Below is a working modified sample code of your method. I have modified only the second for-loop logic
public void implode(int[] ary) {
int swapper = -1;
int[] newARY = new int[ary.length];
int current = -1;
for (int i = 0; i < ary.length; i++) {
if (current != ary[i]) {
newARY[i] = ary[i];
current = ary[i];
}
}
for (int i = 0; i < newARY.length - 1; i++) {
if (newARY[i] == 0 && newARY[i + 1] != 0) {
for (int j = i; (j + 1) < newARY.length; j++) {
swapper = newARY[j + 1];
newARY[j] = swapper;
newARY[j + 1] = 0;
}
}
}
for (int i = 0; i < newARY.length; i++) {
System.out.print(newARY[i] + " ");
}
}
In this first loop:
for (int i = 0; i < ary.length; i++) {
if (current != ary[i]) {
newARY[i] = ary[i];
current = ary[i];
}
}
You fill newARY with elements in ary with duplicated value turns to 0:
newARY: 1 0 2 3 4 0 5 6
However, in the second loop:
for (int i = 0; i < ary.length; i++)
{
if (ary[i] == 0)
{
if (ary[i + 1] != 0)
{
swapper = ary[i + 1];
ary[i] = swapper;
ary[i + 1] = 0;
}
}
}
You're modifying your original ary array. So the newARY is not updated.
However, your attempt to push 0 to the end of array also fail if there are more than two 0s consecutive. And it is also vulnerable to ArrayOutOfBoundIndexException since you try to read ary[i+1] without restriction on i
One simple and straight forward way to push 0s to the end of the array is to create new array with non-0s elements and fill 0s later:
int[] result = new int[ary.lenght];
int resultIndex = 0;
for (int i = 0; i < newARY.length; i++) {
if (newARY[i] != 0) {
result[resultIndex++] = newAry[i];
}
}
for (int i = resultIndex; i < newARY.length; i++) {
result[i] = 0;
}
// Print result array
Hint: Using above strategy, you can simplify your code. No need to create immediate array newARY. Just loop over the original array, push unique elements to the result array, then fill any slot left with 0s.

Get all indexes of a multidimensional table

I am having trouble to create a (recursive) function that prints all possible indexes for a multi dimensional table.
I got the information about the multi-dimensionality as an array.
Example:
int[]{6,6} would be a 2-dimensional table with 6x6 = 36 fields, so the result would be [0,0],[0,1],[1,1],[1,2],[2,2]... and so on.
Another example:
int[]{2,2,2} would be a 3-dimensional table with 8 possible indexes: [0,0,0],[0,0,1],[0,1,1]... and so on
I'm trying to do this in Java 7.
Edit: As requested, what I got so far. Code is producing OutOfBound Exception.
loop(new int[2], new int[]{6, 6}, 0);
private void loop(int[] index, int[] dimensionSizes, int dimensionIndex) {
if (index[dimensionIndex] < dimensionSizes[dimensionIndex] && dimensionIndex < dimensionSizes.length) {
System.out.println(Arrays.toString(index));
index[dimensionIndex] = index[dimensionIndex] + 1;
if (index[dimensionIndex] < dimensionSizes[dimensionIndex]) {
loop(index, dimensionSizes, dimensionIndex);
} else {
loop(index, dimensionSizes, dimensionIndex + 1);
}
}
}
I think this code could respond to your question:
public static void printAllIndex(int[] dimensions) {
int[] index = new int[dimensions.length];
int stepNumber = 0;
// Initialization
for (int i : index) { index[i] = 0; } // init index to 0
for (int d : dimensions) { stepNumber += d; } // count number of iteration needed
System.out.println(Arrays.toString(index)); // print first index [0,0,...]
for(int s = 0; s <= stepNumber - 1; s++) {
boolean allEquals = true;
int value = index[index.length - 1];
for (int i = index.length - 1; i >= 0; i--) {
if(index[i] != value) {
index[i]++;
allEquals = false;
break;
}
}
if (allEquals) { index[index.length - 1]++; }
System.out.println(Arrays.toString(index));
}
}

Implementing a deadlock detection algorithm; issue with the loops

I have been looking for the past 3 hours, and I can't find the problem with this code. The user inputs the number of processes and the number of types of resources and the algorithm determines if there is a deadlock or not. I am certain that the problem is in the stepTwo() method as I have checked everything in the first block of code, and it was all fine.
Here is the pseudocode: https://www.dropbox.com/s/dt9cvk5h3ij7wqz/deadlockdetection.jpg?dl=0
Here is main, variables, etc.:
public class AssignmentIII
{
public static int numProcesses; // Represents the number of processes
public static int numResources; // Represents the number of different types of resources
public static int[] available; // Create matrix for available processes
public static int[][] allocation; // Create allocation matrix
public static int[][] request; // Create request matrix
public static int[] work; // Create work matrix
public static Boolean[] finish; // Create finish matrix
public static void main(String[] args) throws FileNotFoundException
{
try
{
Scanner scan = new Scanner(System.in);
Scanner fileScan = new Scanner(new File("input3.txt")); // Create file scanner
System.out.println("Please enter the total number of processes: ");
numProcesses = scan.nextInt();
System.out.println("Please enter the number of different types of resources: ");
numResources = scan.nextInt();
// Initalize matrices sizes
available = new int[numResources];
allocation = new int[numProcesses][numResources];
request = new int[numProcesses][numResources];
work = new int[numResources];
finish = new Boolean[numProcesses];
// Initialize the available matrix contents
for(int i = 0; i < numResources; i++)
available[i]=fileScan.nextInt();
// Initialize the allocation matrix contents
for(int j = 0; j < numProcesses; j++)
for(int k = 0; k < numResources; k++)
allocation[j][k]=fileScan.nextInt();
// Initialize the request matrix contents
for(int m = 0; m < numProcesses; m++)
for(int n = 0; n < numResources; n++)
request[m][n]=fileScan.nextInt();
// Begin deadlock detection algorithm
for(int i = 0; i < numResources; i++) // Intialize Work := Available
work[i]=available[i];
for(int j = 0; j < numProcesses; j++) // Check for Allocation != 0 and initialize Finish accordingly
{
// the Allocation matrix = 0 if the sum of all its elements = 0
// which is the same as if every element were = 0
int sumAllocation = 0;
for(int i = 0; i < numResources; i++)
{
sumAllocation += allocation[j][i];
}
if (sumAllocation != 0)
finish[j] = false;
else finish[j] = true;
}
stepTwo();
}
catch(FileNotFoundException ex)
{
System.out.println("An error has occured. The file cannot be found.");
}
}
The error is occurring somewhere in here, but I can't figure it out:
public static void stepTwo()
{
// Step 2: Find an index j where Finish[j] = false & Request[j] <= Work
for(int j = 0; j < numProcesses; j++)
{
if (finish[j] == true && j == numProcesses)
{
System.out.println("No deadlocks.");
}
for(int i = 0; i < numResources; i++)
{
if (request[j][i] <= work[i] && finish[j] == false)
{
if (i == (numResources-1))
{
finish[j] = true;
for(int m = 0; m < numResources; m++)
{
work[m] += allocation[j][m];
}
j = -1; // Reset counter
break;
}
}
else if (request[j][i] > work[i] && finish[j] == false)
{
System.out.println("P" + j + " is deadlocked.");
}
}
}
}
}
My input is:
0 0 0
0 1 0
2 0 0
3 0 3
2 1 1
0 0 2
0 0 0
2 0 2
0 0 0
1 0 0
0 0 2
The output I get is:
P1 is deadlocked.
P1 is deadlocked.
The correct output should be "No deadlocks."
Any help would be appreciated.

array swapping for car game

I am trying to design a program to swap the value 0 in an array with the preceding element if it is not a 0.
For instance, if the array is 1 1 0 1 1 1 then the program will keep swapping until it becomes 0 1 1 1 1 1
But when I run this IndexOutOfBoundException occurs. I even tried changing the for loop to:
for(int i = 1; i < newLane.length; i++)
that solved the out of bounds issue, but made it function incorrectly.
The below is my code:
public static int[] down(int[] lane) {
int lan = lane.length; // length of array
int[]newLane = new int[lan]; // creates new 1d matrix
for(int i = 1; i < newLane.length; i++) {
if(newLane[i-1] != 0 && newLane[i] == 0 ){ // getting out of bounds error
int tmp = newLane[i - 1];
newLane[i - 1] = newLane[i];
newLane[i] = tmp;
}
}
return newLane;
}
I think you can simply sort your array :
public static int[] down(int[] lane){
int lan = lane.length; // length of array
int[]newLane = Arrays.copyOf(lane,lan) // creates new 1d matrix
Arrays.sort(newLane);
return newLane;
}
As my comment already says: you're close.
Just add
if(newLane[0] == 0) newLane[0] == 1;
Before the for-loop.
You are nowhere using the elements of array Lane. Currently newLane is an empty array. I have assigned value of Lane to newLane
Change your function to below
public static int[] down(int[] lane){
int lan = lane.length; // length of array
int[]newLane = new int[lan]; // creates new 1d matrix
newLane = lane;
for(int i = 1; i < newLane.length; i++) {
if(newLane[i-1] != 0 && newLane[i] == 0 ){ // getting out of bounds error
int tmp = newLane[i - 1];
newLane[i - 1] = newLane[i];
newLane[i] = tmp;
}
}
if(newLane[0]!=0 && newLane[1]==0)
{
int tmp = newLane[0];
newLane[0] = newLane[1];
newLane[1] = tmp;
}
return newLane;
}
Update
Just after the for loop, check whether the 0th element is non-zero. If yes, then swap it with first.
if(newLane[0]!=0 && newLane[1]==0)
{
int tmp = newLane[0];
newLane[0] = newLane[1];
newLane[1] = tmp;
}
I will try this
public static int[] swapping(int[] lane)
{
int[] result = new int[lane.length];
for(int i = 0; i < result .length; i++) {
if ( result[i]==0)
{
if( i==0)
{
}
else
{
temp = result[i] ;
result[i] = result [i-1] ;
result [i-1] = temp ;
}
else
{
}
return result ;
}

Categories