I'm working on this code in my program right now and it seems that the problem is with the line where I stop the inner loop of the 2nd dimension.
this is a sample output of the array
9 6 6
7 6 4
4 8 5
when i run this code the output is:
4 4 6
5 6 6
7 8 9
my expected output is:
4 4 5
6 6 6
7 8 9
a digit:"6" is not in the correct place. Its because when I try to run the part where there is a nested for loop above a for loop, it only runs once and so it only checks the 1st column instead of getting to the third column where 6 is. The problem is I need to limit that loop in only reading the highest numbers from row#0 column#0 to row#2 column#0.
How do I solve this problem?? I thought of using a one dimensional array and put all two dimensional array elements and sort it there then put it back to the two dimensional array and print it again but that wouldn't make my code solve the needed process of sorting two dimensional array.
public static void sortArray(){
int x = len-1, y = len-1;
int iKey=0,jKey=0;
int cnt=0;
do{
cnt++;
if(y==-1){
x--;
y=len-1;
}
System.out.println(cnt+".)"+x+"-"+y);
int hi = -1;
for(i = 0;i <= x; i++)
for(j = 0;j <= y; j++){
if(twodiArray[i][j]>hi){
hi = twodiArray[i][j];
iKey = i;
jKey = j;
}
}
int temp = twodiArray[iKey][jKey];
twodiArray[iKey][jKey] = twodiArray[x][y];
twodiArray[x][y] = temp;
//dispArray();
y--;
}while(cnt<9);
}
The problem is in your loops where you search max element. Suppose you have array 5x5 and x=1 and y=1. Then you loop will check only following elements: [0][0], [0][1], [1][0], [1][1]. But it should also check [0][2], [0][3], [0][4].
With you previous code you only checked following cells:
XX...
XX...
.....
.....
.....
But you need to check these:
XXXXX
XX...
.....
.....
.....
So you need something like this:
for(i = 0;i <= x; i++) {
int upper; // How many elements we need to check on current row.
if (i != x) {
upper = len - 1; // We are not in last row, so check all elements.
} else {
upper = y; // On the last row we need to check only elements up to y.
}
for(j = 0;j <= upper; j++){
if(twodiArray[i][j]>hi){
hi = twodiArray[i][j];
iKey = i;
jKey = j;
}
}
}
My code checks every row fully until last one.
EDIT
If you use:
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= y; j++) {
...
}
}
then you iterate only on recangle with upper left corner in (0,0) and right bottom cornar in (y,x). E.g. x = 4, y = 3:
XXX...
XXX...
XXX...
XXX...
......
But your goal is to do every row before last one fully. So check 0-th, 1-st and 2-nd rows fully and 3 elements from 3-rd row. My code does it. upper show how many values from row we need to check for all rows except last one it's equals to len - 1 (check full row). For last one it's y.
Your swap code (starting with int temp = twodiArray) is outside the main iteration loop. It needs to be moved inside the innermost loop.
BTW, you can do the swap without storing the indices.
Personally, to save myself some confusion, I would think of it as if it were a 1D array.
// I'm assuming that columnCount and rowCount are stored somewhere
public int getNthElement(int index) {
int colIndex = index % columnCount;
int rowIndex = (index - colIndex) / rowCount;
return twodiArray[rowIndex][colIndex];
}
public void setNthElement(int index, int value) {
int colIndex = index % columnCount;
int rowIndex = (index - colIndex) / rowCount;
twodiArray[rowIndex][colIndex] = value;
}
public void sortArray(int[][] array) {
int elementCount = rowCount * columnCount;
int curIndex = elementCount - 1;
while (curIndex >= 0) {
int highestIndex = -1;
int highestValue = 0;
for (int i = 0; i <= curIndex; i++) {
int nthValue = getNthElement(i);
if (nthValue > highestValue) {
highestIndex = i;
highestValue = nthValue;
}
}
int swapValue = getNthElement(curIndex);
setNthElement(curIndex, highestValue);
setNthElement(highestIndex, swapValue);
curIndex--;
}
}
You can see that I still use the 2D array and never use an actual 1D array, but this code indexes into the array as if it were a 1D array. (Hopefully that is valid in your professor's eyes)
Related
Im currently writing some code that print Pascal's Triangle. I need to use a 2D array for each row but don't know how to get the internal array to have a variable length, as it will also always changed based on what row it is int, for example:
public int[][] pascalTriangle(int n) {
int[][] array = new int[n + 1][]
}
As you can see I know how to get the outer array to have the size of Pascal's Triangle that I need, but I don't know how to get a variable length for the row that corresponds with the line it is currently on.
Also how would I print this 2D array?
Essentially what you want to happen is get the size of each row.
for(int i=0; i<array.size;i++){//this loops through the first part of array
for(int j=0;j<array[i].size;j++){//this loops through the now row
//do something
}
}
You should be able to use this example to also print the triangle now.
This is my first answer on StackOverFlow. I am a freshman and have just studied Java as part of my degree.
To make every step clear, I will put different codes in different methods.
Say n tells us how many rows that we are going to print for the triangle.
public static int[][] createPascalTriangle(int n){
//We first declare a 2D array, we know the number of rows
int[][] triangle = new int[n][];
//Then we specify each row with different lengths
for(int i = 0; i < n; i++){
triangle[i] = new int[i+1]; //Be careful with i+1 here.
}
//Finally we fill each row with numbers
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
triangle[i][j] = calculateNumber(i, j);
}
}
return triangle;
}
//This method is used to calculate the number of the specific location
//in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
public static int calculateNumber(int i, int j){
if(j==0){
return 1;
}
int numerator = computeFactorial(i);
int denominator = (computeFactorial(j)*computeFactorial(i-j));
int result = numerator/denominator;
return result;
}
//This method is used to calculate Factorial of a given integer.
public static int computeFactorial(int num){
int result = 1;
for(int i = 1; i <= num; i++){
result = result * i;
}
return result;
}
Finally, in the main method, we first create a pascalTriangle and then print it out using for loop:
public static void main(String[] args) {
int[][] pascalTriangle = createPascalTriangle(6);
for(int i = 0; i < pascalTriangle.length; i++){
for(int j = 0; j < pascalTriangle[i].length; j++){
System.out.print(pascalTriangle[i][j] + " ");
}
System.out.println();
}
}
This will give an output like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
I am very new to Java and am currently learning about arrays. Our homework this week is to
"Write a program that declares an array "alpha" of 50 elements of type "double". Initialize the array so that the first 25 elements are equal to the square of the index variable and the last 25 elements are equal to three times the index variable"
My question is this. Is the value in the element at an index position considered the index variable. For example if alpha[2] = 3 would 3 be the index variable, and in reading the assignment I would then square 3.
The other thought that I would have is that I have to square the index number [0],[1],[2]...
Thank you for any input, and I apologize if this is in the wrong area.
Thank you for the input so far. What I am trying to get to is what exactly is an "Index Variable"
Here is what I did
// Import various packages to be used in the program
import java.util.*;
import java.lang.*;
public class module5
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
// Declare an array called alpha with 50 pre-defined elements
double []alpha = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
// Process the first 25 elements
for (int i = 0; i < 25; i++) {
// Square the first 25 elements
alpha[i] = Math.pow(alpha[i], 2);
}
// Process the second set of 25
for (int i = 25; i >= 25 && i < 50; i++) {
// Multiply by 3
alpha[i] = alpha[i] * 3;
}
for (int i = 0; i < alpha.length; ++i) {
System.out.print(alpha[i]);
if (i % 10 == 9) {
System.out.println();
} else {
System.out.print(" ");
}
}
}
}
No. In alpha[2] = 3 2 is the index variable, and 3 is the value being indexed. The other thought that I would have is that I have to square the index number [0],[1],[2] Correct.
alpha[0] = 0 * 0;
alpha[1] = 1 * 1;
alpha[2] = 2 * 2;
// ...
alpha[25] = 3 * 25;
// ...
alpha[49] = 3 * 49;
You are expected (I think) to use a loop with a conditional (but you might also use two separate loops with different initial and terminal conditions) to do these assignments.
You are dealing with int(s), so use an int[]. Something like,
int[] alpha = new int[50];
Then you might use a single for loop like,
for (int index = 0; index < alpha.length; index++) {
if (index < 25) {
alpha[index] = index * index;
} else {
alpha[index] = index * 3;
}
}
or two loops like
for (int index = 0; index < 25; index++) {
alpha[index] = index * index;
}
for (int index = 25; index < alpha.length; index++) {
alpha[index] = 3 * index;
}
or using a ternary (conditional operator ? :) and a loop like
for (int index = 0; index < alpha.length; index++) {
alpha[index] = index * ((index < 25) ? index : 3);
}
The index of an array element is the number in the brackets, [].
In the example, alpha[2] = 3, 2 is the index and 3 is the variable stored at index 2.
Also remember that for arrays, index 2 means that it is the third position in the array because the first index is position 0.
For this exercise, you would declare an index variable, i, and iterate through the array such that alpha[0] = 0, alpha[1] = 1, alpha[2] = 4, ... alpha[i] = i*i
I would like to fill a 3x3 2D array with values 1,2,3.
I need each number to appear for a given times.
For example:
1 to appear 2 times
2 to appear 4 times
3 to appear 3 times
What I need is to store this numbers to array in a random position.
For Example:
1,2,2
3,2,2
1,3,3
I already did this in a simple way using only 2 different numbers controlled by a counter. So I loop through the 2D array and applying random values of number 1 and number 2.
I'm checking if the value is 1 and add it in the counter and the same with number 2. if one of the counter exceeds the number I have set as the maximum appear times then it continues and applies the other value.
Is there any better approach to fill the 3 numbers in random array position?
See code below:
int [][] array = new int [3][3];
int counter1 =0;
int counter2 =0;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = (int)random(1, 3); //1,2
if (arrray[i][j]==1) {
counter1++;
} else if (array[i][j] ==2) {
counter2++;
}
//if it is more than 5 times in the array put only the other value
if (counter1>5) {
array[i][j] = 2;
}
//if it is more than 4 times in the array put only the other value
else if (counter2>4) {
array[i][j] = 1;
}
}
}
I finally did this according to this discussion:
How can I generate a random number within a range but exclude some?, with 1D array for tesing, but it does not always works.
Please see attached code:
int []values = new int[28];
int counter1=0;
int counter2=0;
int counter3=0;
for (int i=0; i<values.length; i++) {
if (counter1==14) {
ex = append(ex, 5);
}
if (counter2==4) {
ex =append(ex, 6);
}
if (counter3==10) {
ex =append(ex, 7);
}
values[i] = getRandomWithExclusion(5, 8, ex);
if (values[i]==5) {
counter1++;
} else if (values[i] ==6) {
counter2++;
} else if (values[i] ==7) {
counter3++;
}
}
int getRandomWithExclusion(int start, int end, int []exclude) {
int rand = 0;
do {
rand = (int) random(start, end);
}
while (Arrays.binarySearch (exclude, rand) >= 0);
return rand;
}
I would like to fill the 1D array with values of 5,6 or 7. Each one a specific number. Number 5 can be added 14 times. Number 6 can be added 4 times. Number 7 can be added 10 times.
The above code works most of the times, however somethimes it does not. Please let me know if you have any ideas
This is the Octave/Matlab code for your problem.
n=3;
N=n*n;
count = [1 2; 2 4; 3 3];
if sum(count(:,2)) ~= N
error('invalid input');
end
m = zeros(n, n);
for i = 1:size(count,1)
for j = 1:count(i,2)
r = randi(N);
while m(r) ~= 0
r = randi(N);
end
m(r) = count(i,1);
end
end
disp(m);
Please note that when you address a 2D array using only one index, Matlab/Octave would use Column-major order.
There are a ton of ways to do this. Since you're using processing, one way is to create an IntList from all of the numbers you want to add to your array, shuffle it, and then add them to your array. Something like this:
IntList list = new IntList();
for(int i = 1; i <= 3; i++){ //add numbers 1 through 3
for(int j = 0; j < 3; j++){ add each 3 times
list.append(i);
}
}
list.shuffle();
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = list.remove(0);
}
}
You could also go the other way: create an ArrayList of locations in your array, shuffle them, and then add your ints to those locations.
This is technically a code challenge.
I was asked an interesting question at an interview and am hoping for some insight as the best answer I could come up with was O(2n^2) - n-squared category, but still pretty much brute force.
Let's say you have a matrix that's M by N size ( an array of arrays (int[][]) )
1 2 4 3 1
0 5 3 7 7
5 8 9 2 8
6 7 0 8 9
If a cell contains a Zero, then set that entire row and column to zero.
Making the result:
0 2 0 3 1
0 0 0 0 0
0 8 0 2 8
0 0 0 0 0
What is the fastest and/or best way to do this?
My own answer is to iterate the entire array of arrays, keep track of rows and columns to zero out, and then zero them out.
public void zeroOut(int[][] myArray){
ArrayList<Integer> rowsToZero = new....
ArrayList<Integer> columnsToZero = new....
for(int i=0; i<myArray.length; i++){ // record which rows and columns will be zeroed
for(int j=0; j<myArray[i].length; i++){
if(myArray[i][j] == 0){
if(!rowsToZero.contains(i)) rowsToZero.add(i);
if(!columnsToZero.contains(j)) columnsToZero.add(j);
}
}
}
for(int row : rows){ // now zero the rows
myArray[row] = int[myArray.length];
}
for(int i=0; i<myArray.length; i++){
for(int column: columns){ // now zero the columns
myArray[i][column] = 0;
}
}
}
Is there a better algorithm? Is there a better data-structure to represent this matrix?
you can do this by taking two int but the only condition is the no of rows and cols should less than or equal to 32. You can do the same with greater than 32 but you have to take array of ints.
So the logic is :
take two ints i.e. row and col
traverse the matrix if matrix[i][j] = 0 than set the corresponding bits in the row and col
after traversal traverse again and set the matrix[i][j] = 0 if corresponding bit of either row or column is set.
The time complexity is same O(N^2) but it is memory efficient. Please find my code below .
Check whether the array[row][col] == 0 if 0 than set the corresponding bit in r and c.
int r = 0, c = 0;
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 7; col++) {
if (array[row][col] == 0) {
r = r | (1<<row);
c = c | (1<<col);
}
}
}
Now if either of the bit is set than make the cell to 0.
for (int row = 0; row < 5; row++) {
for (int col = 0; col <7; col++) {
if (((c&(1<<col))!=0) || ((r&(1<<row))!=0)) {
array[row][col] = 0;
}
}
}
What about splitting the matrices into equal smaller matrice parts and calculate the deteriminant, so that you can predict that there is a zero within this matric part.
And then only use the brute force mechanism to this preselected matrices to determin
in wich row or column the zero is.
The determinant is just a suggestion maybe you can use some other kind of linear algebraic
algorithms and rules to predict a zero value
UPDATE:
if you use Quicksort concept to organize temporay every row. Then you have just to loop until the first none zero element occurs.
You need to remember during sorting process which column index was associated with the 0
Means
1 2 6 0 3
Quciksort (
0 1 2 4 6
When you remember the column index you now directly know which row to fill with 0 and which column,
Average of Quicksort ist O(n log n) Worstcase n * n
Maybe this already improves the overall complexisitiy.
Seems no one really came up with a significantly faster/better algorithm so far, so this one seems to be it. Thanks for your input everyone.
public void zeroOut(int[][] myArray){
ArrayList<Integer> rowsToZero = new....
ArrayList<Integer> columnsToZero = new....
for(int i=0; i<myArray.length; i++){ // record which rows and columns will be zeroed
for(int j=0; j<myArray[i].length; i++){
if(myArray[i][j] == 0){
if(!rowsToZero.contains(i)) rowsToZero.add(i);
if(!columnsToZero.contains(j)) columnsToZero.add(j);
}
}
}
for(int row : rows){ // now zero the rows
myArray[row] = int[myArray.length];
}
for(int i=0; i<myArray.length; i++){
for(int column: columns){ // now zero the columns
myArray[i][column] = 0;
}
}
}
I just came across this question and have developed a solution for it.
I am hoping I can get some feedback for the code about how it's better/worse and it's runtime.
Pretty new to all this :)
public static void zeroMatrix(int[][] arr1)
{
ArrayList<Integer> coord = new ArrayList<>();
int row = arr1.length;
int column = arr1[0].length;
for(int i=0; i < row; i++)
{
for(int j=0; j < column; j++)
{
if(arr1[i][j]==0)
{
coord.add((10*i) + j);
}
}
}
for(int n : coord)
{
int j=n%10;
int i=n/10; int k=0;
int l=0;
while(k<row)
{
arr1[k][j]=0;
k++;
}
while(l<column)
{
arr1[i][l]=0;
l++;
}
}
}
I have used HashMap.See if this can help in any way
import java.util.*;
class ZeroMatrix
{
public static void main(String args[])
{
int mat[][]=new int[][]{{0,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,0}};
HashMap<Integer,Integer> ht=new HashMap<Integer,Integer>();
for(int i=0;i<5;i++)
{
for(int j=0;j<4;j++)
{
if(mat[i][j]==0)
ht.put(i,j);
}
}
//Set the Respected Rows and colums to Zeros
Set set=ht.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
int i=(Integer)m.getKey();
int k=(Integer)m.getValue();
for(int j=0;j<4;j++)
{
mat[i][j]=0;
}
for(int j=0;j<5;j++)
{
mat[j][k]=0;
}
}
//Printing the Resultant Zero Matrix
for(int i=0;i<5;i++)
{
for(int j=0;j<4;j++)
{
System.out.print(mat[i][j]);
}
System.out.println();
}
}
}
I'm trying to create a method that will search through a 2d array of numbers. If the numbers add up to a certain sum, those numbers should remain and all of the other numbers should be changed to a 0. For example, if the desired sum is 7 and a row contains 2 5 1 2, the result should be 2 5 0 0 after the method is implemented. I have everything functioning but instead of keeping all of the numbers that add up to the sum, only the last number is retained. So, I am left with 0 5 0 0 . I think I need another array somewhere but not sure exactly how to go about implementing it. Any ideas?
public static int[][] horizontalSums(int[][] a, int sumToFind) {
int[][] b = new int[a.length][a[0].length];
int columnStart = 0;
while (columnStart < a[0].length) {
for (int row = 0; row < a.length; row++) {
int sum = 0;
for (int column = columnStart; column < a[row].length; column++) {
sum += a[row][column];
if (sum == sumToFind) {
b[row][column] = a[row][column];
}
}
}
columnStart++;
}
return b;
}
In your example you use 2 5 1 1, would 0 5 1 1 also be a valid response? Or do you just need to find any combination? A recursive function may be the best solution.
If you just need to scan through the array and add up the numbers until the sum is reached then just add a for loop to copy the previous values from the array to the new array when the sum is found. Something like:
if (sum == sumToFind)
{
for (int i= 0; i<= columnStart; i++)
{
b[row][i] = a[row][i];
}
}
if (sum == sumToFind)
{
for (int i= columnStart; i<= column; i++)
{
b[row][i] = a[row][i];
}
}
A minor tweak was all it needed. If you have columnStart and column like in the other answer, it only finds the first number of the series.