Creating a specific pattern for list of integers - java

int[] box = new int[9*8];
for(int i=0; i<9; i++) {
for(int j=0; j<8; j++) {
box[j] = i;
}
}
I've tried everything and it turns out to be way harder than it looks for me. Without using ArrayLists (I understand this works using box.add(i)) I can only use int[] type. I need to create a list of integers that looks like this [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,..8,8,8,8,8,8,8,8] so 8 sets of integers from 0-8. Can anyone help me?

I believe the problem is that on line 4. The code sets a position on to a value, but this position repeats from 0 to 7.
This should work better:
int[] box = new int[9*8];
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 8; j++) {
box[i * 8 + j] = i;
}
}
Basically, it shift the 0 - 7 over 8 places for every new number.

Related

How can i print all content of one Array in one line?

I'me new here and beginner of JAVA.
I've just started learning about Scanner and Array!
I want to get some input from Scanner. and save it into Array.
the array size is 5 and I succeed save those
but what I could print is only one value from array.
I want to print all values in the array
and I have no idea what should I do or where I should fix!
hope you guys tell me about that.
My code is down below.
import java.util.Scanner;
import jdk.internal.util.xml.impl.Input;
public class Test2 {
public static void main(String[] args) {
int[] array = new int[5];
Scanner scanner = new Scanner(System.in);
System.out.print("five numbers");
for (int i = 0; i <= array.length; i++) {
array[i] = scanner.nextInt();
}
for (int nums : array) {
System.out.print(nums);
}
}
}
this is result :
five numbers1 2 3 5 5
The issue is with the following iteration which is expecting 6 numbers (since i starts at 0 and ends at 5).
This wont work :
for (int i = 0; i <= array.length; i++)
This will work
You should either input 6 numbers and change your array size to 6 elements. Either ways, you need to change the for loop to :
for (int i = 0; i < array.length; i++)
You problem is that you defined an array of size 5:
int[] array = new int[5];
BUT you expect for 6 input numbers, as the for-loop set to loop 6 time due to <=:
for (int i = 0; i <= array.length; i++) {
array[i] = scanner.nextInt();
}
The solution here is to change the condition to i < array.length
Explanation:
By definition:
Array size is 5
array.length = 5
inside the for-loop: array[i] = scanner.nextInt(), when i = array.length i.e. i=5, array[i] is out of bounds.
change
for (int i = 0; i <= array.length; i++)'$'
to
for (int i = 0; i < array.length; i++)'$'
as you want it to loop 5 times.
You can use
either
System.out.print(Arrays.toString(array));
i don't think you need to use
import jdk.internal.util.xml.impl.Input;
package file.
and change the loop statement
for (int i = 0; i <= array.length; i++)
to
for (int i = 0; i < array.length; i++)
otherwise it will rise an error when you will put 6th input like:
java.lang.ArrayIndexOutOfBoundsException

JAVA Writing the diagonal of an 2-dimensional array into an 1-dimensional array

Want to write the diagonal of an 2-dimensional array (n*n Matrix) into an one-dimensional array.
1 2 3
4 5 6 => 1 5 9
7 8 9
public int[] getDiagonalFromArray(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array[0].length];
int k=0;
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
for (int l = 0; l < two_d_array[0].length; l++) {
diagonal_array[k]=two_d_array[i][j];} //HERE SHOULD BE THE ERROR... HOW DO I CYCLE THROUGH THE 1dim "diagonal_array"?
}
}
return diagonal_array;
}
This method delivers wrong values.
This method of mine works, but just Prints the diagonale, instead of putting it into an 1dim array.
public void getDiagonal(int[][] two_d_array){
//int[] diagonal_array = new int[two_d_array[0].length];
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
if (i==j) System.out.print(two_d_array[i][j]+" ");
}
}
}
Where is the logical difference? I tried the if-clause on the first method, but it raises the "outofbound"-Exception.
Thanks in advance.
Why do you need more than one loop?
for (int i = 0; i < two_d_array[0].length; i++) {
diagonal_array[i]=two_d_array[i][i];
}
Seems to be enough to me.
If your matrix has the same width and height, this is a solution:
public int[] getDiagonal(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array.length];
for (int i = 0; i < two_d_array.length; i++) {
diagonal_array[i] = two_d_array[i][i];
}
return diagonal_array;
Here, I consider principal diagonal elements to be the set of elements , where n & m are the number of rows and the number of columns (per row?) respectively.
Thus, the number of diagonal elements is never greater than min(numOfRows, numOfColumns).
And so, you can always try:
public int[] getDiagonalFromArray(int[][] 2DArray){
int[] diagonalArray = new int[Math.min(2DArray.length, 2DArray[0].length]);
int k=0;
for (int i = 0; i < 2DArray.length && k < diagonalArray.l length; ++i) {
for (int j = 0; j < 2DArray[i].length && k < diagonalArray.l length; ++j) {
if (i == j) {
diagonalArray[k++]=2DArray[i][j];
}
}
}
return diagonalArray;
}
Threw in some bounds checks for good measure.
Your input matrix must at be at least rectangular (square makes most sense), otherwise, the code will behave unreliably.
This is the same as #Andreas' answer, but I sacrifice performance and brevity here for the sake of understanding.

How to compare two arrays of different sizes?

So my task is to read a file line by line and store the integers into an array. Then to add the integers in spots 1-5, 2-6, 3-7 etc. and store those into a new array.
In array 1 there is 4 more values than array 2. I need to compare these Arrays and see if array1 is 0.999 bigger than array2.
If it is indeed larger, I need to print out the LOCATION of the number in the array 1.
Right now my problem is my code is outputting that every number is larger than the corresponding number in array 2.
Code:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Asgn7
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner file = new Scanner(new File("asgn7data.txt"));
double[] array = new double[file.nextInt()];
double[] newArray = new double[array.length - 4];
double tempVal = 0;
int j = 0;
int count = 0;
while(file.hasNext())
{
for(int i = 0; i < array.length ; i++)
{
array[i] = file.nextInt();
}
for(j = 0; j < array.length - 4; j++)
{
for(int k = 0; k < 5; k++)
{
newArray[j] += array[j+k] / 5;
}
}
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
}
}
The values which should be compared are from 3-13.
Judging by the picture, you are not placing the values in the correct index in the second array, or you are not matching the correct ones.
If you want it to look exactly like in the picture, the second array should be declared:
double[] newArray = new double[array.length - 2];
And the loop to fill it should be changed to:
for(j = 2; j < array.length - 2; j++)
{
for(int k = -2; k <= 2; k++)
{
newArray[j] += array[j+k] / 5;
}
}
This will put the averages in the third, fourth, fifth... elements in newArray. And now you can compare them directly:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i] + 0.999))
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
If you want to save the two unused spaces, as you originally did, rather than responding exactly to the picture, then you should calculate the values as you originally did. But remember to compare each element to the one two places before it and stop 2 places before the end.
Instead of
for(int i = 2; i < array.length; i++)
use
for(int i = 2; i < array.length - 2; i++)
To print the location, your construct with the count and tempVal is unnecessary. You just need to print i+1. Also note that you have a ; after your if. This means it's an empty if, and the block after it is always performed. Never have a ; after an if, for, while etc.
Not clear with what you are asking for in your question but without questioning what's the logic, by just looking at your code:
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
if you relocate the system.out line as follows, I think you will get what you expect as follows:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
System.out.println(tempVal);
// count++;
// tempVal = count;
}
}
}
PS: Please note that I have also changed the boundary for the loop to stop iteration on 13th member of the array, instead of 15.
Are you sure you're parsing the numbers correctly?
See Java: Reading integers from a file into an array
Why don't you print them out after parsing for verification?
btw, this will overflow the index of the 2nd array (since it is created using new double[array.length - 4]):
for(int i = 2; i < array.length; i++)
so does your code run?

Java - Filling multidimensional (2d) ArrayList like a 2d array

A while ago before I got used to object object oriented programming I created a basic TicTacToe game and to create the board I used an array.
The code is a complete mess because I didn't properly understand how to use objects, but I did initialize the board correctly:
char[][] board = new char[3][3];
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
board[i][j] = '[]' //or something like that...don't remember exactly
}
}
My question is how would you this with an ArrayList?
ArrayList <ArrayList<Character>> board = new ArrayList(); // this initialization is not
// wrong using Java 8 but for earlier versions you would need to state the type on both
//sides of the equal sign not just the left
for (int i = 0; i < board.size(); i++){
for (int j = 0; j < board.get(i).size(); j++){
board.get(i).get(j).add('[]');
}
}
but that does not work.
It does not have to be exactly like this, I just generally want to understand how to handle multidimensional ArrayLists.
-thanks
Unlike arrays, you can't initialize an entire ArrayList directly. You can specify the expected size beforehand (this helps performance when you are using very large lists, so it is a good practice to do it always).
int boardSize = 3;
ArrayList<ArrayList<Character>> board = new ArrayList<ArrayList<Character>>(boardSize);
for (int i = 0; i < boardSize; i++) {
board.add(new ArrayList<Character>(boardSize));
for (int j = 0; j < boardSize; j++){
board.get(i).add('0');
}
}
The main difference is that in your original code you had a multi-dimensional array of primitives (in this case, char) and all you had to do was assign a new primitive value to each slot in the array.
However what you want now is an ArrayList of (ArrayList of Character). When you create the ArrayList it is empty. In order to procede you are going to need to fill it with several (ArrayList of Character) before you can begin to start adding Characters themselves.
So for example,
ArrayList <ArrayList<Character>> board = new ArrayList<>();
for (int i=0; i<3; i++) {
board.add(new ArrayList<Character>());
}
Now you can start adding Characters to your lists:
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
board.get(i).add('A');
}
}
Hope this helps.
First you have to initialize the ArrayList in your first line correctly and than you have to initialize an new ArrayList in each run of your first loop:
ArrayList <ArrayList<Character>> board = new ArrayList<ArrayList<Character>>();
for (int i = 0; i < 3; i++){
ArrayList<Character> innerList = new ArrayList<Character>();
board.add(innerList);
for (int j = 0; j < 3; j++){
innerList.add('[');
}
}

Android: Methods for finding matching elements in arrays?

Hi I am stuck in a particular case
I have two arrays, ArrayA[] with 50 items and another ArrayB[] with 10 items.
I want to convert the values of the ArrayB[] (10 items) to be 1 if they match a value in ArrayA[] and 0 if they don't.
I have been trying various techniques for past 5 hours- would be great to get some guidance in what I can do to get this!
Thanks for any help!
If I understand you well, this is what you are looking for:
public static void method(int[] arrayA, int[] arrayB)
{
boolean match = false;
label: for(int i = 0; i < arrayA.length; i++)
for(int j = 0; j < arrayB.length; j++)
if(arrayA[i] == arrayB[j])
{
match = true;
break label;
}
int k = (match?1:0);
for(int i = 0; i < arrayB.length; i++)
arrayB[i] = k;
}
If not, please elaborate!
List l = Arrays.asList(arrayA);
for (int i = 0; i < arrayB.length; i++)
arrayB[i] = l.contains(arrayB[i]) ? 1 : 0;

Categories