Let's say I have an array in the length of n, and the only values that can appear in it are 0-9. I want to create a recursive function that returns the number of different values in the array.
For example, for the following array: int[] arr = {0,1,1,2,1,0,1} --> the function will return 3 because the only values appearing in this array are 0, 1 and 2.
The function receives an int array and returns int
something like this:
int numOfValues(int[] arr)
If you are using Java 8, you can do this with a simple one-liner:
private static int numOfValues(int[] arr) {
return (int) Arrays.stream(arr).distinct().count();
}
Arrays.stream(array) returns an IntStream consisting of the elements of the array. Then, distinct() returns an IntStream containing only the distinct elements of this stream. Finally, count() returns the number of elements in this stream.
Note that count() returns a long so we need to cast it to an int in your case.
If you really want a recursive solution, you may consider the following algorithm:
If the input array is of length 1 then the element is distinct so the answer is 1.
Otherwise, let's drop the first element and calculate the number of distinct elements on this new array (by a recursive call). Then, if the first element is contained in this new array, we do not count it again, otherwise we do and we add 1.
This should give you enough insight to implement this in code.
Try like this:
public int myFunc(int[] array) {
Set<Integer> set = new HashSet<Integer>(array.length);
for (int i : array) {
set.add(i);
}
return set.size();
}
i.e, add the elements of array inside Set and then you can return the size of Set.
public int f(int[] array) {
int[] counts = new int[10];
int distinct = 0;
for(int i = 0; i< array.length; i++) counts[array[i]]++;
for(int i = 0; i< counts.length; i++) if(counts[array[i]]!=0) distinct++;
return distinct;
}
You can even change the code to get the occurrences of each value.
You can try following code snippet,
Integer[] arr = {0,1,1,2,1,0,1};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
Output: [0, 1, 2]
As you asked for a recursive implementation, this is one bad way to do that. I say bad because recursion is not the best way to solve this problem. There are other easier way. You usually use recursion when you want to evaluate the next item based on the previously generated items from that function. Like Fibonacci series.
Ofcourse you will have to clone the array before you use this function otherwise your original array would be changed (call it using countDistinct(arr.clone(), 0);)
public static int countDistinct(int[] arr, final int index) {
boolean contains = false;
if (arr == null || index == arr.length) {
return 0;
} else if (arr.length == 1) {
return 1;
} else if (arr[index] != -1) {
contains = true;
for (int i = index + 1; i < arr.length; i++) {
if (arr[index] == arr[i]) {
arr[i] = -1;
}
}
}
return countDistinct(arr, index + 1) + (contains ? 1 : 0);
}
int numOfValues(int[] arr) {
boolean[] c = new boolean[10];
int count = 0;
for(int i =0; i < arr.length; i++) {
if(!c[arr[i]]) {
c[arr[i]] = true;
count++;
}
}
return count;
}
Related
Currently working on a method that takes a n*n matrix as input and returns an array consisting of all elements that are found in each sub-array. However, since I need it to also include duplicates etc, it's harder than I thought.
Googled the hell out of it, however, yet to find a solution which matches my criteria of repetition.
Currently I have this, which compares the element's of the first row with every other row and all their elements. If the counter gets to the length where it confirms that the element indeed is present in all rows, it adds it to the array. However, this has faults in it. First of all, since I create a set array in the beginning with the maximum possible length, it might return an array with non-needed 0's in it. And second, the duplicate part is not working correctly, struggling to implement a check there.
Examples of input/output that I need:
Input matrix: {{2,2,1,4},{4,1,2,2},{7,1,2,2},{2,10,2,1}}
Desired output: {1, 2, 2}
My output: {2, 2, 1, 0}
Input matrix: {{2,2,1,4},{4,1,3,2},{7,1,9,2},{2,10,2,1}}
Desired output: {1, 2}
My output: {2, 2, 1, 0}
public static int[] common_elements(int[][] matrix){
int[] final_array = new int[matrix.length];
for (int i = 0; i < matrix.length; i++) {
int counter = 0;
for (int j = 1; j < matrix.length; j++) {
for (int k = 0; k < matrix.length; k++) {
if(matrix.[0][i] == matrix.[j][k]){
counter += 1;
break;
}
}
}
if(counter == a.length-1){
final_array[i] = a[0][i];
}
}
return final_array;
}
EDIT: This is what I finally got together that fits my requirements and works flawlessly, with comments
public static int[] repetitiveInts(int[][] a){
//This is a method declared outside for sorting every row of the matrix ascending-ly before I do the element search.
for (int i = 0; i < a.length; i++) {
sorting(a[i]);
}
//Declaring a LinkedList in order to add elements on the go
LinkedList<Integer> final_list= new LinkedList<Integer>();
//Iterating through the matrix with every element of the first row, counting if it appears in every row besides the first one.
for (int i = 0; i < a.length; i++) {
int counter = 0;
for (int j = 1; j < a.length; j++) {
for (int k = 0; k < a.length; k++) {
//Checking if an element from the other rows match
if(a[0][i] == a[j][k]){
a[j][k] = a[0][i]-1; //If a match is found, the element is changed so finding duplicates is possible.
counter += 1;
break; //Breaking and checking the next row after one row checks out successfully.
}
}
}
//If the element is indeed in every row, adds it to the lit.
if(counter == a.length-1){
final_list.add(a[0][i]);
}
}
//Since I had to return a regular int[] array, converting the LinkedList into an array.
int[] final_realarray= new int[final_list.size()];
for (int i = 0; i < final_list.size(); i++) {
final_realarray[i] = final_list.get(i);
}
return final_realarray;
Grateful for help :)
The most efficient way to solve this problem is by creating a histogram of frequencies for each nested array in the matrix (i.e. determine the number of occurrences for every element in the nested array).
Every histogram will be represented by a Map<Integer, Integer> (array element as a key, its occurrences as a value). To generate a histogram only a single pass through the array is needed. In the solution below this logic resides inside the getFrequencies() method.
After creating all histograms we have to merge them. In terms of set theory we are looking for an intersection of keys in all histograms. I.e. we need only those keys that appear at least once in every histogram and a value for each key will be the smallest in all histograms for that key. This logic is placed in the getCommonElements().
In order to create a merged histogram, we can pick any of the histograms (in the code below the first histogram is used frequencies.get(0).keySet()) and iterate over its keys. Then in the nested loop, for every key, we need to find the minimum value associated with that in every histogram in a list (reminder: that will be the smallest number of occurrences for the key).
At the same time, while merging histograms we can also find the length of the resulting array by adding all the minimal frequencies together. That small optimization will allow to avoid doing the second iteration over the merged map.
The last step required is to populate the resulting array commonElements with keys from the merged histogram. Value of every key denotes how many times it has to be placed in the resulting array.
public static void main(String[] args) {
System.out.println(Arrays.toString(commonElements(new int[][]{{2,2,1,4},{4,1,2,2},{7,1,2,2},{2,10,2,1}})));
System.out.println(Arrays.toString(commonElements(new int[][]{{2,2,1,4},{4,1,3,2},{7,1,9,2},{2,10,2,1}})));
}
public static int[] commonElements(int[][] matrix){
List<Map<Integer, Integer>> frequencies = getFrequencies(matrix);
return getCommonElements(frequencies);
}
private static List<Map<Integer, Integer>> getFrequencies(int[][] matrix) {
List<Map<Integer, Integer>> frequencies = new ArrayList<>();
for (int[] arr: matrix) {
Map<Integer, Integer> hist = new HashMap<>(); // a histogram of frequencies for a particular array
for (int next: arr) {
// hist.merge(next, 1, Integer::sum); Java 8 alternative to if-else below
if (hist.containsKey(next)) {
hist.put(next, hist.get(next) + 1);
} else {
hist.put(next, 1);
}
}
frequencies.add(hist);
}
return frequencies;
}
private static int[] getCommonElements(List<Map<Integer, Integer>> frequencies) {
if (frequencies.isEmpty()) { // return an empty array in case if no common elements were found
return new int[0];
}
Map<Integer, Integer> intersection = new HashMap<>();
int length = 0;
for (Integer key: frequencies.get(0).keySet()) { //
int minCount = frequencies.get(0).get(key); // min number of occurrences of the key in all maps
for (Map<Integer, Integer> map: frequencies) {
int nextCount = map.getOrDefault(key, 0);
minCount = Math.min(nextCount, minCount); // getOrDefault is used because key might not be present
if (nextCount == 0) { // this key isn't present in one of the maps, no need to check others
break;
}
}
if (minCount > 0) {
intersection.put(key, minCount);
length += minCount;
}
}
int[] commonElements = new int[length];
int ind = 0;
for (int key: intersection.keySet()) {
int occurrences = intersection.get(key);
for (int i = 0; i < occurrences; i++) {
commonElements[ind] = key;
ind++;
}
}
return commonElements;
}
output
[1, 2, 2]
[1, 2]
Side note: don't violate the naming conventions, use camel-case for method and variable names.
Update
I've managed to implement a brute-force solution based on arrays and lists only as required.
The most important thing is that for this task you need two lists: one to store elements, another to store frequencies. Lists are bound together via indices. And these two lists are basically mimic a map, frankly saying a very inefficient one (but that's a requirement). Another possibility is to implement a class with two int fields that will represent the data for a common element, and then store the instances of this class in a single list. But in this case, the process of checking whether a particular element already exists in the list will be much more verbose.
The overall logic has some similarities with the solution above.
First, we need to pick a single array in the matrix (matrix[0]) and compare all its unique elements against the contents of all other arrays. Every element with non-zero frequency will be reflected in the list of elements and in the list of frequencies at the same index in both. And when the resulting array is being created the code relies on the corresponding indices in these lists.
public static int[] commonElements(int[][] matrix){
if (matrix.length == 0) { // case when matrix is empty - this condition is required because farther steps will lead to IndexOutOfBoundsException
return new int[0];
}
if (matrix.length == 1) { // a small optimization
return matrix[0];
}
// Map<Integer, Integer> frequencyByElement = new HashMap<>(); // to lists will be used instead of Map, because of specific requirement for this task
List<Integer> frequencies = new ArrayList<>(); // lists will be bind together by index
List<Integer> elements = new ArrayList<>();
int length = 0; // length of the resulting array
for (int i = 0; i < matrix[0].length; i++) {
if (elements.contains(matrix[0][i])) { // that means this element is a duplicate, no need to double-count it
continue;
}
int currentElement = matrix[0][i];
int minElementCount = matrix[0].length; // min number of occurrences - initialized to the max possible number of occurrences for the current array
// iterating over the all nested arrays in matrix
for (int row = 0; row < matrix.length; row++) {
int localCount = 0; // frequency
for (int col = 0; col < matrix[row].length; col++) {
if(matrix[row][col] == currentElement){
localCount++;
}
}
if (localCount == 0) { // element is absent in this array and therefore has to be discarded
minElementCount = 0;
break; // no need to iterate any farther, breaking the nested loop
}
minElementCount = Math.min(localCount, minElementCount); // adjusting the value the min count
}
// frequencyByElement.put(currentElement, minElementCount); // now we are sure that element is present in all nested arrays
frequencies.add(minElementCount);
elements.add(currentElement);
length += minElementCount; // incrementing length
}
return getFinalArray(frequencies, elements, length);
}
private static int[] getFinalArray(List<Integer> frequencies,
List<Integer> elements,
int length) {
int[] finalArray = new int[length];
int idx = 0; // array index
for (int i = 0; i < elements.size(); i++) {
int element = elements.get(i);
int elementCount = frequencies.get(i);
for (int j = 0; j < elementCount; j++) {
finalArray[idx] = element;
idx++;
}
}
return finalArray;
}
I am trying to sum all the int values of a 2D array. I named it array. my function is then called arraySum. If arraySum is null, I return 0. Otherwise, it goes through two for-loops, summing the values of these arrays.
int i = 0;
int j = 0;
static int sum = 0;
int[][] array = new int[i][j];
static int arraySum(int[][] array) {
if (array == null) { // test if the incoming param is null
return 0;
} else {
for (int i = 0; i < array.length; i++) { // length of the outer array
for (int j = 0; j < array[i].length; j++) { // length of the inner array
sum += array[i][j];
}
}
return sum; // moved out of the loop
}
}
my error message:
java.lang.AssertionError: Incorrect result: expected [-217085] but found [-308126]
Fixing the method signature is the first step.
Then you'll need to fix the null check.
Then your loops need to check the size of the inner and outer arrays.
Move the return statement.
Here's the fixed code:
static int arraySum(int[][] array) { // fix the signature
if (array == null) { // test if the incoming param is null
return 0;
} else {
int sum = 0; // you need this in the scope of the method - it will be returned at the end
for (int i = 0; i < array.length; i++) { // length of the outer array
for (int j = 0; j < array[i].length; j++) { // length of the inner array
sum += array[i][j];
}
}
return sum; // moved out of the loop
}
}
Edit: I've concentrated on just the method now - how you call it is up to you. Please note that the method will not affect any externally defined sum variable. It will return the sum and it's up to the caller to store that value somewhere.
Avoid using primitive for statement. See following:
static int arraySum(int[][] array) {
int sum = 0;
if (array == null) return 0;
for(int[] row: array){
for(int col : row) {
sum += col;
}
}
return sum;
}
Streams can do this too:
//Create 2D array
int[][] array = {{1,2,3},{4,5},{6}};
//Sum all elements of array
int sum = Stream.of(array).flatMapToInt(IntStream::of).sum();
System.out.println(sum);
Picking apart the summing code:
Stream.of(array)
Turns the 2D array of type int[][] into a Stream<int[]>. From here, we need to go one level deeper to process each child array in the 2D array as the stream only streams the first dimension.
So at this point we'll have a stream that contains:
an int[] array containing {1,2,3}
an int[] array containing {4,5}
an int[] array containing {6}
.flatMapToInt(IntStream::of)
So far we have a Stream of int[], still two-dimensional. Flat map flattens the structure into a single stream of ints.
flatMapToInt() expands each int[] element of the stream into one or more int values. IntStream.of() takes an array int[] and turns it into an int stream. Combining these two gives a single stream of int values.
After the flattening, we'll have an int stream of:
{1,2,3,4,5,6}
.sum()
Now we have an IntStream with all elements expanded out from the original 2D array, this simply gets the sum of all the values.
Now the disclaimer - if you are new to Java and learning about arrays, this might be a little too advanced. I'd recommend learning about nesting for-loops and iterating over arrays. But it's also useful to know when an API can do a lot of the work for you.
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);
}
I have an array I have created that is a length of 25 and and has randomly generated numbers in it 1 to 25. The array will pretty much always have duplicate numbers in it and all i want to do is display the numbers that occur only once in the array. The code I have so far seems to work as long as the numbers that are repeated only repeat an even number of times. My question is how do I make this work so I only get numbers that occur once added to my string.
I can not use hash or set or anything like that this is part of an assignment.
int count2 = 0;
for (int d = 0; d < copy.length-1; d++)
{
int num = copy[d];
if (num != copy[d+1])
{
s = s + "," + num;
}
else
{
d++;
}
}
Use a HashSet!
Construct two new HashSets, one for the elements appearing just once and one for the duplicates
Iterate through your array
For each value in the array check if it's already in the set of duplicates. If so, do nothing else and continue to the next iteration
Check if the value is already in the set of elements appearing just once
If it's not, add it. If it is, remove it and add it to a list of duplicates
Call hashSet.toArray() and then you will have an array of all the elements appearing only once
You can convert the array to a string or use it however you wish
This approach is very efficient as search, insert, and remove are all O(1) in a HashSet.
I would start by writing a separate method to count the number of occurrences of a value in the given array so you can count how many occurrences there are for each value using a For-Each Loop like
private static int count(int[] arr, int value) {
int count = 0;
for (int item : arr) {
if (item == value) {
count++;
}
}
return count;
}
Then you can leverage that like
public static String toUniqueString(int[] arr) {
StringBuilder sb = new StringBuilder();
for (int value : arr) {
if (count(arr, value) == 1) {
if (sb.length() != 0) {
sb.append(", ");
}
sb.append(value);
}
}
return sb.toString();
}
Finally, to test it
public static void main(String[] args) {
Random rand = new Random();
int[] arr = new int[25];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(arr.length) + 1;
}
System.out.println(toUniqueString(arr));
}
Write a method deleteElement which takes as input an int[] and an int target and deletes all occurrences of target from the array. The method should return the newint[]
. Question to consider:
Why is it that we have to return an array and can't simply change the input parameter array?
public class warm5{
public static void main(String[] args){
int[] array1= {1,2,2,3,4,5,2};
int target1 = 2;
deleteElement(array1,target1);
public static int[] deleteElement(int[] array, int target){
for(int i = 0, i<array.length, i++){
if(array1[i] == target){
}
}
}
}
}
Here is what i wrote, im not sure how to continue it to remove the 2's in the array.
please help!
You can't delete elements from an array, by definition they're of fixed size. What you can do is create a new array, copy all the elements from the old array except the ones that you intend to delete and return the new array. Or, use an ArrayList, which has operations that allow removing elements:
public E remove(int index)
public boolean remove(Object o)
public boolean removeAll(Collection<?> c)
protected void removeRange(int fromIndex, int toIndex)
First, iterate through your array and figure out how many of your target element are present.
Once you know that, you know the size of your new array. As Oscar mentions, you can't "remove" from an array, you just make a new array without the elements you don't want in it.
int targetCount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
targetCount++;
}
}
Now you know how many items will be in your new array: array.length-targetCount.
int[] newArray = new int[array.length-targetCount];
int newArrayIdx = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != target) {
newArray[newArrayIdx] = target;
newArrayIdx++;
}
}
Here we iterate through the old array and check each element to see if it's our target. If it's not, we add it to the new array. We have to keep track of our old array's index and our new array's index independently or we may risk trying to assign an index outside of the array bounds.
This is a common interview question. In the solution presented by Oscar you do not know what will be the size of the new array. So the solution does not work or is memory inefficient.
Trick is to loop over the array and at any time when you encounter an element equal to the given element you put that element towards the end of the array and swap it with the element that was there at the end position. By doing this you are collecting all occurrences of given element at the end of the array.
Here is a working logic
deleteElement(int[] given, int elem) {
int endIdx = array.length - 1;
for(int idx = 0; idx <= endIdx; idx++) {
if(given[idx] == elem) {
//swap idx with endIdx
int tmp = given[endIdx];
given[endIdx] = given[idx];
given[idx] = tmp;
endIdx--;
}
}
return Arrays.copyOfRange(given, 0, endIdx);
}