How to concatenate array with multiple numbers - java

I need to print [1,2,3,4] when I get array like [1,1,2,2,3,3,4].
Other examples:
input=[1,1,1,2] output should be=[1,2]
input=[1,1,1,1] output should be=[1]
int count=1;
//This for counts only the different numbers of the array input.
for(int i=0; i<array.length-1;i++){
if(array[i+1]!=array[i]){
count++;
}
}
//New array only for the needed numbers.
Integer [] res = new Integer[count];
res[0] = array[0];
for(int i = 1;i<count;i++){
if(array[i]!=array[i+1]){
res[i]=array[i+1];
}
}
With input [1,1,2,2,3,3,4] I get [1, 2, null, 3].
Should be [1,2,3,4].

One problem is that you increment the loop's counter even when array[i]==array[i+1], which results in the output array having null values.
Another problem is that you don't iterate over all the elements of the input array in the second loop.
Both problems can be solved if you use two indices, one for the input array (the loop's variable) and another for the current position in the output array :
int count=1;
for(int i=0; i<array.length-1;i++){
if(array[i+1]!=array[i]){
count++;
}
}
Integer [] res = new Integer[count];
res[0] = array[0];
int resIndex = 1;
for(int i = 1; i < array.length - 1; i++){
if(array[i] != array[i+1]) {
res[resIndex] = array[i+1];
resIndex++;
}
}
EDIT :
As fabian suggested, changing the second loop to
for(int i = 1 ; i < array.length - 1 && resIndex < count; i++)
can make it slightly faster if the last unique number of the input array repeats multiple times.

Related

Changing 2D ArrayList code to 2D array code

I found this code online and it works well to permute through the given array and return all possible combinations of the numbers given. Does anyone know how to change this code to incorporate a 2D array instead?
public static ArrayList<ArrayList<Integer>> permute(int[] numbers) {
ArrayList<ArrayList<Integer>> permutations = new ArrayList<ArrayList<Integer>>();
permutations.add(new ArrayList<Integer>());
for ( int i = 0; i < numbers.length; i++ ) {
ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
for ( ArrayList<Integer> p : permutations ) {
for ( int j = 0, n = p.size() + 1; j < n; j++ ) {
ArrayList<Integer> temp = new ArrayList<Integer>(p);
temp.add(j, numbers[i]);
current.add(temp);
}
}
permutations = new ArrayList<ArrayList<Integer>>(current);
}
return permutations;
}
This is what I have attempted:
public static int[][] permute(int[] numbers){
int[][] permutations = new int[24][4];
permutations[0] = new int[4];
for ( int i = 0; i < numbers.length; i++ ) {
int[][] current = new int[24][4];
for ( int[] permutation : permutations ) {
for ( int j = 0; j < permutation.length; j++ ) {
permutation[j] = numbers[i];
int[] temp = new int[4];
current[i] = temp;
}
}
permutations = current;
}
return permutations;
}
However this returns all zeroes. I chose 24 and 4 because that is the size of the 2D array that I need.
Thanks
It’s not really that easy. The original code exploits the more dynamic behaviour of ArrayList, so a bit of hand coding will be necessary. There are many correct thoughts in your code. I tried to write an explanation of the issues I saw, but it became too long, so I decided to modify your code instead.
The original temp.add(j, numbers[i]); is the hardest part to do with arrays since it invloves pushing the elements to the right of position j one position to the right. In my version I create a temp array just once in the middle loop and shuffle one element at a time in the innermost loop.
public static int[][] permute(int[] numbers) {
// Follow the original here and create an array of just 1 array of length 0
int[][] permutations = new int[1][0];
for (int i = 0; i < numbers.length; i++) {
// insert numbers[i] into each possible position in each array already in permutations.
// create array with enough room: when before we had permutations.length arrays, we will now need:
int[][] current = new int[(permutations[0].length + 1) * permutations.length][];
int count = 0; // number of new permutations in current
for (int[] permutation : permutations) {
// insert numbers[i] into each of the permutation.length + 1 possible positions of permutation.
// to avoid too much shuffling, create a temp array
// and use it for all new permutations made from permutation.
int[] temp = Arrays.copyOf(permutation, permutation.length + 1);
for (int j = permutation.length; j > 0; j--) {
temp[j] = numbers[i];
// remember to make a copy of the temp array
current[count] = temp.clone();
count++;
// move element to make room for numbers[i] at next position to the left
temp[j] = temp[j - 1];
}
temp[0] = numbers[i];
current[count] = temp.clone();
count++;
}
assert count == current.length : "" + count + " != " + current.length;
permutations = current;
}
return permutations;
}
My trick with the temp array means I don’t get the permutations in the same order as in the origianl code. If this is a requirement, you may copy permutation into temp starting at index 1 and shuffle the opposite way in the loop. System.arraycopy() may do the initial copying.
The problem here is that you really need to implement properly the array version of the ArrayList.add(int,value) command. Which is to say you do an System.arraycopy() and push all the values after j, down one and then insert the value at j. You currently set the value. But, that overwrites the value of permutation[j], which should actually have been moved to permutations[j+1] already.
So where you do:
permutation[j] = numbers[i];
It should be:
System.arraycopy(permutation,j, permutations, j+1, permutations.length -j);
permutation[j] = numbers[i];
As the ArrayList.add(int,value) does that. You basically wrongly implemented it as .set().
Though personally I would scrap the code and go with something to dynamically make those values on the fly. A few more values and you're talking something prohibitive with regard to memory. It isn't hard to find the nth index of a permutation. Even without allocating any memory at all. (though you need a copy of the array if you're going to fiddle with such things without incurring oddities).
public static int[] permute(int[] values, long index) {
int[] returnvalues = Arrays.copyOf(values,values.length);
if (permutation(returnvalues, index)) return returnvalues;
else return null;
}
public static boolean permutation(int[] values, long index) {
return permutation(values, values.length, index);
}
private static boolean permutation(int[] values, int n, long index) {
if ((index == 0) || (n == 0)) return (index == 0);
int v = n-(int)(index % n);
int temp = values[n];
values[n] = values[v];
values[v] = temp;
return permutation(values,n-1,index/n);
}

What's the output of this code written in java?

int arr[ ] = new int[3];
for (int i = 0; i < 3; i++) {
arr[i] = i;
}
int res = arr[0] + arr[2];
System.out.println(res);
I'm a beginner in java, as you can see, and I'm not quite sure what's the output of this. Can someone answer and explain along the way?
//if you're using Eclipse, press ctrl-shift-f to "beautify" your code and make it easier to read
int arr[] = new int[3]; //create a new array containing 3 elements
for (int i = 0; i < 3; i++) {
arr[i] = i;//assign each successive value of i to an entry in the array
}
int res = arr[0] + arr[2];//add the 0th element value to the 2nd element value, save in res
System.out.println(res);//print res, which is == 0 + 2
basically what you are doing here is
int arr[ ] = new int[3];
for (int i = 0; i < 3; i++) {
arr[i] = i; // you are adding elements on array location
}
int res = arr[0] + arr[2];
System.out.println(res);
when first time loop execute i equals to 0, on location 0 you are assigning 0 there and for 1,2 the same process is being applied. On line int res = arr[0] + arr[2]; you are adding values of location 0 and 2 which are 0and 2 so the output is 2 when you add 0+2 = 2 in basic mathematics
On the first line, you are creating a new array of integers. The array has the elements arr[0], arr[1], and arr[2].
On the next three lines, is your for loop. As you have written in the loop, it will start from i=0 and will continue running while i < 3. Therefore, i will be 0, 1, and 2. In the loop itself, you are saying:
arr[0] = 0, arr[1] = 1, arr[2] = 2.
On the last two lines, you have two statements. The first expression creates an integer called res. Then you are saying res = arr[0] + arr[2]. But as we just saw, in the for loop you made arr[0] = 0 and arr[2] = 2. Therefore, res = 0 + 2 = 2.
On the last line you are just printing the result in the console.

How to print all the elements of an array that are inputed with all the initialized zeros removed?

public String toString(){
String allstr="";
for (int i=0 ; i<this.myArray.length; i++){
}
for (int i=capacity-1 ; i>=0 ; i--){
allstr=(this.myArray[i] + " ") + allstr ;
}
return allstr;
}
this code prints all the elements of my array including the 0 that are initialized. how can i exclude them? remember that my programm allows to input 0 in the array. So inputed zeros =/= initialized zeros. for example if an array has 5 3 2 1 0 0 -1 and the first zero is inputed by me how i can remove the second zero which is there because of the initialization of my array. Τhe code above is a part of a project. Just a method.
Okay, if your array is something like this:
int[] myArray = {0, 0, 0, 0, 0};
You can create boolean array. Let's say that true value is if it's inputed by user, and false if it' initialized.
boolean[] isChanged = {false, false, false, false, false};
Every time you change or input a new value in array you just need to mark this value as "changed"
isChanged[i] = true;
Than your method toString() will be
public String toString(){
String allstr="";
for (int i = 0; i < this.myArray.length; i++){
if (isChanged[i] == true)
allstr = allstr + (this.myArray[i] + " ");
}
return allstr;
}
Using an array of int, there is no way to tell the difference between the value you set to zero, and the one initialized to it. However, if you create, instead, an array of
Integers, you will be able to differentiate between 0 and null.
for instance, using Integer:
Integer[] list = new Integer[3];
list[0] = 1;
list[1] = 0;
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
output
1
0
null
compared to using int:
int[] list = new int[3];
list[0] = 1;
list[1] = 0;
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
output:
1
0
0
If all you have is an array of primitive numbers (like int), then there is simply no way to distinguish between zeroes placed during initialization and zeroes resulting from input. You could use something else to keep track, like a parallel array of boolean to keep track of whether the value was from input, or a list of elements that were input.
Another approach would be to use an array of Number objects, and use a special one to represent the initial zero, like BigInteger.ZERO. All others from input would be Integer or BigDecimal. By using different classes for initialized versus input, there is less chance for mixup. BTW, you should use the for-each syntax, and a StringBuilder if you're building a string iteratively.
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Number num : array) {
if (num != BigInteger.ZERO) {
if (first) {
first = false;
}
else {
buf.append(' ');
}
buf.append(num);
}
}
return buf.toString();
Instead of building the string manually, you might use any of the various equivalents for String.join that Java does not have, provided by different third-party libraries.
The best way of doing this is to use List<Integer> in place of static array.
Read here about ArrayList.
Sample code:
List<Integer> myArray = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
myArray.add((int) ((Math.random() * 5) + 1));
}
}
System.out.println(Arrays.toString(myArray.toArray(new Integer[] {})).replaceAll(
"[\\[,\\]]", ""));

Adding elements to last array position

Im trying to add an element to an array at its last position in Java, but I am not able to...
Or rather, I don't know how to. This is the code at the moment:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][coordinates[0].length] = values[i];
} else { //THIS IS ODD VALUE
coordinates[1][coordinates[1].length] = values[i];
}
}
EDITED VERSION:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
int x_pos = 0;
int y_post = 0;
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][x_pos] = values[i];
x_pos++;
} else { //THIS IS ODD VALUE
coordinates[1][y_pos] = values[i];
y_pos++;
}
}
values is being read from a CSV file. My code is I believe wrong, since it will try to add the values always at the maximum array size for coordinates[] in both cases.
How would I go around adding them at the last set position?
Thanks!
/e: Would the EDITED VERSION be correct?
Your original code has two problems:
it addresses the array badly, the las element in a Java array is at position length-1, and this would result in an ArrayOutOfBoundsException
even if you'd correct it by subtracting 1, you would always overwrite the last element only, as the length of a Java array is not related to how many elements it contains, but how many elements it was initialised to contain.
Instead of:
coordinates[0][coordinates[0].length] = values[i];
You could use:
coordinates[0][(int)Math.round(i/2.0)] = values[i];
(and of course, same with coordinates[1]...)
EDIT
This is ugly of course:
(int)Math.round(i/2.0)
but the solution I'd use is far less easy to understand:
i>>1
This is a right shift operator, exactly the kind of thing needed here, and is quicker than every other approach...
Conclusion: this is to be used in a live scenario:
Use
coordinates[0][i>>1] = values[i];
EDIT2
One learns new things every day...
This is just as good, maybe a bit slower.
coordinates[0][i/2] = values[i];
If you know you'll definitely have an even number of values you can do
for(int i = 0; i < values.length / 2; i++) {
coordinates[0][i] = values[2*i];
coordinates[1][i] = values[2*i + 1];
}
You have to store the last position somewhere. .length gives you the size of the array.
The position in the array will always be the half of i (since you put half of the elements in one array and the other half in the other).
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][ i / 2] = values[i];
} else { //THIS IS ODD VALUE
coordinates[1][ i / 2 + 1 ] = values[i];
}
}
The array index for java is from "0" to "array length - 1".
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
why not:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i+=2) {
coordinates[0][i/2] = values[i];
coordinates[1][i/2] = values[i+1];
}

How can I locate and print the index of a max value in an array?

For my project, I need to make a program that takes 10 numbers as input and displays the mode of these numbers. The program should use two arrays and a method that takes array of numbers as parameter and returns max value in array.
Basically, what I've done so far is used a second array to keep track of how many times a number appears. Looking at the initial array, you will see that the mode is 4. (Number that appears most). In the second array, the index 4 will have a value of 2, and thus 2 will be the maximum value in the second array. I need to locate this max value in my second array, and print the index. My output should be '4'.
My program is good up until I attempt to produce the '4', and I've tried a few different things but can't seem to get it to work properly.
Thank you for your time!
public class arrayProject {
public static void main(String[] args) {
int[] arraytwo = {0, 1, 2, 3, 4, 4, 6, 7, 8, 9};
projecttwo(arraytwo);
}
public static void projecttwo(int[]array){
/*Program that takes 10 numbers as input and displays the mode of these numbers. Program should use parallel
arrays and a method that takes array of numbers as parameter and returns max value in array*/
int modetracker[] = new int[10];
int max = 0; int number = 0;
for (int i = 0; i < array.length; i++){
modetracker[array[i]] += 1; //Add one to each index of modetracker where the element of array[i] appears.
}
int index = 0;
for (int i = 1; i < modetracker.length; i++){
int newnumber = modetracker[i];
if ((newnumber > modetracker[i-1]) == true){
index = i;
}
} System.out.println(+index);
}
}
Your mistake is in comparing if ((newnumber > modetracker[i-1]). You should check if the newnumber is bigger then the already found max. That is if ((newnumber > modetracker[maxIndex])
You should change your last rows to:
int maxIndex = 0;
for (int i = 1; i < modetracker.length; i++) {
int newnumber = modetracker[i];
if ((newnumber > modetracker[maxIndex])) {
maxIndex = i;
}
}
System.out.println(maxIndex);
You could change last part to:
int maxIndex = 0;
for (int i = 0; i < modetracker.length; i++) {
if (modetracker[i] > max) {
max = modetracker[i];
maxIndex = i;
}
}
System.out.println(maxIndex);

Categories

Resources