I would like to count subsequently equal values in an int array and return an array with the count and another array with the value order.
E.g. i would like to transform:
int arr = {0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,0,0,0,1,1,1,2,2,2,2,0,0,0,0};
To:
int arr = {11,5,4,3,3,4,4}; // The count
int idx = {0,1,2,0,1,2,0}; // The order
Can you help me achieve this?
This should do the job:
int[] arr = {0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,0,0,0,1,1,1,2,2,2,2,0,0,0,0};
//First determine how many subsequently equal values there are
int countEquals = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i-1]) {
countEquals++;
}
}
//Then calculate the order and count
int[] count = new int[countEquals];
int[] order = new int[countEquals];
int index = 0;
Arrays.fill(count, 1);
for (int i = 1; i < arr.length; i++) {
if (arr[i] == arr[i-1]) {
count[index]++;
} else {
order[index] = arr[i-1];
index++;
}
}
Related
Basically, I am trying to make an entirely new array of a new length that contains only the even ints in an array of integers.
However, I am getting an index out of bounds error. Can you help me find what I did wrong?
import java.util.Arrays;
public class findevens {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[]{4,8,19,3,5,6})));
}
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
//add even ints to new array
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[i] += arr[i];
}
}
return result;
}
}
You should use a new variable to keep track of the current result index (let's say, j):
public static int[] evens(int[] arr) {
int length = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
// Access result with `j` and update its value
result[j++] = arr[i];
}
}
return result;
}
Also, you can you streams:
int[] array = {1, 3, 4, 5, 6};
int[] even = IntStream.of(array).filter(item -> item%2 == 0).toArray();
System.out.println(Arrays.toString(even));
You need a new index variable for the result array and your assignment is also wrong as instead of assigning you are adding the even number to the result array element.
int j = 0;
int[] result = new int[length];
// add even ints to new array
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0)
{
result[j++] = arr[i];
}
}
Problem is you are using i for the result array AND the original array. You should only increment the result array inside of the IF (when you find an even number) otherwise, you go out of bounds due to i (the original arr) being a larger size than the result array.
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
//add even ints to new array
int resultCount = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[resultCount] += arr[i];
resultCount++;
}
}
return result;
}
Simply when you want to assign a value to result[] you do it with the index in the array arr, 0, 1 and 5. You just have to declare an auxiliary int aux = 0; variable before second loop and increment according to arr[i] % 2 == 0 so true
result[i] += arr[i];
a
int aux = 0;
result[aux++] += arr[i];
Complete code
public class findevens {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[]{4,8,19,3,5,6})));
}
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
int aux = 0;
//add even ints to new array
for (int i = 0; i < arr.length; i++){
if (arr[i] % 2 == 0) {
result[aux++] += arr[i];
}
}
return result;
}
}
Since you don't really know how long the resultant array will be you can copy them to the front of the current array. Then use the final location as the count of values.
int[] input = {1,2,3,4,5,6,7,8,9};
int k = 0;
for(int i = 0; i < input.length; i++) {
if (input[i] % 2 == 0) {
input[k++] = input[i];
}
}
int[] evens = Arrays.copyOf(input, k);
System.out.println(Arrays.toString(evens));
Prints
[2, 4, 6, 8]
A simple way is to filter even numbers using the Stream API and return the result as an array.
Arrays.stream(arr)
.filter(n -> n % 2 == 0)
.toArray();
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[] { 4, 8, 19, 3, 5, 6 })));
}
static int[] evens(int[] arr) {
return Arrays.stream(arr).filter(n -> n % 2 == 0).toArray();
}
}
Output:
[4, 8, 6]
What went wrong with your code:
result.length is 3 and therefore in result[], the maximum index you can access is 2 (i.e. result.length -1) whereas your second loop counter goes up to 5 (i.e. arr.length - 1) and you are using the same counter to access elements in result[] resulting in ArrayIndexOutOfBoundsException.
If you want to do it in your own way, you need to use a separate counter for result[] e.g.
int[] result = new int[length];
//add even ints to new array
for (int i = 0, j = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[j++] = arr[i];
}
}
The contents of arr[] change somehow so when I try to print the contents of the returned array from the method it says null.
This method takes a text file path from the user and puts every individual word into an array and compares it with a dictionary array (book) and the ones that aren't in the dictionary are supposed to be returned in dif[].
int d = arr.length-compare(book, arr);
int l = 0;
int bi = 0;
String[] dif = new String[d];
if (d >= 1) {
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < book.length; a++) {
if (book[a].equalsIgnoreCase(arr[i])) {
//IF I TRY TO PRINT ARR[I] HERE IT HAS A VALUE
bi = 1;
}
}
if (bi != 1) {
dif[l] = arr[i];
//HERE ARR[I] IS NULL
System.out.println(arr[i]);
l = l + 1;
}
}
return dif;
}
else {
return null;}
}
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < book.length; a++) {
if (book[a].equalsIgnoreCase(arr[i])) {
//IF I TRY TO PRINT ARR[I] HERE IT HAS A VALUE
bi = 1;
}
}
if (bi != 1) {
dif[l] = arr[i];
//HERE ARR[I] IS NULL
System.out.println(arr[i]);
l = l + 1;
}
}
You never reset the value of bi, so as soon as there is one entry in arr that is equal to one entry in book all subsequent values in arr will be outputted which might include null.
public class Sort {
public static void main(String[] args) {
//fill the array with random numbers
int[] unsorted = new int[100];
for(int i = 0; i < 100; i++) {
unsorted[i] = (int) (Math.random() * 100);
}
System.out.println("Here are the unsorted numbers:");
for(int i = 0; i < 100; i++) {
System.out.print(unsorted[i] + " ");
}
System.out.println();
int[] sorted = new int[100];
for(int i = 0; i < 100; i++) {
int hi = -1;
int hiIndex = -1;
for(int j = 0; j < 100; j++) {
if(unsorted[j] > hi) {
hi = unsorted[j];
hiIndex = j;
}
}
sorted[i] = hi;
unsorted[hiIndex] = -1;
}
System.out.println("Here are the sorted numbers: ");
for(int i = 0; i < 100; i++) {
System.out.print(sorted[i] + " ");
}
System.out.println();
}
}
So this is in descending order but I want to reverse it.
I tried changing the if(unsorted[j] > hi) {
to a if(unsorted[j] < hi) {
[edit:changed greater than to less than, both were same]
Okay, you want the numbers to be in ascending order. So for descending, you assume that compared number would be -1 and all other number must be grater than this -1, now instead of -1 use the maximum value a number could be. Assign Integer.MAX_VALUE where you were assigning -1. So change your code like this:
int[] sorted = new int[100];
for(int i = 0; i < 100; i++) {
int hi = Integer.MAX_VALUE;
int hiIndex = i;
for(int j = 0; j < 100; j++) {
if(unsorted[j] < hi) {
hi = unsorted[j];
hiIndex = j;
}
}
sorted[i] = hi;
unsorted[hiIndex] = Integer.MAX_VALUE;
I need help with sorting Random numbers into a 2D array. I have to generate 50 random numbers into a column of the array, then sort the numbers in order (ascending or descending). This is what I have so far and am so lost. Please Help.
UPDATED VERSION
public static void main(String[] args)
{
int rows = 2;
int columns = 50;
int[][] anArray = new int[rows][columns];
Random rand = new Random();
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
int n = rand.nextInt(100);
anArray[i][j] = n;
}
}
int []temp;
for (int i=0;i<anArray.length;i++)
{
for (int j=0;j<anArray.length-i;j++ )
{
if (anArray[i][j]>anArray[i][j+1])
{
temp =anArray[j];
anArray[j+1]=anArray[j];
anArray[j+1]=temp;
}
}
}
for (int i = 0; i < anArray.length; i++)
{
for (int j=0;j<anArray.length-i;j++ )
{
System.out.println(anArray[i][j]);
}
}
}
}
You can sort 2D arrays on their initial element using a custom Comparator:
Arrays.sort(anArray, new Comparator<int[]>() {
public int compare(int[] lhs, int[] rhs) {
return lhs[0]-rhs[0];
}
});
First of all, you need nested for loops in order to properly insert the random numbers into the two dimensional array. I have also updated my response to show how the sorting should be done. Hope this helps!
EDITED TO SATISFY REQUIREMENTS MENTIONED IN COMMENT BELOW.
import java.util.Arrays;
import java.util.Random;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
int rows = 2;
int columns = 50;
int[][] anArray = new int[rows][columns];
Random rand = new Random();
//initialize the first row only
for (int j = 0; j < anArray[0].length; j++)
{
int n = rand.nextInt(100);
anArray[0][j] = n;
}
System.out.println("-----------Before the Sort----------------");
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
System.out.print(anArray[i][j] + ", "); //format any way you want
}
System.out.println(); //to make each row print on a new line.
}
anArray = mySort(anArray);
System.out.println("-----------After the Sort----------------");
for (int i = 0; i < anArray.length; i++)
{
for (int j = 0; j < anArray[0].length; j++)
{
System.out.print(anArray[i][j] + ", "); //format any way you want
}
System.out.println(); //to make each row print on a new line.
}
}
private static int[][] mySort(int[][] anArray) {
int [][] result = new int[anArray.length][anArray[0].length];
int thisRow[] = getRow(anArray, 0);
Arrays.sort(thisRow);
for(int j = 0; j < thisRow.length; j++){
result[0][j] = anArray[0][j];
result[1][j] = thisRow[j];
}
return result;
}
private static int[] getRow(int[][] anArray, int row) {
int thisRow[] = new int[anArray[row].length];
for(int j = 0; j < anArray[row].length; j++){
thisRow[j] = anArray[row][j];
}
return thisRow;
}
}
You can sort by considering the 2D array 1D. Let's consider a 3x4 array.
1st element's index is 0, 2nd is 1, 3rd is 2, 4th is 3, 5th is 4, etc.
General formula to convert from a 1D index to a 2D:
row_index = _1D_index % nRows;
col_index = _1D_index % nCols;
For example the 5th element has the 1D index of 4, to get the row: 4 % 3 = 1, to get the col, 4 % 4 = 0, so your element is at 1,0. What's the point of all this? Now you can just make a function
int GetAt(int index)
{
return array[index % nRows][index % nCols];
}
and something along the lines of:
void Swap(int index1, int index2)
{
int r1 = index1 % nRows;
int c1 = index1 % nCols;
int r2 = index2 % nRows;
int c2 = index2 % nCols;
int temp = array[r1][c1];
array[r1][c1] = array[r2][c2];
array[r2][c2] = temp;
}
And sort the array as if it was one dimensional :)
I am trying to extract specific index values from an array, and place them into a new array. The primary array values are as follows:
int a[] = {7, 8, 9, 9, 8, 7};
The call I am making to the method is as follows:
print(findAll (a,7));
print(findAll (a,2));
The method I am using is as follows:
public int[] findAll(int a[], int target)
{
int count = 0;
int i = 0;
int index = 0;
int spotIndex = 0;
for (i = 0; i < a.length; i++)
{
if (a[i] == target)
count = count + 1;
spotIndex = i;
}
int result[] = new int[count];
for (index = 0; index < count; index++)
{
result[index] = spotIndex;
index++;
}
return result;
}
The results should be:
{0, 5}
{}
My results are below; if I change the target argument I get the same results.
{5, 0}
{}
Thanks in advance....
Small advice:
for (index = 0; index < count; index++)
{
result[index] = spotIndex;
index++;
}
you index++ call double times. This is bad practice to use index in method scope, better is:
for (int index = 0; index < count; index++)
{
result[index] = spotIndex;
}
Notice that you put spotIndex (the same value) in all result elements.
Why you don't use List?
public Integer[] findAll(int a[], int target) {
List<Integer> result = new ArrayList<Integer>();
for (int i=0; i<a.length; i++) {
if (a[i] == target) {
result.add(i);
}
}
return result.toArray(new Integer[result.size()]);
}
spotIndex isn't serving the purpose you thought needed for.
for (i = 0; i < a.length; i++)
{
if (a[i] == target)
count = count + 1;
spotIndex = i; // spotIndex comes in for loop but not in if condition.
// and this gets modified at every step in loop.
// simply assigning value of i to it.
}
Instead the logic should be -
for (i = 0; i < a.length; i++)
{
if (a[i] == target)
count = count + 1;
}
count gives the number of times target is repeated. Now, create an array of size count to actually copy those element's index in to the array.
int result[] = new int[count];
int copyIndex = 0;
for (index = 0; index < a.length; index++)
{
if( a[index] == target )
{
result[copyIndex] = index ;
++copyIndex;
if( copyIndex == count )
return result ;
}
}
I don't see the use of this statement - spotIndex = i; in first loop.
Note: The logic assumes that search element( i.e., target ) is definitely present in the array. With slight modification though, we can return the indexes if element is present only.