As I said, I would like to "scroll" through a Multi Dimensional array via the secondary diagonal, my desired input to be: (Case a) [It can be in either C++ or Java, it doesn't matter]
NOTE+EDIT: The order is not random. It starts from the 1 at the bottom and goes its way up.
Is this possible?
If not then at least half of the code? (Case b)
// Case a:
16 15 13 10
14 12 9 6
11 8 5 3
7 4 2 1
// Case b:
0 0 0 1
0 0 9 6
0 8 5 3
7 4 2 1
You can do this with a simple loop (this is Java):
int size = 4;
int[][] matrix = new int[size][size];
// . . .
for (int i = 0; i < size; ++i) {
doSomethingWith(matrix[i][size - i - 1]);
}
int[][] a={{7,6,4,1},{5,3,9,6},{2,8,5,3},{7,4,2,1}};
for(int i=0; i<a.length; i++)
{
for(int j=a[i].length-1; j>=a[i].length-(i+1); j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
Related
So the instructions are to create a matrix 10x10 and randomize values between 1~20 for each index
Then ask the user to enter 6 numbers between 1~20, and use those numbers to create
another 2x3 Matrix.
Then the program has to check if the 10x10 matrix contains the 2x3 matrix from the user.
Also i'm not allowed to use functions.
Example for input:
Enter the1 number in the matrix: 17
Enter the2 number in the matrix: 17
Enter the3 number in the matrix: 17
Enter the4 number in the matrix: 5
Enter the5 number in the matrix: 13
Enter the6 number in the matrix: 14
Output:
The random matrix:
14 14 3 18 2 10 19 10 3 3
2 17 15 16 5 17 7 17 15 10
13 1 3 9 5 4 11 9 1 8
17 14 13 9 8 1 18 3 17 18
12 17 5 14 13 4 16 14 13 4
8 12 8 19 6 5 3 3 14 18
16 16 17 9 9 10 17 3 8 5
13 8 6 17 6 17 17 7 19 5
5 14 6 15 11 11 13 17 17 17
17 13 13 18 11 4 15 5 13 14
The matrix you entered:
17 17 17
5 13 14
The random matrix contains the users matrix.
My Code so far =
int[][] big = new int[10][10];
int[][] small =new int [][] {{the1,the2,the3},{the4,the5,the6}};
for(int i = 0; i < big.length; i++ )
{
for(int j = 0; j < big[i].length; j++)
{
big[i][j]= (int)((Math.random()*20)+1);
}
}
for(int i =0; i < big.length; i++)
{
for(int j = 0; j < big.length; j++)
{
Boolean isEqual=true;
for(int k = 0; k < 2 && isEqual; k++)
{
for(int m = 0; m < 3; m++)
{
if (big[i+k][j+m]!=small[k][m])
{
isEqual=false;
break;
}
}
}
}
}
My general idea was basically running through the indexes of the big matrix while checking for equal numbers, and if one found, the routine continues, otherwise it breaks, and going to the next index in the big matrix.
Your general idea is correct and should work for the described scenario. The only issue you are having is your break statement doesent work as you think.
According to nested loop, if you put break statement in inner loop, compiler will jump out from inner loop and continue the outer loop again. If you need to jump out from the outer loop using break statement given inside inner loop you can use a labelled loop, i.e give your loop a name and use it with the break statement.
In your code above you shold not only breake the inner most loop but also the one above:
public static void main(String[] args) {
int[][] big = new int[10][10];
int[][] small = new int[][]{{12, 13, 14}, {13, 14, 15}};
for (int i = 0; i < big.length; i++) {
for (int j = 0; j < big[i].length; j++) {
big[i][j]= (int)((Math.random()*20)+1);
}
}
// just added this loop to print the random array so you can check the output
for(int[] row : big){
System.out.println(Arrays.toString(row));
}
for(int i = 0; i<big.length-1; i++){
for(int j = 0; j<big[0].length-2; j++){
boolean isEqual = true;
LoopIwannaBreak:for(int k = 0; k<small.length; k++){
for(int m = 0; m<small[0].length; m++){
if(big[i+k][j+m] != small[k][m]){
isEqual = false;
break LoopIwannaBreak;
}
}
}
// added this to tell at which index the match was found
if(isEqual){
System.out.println("found at big["+i+"]["+j+"]");
}
}
}
}
I am trying to make a method where a 2D array is created in the main, which can be any dimension. After that, we are supposed to make 2 methods, one which increments each next value in the array by a given number labeled step. One method is supposed to increment the rows, and the other increments it by columns.
This is what I have:
public static void main (String [] args){
int [][] fillRightArray = new int [5][8];
fillRight(fillRightArray, 2);
int [][] fillDownArray = new int[5][8];
fillDown(fillDownArray, -2);
For the fill right method, this is the what the output should be:
2 4 6 8 10 12 14 16
18 20 22 24... //all the way to 80, since the array has 40 elements (40*2=80)
This is my method:
public static void fillRight (int [][] fillRightArray, int step){
for (int i = 0; i< fillRightArray.length; i++){
for (int j = 0; j< fillRightArray[i].length; j++){
fillRightArray[i][j] += step*(j+1);
System.out.print(fillRightArray[i][j] + " ");
}
System.out.print("\n");
}
But for some reason, my output is:
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
Any idea as to why this is happening? Same thing happens when I go with the fillDown method, the output is supposed to be:
2 12 22....
4 14 24....
6 16 26....
8 18 28....
10 20 30.... all the way to 80
But instead I get:
2 2 2 2 2
4 4 4 4 4
6 6 6 6 6
8 8 8 8 8
10 10 10 10 10
Your code doesn't work because you aren't taking into account the previous cell.
Your logic for determining the value of a specific cell is fillRightArray[i][j] += step*(j+1); .
This line only considers the value of j to determine the value of a cell within your array, when it should also consider the value of i (explicitly or implicitly).
You should add a counter that keeps track of how many cells you have set, and set the next cells value based on the number of cells that have already been set.
Your fillRight method should instead look like this:
public static void fillRight (int [][] fillRightArray, int step){
int count = 0;
for (int i = 0; i< fillRightArray.length; i++){
for (int j = 0; j< fillRightArray[i].length; j++){
count++;
fillRightArray[i][j] += step*count;
System.out.print(fillRightArray[i][j] + " ");
}
System.out.print("\n");
}
}
You're constantly repeating the same work and going back to 0 each time.
In your fillRight, each row is doing 2,4,6,8,10 because you're doing step*(j+1), where j resets to 0 after each iteration of the loop. You need to find a way to include i as well as j when setting the value, or just have a counting variable that is incremented each step
Like this:
step += 2
fillRightArray[i][j] = step
That way you don't need to worry about position.
I have been confronting with a very confusing situation, I wrote this BubbleSort program and it ran just fine. with the correct output:
public class BubbleSortInput {
private static void Sorting(int[] intArray)
{
int i, temp=0;
int n = intArray.length;
for(i=0; i < n - 1; i++)
{
for(int j = 0; j < n-i-1; j++)
{
if(intArray[i]>intArray[i+1])
{
temp = intArray[i+1];
intArray[i] = intArray[i+1];
intArray[i] = temp;
}
}
}
}
public static void main(String[] args) {
int array[] = {1,5,65,34,76,234};
Sorting(array);
for(int k = 0; k < array.length; k++)
{
System.out.println(array[k]);
}
}
}
However, I tried to write basically the same code, in the main method, in another class:
class BubbleSort {
public static void main(String[] args) {
int numbers[] = {12,43,65,12,65,92,32,54};
int i,temp=0;
for(i=0; i < numbers.length-1; i++)
{
for(int j = 0; j < numbers.length-i-1; j++)
{
if(numbers[i]>numbers[i+1])
{
temp = numbers[i+1];
numbers[i] = numbers[i+1];
numbers[i]= temp;
}
}
}
for(i=0;i<numbers.length;i++)
{
System.out.println(numbers[i]);
}
}
}
The output I get on the second file is completely wrong, even though I used almost the same code, Can someone explain this please?
Output:
12
43
12
12
65
32
32
54
As others pointed out, you should take a look at the bubble sorting algorithm. And just a reminder, run many test cases before stating that your original piece of code works fine. Just to be clear, the first program also gives a wrong output. The output you may have gotten for your input set may be true, but that was a bit sorted to begin with. Try the input set you used in the second program for your first code and identify the errors.And also, take a look at the swapping code inside your for loops.
temp = intArray[i+1];
intArray[i] = intArray[i+1];
intArray[i] = temp;
You are assigning the value at [i+1] position to temp. And you are again assigning the value at [i+1] to the location i. So the value at the location [i] was lost in the process. Now value at location [i] and [i+1] are same. So work on that as well.
That aside. In Bubble sort, sorting works by swapping adjacent elements. So by the end of the first pass(ascending order sorting), the largest element in the array will be at the end. This process goes on until, all the elements are sorted.
Example:
First Pass:
( 6 1 3 2 9 ) –> ( 1 6 3 2 9 ), Here, algorithm compares the first two elements, and swaps since 6 > 1.
( 1 6 3 2 9 ) –> ( 1 3 6 2 9 ), Swap since 6 > 3
( 1 3 6 2 9 ) –> ( 1 3 2 6 9 ), Swap since 6 > 2
( 1 3 2 6 9 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (9 > 6), algorithm does not swap them.
Second Pass:
( 1 3 2 6 9 ) –> ( 1 3 2 6 9 )
( 1 3 2 6 9 ) –> ( 1 3 4 6 9 ), Swap since 3 > 2
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
( 1 2 3 5 9) –> (1 2 3 5 9 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 3 5 9 ) –> (1 2 3 5 9 )
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
I don't think your bubble sorting code is correct. Here is your loop:
for(i=0; i < n - 1; i++)
{
for(int j = 0; j < n-i-1; j++)
{
if(intArray[i]>intArray[i+1])
{
temp = intArray[i+1];
intArray[i] = intArray[i+1];
intArray[i] = temp;
}
}
}
Note that you never use the variable j. So all it does is loop through the array and then swap the two elements if the first one is larger than the second one. You should take a look at the Bubble sort algorithm again and re-write your code.
The sorting logic you are using is incorrect.
Bubble sort compares each pair of adjacent items and swaps them if they are in the wrong order (not in ascending order).
By the end of the first pass(ascending order sorting), the largest element in the array will be at the last index.
By the end of the second pass(ascending order sorting), the second largest element in the array will be at the second last index and so on.....
Visit http://visualgo.net/sorting for better understanding.
So, in your code you should compare the items with the 2nd initialization (variable j in your case). After modification it should look like:
for(i=0; i < n - 1; i++)
{
for(int j = 0; j < (n-i)-1; j++)
{
if(intArray[j]>intArray[j+1])
{
temp = intArray[j];
intArray[j] = intArray[j+1];
intArray[j+1] = temp;
}
}
}
I'm trying to split the array into odd and even numbers. Note that sorting numbers in the final result does not matter. I'm compiling the code and the output contains some bug. My code arranges odd numbers correctly while the even numbers are giving me some trouble. Could somebody please help me out with the arrangement of even numbers?
Basically, I arrange odd numbers in the left side of the array and have oddPos = 0 in the beginning; even numbers are in the right side and the positioning starts from the very end of the array evenPos = myArray.length - 1.
public class EvenOddArray {
public static void main(String[] args){
int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int oddPos = 0;
int evenPos = myArray.length - 1;
for(int i = 0; i < myArray.length; i++){
if(myArray[i] % 2 == 0){
myArray[evenPos] = myArray[i];
evenPos--;
}
else{
myArray[oddPos] = myArray[i];
oddPos++;
}
}
for(int i = 0; i < myArray.length; i++){
System.out.print(myArray[i] + " ");
}
}
}
Output:
1 3 5 7 2 4 6 6 4 2
int current = 0;
int evenPos = myArray.Length - 1;
while (current < evenPos) {
if (myArray[current] % 2 == 0) {
swap(myArray, evenPos, current);
evenPos--;
} else {
current++;
}
}
A squeezed funny version:
for (int curPos=0, evenPos=myArray.length-1; curPos < evenPos;)
if (myArray[curPos] % 2 == 0)
swap(myArray, evenPos--, curPos);
else
curPos++;
More fun version:
for (int curPos=0, evenPos=myArray.length-1; curPos < evenPos;)
swap(myArray, curPos, myArray[curPos]%2==0 ? evenPos-- : curPos++);
explanation:
You don't have to swap values when the number is odd. you only
increase the current counter.
you can't use the for loop counter as an index to the array too. to
not miss the numbers that gets swapped to the counter index not
processed. this is the mistake that other answers didn't cover.
Actually you are editing the same myArray array while reading from it. So what happens is,
You insert 6 into the myArray[7] th position, in the 6th iteration of the loop. So, during the 7th iteration when you read the myArray[7], it is 6. Not 8. Because, you have over written 8 with 6 in the previous iteration.
Therefore, use a separate array to hold the results. Hope you get the point.
You can do something like this,
int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] resultArray = new int[myArray.length];
int oddPos = 0;
int evenPos = myArray.length - 1;
for(int i = 0; i < myArray.length; i++){
if(myArray[i] % 2 == 0){
resultArray[evenPos] = myArray[i];
evenPos--;
}
else{
resultArray[oddPos] = myArray[i];
oddPos++;
}
}
Lets see what happens with each Iteration of your for loop.
Original: 1 2 3 4 5 6 7 8 9 10
1st Iter: 1 2 3 4 5 6 7 8 9 10
2nd Iter: 1 2 3 4 5 6 7 8 9 2
3rd Iter: 1 3 3 4 5 6 7 8 9 2
4th Iter: 1 3 3 4 5 6 7 8 4 2
5th Iter: 1 3 5 4 5 6 7 8 4 2
6th Iter: 1 3 5 4 5 6 7 6 4 2
7th Iter: 1 3 5 7 5 6 7 6 4 2
8th Iter: 1 3 5 7 5 6 6 6 4 2
9th Iter: 1 3 5 7 5 4 6 6 4 2
10th Iter: 1 3 5 7 2 4 6 6 4 2
As you can see, you are modifying the array "inplace". You are modifying the array without using all the values. For example, look at 9, It gets over written before it is ever accessed. So, your algo is wrong.
Suggestions:
Use a new array to hold the results as in tibzon's answer
Use swapping instead of overwriting. You have to update your algo accordingly. I was going to provide one. But Murenik already provided one.
Here is my optimized version, which uses around half of the swaps compared to the #hasan83 version.
int n = myArray.length;
int oddPos = 0;
int evenPos = n - 1;
while (true) {
while (oddPos < n && myArray[oddPos] % 2 == 1) {
oddPos++;
}
while (evenPos >= 0 && myArray[evenPos] % 2 == 0) {
evenPos--;
}
if (oddPos >= evenPos) break;
swap(myArray, oddPos, evenPos);
}
For example, say we have a Sudoku board like this:
0 0 6 5 8 9 7 4 3
0 5 0 0 0 0 0 6 0
7 0 9 0 6 0 1 0 0
0 3 0 0 0 2 0 8 7
0 0 1 0 0 0 4 0 0
8 9 0 6 0 0 0 5 0
0 0 2 0 5 0 3 0 6
0 7 0 0 0 0 0 9 0
3 1 8 4 9 6 5 0 0
I want to store it into one array such that the first 9 elements of the array are the first sub block, i.e. the values {0 0 6 0 5 0 7 0 9} and followed by {5 8 9 0 0 0 0 6 0}.
I've tried finding a solution but I always get an array index out of bounds error and it is too brute force. Something similar to this:
while(st.hasMoreTokens()) {
if(ctr == 27) {
c.addSubBlock(sb1);
c.addSubBlock(sb2);
c.addSubBlock(sb3);
sb1 = new SubBlock();
sb2 = new SubBlock();
sb3 = new SubBlock();
ctr = 0;
}
sb1.addElement(Integer.parseInt(st.nextToken()));
sb1.addElement(Integer.parseInt(st.nextToken()));
sb1.addElement(Integer.parseInt(st.nextToken()));
sb2.addElement(Integer.parseInt(st.nextToken()));
sb2.addElement(Integer.parseInt(st.nextToken()));
sb2.addElement(Integer.parseInt(st.nextToken()));
sb3.addElement(Integer.parseInt(st.nextToken()));
sb3.addElement(Integer.parseInt(st.nextToken()));
sb3.addElement(Integer.parseInt(st.nextToken()));
ctr+=9;
}
Please give me some tips. Code snippets would also be a great help.
EDIT: This thread somehow helped me figured it out. And yes, this is part of the Sudoku where I'm trying to encode the board into an array.
What I did was to transform first the input String into a 2d array (9x9) and use int block = (row/3)*3 + (col/3); to compute exactly which sub block each element belongs.
Create a 3x3 array of sub blocks
Use 2 counters (x & y) for tracking the position in the full board of each element read
Add the values at (x,y) into sub block (x/3,y/3)
Something like this:
SubBlock board[][] = new SubBlock[3][3];
int x, y;
for ( y=0; y<9; y++ )
for ( x=0; x<9; x++ )
board[y/3][x/3].addElement(Integer.parseInt(st.nextToken()));
board[0][0] will be the top-left SubBlock, board[2][2] the bottom-right one.
Store everything in a two dimension array. E.g.
int[] board = {
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}};
//looping
public static void Main(string[] args){
for(int i = 0; i < 9; i++)
{
System.out.println("SubBlock number"+i);
for(int j = 0; j < 9; j++){
System.out.println(board[i][j]);
}
}
}
Assuming that you are reading input left to right, top to bottom, try a set of 4 nested loops like this:
int board[] = new int[81];
for (int outY = 0; outY < 3; outY++)
{
for (int outX = 0; outX < 3; outX++)
{
for (int inY = 0; inY < 3; inY++)
{
for (int inX = 0; inX < 3; inX++)
{
board[27*outY + 9*outX + 3 * inY + inX] = //parse an int from your input here
}
}
}
}
It would be great if we knew why you are trying to loop through the board.
If you want to check if you can enter a number, I recommend you use maps for each of the 3x3 squares.
Then check if the item is in the map already or not. For the rows and columns, you can either loop over the 2D array and check each element, or -again- use a map for each column and a map for each row.
I'm not entirely sure if you want an answer for a single-dimension array or if you're willing to make it a two-dimensional array (as you mention each nine element set with curly braces), but if two-dimensional is OK...
The OP in this Code Review posting used a 'fancy' way of sifting through the subgrids by using the math (i % 3) + rowStart inside one of the square brackets and (i / 3) + colStart inside the other. One commenter noted this modulo method to be a bit obscure, and I'm prone to agree, but for how clean it is and the fact that it works, I think it's a solid solution. So, paired with the iteration of the for loop, we can sift through each 'subgrid' cell, as well as each element of row + col.
for(i=0; i<9; ++i)
{
if (puzzle[row][i] == num) return 0;
if (puzzle[i][col] == num) return 0;
if (puzzle[rowStart + (i%3)][colStart + (i/3)] == num) return 0;
}
If we find a number in one of the cells that matches, it's a duplicate, and we exit the function as 'false', or, 0.
EDIT:
Now that I think of it, you could use this same trick for a single-dimension array by using i % 9 instead of 3. You could then determine which 'row' we're on by doing i / 9 and trusting that, since we're dealing with type ints, we'll truncate the unnecessary decimals.
This does verify that this trick is a bit prone towards N-1 indexed data, as someone would assume 'go to the 81st element' would mean go to the 9th column of the 9th row, but using 81 % 9 would yield 0, and 81 / 9 would yield 9, so we'd go to the 0th place at row 9.