I want to be able to tell if a any number in an int[] appears 3 or more times? How can I do this?
Would be awesome to have method
boolean hasTriples(int[] numbers) {
//some code
}
Create a Map<Integer, Integer>, and let integer n map to the number of occurrences of n.
Loop through the array to populate the map, then loop through the keys in the map to check which keys map to a value >= 3.
Here's some code to get you started:
int[] arr = { 1, 3, 2, 3, 3, 4, 2, 2 };
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
// Count occurrencies
for (int i : arr) {
if (!counts.containsKey(i))
counts.put(i, 0);
counts.put(i, 1 + counts.get(i));
}
// Print how many times each number occurs in arr.
for (int i : counts.keySet())
System.out.printf("i: %d, count: %d%n", i, counts.get(i));
public boolean anyRepeatThreeTimes( int [] array ) {
Map<Integer, Integer > map = new HashMap<Integer, Integer>();
for ( int index = 0; index < array.length; index++ ) {
Integer total = map.get(array[ index ]);
int count;
if ( total == null ) {
count = 1;
}
else {
count = total + 1;
if ( count >= 3 ) {
return true;
}
}
map.put( array[ index ], count );
}
return false;
}
Here's what's going on:
You pass in the array of ints.
You set up a map of array values to a count of the value.
You walk the array. For each integer in the array:
a. you retrieve the current count for that array value
b. if no value exists, then start with a value of 1
c. if a value does exist in the map for the given value, add one to it
d. if the value retrieved from the map + 1 exceeds your limit of 3, then you have demonstrated that there is a value in the array that is repeated at least three times.
if you make it to the end of the loop without ever returning true, then return false instead, because no value is repeated 3 times.
Here is a way to do it without using any extra classes such as the Map class. It might be slower but hopefully is easier to understand.
public boolean hasTriples(int[] list) {
for (int i = 0; i < list.length; i++){
int duplicates = 0;
for (int j = i+1; j < list.length; j++){
if (list[i] == list[j]) {
duplicates++;
if (duplicates >= 3) return true;
}
}
}
return false;
}
Here is what this code is doing. The outer for loop is running through the list to make sure that every value is checked for duplicates. The inner loops runs through the remeinder of the list to check how many duplicate values there are. If three or more duplicates are found the function will return true and not process the rest of the list. If the outer for loop finishes without the method returning true false is returned as there must not be any three duplicates.
Hope this helps!
Related
So, I am trying to create 2 randomly generated arrays,(a, and b, each with 10 unique whole numbers from 0 to 20), and then creating 2 arrays with the info of the last two. One containing the numbers that appear in both a and b, and another with the numbers that are unique to a and to b. The arrays must be listed in a "a -> [1, 2, 3,...]" format. At the moment I only know how to generate the 2 arrays, and am currently at the Intersection part. The problem is, that I can create a array with the correct list of numbers, but it will have the same length of the other two, and the spaces where it shouldn't have anything, it will be filled with 0s when its supposed to create a smaller array with only the right numbers.
package tps.tp1.pack2Arrays;
public class P02ArraysExtractUniqsAndReps {
public static void main(String[] args) {
int nbr = 10;
int min = 0;
int max = 20;
generateArray(nbr, min, max);
System.out.println();
}
public static int[] generateArray(int nbr, int min, int max) {
int[] a = new int[nbr];
int[] b = new int[nbr];
int[] s = new int[nbr];
s[0] = 0;
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * (max - min));
b[i] = (int) (Math.random() * (max - min));
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
i--;
}
if (b[i] == b[j]) {
i--;
}
}
}
System.out.println("a - > " + Arrays.toString(a));
System.out.println("b - > " + Arrays.toString(b));
for (int k = 0; k < a.length; k++) {
for (int l = 0; l < b.length; l++) {
if (a[k] == b[l]) {
s[l] = b[l];
}else {
}
}
}
System.out.println("(a ∪ (b/(a ∩ b)) - > " + Arrays.toString(s));
return null;
}
public static boolean hasValue(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
}
Is there any way to create the array without the incorrect 0s? (I say incorrect because it is possible to have 0 in both a and b).
Any help/clarification is appreciated.
First, allocate an array large enough to hold the intersection. It needs to be no bigger that the smaller of the source arrays.
When you add a value to the intersection array, always add it starting at the beginning of the array. Use a counter to update the next position. This also allows the value 0 to be a valid value.
Then when finished. use Array.copyOf() to copy only the first part of the array to itself, thus removing the empty (unfilled 0 value) spaces. This works as follow assuming count is the index you have been using to add to the array: Assume count = 3
int[] inter = {1,2,3,0,0,0,0};
inter = Arrays.copyOf(inter, count);
System.out.println(Arrays.toString(inter);
prints
[1,2,3]
Here is an approach using a List
int[] b = {4,3,1,2,5,0,2};
int [] a = {3,5,2,3,7,8,2,0,9,10};
Add one of the arrays to the list.
List<Integer> list = new ArrayList<>();
for(int i : a) {
list.add(i);
}
Allocate the intersection array with count used as the next location. It doesn't matter which array's length you use.
int count = 0;
int [] intersection = new int[a.length];
Now simply iterate thru the other array.
if the list contains the value, add it to the intersection array.
then remove it from the list and increment count. NOTE - The removed value must be converted to an Integer object, otherwise, if a simple int value, it would be interpreted as an index and the value at that index would be removed and not the actual value itself (or an Exception might be thrown).
once finished the intersection array will have the values and probably unseen zeroes at the end.
for(int i = 0; i < b.length; i++) {
int val = b[i];
if (list.contains(val)) {
intersection[count++] = val;
list.remove(Integer.valueOf(val));
}
}
To shorten the array, use the copy method mentioned above.
intersection = Arrays.copyOf(intersection, count);
System.out.println(Arrays.toString(intersection));
prints
[3, 2, 5, 0, 2]
Note that it does not matter which array is which. If you reverse the arrays for a and b above, the same intersection will result, albeit in a different order.
The first thing I notice is that you are declaring your intersection array at the top of the method.
int[] s = new int[nbr];
You are declaring the same amount of space for the array regardless of the amount you actually use.
Method Arrays.toString(int []) will print any uninitialized slots in the array as "0"
There are several different approaches you can take here:
You can delay initializing the array until you have determined the size of the set you are dealing with.
You can transfer your content into another well sized array after figuring out your result set.
You could forego using Array.toString, and build the string up yourself.
I am trying to find a comparable value that is common to all rows in a 2D array.
For that value, I'd like to find the minimal (> 0) number of repetitions that exist in all rows.
For example, when working with a 2D array of String:
{
{A, C, B},
{A, A, B},
{C, D, A}
}
The only value that exists in all rows is "A". The minimal number of appearances in a row is 1, so the answer would be 1 A.
Here is my code: I am trying to search each column in a row for duplicates (or triplets, etc.), determine the count for a given row and compare it to the other rows to determine the row with the lowest quantity. Also, maybe there is a more elegant approach? For some reason it is not working (Collections is a 2d String array):
public class CommonElements {
ArrayList<String> commonCollections = new ArrayList<String>();
private int comparisons = 0;
int i, j, k;
int count, lowestCount;
String previousString = "";
int row[];
String current;
public Comparable[] findCommonElements(Comparable[][] collections) {
Arrays.sort(collections[0]);
row = new int[collections[0].length];
for (i = 0; i < collections[0].length; i++) { // first row column selection
current = collections[0][i].toString();
lowestCount = 1;
for (j = 0; j < collections.length; j++) { // row
count = 0;
for (k = 0; k < collections[0].length; k++) { // column
if (current.equals(collections[j][k].toString())) { // if contains same string as first row column selected
count++;
System.out.print(count + "\n");
}
}
if (lowestCount < count) {
lowestCount = count;
}
}
}
System.out.print(lowestCount);
return collections[0];
}
public int getComparisons() {
return comparisons;
}
}
Well, first you take collections[0][i].toString() when i is 0 so that evaluates to A, then program goes through all those loops and lowestCount is set to 1. Then your first for loop moves on to B and lowestCount is reseted without it being saved anywhere. You should save your lowestCount perhaps in array or a list, and at the end of the first for loop (after 2 other for loops) add the lowestCount to that array and you will have the lowest count of every letter. If you don't want to save it you can just System.out.println("Lowest count of letter: "+current+" is: "+lowestCount);. If you want to determine the row with the lowest count you can also save it in array (row with lowest count for every letter) and set it in that if that if statement passes (if(lowestCount < count)).
I'm not sure if I understood you correctly, but there is definitely a better approach to solving this problem.
You can do like this
int[][] arr = new int[5][2];
int count =0;
for(int[] i : arr){
count = count + i.length;
}
System.out.println(count);
i have some int values stored in ArrayList1 (imagine a table with one column). I need to create another ArrayList2 (second column), which will have values, that are the max values of a range in ArrayList1, for example last 3 values. for example:
1 null
2 null
1 2
3 3
2 3
1 3
So the secondt column - ArrayList2, will contain for each row max value of the last 3 corresponding rows in ArrayList1. (same as in xls, B3=MAX(A1:A3)...).
I can do it by creating for each row with a loop that goes and finds out max value, or i can loop and create subArrayList and use collections.max, but both these solutions require a loop for every row, which isn't very practical, isnt there a simpler way? something like arrayList.max(1,3) to get the number straight away?
You can do something like the code I show below. You iterate the first array, calculating the maximum and updating the second array accordingly. Note that you need an extra array to store the intervals.
private void m1(List<Integer> array1, List<Integer> array2, int range) {
Integer[] rangeArray = new Integer[range];
//Iterate first array
for(int i = 0; i < array1.size(); i++) {
Integer x = array1.get(i);
rangeArray[i%range] = x;
//Update second array
if(i < range - 1) {
array2.add(null);
}
else {
int max = Collections.max(Arrays.asList(rangeArray));
array2.add(max);
}
}
}
Using Collections.max
int startFrom = 2; // configurable number
List<Integer> intList = Arrays.asList(1,2,1,3,2,1,4);
List<Integer> sortedList = new ArrayList<>();
for (int i = 0; i < intList.size(); i++) {
if(i < startFrom){
sortedList.add(null);
continue;
}
ArrayList<Integer> list = new ArrayList<Integer>(intList.subList(i -startFrom, i+1));
sortedList.add(Collections.max(list));
}
System.out.println(sortedList);
Output is :[null, null, 2, 3, 3, 3, 4]
Ok. So your size of list to compare can vary , in that case build an array list out of the numbers to compare say List<?> list = Arrays.asList( numbersToCompare );
then Collections.max( list ), the list should contain objects that can be compared in other words needs to be comparable. ( If not write your own comparator )
I am trying to loop through an arraylist and gradually remove an element every 3 indices. Once it gets to the end of the arraylist I want to reset the index back to the beginning, and then loop through the arraylist again, again removing an element every 3 indices until there is only one element left in the arraylist.
The listOfWords is an array with a length of 3 that was previously filled.
int listIndex = 0;
do
{
// just to display contents of arraylist
System.out.println(listOfPlayers);
for(int wordIndex = 0; wordIndex < listOfWords.length; wordIndex++
{
System.out.print("Player");
System.out.print(listOfPlayers.get(wordIndex));
System.out.println("");
listIndex = wordIndex;
}
listOfPlayers.remove(listOfPlayers.get(listIndex));
}
while(listOfPlayers.size() > 1);
I have tried to implement for several hours yet I am still having trouble. Here's what happens to the elements of the arraylist:
1, 2, 3, 4
1, 2, 4
1, 2
Then it throws an 'index out of bounds error' exception when it checks for the third element (which no longer exists). Once it reaches the last element I want it to wrap around to the first element and continue through the array. I also want it to start where it left off and not from the beginning once it removes an element from the arraylist.
Maybe I have just missed the boat, but is this what you were after?
import java.util.ArrayList;
import java.util.Random;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random r = new Random();
//Populate array with ten random elements
for(int i = 0 ; i < 4; i++){
numbers.add(r.nextInt());
}
while(numbers.size() > 1){
for(int i = 0; i < numbers.size();i++){
if(i%3 == 0){//Every 3rd element should be true
numbers.remove(i);
}
}
}
}
}
You could move every third element to a temporary list then use List#removeAll(Collection) to remove the items when you finish each loop...until the master list was empty...
Lets back up and look at the problem algorithmically.
Start at the first item and start counting.
Go to the next item and increment your count. If there is no next item, go to the beginning.
If the count is '3', delete that item and reset count. (Or modulo.)
If there is one item left in the list, stop.
Lets write pseudocode:
function (takes a list)
remember what index in that list we're at
remember whether this is the item we want to delete.
loop until the list is size 1
increment the item we're looking at.
increment the delete count we're on
should we delete?
if so, delete!
reset delete count
are we at the end of the list?
if so, reset our index
Looking at it this way, it's fairly easy to translate this immediately into code:
public void doIt(List<String> arrayList) {
int index = 0;
int count = 0;
while(arrayList.size() != 1) {
index = index + 1;
count = count + 1; //increment count
String word = arrayList.get(index);//get next item, and do stuff with it
if (count == 3) {
//note that the [Java API][1] allows you to remove by index
arrayList.remove(index - 1);//otherwise you'll get an off-by-one error
count = 0; //reset count
}
if (index = arrayList.size()) {
index = 0; //reset index
}
}
}
So, you can see the trick is to think step by step what you're doing, and then slowly translate that into code. I think you may have been caught up on fixing your initial attempt: never be afraid to throw code out.
Try the following code. It keeps on removing every nth element in List until one element is left.
List<Integer> array = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
int nth = 3;
int step = nth - 1;
int benchmark = 0;
while (array.size() > 1) {
benchmark += step;
benchmark = benchmark > array.size() - 1 ? benchmark % array.size() : benchmark;
System.out.println(benchmark);
array.remove(array.get(benchmark));
System.out.println(array);
}
You could use a counter int k that you keep incrementing by three, like k += 3. However, before you use that counter as an index to kick out any array element, check if you already went beyond and if so, subtract the length of this array from your counter k. Also make sure, to break out of your loop once you find out the array has only one element left.
int k = -1;
int sz = list.length;
while (sz > 1)
{
k += 3;
if (k >= sz)
{
k -= sz;
}
list.remove(k);
sz --;
}
This examples shows that you already know right away how often you will evict an element, i.e. sz - 1 times.
By the way, sz % 3 has only three possible results, 0, 1, 2. With a piece of paper and a cup of coffee you can find out what the surviving element will be depending on that, without running any loop at all!
You could try using an iterator. It's late irl so don't expect too much.
public removeThirdIndex( listOfWords ) {
Iterator iterator = listOfWords.iterator
while( iterator.hasNext() ){
iterator.next();
iterator.next();
iterator.next();
iterator.remove();
}
}
#Test
public void tester(){
// JUnit test > main
List listOfWords = ... // Add a collection data structure with "words"
while( listOfWords.size() < 3 ) {
removeThirdIndex( listOfWords ); // collections are mutable ;(
}
assertTrue( listOfWords.size() < 3 );
}
I would simply set the removed to null and then skip nulls in the inner loop.
boolean continue;
do {
continue = false;
for( int i = 2; i < list.length; i += 3 ){
while( list.item(i++) == null && i < list.length );
Sout("Player " + list.item(--i) );
continue = true;
}
} while (continue);
I'd choose this over unjustified shuffling of the array.
(The i++ and --i might seem ugly and may be rewritten nicely.)
I am trying to solve this, but i don't know how...
Values[10] = {1,1,4,4,2,3,3,2,1,3}
to print:
{1,2,3,4} or {1,4,2,3} (not sorted, any order, but distinct)
I also need to count the number of times each number has occurred, both without sort, new arrays or boolean methods or other data structures, please advise as i am stuck.
Is there a simple method i can use to just print the unique values/ distinct values ?
It can be accomplished if your are willing to destroy your current array. and you assume that the array is either of type Integer (so nullable) or if not there is some bound such as all int are poistive so you can use -1.
for(int i = 0; i < values.length; i++){ //for entire array
Integer currVal = values[i]; // select current value
int count = 1; // and set count to 1
if(currVal != null){ // if value not seen
for( int j = i + 1; j < values.length; j++){ // for rest of array
if(values[j] == currVal){ // if same as current Value
values[j] = null; // mark as seen
count++; // and count it
}
}
System.out.print("Number : " + currVal + " Count : " + count + "\n");
//print information
}
// if seen skip.
}
In plain english, Go through the array in 2 loops, roughly O(n^2) time.
Go to index i. If index has not yet been seen (is not null) then go through the rest of array, mark any indexs with same value as seen (make it null) and increment count varable. At end of loop print value and count. If Index has be seen (is null) skip and go to next index. At end of both loops all values will be left null.
Input : Values[] = {1,1,4,4,2,3,3,2,1,3}
Output : Values[] = {1,null,4,null,2,3,null,null,null,null}
Number : 1 Count : 3
Number : 4 Count : 2
Number : 2 Count : 2
Number : 3 Count : 3
Edit: corrected my mistake in output, pointed out by commenters.
Another solution, without creating additional objects:
Arrays.sort(values);
for(int i = 0; i < values.length; i++) {
if (i == 0 || value[i] != value[i-1]) {
System.out.println(values[i]);
}
}
And the shortest solution I can think of:
Integer[] values = {1,1,4,4,2,3,3,2,1,3};
Set<Integer> set = new HashSet<Integer>();
set.addAll(Arrays.asList(values));
System.out.println(set);
Assuming the values are guaranteed to be integers, you could also do it by incrementing a check value, scan over the array, sum the number of that check value in the array, add it to an accumulator and loop while the accumulator < array.length.
Something like this (untested):
public void checkArray(int[] toCheck) {
int currentNum = 0;
int currentCount = 0;
int totalSeen = 0;
StringBuilder sb = new StringBuilder();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i=0; i<toCheck.length; i++) {
min = Math.min(toCheck[i], min);
max = Math.max(toCheck[i], max);
}
System.out.print("{ ");
for(currentNum = min; currentNum < max; currentNum++) {
for(int i=0; i<toCheck.length; i++) {
if(toCheck[i] == currentNum) currentCount++;
}
if(currentCount != 0) {
if(currentNum == min) System.out.print(currentCount + "(" +currentCount+ ")");
else System.out.print(", " + currentCount + " (" +currentCount+ ")");
}
totalSeen += currentCount;
currentCount = 0;
}
System.out.println(" }");
}
It should be noted that while this technically fulfills all your requirements, it will be far less efficient than gbtimmon's approach.
If your ints were {1,2,3,150000}, for example, it will needlessly spin over all the values between 4 and 149999.
Edit: added better limits from tbitof's suggestion.
Your question isn't quite clear to me, since it sounds like you want to do these things without creating any additional objects at all. But if it's just about not creating another array, you could use a Map<Integer, Integer>, where the key is the number from your original array, and the value is the count of times you've seen it. Then at the end you can look up the count for all numbers, and print out all the keys by using Map.keyset()
Edit: For example:
Map<Integer,Integer> counts = new HashMap<Integer, Integer>();
for( int i : values ) {
if( counts.containsKey(i) ) {
counts.put(i, counts.get(i) + 1);
} else {
counts.put(i, 1);
}
}
// get the set of unique keys
Set uniqueInts = counts.keyset();