dynamical two dimension array according to input
Boost implements matrices (supporting mathematical operations) in its uBLAS library, and provides usage syntax like the following.
#include <boost/numeric/ublas/matrix.hpp>
int main(int argc, char* argv[])
{
unsigned int N = atoi(argv[1]);
boost::matrix<int> myMatrix(N, N);
for (unsigned i = 0; i < myMatrix.size1 (); ++i)
for (unsigned j = 0; j < myMatrix.size2 (); ++j)
myMatrix(i, j) = 3 * i + j;
return 0;
}
How to take inputs for 2 Dimensional dynamic array in Java?
You have 3 issues with your code:
- You never initialize the inner arrays. Do it with
arr[z] = new char[s.length()];
. - The way you define
arrOfStr
. You split the string by the blank sub-string. Instead just uses
usecharAt
like this:arr[z][y] = s.charAt(y);
- As the comments suggested, there is the issue with
nextInt
that does not take into account the\n
(enter) char.
So useint no=Integer.parseInt(in.nextLine());
, instead of usingnextInt
.
The final code should look like this:
for(z=0 ; z<no ; z++)
{
String s = in.nextLine();
arr[z] = new char[s.length()];
for( y =0 ; y<s.length() ; y++)
{
arr[z][y]=s.charAt(y);
}
}
Creating N-dimensional dynamical array based on user's input?
>>> rows = 486
>>> columns = 5
>>> A = [[None] * columns for x in xrange(rows)]
>>> len(A)
486
>>> len(A[0])
5
Dynamically Allocated input, and output 2-D Arrays in C++
I solved it:
#include <iostream>
//#include <vector>
using namespace std;
int main() {
int row, col;
cout << "Please enter the rows size: " << endl;
cin >> row;
cout << "Please enter the column size: " << endl;
cin >> col;
cout << "Please enter the numbers you want to put into a 2D array (it should
look like a matrix graph)." << endl;
cout << "Press enter after each number you input: " << endl;
int** map = new int*[row];
for (int i = 0; i < row; ++i)
map[i] = new int[col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cin >> map[i][j];
}
}
cout << endl;
//Print
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << map[i][j] << " ";
}
cout << endl;
}
cout << endl;
// DON'T FORGET TO FREE
for (int i = 0; i < row; ++i) {
delete[] map[i];
}
delete[] map;
system("pause");
return 0;
}
2D Dynamic Array Based on User Input
A better way to do your current program, using std::vector
, could be like this:
#include <iostream>
#include <vector>
#include <fstream>
int main()
{
std::ifstream dataFile("data.txt");
// Get the number of "rooms"
unsigned roomCount;
if (!(dataFile >> roomCount))
{
// TODO: Handle error
}
// Create the vector to contain the rooms
std::vector<std::vector<int>> rooms(roomCount);
for (unsigned currentRoom = 0; currentRoom < roomCount; ++currentRoom)
{
unsigned personCount;
if (dataFile >> personCount)
{
rooms[currentRoom].resize(personCount);
}
else
{
// TODO: Handle error
}
}
// Don't need the file anymore
dataFile.close();
// Print the data
std::cout << "Number of rooms: " << rooms.size() << '\n';
for (unsigned currentRoom = 0; currentRoom < rooms.size(); ++currentRoom)
{
std::cout << "Room #" << currentRoom + 1 << ": " << rooms[currentRoom].size() << " persons\n";
}
}
As you can see, it's now possible to get the "sizes" of the data after you're done with the reading from the file.
Reading two dimensional array with dynamic size of integers and output it vertically
You can do it by taking the input line by line, and then extracting the numbers delimited by space using strtok. See the code live here
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void input_matrix(int matrix[][100], int *rows, int *cols)
{
char *buffer;
size_t buffer_size = 200;
int row = 0;
int col = 0;
int ret;
buffer = (char *)malloc(sizeof(char) * buffer_size);
while((ret = getline(&buffer, &buffer_size, stdin)) > 0) {
char *split = NULL;
//printf("ret: %d\n", ret);
split = strtok(buffer, " ");
col = 0;
while (split) {
matrix[row][col] = strtol(split, NULL, 10);
col++;
split = strtok(NULL, " ");
}
row++;
}
free(buffer);
*rows = row;
*cols = col;
}
void print_matrix(int matrix[][100], int rows, int cols)
{
printf("Printing matrix: \n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
void print_transpose(int matrix[][100], int rows, int cols)
{
printf("Printing transpose: \n");
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main()
{
int m_input[100][100];
int rows;
int cols;
input_matrix(m_input, &rows, &cols);
printf("Input row: %d, col: %d\n", rows, cols);
print_matrix(m_input, rows, cols);
print_transpose(m_input, rows, cols);
return 0;
}
Changing the size of a two-dimensional array based on user input
Assuming you know how to POST the data from the html form back to your server, the php code which processes the request could look something like the following. It seems your question comes down to how to code a dynamically sized 2-dimensional array (matrix).
create a nested for loop. The inner for loop builds each row ( $this_row
) by appending items to it: $this_row[] = rand($min, $max);
, then each new row is appended to the $matrix
array.
Keep in mind the rand
function and $min
and $max
variables are not defined in the following example. You'll need to define them.
<?php
$num_cols = filter_input(INPUT_POST, 'columns', FILTER_VALIDATE_INT);
$num_rows = filter_input(INPUT_POST, 'rows', FILTER_VALIDATE_INT);
$matrix = array();
for ( $j = 0; $j < $num_rows; $j ++ ) {
$this_row = array()
for ( $k = 0; $k < $num_cols; $k ++ ) {
$this_row[] = rand($min, $max);
}
$matrix[] = $this_row;
}
//now you have your matrix
?>
Is it possible to dynamically build a multi-dimensional array in Java?
It is actually possible to do in java. (I'm a bit surprised I must say.)
Disclaimer; I never ever want to see this code anywhere else than as an answer to this question. I strongly encourage you to use List
s.
import java.lang.reflect.Array;
import java.util.*;
public class Test {
public static int[] tail(int[] arr) {
return Arrays.copyOfRange(arr, 1, arr.length);
}
public static void setValue(Object array, String value, int... indecies) {
if (indecies.length == 1)
((String[]) array)[indecies[0]] = value;
else
setValue(Array.get(array, indecies[0]), value, tail(indecies));
}
public static void fillWithSomeValues(Object array, String v, int... sizes) {
for (int i = 0; i < sizes[0]; i++)
if (sizes.length == 1)
((String[]) array)[i] = v + i;
else
fillWithSomeValues(Array.get(array, i), v + i, tail(sizes));
}
public static void main(String[] args) {
// Randomly choose number of dimensions (1, 2 or 3) at runtime.
Random r = new Random();
int dims = 1 + r.nextInt(3);
// Randomly choose array lengths (1, 2 or 3) at runtime.
int[] sizes = new int[dims];
for (int i = 0; i < sizes.length; i++)
sizes[i] = 1 + r.nextInt(3);
// Create array
System.out.println("Creating array with dimensions / sizes: " +
Arrays.toString(sizes).replaceAll(", ", "]["));
Object multiDimArray = Array.newInstance(String.class, sizes);
// Fill with some
fillWithSomeValues(multiDimArray, "pos ", sizes);
System.out.println(Arrays.deepToString((Object[]) multiDimArray));
}
}
Example Output:
Creating array with dimensions / sizes: [2][3][2]
[[[pos 000, pos 001], [pos 010, pos 011], [pos 020, pos 021]],
[[pos 100, pos 101], [pos 110, pos 111], [pos 120, pos 121]]]
Related Topics
Is There a Replacement For Unistd.H For Windows (Visual C)
How Does C++ Linking Work in Practice
C++11 Reverse Range-Based For-Loop
Why Vector≪Bool≫::Reference Doesn't Return Reference to Bool
Error Lnk2019: Unresolved External Symbol _Winmain@16 Referenced in Function _Tmaincrtstartup
Std::Cin.Getline( ) Vs. Std::Cin
How Std::Unordered_Map Is Implemented
Why Do We Need a Pure Virtual Destructor in C++
Checking Cin Input Stream Produces an Integer
What How to Use Instead of the Arrow Operator, '-≫'
Export All Symbols When Creating a Dll
Downcasting Using the 'Static_Cast' in C++
Executing Cv::Warpperspective For a Fake Deskewing on a Set of Cv::Point
Combining Several Static Libraries into One Using Cmake
How to Find If a Given Key Exists in a C++ Std::Map
What Is the Type of Lambda When Deduced With "Auto" in C++11