Can someone please explain in a little detail to me why this code prints 2?
import java.util.*;
public class TestCode2 {
public static void main(String[] args) {
int[][] array = {{1,2,3,4}, {5,6,7,8}};
System.out.println(m1(array)[0]);
// System.out.println(m2(array)[1]);
}
public static int[] m1(int[][] m) {
int[] result = new int[2];
result[0] = m.length;
result[1] = m[0].length;
return result;
}
}
int[][] array = {{1,2,3,4}, {5,6,7,8}};
=> int[][] array = {arrayOne, arrayTwo};
The length of array is 2 because it's just a bi-dimensionnal array which contains 2 sub arrays (which have both a length of 4).
So
array.length = 2;
array[0].length = length of arrayOne (i.e: length of {1,2,3,4}) = 4
array[1].length = length of arrayTwo (i.e: length of {5,6,7,8}) = 4
To summarize :
public static int[] m1(int[][] m) {
int[] result = new int[2];
result[0] = m.length; //m.length = 2
result[1] = m[0].length; //m[0].length = length of {1,2,3,4} = 4
return result; //{2,4}
}
Then you just print the first element of this array returned, i.e 2.
This is a 2d array so :
when you do like this :
int [][] array = {{1,2,3,4},{5,6,7,8}}
int a=array.length; \ i.e a=2
this is because the array treats the 2 sets as its element means {1,2,3,4} and {5,6,7,8} are considered as single element
sorry for wrong format as i am using mobile
m1() is taking 2D array as i/p & returning a (1D) array with first element as length of the i/p array, which - in this case is 2; Hence 2.
Related
I have to create a method that will remove at certain value from an array and create a new array without that certain value. For example, if my array is (0,2,3,5,3) and I want to remove 3, the new array should be (0,2,5). For some reason, it only works for the first two digits.
import java.util.Scanner;
public class removeDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//array of numbers
int array[] = new int[] {0,1,2,3,4,5};
//invokes method and prints result
//System.out.println(remove(3,array));
remove(3,array);
}
//method remove that removes selected number from array
public static int[] remove(int v, int[] in) {
//count variable counts how many non-target numbers
int count = 0;
//for loop that checks if value at certain index is not equal to "v", the target number for removal
for(int k = 0; k < in.length; k++) {
//checks if certain number at certain index of array is not equal to v, or in this case, 3
if(in[k] != v) {
//counter
count++;
}
}
//new array that will stores values except "v"
int copy[] = new int[count];
//prints the length
System.out.println("array length: " + copy.length);
//for loop that checks if number not 3
for(int a = 1; a < in.length;) {
// sets number at certain index of main array into new array
if(in[a] != 3){
copy[a] = in[a];
a++;
System.out.println(copy[0]);
System.out.println(copy[1]);
System.out.println(copy[2]);
System.out.println(copy[3]);
}
else if(in[a] == 3) {
copy[a] = in[a+1];
}
}
//returns new array
return copy;
}
}
As said before, I need the new array to exclude the targeted number for removal.
You need two index variables for making the copy: one runs through the input array (a, as in the original code), and the other tracks your position in the output array (b, new variable). They can not be calculated from each other (they are the same at the beginning, but b can be significantly less than a at the end)
int b = 0;
for(int a = 0; a < in.length; a++) {
if(in[a] != v) {
copy[b] = in[a];
b++;
}
}
Using Java8 and it's streams feature you could do something like :
public static void main(String[] args) {
int[] array = {3236,47,34,34,73,46,3,64,473,4,4,346,4,63,644,4,6,4};
int[] newArray = removeAllOccurencesOf(array, 4);
System.out.println(Arrays.toString(newArray));
}
public static int[] removeAllOccurencesOf(int[] array, int numberToRemove)
{
//stream integers from array, filter the ones that correspond to number to remove, get what's left to new array
int[] newArray = IntStream.of(array).filter(i->i!=numberToRemove).toArray();
return newArray;
}
You can achieve the same result with some code like this:
// Add to params all inputs to remove from array
List<Integer> params = new ArrayList<>();
// Use Integer class instead of int datatype
Integer array[] = new Integer[] {0,1,2,3,4,3};
// Convert array to List class
List<Integer> list = new ArrayList<>(Arrays.asList(array));
// Remove all matches
list.removeAll(params);
I have an array of unknown length in java.
I want to remove 1 percent of the total elements of the array after sorting it.
How can I do that? If I pass an array and a length to a function.
public double deleteElements(double array[], int length) {
int trimmedLength = array.length-length;
for (int i = 0; i < trimmedLength; i++) {
}
}
I assume you mean something like :
import java.util.Arrays;
public class Test{
public static void main(String[] args){
double[] testArray = new double[]{0,1,2,3,4,5,6,7,8,9};
//implement sort, if needed
System.out.println(Arrays.toString( deleteElements(testArray, 5) ));
}
public static double[] deleteElements(double array[],int newLength){
//add check array != null
//add check length is <= array.length
double[] returnArray = new double[newLength];
for(int i=0;i<newLength;i++){
returnArray[i] = array[i];
}
return returnArray;
}
}
I made an assumption that the length you are passing in is the percent of elements you want to remove from the list.
This converts your array to a list, sorts it, and converts the remaining percentage back to an array which is returned.
public double[] deleteElements(double[] doubles, int length)
{
List<Double> elements = Arrays.stream(doubles).boxed()
.collect(Collectors.toList());
Collections.sort(elements);
int startElement = (int) (elements.size() / 100.0 * length);
List<Double> subList = elements.subList(startElement, elements.size());
return subList.stream().mapToDouble(d -> d).toArray();
}
My code is intended to take in an array of ints and return an array of ints with a length of twice the original array's length, minus 2.
The returned array should have values 1/3 and 2/3 between any given two values in the original array.
For example input array:
{400, 500, 600}
will return:
{400,433,466,500,533,566,600}
The code I have is as follows:
public static void main(String[] args){
System.out.println("Problem 9 tests");
int[] arr7={300, 400, 500};
System.out.println(highDef(arr7));
System.out.println(" ");
public static int[] highDef(int[] original) {
int[] newarr = new int[original.length*3-2];
newarr[0]=original[0];
int count=0;
while (count!=newarr.length) {
int increment=(original[count+1]-original[count])/3;
newarr[count+1]=original[count]+increment;
newarr[count+2]=original[count]+(count*increment);
count+=1;
}
return newarr;
Haven't looked good enough the first time :)
Here you go:
public static void main(String[] args) {
System.out.println("Problem 9 tests");
int[] arr7 = {300, 400, 500};
System.out.println(Arrays.toString(highDef(arr7)));
System.out.println(" ");
}
public static int[] highDef(int[] original) {
int[] newarr = new int[original.length * 3 - 2];
newarr[original.length * 3 - 3] = original[original.length-1];
for(int i=0; i<original.length-1; i++){
newarr[i*3] = original[i];
int increment = (original[i+1] - original[i])/3;
newarr[i*3+1] = original[i] + increment;
newarr[i*3+2] = original[i] + increment*2;
}
return newarr;
}
With array out of bound exceptions, try to think of the last case.
In your example:
original.length = 3
newarr.length = (original.length * 3) - 2 = 7
while (count!=newarr.length) // this means: while count does not equal to 7. Therefore *Count* value can go upto 6
// imagine the last case, count = 6
newarr[count+2]=original[count]+(count*increment); // the problem is here
// count(6) + 2 = 8, which is out of bounds
same issue with this line: int increment=(original[count+1]-original[count])/3;
count will go upto 6 but original[count+1] = original[7] which is out of bound as well
I'm trying to find out particular elements in my ArrayList (arrayOne). Each element should be an int[]. I've tried System.out.println(arrayOne), which compiles but gives a irregular and strange number "[[I#370968]".
I've also tried System.out.println(arrayOne[0]) but it won't compile and emits the error
Array required but java.util.ArrayList found.
Given is the following code, with {1,12,3,13,123,2} passed to eg:
import java.util.ArrayList;
public class arrayTest {
private ArrayList<int[]> arrayOne;
public arrayTest(int[] eg) {
int[] xy = new int[2];
arrayOne = new ArrayList<int[]>(eg.length);
for (int i = 0; i < eg.length; i++) {
int sv = String.valueOf(eg[i]).length();
if (sv == 1) {
xy[0] = 0;
xy[1] = eg[i];
arrayOne.add(xy);
}
else if (sv == 2) {
System.out.println("two digits");
// TODO add code to make xy[0] = the first
// digit of eg and xy[1] = the second digit
}
else {
System.out.println("too many digits");
// and throw error accordingly
}
System.out.println(arrayOne);
}
}
}
How do make sure and print out the int array at arrayOne[0]
Given the code above if (sv == 2) and i want to split each individual number into an int[] with [0] being the first digit and [1] being the second digit how would i get the int value of each individual digit.
Use Arrays.toString(yourArray); to print out arrays in human readable form.
First of all, the string [I#370968 is displayed because you are trying to print an int[], which is actually an object. Because this object does not override the object's toString() method, that method is derived from the Object class. The Object.toString() implementation, which prints the class name (in this case [I, because it is an int array), then an # sign, and then the hash code of the object.
Your ArrayList contains a number of int[]s. Because an ArrayList is not an array (the one with the square brackets, like int[]), you can't call an element on it as if it were an array. In short, you cannot call arrayOne[someDesiredIndex].
In order to get an element from the ArrayList, call get(int index) on it; it returns the desired int[]. As already pointed out by another answer, you can use Arrays.toString(int[]) to print it in a human readable form.
To answer your questions:
You can retrieve the first index (0) of the first array inside arrayOne with the following code: arrayOne.get(0)[0].
The following code should work:
private static int[] intToArray(int n) {
String str = String.valueOf(n);
int length = str.length();
int[] ints = new int[length];
for (int i = 0; i < length; i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
return ints;
}
Above method puts each digit into the next array position (it also works with digits greater than 99). With this method you can easily get each individual digit:
int[] digits = intToArray(47);
int a = digits[0]; // Will be 4
int b = digits[1]; // Will be 7
So this is the class rewritten:
public class Rewrite {
private ArrayList<int[]> arrayOne = new ArrayList<int[]>();
public Rewrite(int[] eg) {
for (int i = 0; i < eg.length; i++) {
int length = String.valueOf(eg[i]).length();
switch (length) {
case 1:
this.arrayOne.add(new int[] { 0, eg[i] });
break;
case 2:
this.arrayOne.add(intToArray(eg[i]));
break;
default:
throw new IllegalArgumentException("Number " + eg[i] + " has too many digits");
// Or display the error or something.
}
System.out.println(Arrays.toString(this.arrayOne.get(i)));
}
}
private static int[] intToArray(int n) {
String str = String.valueOf(n);
int length = str.length();
int[] ints = new int[length];
for (int i = 0; i < length; i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
return ints;
}
public static void main(String[] args) {
Rewrite r = new Rewrite(new int[] { 47, 53, 91, 8 });
}
i have integer a = 4 and array b 7,8,9,4,3,4,4,2,1
i have to write a method that removes int ALL a from array b
desired result 7,8,9,3,2,1
This is what I have so far,
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
boolean[] barray = new boolean [array3.length];
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
int[] array4 = new int [array3.length - counter];
int num = 0;
for (int j=0; j<array3.length; j++)
{
if(barray[j] == false)
{
array4[num] = array3[j];
num++;
}
}
return array4;
I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Utility.removeTwo(Utility.java:50)
at Utility.main(Utility.java:18)
Java Result: 1
Any help would be much appreciated!
The error stems from this for loop:
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
when you create int[] array4 = new int [array3.length - counter]; you are creating an array with size 0. You should only increment the counter if the item is the desired item to remove:
for (int k=0; k<array3.length; k++)
{
boolean b = (x == array3[k]);
barray[k] = b;
if(b) {
counter++;
}
}
To answer your question in the comment, the method should be called and can be checked like this:
public static void main(String[] args) {
int[] array3 = {0,1,3,2,3,0,3,1};
int x = 3;
int[] result = removeTwo(x, array3);
for (int n : result) {
System.out.print(""+ n + " ");
}
}
On this line:
int[] array4 = new int [array3.length - counter];
You create an array with size 0, as counter is equal to array3.length at this point.
This means that you cannot access any index in that array.
You are creating
int[] array4 = new int [array3.length - counter];// 0 length array.
you can't have 0th index there. At least length should 1 to have 0th index.
BTW my suggestion, it is better to use List. Then you can do this easy.
Really an Array is the wrong tool for the job, since quite apart from anything else you will end up with stray values at the end that you cannot remove. Just use an ArrayList and that provides a removeAll() method to do what you need. If you really need arrays you can even do:
List<Integer> list = new ArrayList(Arrays.asList(array))
list.removeAll(4);
array = list.toArray();
(Exact method names/parameters may need tweaking as that is all from memory).
the simplest way is to work with a second array where you put in the correct values
something likte that
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
int[] array4 = new int[array3.lenght];
for (int i = 0; i < array3.lenght; i ++) {
if(array3[i] == x){
array4[counter] = array3[i];
}
}
return array4;
}
anoterh way is to remove the x calue from the array3 and shift the values behind forward
The best way to remove element from array is to use List with Iterator. Try,
Integer[] array = {7, 8, 9, 4, 3, 4, 4, 2, 1};
List<Integer> list = new ArrayList(Arrays.asList(array));
for(Iterator<Integer> it=list.iterator();it.hasNext();){
if(it.next()==4){
it.remove();
}
}