Do I keep many arrays in a vector?
I want like this...
[{1,2,3},{4,5,6},{7,8,9},{10,11,12}]
I am trying in this way and get error.
Vector< int[]> v=new Vector();
for(int i=0;i<n;i++){
int a[]=new int[3];
for(int j=0;j<3;j++){
a[j]=ob.nextInt();
}
v.add(a);
}
for(int i=0;i<n;i++){
System.out.println(v.get(i));
}
I know this way
Vector< Vector<Integer>> v=new Vector();
for(int i=0;i<n;i++){
Vector< Integer> v1=new Vector();
for(int j=0;j<3;j++){
v1.add(ob.nextInt());
}
v.add(v1);
}
for(int i=0;i<n;i++){
System.out.println(v.get(i));
}
But I want to keep those element (in a vector) using array .Can I?
If you really want use Vector, you can try something like this (I assume, your ob is Random object):
Random ob = new Random();
final int n = 3;
Vector<int[]> v = new Vector<>();
for (int i = 0; i < n; i++) {
int[] a = new int[n];
for (int j = 0; j < n; j++) {
a[j] = ob.nextInt();
}
v.add(a);
}
for (int i = 0; i < v.size(); i++) { //changed
for (int j = 0; j < v.get(i).length; j++) {
System.out.println(v.get(i)[j]);
}
}
you were probably surprised by the display of int [] on your console. In my case:
[I#7229724f
[I#4c873330
[I#119d7047
You can read more about it here.
But I recommend change Vector to List (you can read this for more details).
You can also use NOT primitive type with
Vector<Integer[]> v = new Vector();
But, what's the problem? Where is the error?
Scanner ob = new Scanner(System.in).useDelimiter("\\s");
int n = 2;
Vector<int[]> v = new Vector();
for (int i = 0; i < n; i++) {
int[] a = new int[3];
for (int j = 0; j < 3; j++) {
a[j] = ob.nextInt();
}
v.add(a);
}
for (int i = 0; i < n; i++) {
System.out.println(Arrays.toString(v.get(i))); //change output
}
Input: 1 2 3 4 5 6
Output:
[1, 2, 3]
[4, 5, 6]
Related
I am working on a merge sort algorithm. Below is what i have written so far. The problem is when I try and run it to see if it is working I get the index out of bounds error on the if statement I marked with a comment.
Why am I getting index out of bounds on the line I commented next to?
I know what the error means but am unable to decipher why its out of bounds.
public class MergeSort {
public static int mergeSort(int[] list1, int[] list2) {
int[] list3 = new int[list1.length + list2.length];
int smallest1 = list1[0];
int smallest2 = list2[0];
int position1 = 0;
int position2 = 0;
for (int i = 0; i<list1.length + list2.length; i++) {
for (int j =0; j<= list1.length; j++) {
if (list1[j] < smallest1) { //here index out of bouds
smallest1 = list1[j];
System.out.print(list1[j]+"smallest value");
position1 = j;
}
}
for (int l =0; l<= list2.length; l++) {
if (list2[l] < smallest2) {
smallest2 = list2[l];
System.out.print(list2[l]+"smallest value");
position2 = l;
}
}
if (smallest1< smallest2) {
list3[i] = smallest1;
} else if (smallest2< smallest1) {
list3[i] = smallest2;
}
}
//print the array
for (int l =0; l<= list2.length; l++) {
System.out.print("new array 3" + list3[l]);
}
return 1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list1 = {17, 22, 35, 42, 60};
int[] list2 = {9, 14, 66};
int[] list3;
mergeSort(list1, list2);
}
}
Indexes run from 0, this means when list1.length = 5 then the index can be 0 through 4
change
for (int j =0; j<= list1.length; j++)
to
for (int j =0; j < list1.length; j++)
This is because your for loop condition is <=. Try to use <
I am having difficulties for writing an algorithm that will create an array of arrays, from a single array of integers.
Say, I have an
int[] intArray = new int[] {1,2,3,4,5};
What I need from it is an array of an arrays that will look like this:
int[][] array = new int[][]{
{-1,2,3,4,5},
{1,-2,3,4,5},
{1,2,-3,4,5},
{1,2,3,-4,5},
{1,2,3,4,-5};
Thank you in advance!!
EDIT:
The following code works for the case if I want to have only one negative value. How about if I would like to have 2,3,4... negative values? Is there a way to make it more dynamic? For example, from {1,2,3,4,5}; to get: {-1,-2,3,4,5}, {-1,2,-3,4,5}, {-1,2,3,-4,5}, {-1,2,3,4,-5}, {1,-2,-3,4,5},{1,-2,3,-4,5}, {1,-2,3,4,-5}.... or for 3 negative values: {-1,-2,-3,4,5}, {-1,-2,3,-4,5}, {-1,-2,3,4,-5}, {1,-2,-3,-4,5}, {1,-2,-3,4,-5}, {1,2,-3,-4,-5}...etc I hope you get my point! Thanks again guys!!
You could try this:
int l = intArray.length;
int[][] newArray = new int[l][l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
newArray[i][j] = j == i ? intArray[j] * -1 : intArray[j];
}
}
newArray will have the values you are expecting.
how about
public class x
{
public static int[][] convert(int in[])
{
int s = in.length;
int out[][] = new int[s][s];
for (int i = 0; i < s; ++i) { // row loop
for (int j = 0; j < s; ++j) {
if (i == j)
out[i][j] = -in[j];
else
out[i][j] = in[i];
}
}
return out;
}
public static void print(int in[][])
{
for (int i = 0; i < in.length; ++i) {
String sep = "";
for (int j = 0; j < in[i].length; ++j) {
System.out.print(sep + in[i][j]);
sep = ", ";
}
System.out.println("");
}
}
public static void main(String argv[])
{
int in[] = { 1, 2, 3, 4, 5 };
int out[][];
out = convert(in);
print(out);
}
}
int[] intArray = new int[] {1,2,3,4,5};
int algoIntArray[][] = new int[intArray.length][intArray.length];
for(int i = 0; i < intArray.length; i++){
for (int j = 0; j < algoIntArray[i].length; j++){
if (i == j){
algoIntArray[i][j] = -intArray[j];
} else {
algoIntArray[i][j] = intArray[j];
}
}
}
This code will work for you!
I am trying to make the following code or something similar to work:
static String[][] arr = new String[4][4];
static int[][] arr2 = new int[4][4];
for(int i = 0; i < arr.length; i++){
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = "1";
arr2[i][j] = Integer.parseInt(arr[i][j]);
if(arr2[i][j] instanceof int){
System.out.println("Works");
}
}
}
Instead the IDE marks it red and gives an error "Inconvertible types; cannot cast int to int".
Can somebody help?
With the limited information you provided.
You will have to change every place where it says int to Integer because instanceof cannot check for primitive types. Your code would look like this:
static String[][] arr = new String[4][4];
static Integer[][] arr2 = new Integer[4][4];
for(int i = 0; i < arr.length; i++){
for (int j = 0; j < arr[0].length; j++) {
arr[i][j] = "1";
arr2[i][j] = Integer.parseInt(arr[i][j]);
if(arr2[i][j] instanceof Integer){
System.out.println("Works");
}
}
}
So I'm trying to make a program that counts the occurences of int in an array. what i tried to do is to make a method that lists the unique integers, then another method to compare the list items to the original array items.
public List listUnique(int[] arr){
Arrays.sort(arr);
List <Integer> temp = new ArrayList<>();
int currentInt = 0;
for (int i = 0; i < arr.length; i++){
if(arr[i] != currentInt){
temp.add(arr[i]);
currentInt = arr[i];
}
}
return temp;
}
public int[] countDupli(List unique, int[] arr){
int [] ret = new int[unique.size()];
Iterator <Integer> iterator = unique.iterator();
for (int l = 0; l < unique.size(); l++){
ret[l] = iterator.next().intValue();
}
int[] dupli = new int[ret.length];
for (int j = 0; j < ret.length; j++){
dupli[j] = 0;
}
for (int k = 0; k < ret.length; k++){
for (int i = 0; i < arr.length; i++){
if ( ret[k] == arr[i]){
dupli[k]+= 1;
}
}
k++;
}
return dupli;
}
It isn't doing what is intended to do tho. For example, an input of {1,2,...,1,2} 10 items of those, prints the correct unique items but only outputs the count of 1 but not 2. dupli = [5,0]. where did the algorithm go wrong? thanks
In your code try debugging or just print ret[] values and see if all unique values are present.
Other Suggestions:
List <Integer> temp = new ArrayList<>();
int currentInt = 0;
for (int i = 0; i < arr.length; i++){
if(arr[i] != currentInt){
temp.add(arr[i]);
currentInt = arr[i];
}
You can simply use HashSet, then you don't have to write above code to find unique values. HashSet does not store duplicate values.
Set<Integer> set = new HashSet<Integer>(Arrays.asList(arr));
Then you can use iterator and compare with your sorted array and increase count simultaneously.
You can skip the following for loop, as java initializes it to 0 by default.
int[] dupli = new int[ret.length];
for (int j = 0; j < ret.length; j++){
dupli[j] = 0;
}
Here is the code I have so far:
public static int mode(int[][] arr) {
ArrayList<Integer> list = new ArrayList<Integer>();
int temp = 0;
for(int i = 0; i < arr.length; i ++) {
for(int s = 0; s < arr.length; s ++) {
temp = arr[i][s];
I seem to be stuck at this point on how to get [i][s] into a single dimensional array. When I do a print(temp) all the elements of my 2D array print out one a time in order but cannot figure out how to get them into the 1D array. I am a novice :(
How to convert a 2D array into a 1D array?
The current 2D array I am working with is a 3x3. I am trying to find the mathematical mode of all the integers in the 2D array if that background is of any importance.
In Java 8 you can use object streams to map a matrix to vector.
Convert any-type & any-length object matrix to vector (array)
String[][] matrix = {
{"a", "b", "c"},
{"d", "e"},
{"f"},
{"g", "h", "i", "j"}
};
String[] array = Stream.of(matrix)
.flatMap(Stream::of)
.toArray(String[]::new);
If you are looking for int-specific way, I would go for:
int[][] matrix = {
{1, 5, 2, 3, 4},
{2, 4, 5, 2},
{1, 2, 3, 4, 5, 6},
{}
};
int[] array = Stream.of(matrix) //we start with a stream of objects Stream<int[]>
.flatMapToInt(IntStream::of) //we I'll map each int[] to IntStream
.toArray(); //we're now IntStream, just collect the ints to array.
You've almost got it right. Just a tiny change:
public static int mode(int[][] arr) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
// tiny change 1: proper dimensions
for (int j = 0; j < arr[i].length; j++) {
// tiny change 2: actually store the values
list.add(arr[i][j]);
}
}
// now you need to find a mode in the list.
// tiny change 3, if you definitely need an array
int[] vector = new int[list.size()];
for (int i = 0; i < vector.length; i++) {
vector[i] = list.get(i);
}
}
I'm not sure if you're trying to convert your 2D array into a 1D array (as your question states), or put the values from your 2D array into the ArrayList you have. I'll assume the first, but I'll quickly say all you'd need to do for the latter is call list.add(temp), although temp is actually unneeded in your current code.
If you're trying to have a 1D array, then the following code should suffice:
public static int mode(int[][] arr)
{
int[] oneDArray = new int[arr.length * arr.length];
for(int i = 0; i < arr.length; i ++)
{
for(int s = 0; s < arr.length; s ++)
{
oneDArray[(i * arr.length) + s] = arr[i][s];
}
}
}
change to:
for(int i = 0; i < arr.length; i ++) {
for(int s = 0; s < arr[i].length; s ++) {
temp = arr[i][s];
"How to convert a 2D array into a 1D array?"
String[][] my2Darr = .....(something)......
List<String> list = new ArrayList<>();
for(int i = 0; i < my2Darr.length; i++) {
list.addAll(Arrays.asList(my2Darr[i])); // java.util.Arrays
}
String[] my1Darr = new String[list.size()];
my1Darr = list.toArray(my1Darr);
I know its already been answered but here is my take. This function will take a 2d array input and return a 1d array output.
public int[] output(int[][] input){
int[] out = new int[input.length * input[0].length]
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
out[i + (j * input.length)] = input[i][j]
}
}
return out;
}
System.arraycopy should be faster than anything we can write. Also use the built-in java iterator on rows. Here is an example for double arrays. You should be able to use any type or class. If your rows are all the same length, then totalNumberElements = array2D.length * array2D[0].length;
static double[] doubleCopyToOneD(double[][] array2D, int totalNumberElements) {
double[] array1D = new double[totalNumberElements];
int pos = 0;
for (double[] row: array2D) {
System.arraycopy(row, 0, array1D, pos, row.length);
pos += row.length;
}
return array1D;
}
import java.util.*;
public class Main {
public static int A[][] = new int[3][3];
public static int B[] = new int[9];
public static void main(String[] args) {
int temo = 0,t;
Scanner s = new Scanner(System.in);
System.out.println("Enter No for Matrix A");
for (int row = 0; row < A.length; row++) {
for (int col = 0; col < A.length; col++) {
A[row][col] = s.nextInt();
}
System.out.print("\n");
}
for (int row = 0; row < A.length; row++) {
for (int col = 0; col < A.length; col++) {
t= A[row][col];
B[temo]= t;
temo++;
}
System.out.print("\n");
}
System.out.print("After Converted to one d \n");
for(int i =0;i<B.length;i++) {
System.out.print(" "+B[i]+" ");
}
}
}