private void enterbtnActionPerformed(java.awt.event.ActionEvent evt) {
int [][] array = new int [4][4]; // my array
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j]= ;// use for feeding the code
}
popfield.setText(Arrays.deepToString( array ) );
}
I want to insert integers into 2d array via 2 textfields one for columns and one for rows elements via two text fields xfield and yfield
So.. For create 2D int array:
//int 2 dimensional array
int[][] array = null;
//your fields values
final int xFieldVal = 5;
final int yFieldVal = 7;
//values to fill into array
final int minArrayVal = 50;
final int maxArrayVal = 100;
//create matrix / grid with dimensions (xFieldVal x yFieldVal)
array = new int[xFieldVal][yFieldVal];
(that creates recangle xFieldVal x yFieldVal- or Y*X..)
While you have rectangle array you can acces to all value for filling eg. like that:
//random generator
Random rnd = new Random();
for (int i = 0; i < xFieldVal; i++) {
for (int j = 0; j < yFieldVal; j++) {
//generate new int in interval
array[i][j] = minArrayVal + rnd.nextInt(maxArrayVal- minArrayVal+ 1);
}
}
While you will dont have rectangle array (you can have eg. just 1st dimension fixed, and 2nd not- I mean each "row" can have difference "columns" count), you have to use that loop:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
//printing next line
System.out.println();
}
Eg. to find min and max value, you can use that:
//set on the max possible (every value should be less than that)
int min=Integer.MAX_VALUE;
//set on the min possible (every value should be more than that)
int max=Integer.MIN_VALUE;
//iteration through 1st index (eg. iteration through rows)
for (int i = 0; i < array.length; i++) {
//iteration through 2nd index of 1st index (eg. through all columns)
for (int j = 0; j < array[i].length; j++) {
//compare and assign if array value is less than actual found min
if(min > array[i][j]){
min = array[i][j];
}
//compare and assign if array value is more than actual found max
if(max < array[i][j]){
max = array[i][j];
}
}
}
I dont think you understand what a 2D array is
think of it as a grid. you insert into a single cell at a time.
a single cell belongs to a row and a column hence has a row number and column number...like an excel work book? cell b5?
so if you want to input numbers all you gotta do is have a single textfield lets call it txt
the rest is as follows
private void enterbtnActionPerformed(java.awt.event.ActionEvent evt)
{
int [][] array = new int [4][4]; // my array
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j]= Integer.parseInt(txt.getText());// use for feeding the code
}
popfield.setText(Arrays.deepToString( array ) );
}
Related
I need help completing one task from Java book that I read. I need to create a 3-dimentional array of int that will be able to store 30 values.
It's described as cuboid containing cubes. Each cube is supposed to be a cell and they should store ints from 30 to 59. How should it look like? I try to draw it but it's pretty hard for me. Here is what I've tried.
public class cw124{
public static void main (String[]args){
int tab[][][]=new int[31][30][30];
int wypelniacz=30;
for (int i=0; i<tab.length; i++){
for (int j=0; j<tab[j].length; j++){
wypelniacz=30;
for (int k=0; k<tab[k].length; k++){
tab[i][j][k]=wypelniacz++;
}
}
}
for (int i=0; i<tab.length; i++) {
for (int j=0; j<tab[j].length; j++){
for (int k=0; k<tab[k].length; k++){
wypelniacz=30;
tab[i][j][k]=wypelniacz++;
System.out.println("Row "+i+" Cell 1 "+j+" Cell 2 "+k+" "+tab[i][j][k]);
}
}
}
}
}
Your 3D array currently has 31*30*30 = 27,900 cells. If you need a 3D array with 30 cells, you can do this:
int tab[][][]=new int[5][3][2];
This will give you a 3D array with 5*3*2 = 30 cells.
You can imagine each value in square brackets to be the length of one side of the cuboid.
The next step would be:
int counter = 30;
for(int i = 0; i < tab.length; i++)
{
for(int j = 0; j < tab[0].length; j++)
{
for(int k = 0; k < tab[0][0].length; k++)
{
tab[i][j][k] = counter;
counter++;
}
}
}
This will populate all the cells with numbers from 30 to 59.
I think the following code may help you understand the task.
You have to think of the 3 dimensions as a cube, the cube contains grids, each grid has rows which then have multiple columns)
(imagine a Rubik's cube, which has 3 layers=grids, each grid then has 3 rows and each of those rows again has 3 columns)
final int gridCount = 5;
final int rowCount = 5;
final int colsPerRow = 15;
final int[][][] cube = new int[gridCount][rowCount][colsPerRow];
for (final int[][] grid : cube) {
for (int col = 0; col < grid.length; col++) { //just to show the two different versions of 'for'
final int[] row = grid[col];
row[col] = 42+ col; //set it to whatever number
}
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numberOfRows, numberOfColumns;
double arrayElements[][] = null;
int index[] = null;
System.out.print("Enter number of rows in array: ");
numberOfRows = keyboard.nextInt();
System.out.print("Enter number of columns in array: ");
numberOfColumns = keyboard.nextInt();
arrayElements = new double[numberOfRows][numberOfColumns]; //this command allocates memory for the array arrayElements
for (int row = 0; row < numberOfRows; row++)
{
for (int column = 0; column < numberOfColumns; column++)
{
System.out.print("Enter the Value for Row [" + row + "], Column " + "[" + column + "]: ");
arrayElements[row][column] = keyboard.nextDouble();
}
}
System.out.printf("\n Two-Dimensional Array: %d rows x %d columns\n", numberOfRows, numberOfColumns);
for (int row = 0; row < numberOfRows; row++)
{
System.out.printf("Row %3d:", row);
for (int column = 0; column < numberOfColumns; column++)
{
System.out.printf("%7.1f", arrayElements[row][column] );
}
System.out.println();
index = locateLargest( arrayElements );
}
}
public static int[] locateLargest( double[][] arrayx2 ){
}
Hello all,
I am trying to write a method for finding the largest element in a two-dimensional array, and return the index of the element with the highest value to the single-dimensional array 'index'. I have the signature written, but can anyone please help me figure out how to actually write the method that will search each element of the two-dimensional array and find the index location of the largest number?
Thank you so much!
/*Finds max value in an Array*/
public int maxValue(int array[]){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return Collections.max(list);
}
For 2 dimensional array use that:
int maxValue = 0;
System.out.println("\nMax values in 2D array: ");
for (int i = 0; i < twodArray.length; i++) {
for (int j = 0; j < twodArray[i].length; j++) {
if (twodArray[i][j] > maxValue) {
maxValue = twodArray[i][j];
}
}
System.out.println("Max value of row " + i + ": " + maxValue);
}
Reference: https://stackoverflow.com/a/5877271/1848929
Firstly, if you want the returned array of your method to contain the largest element as well as the index, the return type should be double[] and not int[] since the type of the elements of the matrix is double. The method bellow will return an array containing three elements. the first element is the row index, the second is the column index, and the third is the element value. if you are going to use the code bellow, make sure to change the return type and also the type of index in your code to double[]. I hope this is helpful.
// first we assume the largest element is the one located at row 0, and
//column 0, then we compare it with the other elements in the matrix
public static double[] locateLargest( double[][] arrayx2 ){
double max = arrayx2[0][0];
int row = 0, col = 0;
double[] indexAndMaxVal = new double[3];
for (int i = 0; i < arrayx2.length; i++) {
for (int j = 0; j < arrayx2[i].length; j++) {
if (arraux2[i][j] > max) {
maxValue = arrayx2[i][j];
row = i;
col = j
}
}
}
indexAndMaxVal[0] = row;
indexAndMaxVal[1] = col;
indexAndMaxVal[2] = max;
return indexAndMaxVal;
}
I need to delete row and column where max value in 2d array exist,please suggest how to do it.
Here is an array in which specific row and column must be delted. I suppose here can be used aaraycopy
import java.util.Scanner;
public class Test{
public static void main (String[] args){
int maxValue=0;
int[][] multiplyTab = new int[5][10];
int row = 0;
int column=0;
for (int i = 0; i < multiplyTab.length; i++) {
for (int j = 0; j <multiplyTab[i].length ; j++) {
multiplyTab[i][j] =((i+1)*(j+1));
System.out.print(multiplyTab[i][j] + "\t");
}
System.out.println();
}
for (int i = 0; i < multiplyTab.length; i++) {
for (int j = 0; j < multiplyTab[i].length; j++) {
if (multiplyTab[i][j] > maxValue) {
maxValue = multiplyTab[i][j];
row=i;
column=j;
}
}
}
}
}
To delete row i from a 2D array like yours, first create a new 2D array that is one element shorter (4 instead of 5 in your example). Copy rows 0 through i - 1 and rows i + 1 through originalTable.length - 1 into the new array.
Edit: when maxValue is in the last row (as here if I am not mistaken) and hence the last row is to be deleted, it is of course a bit easier since there are no rows i + 1 through originalTable.length - 1 to copy.
To delete column j do similarly to every inner array of the table.
I'm trying to return the mode of a 2D array using a frequency array. I have an array, score, which is of length 10, and has 3 columns. Each column contains an int that is between 0 and 100.
I'm trying to find a way that will iterate through the array and return the modal value. What I have so far is:
int value = 0;
int[] freq = new int[100];
for (int row = 0; row < score.length; row++) {
for (int col = 0; col < score[row].length; col++) {
score[row][col] = value;
freq[value]++;
}
}
int largest = 0;
int mode = -1;
for (int i = 0; i < 100; i++) {
if (freq[i] > largest)
{
largest = freq[i];
mode = i;
}
}
System.out.println("modal score is: " +mode);
Problem is that this is just returning the modal score as 0, which it isn't.
You have a problem on generating the freq array. If I understand correctly, on the first double-for block you are trying to put the frequencies of the numbers inside the freq array.
But all you do is:
int value = 0;
.....
score[row][col] = value;
freq[value]++;`
firstly you are changing the score array,( which is a problem for you I guess...) and the you go to freq[0] and do ++. Obviously modal is 0, that number appears in all of the array.
SOLUTION: in the first double for block you should do:
value = score[row][col];
freq[value]++;
so I think you mixed up the order of the line, it should be the other way around.
private static void printMode(double[][] doubles) {
HashMap<Double , Double> map = new HashMap();
for (int i = 0; i < doubles.length; i++) {
for (int j = 0; j < doubles[i].length; j++) {
double temp = doubles[i][j];
if(map.get(temp)==null){
map.put(doubles[i][j],1.0);
}else {
double temp2 = (double) map.get(temp);
map.put(doubles[i][j],++temp2);
}
}
}
Object[] objects = map.values().stream().sorted().toArray();
Stream stream = map.entrySet().stream().filter(val-> val.getValue().equals(objects[objects.length-1]));
stream.forEach(System.out::println);
}
I think using Stream for finding mode is the best way.
use int instead of double doesn't cause any problems.
int value = 0;
int [] freq = new int [arr.length];
for (int i = 0; i < arr.length; i++){
for (int j = 0; j < arr[i].length; j++){
value = arr[i][j];
freq[value]++;
}
}
int largest = 0;
int mode = 0;
for (int i = 0; i < freq.length; i++) {
if (freq[i] > largest)
{
largest = freq[i];
mode = i;
}
}
System.out.println("modal score is: " +mode);
I am trying to implement kmeans algorithm for a certain Music Recommendation System in Java.
I have generated 2 arrays,playsFinal[](the total play-count of an artist by all users in the dataset) and artFinal[] (the unique artists in the entire dataset) . The playcount of every artFinal[i] is playsFinal[i]. For k,I have chosen kclusters=Math.sqrt(playsFinal.length)/2.
I have an array clusters[kclusters][playsFinal.length] and the first position clusters[i][0] for every 0<i<kclusters is filled with a certain value,which is basically the initial mean as in kmeans algorithm.
int j = 0;
for (int i = 0; i < n && j < kclusters; i += kclusters) {
clusters[j][0] = weighty[j];//initial means
System.out.println(clusters[j][0]);
j++;
}
Here,weight[] is a certain score given to every artist.
Now,in the following function I am returning the index,ie,which cluster the plays[i] should be added to.
public static int smallestdistance(double a, double[][] clusters) {
a = (double) a;
double smallest = 0;
double d[] = new double[kclusters];
for (int i = 0; i < kclusters; i++) {
d[i] = a - clusters[i][0];
}
int index = -1;
double d1 = Double.POSITIVE_INFINITY;
for (int i = 0; i < d.length; i++)
if (d[i] < d1) {
d1 = d[i];
index = i;
}
return index;
}
If not obvious,I am finding the minimum distance between playsFinal[i] and the initial element in every clusters[j][0] and the one that is the smallest,I am returning its index (kfound). Now at the index of the clusters[kfound][] I want to add the playsFinal[i] but here is where I am stuck. I can't use .add() function like in ArrayList. And I guess using an ArrayList would be way better. I have gone through most of the articles on ArrayList but found nothing that could help me. How can I implement this using a multidimensional ArrayList?
Thanks in advance.
My code is put together as follows:
int j = 0;
for (int i = 0; i < n && j < kclusters; i += kclusters) {
clusters[j][0] = weighty[j];//initial means
System.out.println(clusters[j][0]);
j++;
}
double[] weighty = new double[artFinal.length];
for (int i = 0; i < artFinal.length; i++) {
weighty[i] = (playsFinal[i] * 10000 / playsFinal.length);
}
n = playsFinal.length;
kclusters = (int) (Math.sqrt(n) / 2);
double[][] clusters = new double[kclusters][playsFinal.length];
int j = 0;
for (int i = 0; i < n && j < kclusters; i += kclusters) {
clusters[j][0] = weighty[j];//initial means
System.out.println(clusters[j][0]);
j++;
}
int kfound;
for (int i = 0; i < playsFinal.length; i++) {
kfound = smallestdistance(playsFinal[i], clusters);
//HERE IS WHERE I AM STUCK. I want to add playsFinal[i] to the corresponding clusters[kfound][]
}
}
public static int smallestdistance(double a, double[][] clusters) {
a = (double) a;
double smallest = 0;
double d[] = new double[kclusters];
for (int i = 0; i < kclusters; i++) {
d[i] = a - clusters[i][0];
}
int index = -1;
double d1 = Double.POSITIVE_INFINITY;
for (int i = 0; i < d.length; i++)
if (d[i] < d1) {
d1 = d[i];
index = i;
}
return index;
}
Java's "multidimensional arrays" are really just arrays whose elements are themselves (references to) arrays. The ArrayList equivalent is to create a list containing other lists:
List<List<Foo>> l = new ArrayList<>(); //create outer ArrayList
for (int i = 0; i < 10; i++) //create 10 inner ArrayLists
l.add(new ArrayList<Foo>());
l.get(5).add(foo1); //add an element to the sixth inner list
l.get(5).set(0, foo2); //set that element to a different value
Unlike arrays, the lists are created empty (as any list), rather than with some specified number of slots; if you want to treat them as drop-in replacements for multidimensional arrays, you have to fill them in manually. This implies your inner lists can have different lengths. (You can actually get "ragged" multidimensional arrays by only specifying the outer dimension (int[][] x = new int[10][];), then manually initializing the slots (for (int i = 0; i < x.length; ++i) x[i] = new int[i]; for a "triangular" array), but the special syntax for multidimensional array creation strongly predisposes most programmers to thinking in terms of "rectangular" arrays only.)