I wanted to create two-dimensional matrixes on an automated routine (depending on inputs) and then make them return to see the results.
Here's my code:
public class Two_dimensional_arrays {
static int[][] array1;
public static int[][] create_array(int number1, int number2) {
int k = 1;
for (int j = 0; j <= number2; j++) {
for (int i = 0; i <= number1; i++) {
array[i][j] = k;
k++;
}
}
return array1;
}
}
The logic behind all of that was to fill any matrix in order like (let's make a 3x3 one)
1-2-3
4-5-6
7-8-9
So the matrix would be automatically filled (in ascending order), but it didn't work out as expected since I'm kind of new to programming.
You have to actually allocate the array somewhere.
static int[][] array1;
This declares a variable capable of holding a reference to an array; it is not the array. The array is allocated by 'new':
static int[][] array1 = new int[3][3];
A couple of other points:
The 'array' in your loop should probably be 'array1'.
Since 'array1' is a member variable there's probably no point in returning it as well. You could go either way: have a single array, as at present, and your create_array method will overwrite it each time; OR have create_array allocate an array of the intended size (new int[number1][number2]) and return it. I'd go for the latter.
The arguments could be named better: 'row_count' rather than 'number1', 'column_count' rather than 'number2' -- or anything similar that conveys the intended meaning. (Typically Java programmers use camel-case names, like rowCount, rather than underscore, but that's not a particularly interesting discussion and not my point here).
public class Two_dimensional_arrays {
public static int[][] create_array(int number1, int number2){
int[][] matrix = new int[number1][number2];
int k = 1;
for(int i = 0; i<number1; i++){
for(int j = 0; j<number2; j++){
matrix[i][j] = k;
k++;
}
}
return matrix;
}
}
Related
Need some advice for a project in an intro Java class. I'm stuck at creating a assignment constructor which takes an array as input and completes a deep copy. The constructor in question is found in the second block of code.
import java.util.Scanner;
public class NumberList
{
public static final int MAX_CAPACITY = 100;
private double [] numbers;
private int length;
public NumberList()
{
numbers = new double[MAX_CAPACITY];
int i;
for(i = 0; i < MAX_CAPACITY; i++)
numbers[i] = 0;
length = 10;
}
Everything before this line compiles. The constructor below is to complete a deep copy from the array parameter to the numbers array.
NumberList(final double a[])
{
double a[] = new double[MAX_CAPACITY];
numbers = a[];
}
Following errors received:
NumberList.java:67: error: '.class' expected
numbers = a[];
For the life of me, I cannot figure out how to do fix this. I've tried with a "for" loop, as well.
NumberList(final double a[])
{
double a[] = new double[MAX_CAPACITY];
numbers = a[];
}
The first line is attempting to re-declare the parameter a; you can't do that.
And the second line uses an invalid syntax: you never use [] except in the declaration of array variables, or the initialization of those variables.
The easiest way to copy a is to write:
numbers = Arrays.copyOf(a, a.length);
But you can write this with a loop like Mureinik shows you.
Note that you should write double[] a, not double a[]. The two are semantically identical, but the former is preferred because [] is part of the type, not the variable name.
The double a[]-style was put into Java "as a nod to the tradition of C and C++". You can read more here.
You can simply use:
NumberList(final double[] a) {
numbers = Arrays.copyOf(a, a.length);
}
Just run over a and copy its elements to numbers:
public NumberList(final double[] a) {
this.numbers = new double[a.length];
for (int i = 0; i < a.length; ++i) {
this.numbers[i] = a[i];
}
}
I am trying to find the minimum value in an array by way of creating a new Java class. I am having trouble passing in the array and using it to find the minimum value of an array.
I have a total of two separate arrays that I am trying to find the value of.
Here is the first class I created:
import java.util.*;
public class mooseWeight
{
public int main(String[] args)
{
int[] length1;
int[] length2;
length1 = new int[20];
length2 = new int[50];
//Length 1
System.out.println("Array 1:");
Random rnd = new Random();
for(int i = 0; i<length1.length; i++)
{
length1[i] = rnd.nextInt(400) + 250;
System.out.println(length1[i]);
return length1[i];
}
System.out.println("-----------------------------------");
//Length2
System.out.println("Array 2:");
Random rnd2 = new Random();
for(int j = 0; j < length2.length; j++)
{
length2[j] = rnd2.nextInt(400) + 250;
System.out.println(length2[j]);
return length2[j];
}
}
}
This is currently set up to find the minimum value of length1[] (aka the first array).
This is the class I am trying to pass the arrays into:
public class minWeight
{
public static int getArrayMin(int[] arr)
{
mooseWeight array1[] = new mooseWeight[];
int minValue = array1[0];
for (int i = 0; i < array1.length; i++)
{
if (array1[i] < minValue)
{
minValue = array1[i];
}
//return minValue;
}
return minValue;
System.out.println(minValue);
}
}
My current error:
1 error found:
File: D:\2016-2017\Fall2016\201_CSCE_Programming\Lab 7\minWeight.java [line: 5]
Error: array dimension missing
The error in minWeight not fom the array parameter, it is from this line:
mooseWeight array1[] = new mooseWeight[];
You cannot allocate an array of unknown dimension in java.
Also, your attempt to do so makes no sense.
Just delete the line above from your java method and change the name of the parameter to array1.
Get an IDE like netbeans or eclipse.
Your mooseWeight class contains your main, so when you're creating array1, you're trying to create an array containing your actual program.
mooseWeight array1[] = new mooseWeight[]; is creating an array of mooseWeight objects.
As you don't define a size, this will fail, but even if it didn't, it wouldn't work.
I assume that you meant to create an array of int, then loop over it.
If you created an array of int, then tried to loop over it without adding anything, the loop won't do anything as there's nothing to iterate over.
In your method, you pass in an array of int called arr, so you need to use that to loop over.
If you're trying to pass 2 arrays into the method, creating an array as part of your method still won't work.
You need to modify your method declaration to accept a second array.
Assuming you want to find the smallest value from both of these arrays, I've modified my code snippet to do just that.
If you need to process your second array differently, modify the loop which deals with secondArr.
As mentioned in comments, your mooseWeight class should be named MooseWeight to keep with correct Java naming conventions.
A class name is in PascalCase, with instances in camelCase.
To call the method, use the following snippet.
int[] ar1 = new int[20];
int[] ar2 = new int[50];
//Populate your arrays with values....
int minValue = MinWeight.getArrayMin(ar1, ar2);
Class:
public class MinWeight {
public static int getArrayMin(int[] arr, int[] secondArr) {
int minValue = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < minValue)
{
minValue = arr[i];
}
}
for (int i = 0; i < secondArr.length; i++) {
if (secondArr[i] < minValue)
{
minValue = secondArr[i];
}
}
System.out.println(minValue);
return minValue;
}
}
As a final concern, in your code, you return minValue before you try to print the result, so the print instruction is always unreachable.
I'm reading and learning about a Java implementation of radix sort, as shown below. It would be great if someone could clarify the logical meaning of pointTo, index and globalPtr.
https://www.hackerrank.com/challenges/string-similarity/editorial
private void radixSort0() {
globalPtr = 0;
Arrays.fill(bucketHead, -1);
Arrays.fill(next, -1);
for (int i = 0; i < n; i++) {
int value = nr0[index[i]];
if (bucketHead[value] == -1) bucketHead[value] = bucketTail[value] = globalPtr;
else bucketTail[value] = next[bucketTail[value]] = globalPtr;
pointTo[globalPtr++] = index[i];
}
int ptr = 0;
for (int i = 0; i < M; i++)
for (int j = bucketHead[i]; j != -1; j = next[j])
index[ptr++] = pointTo[j];
}
This radixSort0() is not a complete radix sort. If your goal is to learn about radix sort, look elsewhere.
In both (needlessly duplicated) radixSort methods, int[] next is used to establish singly linked lists - using indexes instead of references, and -1 instead of null. (You can not just set next[some_index_depending_on value] to index[i] - there would be no lists.) The int[] pointTo would probably be more descriptively be named value. Think of next&value as linked lists, represented in an instance with two data members of type array, as an alternative to an array of instances with members next&value. globalPtr is the smallest index not yet allocated in that/those array/s.
(The blaring lack of comments in the code to follow is owing to my lack of understanding why anyone should try and construct a suffix array using this, or what the pieces of code contribute to that goal: feel free to correct&amend.)
Not even thinking about testing, the Java way of handling this might be
private void radixSortStep(int[]nr) {
List<Integer> value[] = new List[M];
for (int i = 0; i < value.length; i++)
value[i] = new ArrayList<Integer>(0);
for (int i: indexes)
value[nr[i]].add(i);
int ptr = 0;
for (int i = 0; i < M; i++)
for (int val: value[i])
indexes[ptr++] = val;
}
(with a bit of hand-waving about M (set to n+1) and nr1 (initialise entries not copied from rank to n, not -1))
import java.io.*;
import java.util.*;
public class St {
public static int calculate(String s){
char[]arr=s.toCharArray();
int length=arr.length;
int count=length;
for(int i=1;i<length;i++){
int len=length-i;
int j=0;
for(;j<len;j++)
if(arr[j]!=arr[j+i]){
break;
}
count+=j;
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner( System.in );
int n=scanner.nextInt();
for(int i=0;i<n;i++){
String s=scanner.next();
System.out.println(calculate(s));
}
}
}
it almost passed all testcases except last two due to timeout hope my work helps happy coding..
I'm working with a 2D array and what I'm trying to do in the below method is swap two values. The 'currentBoard' variable is a 2D array that needs should not be edited. The 'cpy' variable a duplicate of the 'currentBoard' and needs its variables to be changed. 'nbt' and 'bt' are 1D arrays that used to point to an index in the 2D array. The code for the function 'copyBoard' is always below if it helps
The issue I'm having is that at on the line marked with ** when the value in the 'cpy' array is changed for some reason the value in 'currentBoard' is being changed as well. I really can't figure out why this is happening....
private void Swap(int[] nbt, int[] bt, ArrayList<State> children, String direction) {
int[][] cpy = copyBoard(currentBoard);
int temp = cpy[nbt[0]][nbt[1]];
**cpy[nbt[0]][nbt[1]] = currentBoard[bt[0]][bt[1]];
cpy[bt[0]][bt[1]] = temp;
children.add(new Board(cpy, this.getGOAL(), this.getRows(), this.getColumns(), (this.getDirections() + direction + ", ")));
}
In case it helps here is the values that are assigned to the variables at the point when the code is on the line marked with **
nbt = {1, 0}
bt = {0, 0}
private int[][] copyBoard(int[][] state)
{
int[][] returnArray = new int[rows][columns];
for (int i = 0, j = 0; i*j < PUZZLE_SIZE; i++, j++)
{
returnArray[i] = state[i];
}
return returnArray;
}
A 2D array is an array of references to arrays. So if you assign returnArray[i] = state[i], you are simply making returnArray[i] refer to the same array that state[i] refers to. Thus, modifying returnArray[i][j] will modify the j'th element of whatever state[i] was. You have to create a deep copy of the "rows", too, e.g.:
private int[][] copyBoard(int[][] state)
{
int[][] returnArray = new int[rows][columns];
for (int i = 0, j = 0; i*j < PUZZLE_SIZE; i++, j++)
{
// deep copy of row:
returnArray[i] = Arrays.copyOf(state[i], state[i].length);
}
return returnArray;
}
Check out this short write-up on 2D arrays, it should give you a better idea of what's going on here. In particular, this little image, which represents int nums[][] = new int[5][4] (although it makes more sense in context):
By the way, your loop logic looks a little odd to me; even if the math happens to work out in your situation, it is a bit clearer to do this instead:
for (int i = 0; i < rows; i++)
Or more generally:
for (int i = 0; i < returnArray.length; i++)
These, of course, assume that state.length == rows; but you get the idea.
A project I am doing requires me to find horizontal and vertical sums in 2 dimensional arrays. So pretty much its a word search (not using diagonals) but instead of finding words, the program looks for adjacent numbers that add up to int sumToFind. The code below is what I have come up with so far to find horizontal sums, and we are supposed to implement a public static int[][] verticalSums as well. Since I have not yet completed the program I was wondering, first of all, if what I have will work and, secondly, how the array verticalSums will differ from the code below. Thank you
public static int[][] horizontalSums(int[][] a, int sumToFind) {
int i;
int start;
int sum = 0;
int copy;
int [][] b = new int [a[0].length] [a.length];
for (int row = 0; row < a.length; row++) {
for ( start = 0; start < a.length; start++) {
i = start;
sum = i;
do {
i++;
sum = sum + a[row][start];
}
while (sum < sumToFind);
if(sum == sumToFind) {
for (copy = start; copy <= i; copy++) {
b[copy] = a[copy];
}
}
for (i = 0; i < a[0].length; i++) {
if (b[row][i] != a[row][i])
b[row][i] = 0;
}
}
}
return b;
}
Your code won't work.... (and your question is "if what I have will work?" so this is your answer).
You declare the int[][] b array as new int [a[0].length] [a.length] but I think you mean: new int [a.length] [a[0].length] because you base the row variable off a.length, and later use a[row][i].
So, if your array is 'rectangular' rather than square, you will have index-out-of-bounds problems on your b array.
Your comments are non-existent, and that makes your question/code hard to read.
Also, you have the following problems:
you set sum = i where i = start and start is the index in the array, not the array value. So, your sum will never be right because you are summing the index, not the array value.
in the do..while loop you increment i++ but you keep using sum = sum + a[row][start] so you just keep adding the value to itself, not the 'next' value.
At this point it is obvious that your code is horribly broken.
You need to get friendly with someone who can show you how the debugger works, and you can step through your problems in a more contained way.
Test is very simple
public static void main(String[] args) {
int[][] a = {{1, 2}, {1, 0}};
int[][] result = Stos.horizontalSums(a, 1);
System.out.println(Arrays.deepToString(result));
}
Result
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
When you fix this problem, then this should print something like this
[[1, 2], [1, 0]]