If I have the following Java code:
int[][] readAPuzzle()
{
Scanner input = new Scanner(System.in);
int[][] grid = new int[9][9];
for (int i=0; i<9; i++)
for (int j=0; j<9; j++)
grid[i][j] = input.nextInt();
return grid;
}
public static void main(String[] args) {
// Read a Sudoku puzzle
int[][] grid = readAPuzzle();
}
How can I convert this to C++? I get hung up on passing the array. Here is my attempt:
#include <iostream>
using namespace std;
const int puzzle_width = 9;
const int puzzle_height = 9;
void readAPuzzle(int (&grid)[puzzle_height][puzzle_width])
{
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
grid[i][j] = cin >> grid[i][j];
return;
}
int main()
{
int[9][9] grid;
readAPuzzle(grid);
}
What am I doing wrong in general?
You need to read in the input text into your array grid and pass it on.
grid[i][j] = cin >> grid[i][j];
Doesn't do what you think it does, it tries to assign an object of type istream to grid[ i ][ j ]
cin >> grid[i][j];
however suffices.
Also, note in C++ the dimensions follow the identifier as in:
int grid[9][9];
Try
#include <iostream>
using namespace std;
const int puzzle_width = 9;
const int puzzle_height = 9;
void readAPuzzle(int grid[puzzle_height][puzzle_width])
{
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
cin >> grid[i][j];
}
int main()
{
int grid[9][9];
readAPuzzle(grid);
}
In general, arrays are automatically passed by reference, and array sizes go after the name of the array not after their type.
And if you declared constants, you should always use puzzle_width and puzzle_height (perhaps shorten their names though) and not magic numbers like 9.
The simple answer is to use vectors instead of arrays. C++'s rules for passing arrays as function parameters are esoteric and derived from C. Here are some of the issues:
You can't use arrays for long without understanding and using pointers
Array subscripting is pointer subscripting. Arrays are accessed using pointer arithmetic. Arrays as function parameters are actually pointers in disguise.
Functions don't get information about array size when taking an array argument
Consider the declaration:
void inc_all(int myarray[]); /* increments each member of the array */
Unfortunately, that array parameter is not an array parameter! It's actually a pointer parameter:
void inc_all(int *myarray); /* Exactly the same thing! */
And a pointer doesn't know how many items are in the sequence it points at. As a result this function cannot have the information necessary to know when the array stops. You either need to pass the length:
void inc_all(int *myarray, size_t len); /* size_t rather than int */
or you need to use a sentinel value to mark the end of the array. Either way, an array is not a self-contained encapsulated datatype like a vector is.
You can't pass an arbitrarily-sized two-dimensional array to a function
If you try to create a function which takes a two-dimensional array:
void inc_all(int myarray[][]); /* XXX won't compile! */
it won't compile. The problem is you have an indeterminate length array of indeterminate length arrays of ints. The outer array doesn't know how large its members (the inner arrays) are and therefore doesn't know how to step through them in memory. You need to specify the size of the inner arrays:
void inc_all(int myarray[][10]);
at which point your code is probably not as general as you were hoping it was going to be.
If you use vectors and vectors of vectorss, these problems don't arise because the vectors themselves know how many members they have and carry that information with them.
If you still want to learn more about arrays and pointers I recommend section 6 of the comp.lang.c FAQ.
I think your should to use your constants first of all. You can pass as value pointer as well as ref on pointer (both 4bytes), also it is a pointer on memory (it is valueble).
#include <iostream>
using namespace std;
const int puzzle_width = 9;
const int puzzle_height = 9;
void readAPuzzle(int grid[puzzle_height][puzzle_width])
{
for(int i = 0; i < puzzle_height; i++)
for(int j = 0; j < puzzle_width; j++)
cin >> grid[i][j];
}
int main()
{
int grid[puzzle_height][puzzle_width];//I think your need to do this
readAPuzzle(grid);
}
Related
I'm having some trouble with the question below, not entirely sure if its write as I can't figure out how to call the method in the driver method to print the result.
(Question) Create a Method with header:
public static int[][] multiplyArrays(int[][] a, int[][] b)
The above method will multiply two 2D arrays referred to by a and b, and return a 2D array
reference of a × b. Multiplying two 2D array work on the following algebraic expression to
find out the resultant array: result[i][j]= a[i][k] * b[k][j]
Hint: In this case, inside the method, declare a 2D int[][] array reference variable and
instantiate it with a size of a.length x b[0].length. They complete the rest using the
series multiplication. This is an application of nested loop. The outermost loop will run from
0 to N. The middle loop will run for index i and the innermost one will run for index j.
My code so far:
public static int[][] multiplyArrays(int[][] a, int[][] b) {
var aNumRows = a.length;
var aNumCols = a[0].length;
var bNumCols = b[0].length;
int[][] m = new int[aNumRows][bNumCols];
for (var r = 0; r < aNumRows; ++r) {
for (var c = 0; c < bNumCols; ++c) {
m[r][c] = 0;
for (var i = 0; i < aNumCols; ++i) {
m[r][c] += a[r][i] * b[i][c];
System.out.printf("%3d",r, c);
}
}
}
return m;
}
Since the method you defined is static, you could simply use classname.multiplyArrays(a, b) ; where a and b are the names of the variables in your driver method.
I'm trying to multiply an array and a 2d array on java and my program compiles but keeps returning the error java.lang.NullPointerException; null when I try to input anything into it. Here is my code so far:
static double[][] productWithDiagonal(double[] a, double[][] b)
{
double[][] c = new double[3][];
{
for (int i = 0; i < b.length; ++i) {
for (int j = 0; j < b[1].length; ++j) {
c[i][j] = a[j] * b[i][j];
}
}
}
return c;
}
Thanks
This here:
double[][] c = new double[3][];
Only instantiates your "rows". You need something like
double[][] c = new double[3][3];
Or more useful probably
... c = new double[b.length][b[0].length];
instead. But just to be sure: those numbers there matter; you should make sure that b for example is really a "regular rectangle" shaped matrix - so that all rows have the same number of columns. And of course a should have the same number of columns as b, too. You could add such checks in the beginning of your method; to ensure that the shapes of a and b actually allow for this multiplication!
You see, in Java, a two-dim array is nothing but an array that contains another array. Your initial code would only initiate that "outer" array, leaving the "inner" arrays at null.
Help! I have this school assignment that wants me to write a method to find the area of rectangles (an array of ints) by multiplying width (an ArrayList) by length (an array of doubles). I'm very very new to coding; I've tried for over five hours to get this working, but I keep doing things wrong and I simply can't get it right. This is the code for the method that I've written:
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
double temp = length[index];
for(index = 0; index < length.length; index++)
{
for(index = 0; index < width.size(); index++)
{
Object widthObj = (int)width.get(index);
area[index] = temp * widthObj;
}
}
}
The full starter code we were given is here, if you need more context (it's commented): http://pastie.org/pastes/916496
Thank you so much for any help you can give me in writing this method. I've been working for hours and I just can't get it...
The length of the array and size of the arraylist should be same , And you have to change the method logic a bit, Have a look at the below code snippet
public static int[] calcRectangleArea(List<Double> width, double[] length)
{
int[] area=new int[length.length];
for(int index = 0; index < length.length; index++)
{
area[index] = (int) (length[index]*width.get(index));
}
return area;
}
Call this method passing width arraylist and length array. It will return area array of ints
You dont really need two loops here. Assuming that width[1] correlates to length[1] you can just loop through both collections at the same time in the same loop.
This should work (i haven't written a line of java in ~2 years so it may not be 100%)
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
//assuming length.length == width.size
for(index = 0; index < length.length; index++)
{
int anArea = (int)(width.get(index) * length[index]);
area[index]=anArea;
}
}
again the code above assumes the size of the collections are the same.
Firstly, you don't need to assign temporary variables:
double temp = length[index];
...
Object widthObj = (int)width.get(index);
Since you will only reference them once. Reference them directly instead:
area[index] = length[index] * (int)width.get(index);
Secondly, your for loops are unneeded, and they are declared wrong. You're trying to increment the index (and twice nonetheless) that was passed to the function which will cause problems. If you were to use nested for loops, you would declare a new iterator variable for each of them:
for (int i = 0; i < something; i++) {
for (int j = 0; j < somethingElse; j++) {
doSomething();
}
}
However in this case you don't even need them.
In addition, you should not have created an Object when you wanted to cast an int:
Object widthObj = (int)width.get(index);
should have been
int width = (int)width.get(index);
However again, this line is unnecessary, and you shouldn't be casting to int this early.
Ultimately, all you need to do is the one line:
area[index] = (int)(length[index] * width.get(index));
Write a method called fillIntArray that takes two parameters – an integer array and an integer. The method must copy the integer parameter into each element of the integer array. The method does not have a return value.
Below is my current code, the test method applies random array lengths and variables for the integer, but I'm struggling with the concept of inputting data into an array. I understand pulling info but unsure of how to write the code to input it.
Can someone please indicate effective ways of writing this code?
public class Q8 {
void fillIntArray(int [] array, int x) {
for(int i = 0; i < x; ++i) {
array[i] = +x;
}
}
}
That code demonstrates knowledge of how to insert data into an array. But a few hints:
Your loop should go from 0 to array.length, not 0 to x.
It's a good idea to use x in the assignment statement, not +x. This makes the code more clear, and prevents bozos like me from thinking it will make the code not work.
Try following code. You should iterate over the whole array and put value x in each location.
public class Q8 {
void fillIntArray(int [] array, int x) {
for(int i = 0; i < array.length; ++i) {
array[i] = x;
}
}
}
The fasted way:
void fillIntArray(int[] array, int val) {
for (int i = 0, len = array.length; i < len; i++)
array[i] = val;
}
To speed up my image processing application, I'm trying to address values in an array starting in the middle, and using indices starting at 0.
For example, when I work with two arrays, I often have a situation like this:
public void work(int[] array1, int[] array2, int offset)
{
int len = array1.length;
for (int i = 0; i < len; i++)
array1[i] += array2[i + offset];
}
so I would like to create a new variable, array3 that directly maps into the middle of array2 (not a copy), so I can do this:
public void work(int[] array1, int[] array2, int offset)
{
int[] array3 = array2[offset]...;
int len = array1.length;
for (int i = 0; i < len; i++)
array1[i] += array3[i];
}
In effect, I want a Java equivalent to this c statement:
int *array3ptr = array2ptr + offset;
Note: I don't have any experience with JNI or anything, so if it boils down to using this, please provide working examples.
This is not possible to do by using pure Java arrays and the array[index] notation. In Java arrays can never overlap.
You could however wrap your arrays in IntBuffer. If you use a direct buffer (see allocateDirect) you should get real good performance.
A statement such as
int *array3ptr = array2ptr + offset;
would be written as
IntBuffer array3 = array2.slice().position(offset);
These
In java even integer arrays are objects on the heap. Hence the int[] array2 is actually directly refering to the integer array in the memory. no copy is created of the object (i.e array), duplicate is only of the reference to the array.
I don't have much experience with them, but I think you could be able to do that by wrapping your arrays (and sub-arrays) into IntBuffer instances.