How to convert a 1d array to 2d array?
Without writing any code for you...
- Think about how big your 2d array needs to be.
- Recognize that you'll need to loop over the contents of your source array to get each value into your destination array.
So it will look something like...
- Create a 2d array of appropriate size.
- Use a for loop to loop over your 1d array.
- Inside that for loop, you'll need to figure out where each value in the 1d array should go in the 2d array. Try using the mod function against your counter variable to "wrap around" the indices of the 2d array.
I'm being intentionally vague, seeing as this is homework. Try posting some code so we can see where you get stuck.
Convert a 1D array to a 2D array in numpy
You want to reshape
the array.
B = np.reshape(A, (-1, 2))
where -1
infers the size of the new dimension from the size of the input array.
Converting a 1D array to a 2D array
You're assigning the wrong value to arr[i][j]
:
for (int i = 0; i <arr.length ; i++) {
for (int j = 0; j <arr[j].length ; j++) {
arr[i][j] = array[i * arr[j].length + j];
}
}
Write a C program to convert 1D array to 2D array using pointers
in
void main()
{
int m, n, arr[max], mat[max][max];
int size = m*n;
you compute size while m and n are not yet (possibly) initialized, so the value of size is undefined with undefined behavior
In
void array_to_matrix(int **matrix, int *arr, int row, int col)
{
int i,j,k=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
matrix[i][j] = arr[k];
}
}
}
the signature of the function says matrix is an array of pointers to int, but this is not compatible with your main where you use a 2D array. To be compatible :
void array_to_matrix(int (*matrix)[max], int *arr, int row, int col)
and same for print_matrix :
void print_matrix(int (*matrix)[max], int row, int col)
or if you prefer :
void array_to_matrix(int matrix[][max], int *arr, int row, int col)
void print_matrix(int matrix[][max], int row, int col)
But :
Write a C program to convert 1D array to 2D array using pointers
"2D array using pointers" is an is an abuse of language and means a 1D array of pointer to int, there is no 2D array.
In your previous version you limited the dimensions to 100, you do not have a reason to do that, just allocate the arrays in the heap.
Note also k always values 0 in array_to_matrix, so you always use arr[0]
And :
void main()
is wrong, main returns an int
I also encourage you to always check the result of scanf to be sure a valid input was used, else you works with non initialized value with an undefined behavior. When you read the number of rows and columns check there are not less than 1
In print_array to separate the print value with a space will help to make the result readable
Finaly :
#include <stdio.h>
#include <stdlib.h>
void input_array (int *arr,int size);
void print_array (int *arr, int size);
void array_to_matrix(int ** matrix, int *arr, int row, int col);
void print_matrix(int ** matrix, int row, int col);
int main()
{
int m, n, * arr, ** mat;
int size, i;
printf("Enter the number of rows(m):");
if ((scanf("%d",&m) != 1) || (m < 1)) {
puts("invalid value for rows");
return -1;
}
printf("Enter the number of columns(n):");
if ((scanf("%d",&n) != 1) || (n < 1)) {
puts("invalid value for columns");
return -1;
}
size = m*n;
if (((arr = malloc(size * sizeof(int))) == NULL) ||
((mat = malloc(m * sizeof(int))) == NULL)) {
puts("not enouh memory");
exit(-1);
}
for (i = 0; i < m; ++i) {
if ((mat[i] = malloc(n * sizeof(int))) == NULL) {
puts("not enouh memory");
exit(-1);
}
}
input_array (arr,size);
print_array (arr,size);
array_to_matrix(mat, arr, m, n);
print_matrix(mat, m, n);
/* free resources */
free(arr);
for (i = 0; i < m; ++i)
free(mat[i]);
free(mat);
return 0;
}
void input_array (int *arr,int size)
{
int i;
for(i=0;i<size;i++)
{
printf("Enter element a[%d]",i);
if (scanf("%d",&arr[i]) != 1) {
int c;
puts("invalid value, redo");
/* flush invalid value up to the end of line */
while ((c = getchar()) != '\n') {
if (c == EOF) {
puts("EOF, abort");
exit(-1);
}
}
i -= 1;
}
}
}
void print_array (int *arr, int size)
{
int i;
printf("\n 1D array is as follows : \n");
for(i=0;i<size;i++)
{
printf("%d ",arr[i]);
}
}
void array_to_matrix(int ** matrix, int *arr, int row, int col)
{
int i,j,k=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
matrix[i][j] = arr[k++];
}
}
}
void print_matrix(int ** matrix, int row, int col)
{
int i,j;
printf("\n 2D matrix is as follows : \n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d ",matrix[i][j]);
}
printf("\n");
}
}
Compilation and execution :
pi@raspberrypi:/tmp $ gcc -g -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
Enter the number of rows(m):2
Enter the number of columns(n):aze
invalid value for columns
pi@raspberrypi:/tmp $ ./a.out
Enter the number of rows(m):-1
invalid value for rows
pi@raspberrypi:/tmp $ ./a.out
Enter the number of rows(m):2
Enter the number of columns(n):3
Enter element a[0]1
Enter element a[1]aa
invalid value, redo
Enter element a[1]2
Enter element a[2]3
Enter element a[3]4
Enter element a[4]5
Enter element a[5]6
1D array is as follows :
1 2 3 4 5 6
2D matrix is as follows :
1 2 3
4 5 6
pi@raspberrypi:/tmp $
How to transform 1D Array to 2D Array with duplication
With numpy.tile
.
>>> a = np.arange(5)
>>> np.tile(a, (3, 1))
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Convert a 1D array to 2D array
You can use this code :
const arr = [1,2,3,4,5,6,7,8,9];
const newArr = [];
while(arr.length) newArr.push(arr.splice(0,3));
console.log(newArr);
Convert 1D array into 2D array JavaScript
var array1 = [15, 33, 21, 39, 24, 27, 19, 7, 18, 28, 30, 38];
var i, j, t;
var positionarray1 = 0;
var array2 = new Array(4);
for (t = 0; t < 4; t++) {
array2[t] = new Array(3);
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
array2[i][j] = array1[i*3+j]; //here was the error
}
positionarray1 = positionarray1 + 1; //I do this to know which value we are taking
}
console.log(array2);
I just solved it thanks for your comments. I actually used one apportation, but it was 3 instead of 2.
Transfering 1d array into 2d array without numpy
As far as I understand you need to convert a 1d array into a 2d array. You can do it either using a while loop, for loop or list comprehension.
using a while loop:
fixedarr = []
name = str(input("Name : "))
i=0
name_len = len(name) # name lenght
while i < name_len:
fixedarr.append([name[i:i+4]])
i += 4
using for loop:
for i in range(0, len(name), 4):
fixedarr.append(name[i:i+4])
using list comprehension:
fixedarr = [name[i:i+4] for i in range(0, len(name), 4)]
Related Topics
Java - Removing Duplicates in an Arraylist
How to Use Parameters, Request and Session Objects Present in Actioncontext
Find Place for Dedicated Application Folder
What Are the Pros and Cons of Performing Calculations in SQL VS. in Your Application
Keeping the Correct Style on Text Retrieval
Bitset to and from Integer/Long
Handling Java Crypto Exceptions
How to Use Mdc with Thread Pools
Java Swing; Two Classes, Where to Put If Statements and New Actionlisteners
How to Handle Precision Error with Float in Java
"The Public Type <<Classname>> Must Be Defined in Its Own File" Error in Eclipse
Why Is This Java Stream Operated Upon Twice
How to Test That No Exception Is Thrown
Increase Http Post Maxpostsize in Spring Boot
How to Make Lombok and Aspectj Work Together