how would I increment the key [i] by 1 in this situation every time I run through this for loop with the way I currently have it set up all the elements only get mapped to 1. I am trying to find out how many times each number occurs. I have tried +1 in the empty spot after list.get(i) but again only maps each element to 1. thank you.
List<Integer> list = new ArrayList<Integer>();
HashMap<Integer,Integer> Mode = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
list.add(arr[i][j]);
}
}
System.out.println(list);
int count = 1;
for(int i = 0; i < list.size(); i ++) {
Mode.put(list.get(i), );
You need to specify a Key here.
for(int i = 0; i < list.size(); i++) {
int value=list.get(i);
if(!Mode.containsKey(value))
Mode.put(value,1);
else
Mode.put(value,Mode.get(value)+1);
}
According to your comment,
for(int i = 0; i < list.size(); i ++) {
if(Mode.containsKey(list.get(i)) ){
Integer count = Mode.get(list.get(i));
Mode.put(list.get(i), ++count);}
else
Mode.put(list.get(i), 1);
If you have the option, you may find it easier to use something like Multiset from Guava.
Multiset<Integer> seen = HashMultiset.create();
for (int[] row : arr) {
for (int elem : row) {
seen.add(elem); // none of that nasty dealing with the Map
}
}
// you can look up the count of an element with seen.count(elem)
E mostCommon = null;
int highestCount = 0;
for (Multiset.Entry<Integer> entry : seen.entrySet()) {
if (entry.getCount() > highestCount) {
mostCommon = entry.getElement();
highestCount = entry.getCount();
}
}
return mostCommon; // this is the most common element
Related
My code throws a run-time error, can anyone explain why? My solution envolves adding to an array the differences between j and i, and then find the minimum of the two, only to return it. But for some reason it gives me a timeout error. The question is question is this:
We define the distance between two array values as the number of indices between the two values. Given A find the minimum distance between any pair of equal elements in the array. If no such value exists, print -1 The minimum difference is calculated by the difference between index j and index i
static int minimumDistances(int[] a) {
int[] difference = new int[a.length];
int lowest = 0;
boolean pairFound = false;
for(int i = 0; i < a.length; i++) {
for(int j = i + 1; j < a.length; j++) {
for(int l = 0; l < difference.length; l++) {
if(a[i] == a[j]) {
difference[l] = j - i;
pairFound = true;
} else if(pairFound == false) {
lowest = -1;
}
}
}
}
if(pairFound == true) {
lowest = difference[0];
for(int i = 0; i < difference.length; i++) {
if(difference[i] < lowest) {
lowest = difference[i];
}
}
}
return lowest;
}
Give this a try and check to see if this works:
int[] difference = new int[a.length];
You are looping 3 times, that is 𝓞(n³) too slow. Try a different approach.
Here is my code using streams.
static int minimumDistances(int[] a) {
Map<Integer,List<Integer>> map = IntStream.range(0, a.length).boxed()
.collect(Collectors.groupingBy(i -> a[i]));
return map.entrySet().stream().filter(m -> m.getValue().size() > 1)
.map(m -> m.getValue().stream()
.reduce((acc,val)-> Math.abs(acc - val)).get())
.mapToInt(Integer::valueOf).min().orElse(-1);
}
I have a List called listTeams which comprises of Strings. I need to generate all unique combinations of these strings and store them in another ArrayList called lines. I've tried the following but the results are not desirable:
for(int i=0; i<listTeams.size();i++){
for(int j=1;j<listTeams.size();j++){
if (listTeams.get(j).equals(listTeams.get(i)))
continue;
for(int k=2;k<listTeams.size();k++){
if (listTeams.get(k).equals(listTeams.get(i)) || listTeams.get(k).equals(listTeams.get(j)))
continue;
String str = listTeams.get(i)+listTeams.get(j)+listTeams.get(k);
lines.put(str,new ArrayList<String>());
}
}
}
Here's the original list : {"A","B","C","D"}
What I am getting is
a_b_c
a_b_d
a_c_d
a_d_c
b_c_d
b_d_c
c_b_d
d_b_c
What I desire is:
a_b_c
a_b_d
a_c_d
b_c_d
for(int i=0; i<listTeams.size();i++){
for(int j=i+1;j<listTeams.size();j++){
for(int k=j+1;k<listTeams.size();k++){
String str = listTeams.get(i)+listTeams.get(j)+listTeams.get(k);
lines.put(str,new ArrayList<String>());
}
}
}
You need to modify your for loops like this:
for (int j = i;
and
for (int k = j;
So that only unique combinations appear
As #Berger said, the following code is working as you expect.
for (int i = 0; i < listTeams.size(); i++) {
for (int j = i+1; j < listTeams.size(); j++) {
if (listTeams.get(j).equals(listTeams.get(i)))
continue;
for (int k = j+1; k < listTeams.size(); k++) {
if (listTeams.get(k).equals(listTeams.get(i)) || listTeams.get(k).equals(listTeams.get(j)))
continue;
String str = listTeams.get(i) + listTeams.get(j) + listTeams.get(k);
lines.add(str);
}
}
}
I have 2 methods in my program, one to add ***** above and below the smallest int in the array and one to add %%%%% above and below the largest. The method for the largest is essentially the same as the other but for some reason isn't adding what is needed.
Here is the smallest element method:
public static ArrayList smallestElement() {
int smallest = array[0];
for (int i = 0; i < array.length; i++)
if (array[i] < smallest)
smallest = array[i];
String smallestString = String.valueOf(smallest);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
if (smallestString.equals(String.valueOf(array[i]))) {
list.add("*****");
list.add(Integer.toString(array[i]));
list.add("*****");
} else {
list.add(Integer.toString(array[i]));
}
}
return list;
}
Here is the method for the largest element:
public static ArrayList largestElement() {
int largest = array[0];
for (int i = 0; i < array.length; i++)
if (array[i] > largest)
largest = array[i];
String largestString = String.valueOf(largest);
for(int i = 0; i < array.length; i++) {
if (largestString.equals(String.valueOf(array[i]))) {
smallestElement().add("%%%%%");
smallestElement().add(Integer.toString(array[i]));
smallestElement().add("%%%%%");
} else {
smallestElement().add(Integer.toString(array[i]));
}
}
System.out.println(smallestElement());
return smallestElement();
}
}
If anyone knows why this isn't performing correctly, I would really appreciate the help
You are creating a new object every time you are executing the smallestElement function. Instead do something like,
ArrayList<String> list = smallestElement();
Then use this list object every time you are calling smallestElement() method
You have already created the list 3 times over by this line
smallestElement().add("%%%%%");
smallestElement().add(Integer.toString(array[i]));
smallestElement().add("%%%%%");
Create just 1 list and use it instead of calling the smallestelementelement() function multiple times
You are overcomplicating things here. There is no need to turn that minimum array value into a string right there (and to then do String comparisons later on). Btw: those string comparisons are also your problem: your code will definitely not work when your minimal value shows up several times in your array - because your code will put in those patterns for each match!
Instead, you could do something like:
int indexToUse = 0;
for (int i = 0; i < array.length; i++) { // please always use braces!
if (array[i] < array[indexToUse]) {
indexToUse = i;
}
}
List<String> valuesWithMarkerStrings = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (i == indexToUse -1 || i == indexToUse+1) {
valuesWithMarkerStrings.add("******");
} else {
valuesWithMarkerStrings.add(Integer.toString(array[i]);
}
}
(where my solution assumes that you want to have *** ... instead of array[i] for such rows ... )
I have an ArrayList of LinkedLists (an array of linked lists). The LinkedLists contains integers (Integer).
private List<LinkedList> buckets;
buckets = new ArrayList<LinkedList>();
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
buckets.add(temp);
}
I later want to remove the items from the linked list (in the order they were added) and add them to an array list. When I try this:
ArrayList<Integer> sorted = new ArrayList<Integer>(unsorted.size());
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
sorted.add(buckets.get(j).removeLast());
// sorted.add((Integer)buckets.get(j).removeLast());
}
}
I get an error saying:
add(java.lang.Integer) in ArrayList cannot be applied to (java.lang.Object)
But when I cast it to an Integer (the commented out line), the array is full of null values. Anyone see what I am doing wrong?
Here is where I am adding items to bucket:
for (int i = 0; i < unsorted.size(); i++) {
int digit = (unsorted.get(i) / position) % 10;
buckets.get(digit).add(unsorted.get(i));
}
Note that sorted is an ArrayList<Integer>. When I trace it in debug mode, I can see that the LinkedLists have Integer objects with the correct values.
Screenshot of buckets contents:
Working Example:
class Ideone {
private static List<LinkedList<Integer>> buckets;
public static void main (String[] args) throws Exception {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(6);
arr.add(8);
arr.add(1);
arr.add(3);
arr.add(9);
System.out.println(arr);
arr = sort(arr);
System.out.println(arr);
}
public static ArrayList<Integer> sort(ArrayList<Integer> unsorted) {
buckets = new ArrayList<LinkedList<Integer>>();
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
buckets.add(temp);
}
ArrayList<Integer> sorted = new ArrayList<Integer>(unsorted.size());
for (int i = 0; i < unsorted.size(); i++) {
int digit = unsorted.get(i) % 10;
buckets.get(digit).add(unsorted.get(i));
}
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
sorted.add(buckets.get(j).poll());
// sorted.add((Integer)buckets.get(j).removeLast());
}
}
return sorted;
}
}
You are using the raw form of LinkedList here:
private List<LinkedList> buckets;
Because of this, removeLast will return Object, not Integer. Try
private List<LinkedList<Integer>> buckets;
and
buckets = new ArrayList<LinkedList<Integer>>();
Casting the return of removeLast to Integer was the pre-generics way of getting this to work. However, you never inserted any items into each LinkedList, so removeLast returns null. If you want something returned, first insert something into each LinkedList that gets inserted into buckets.
Casting to Integer would still work, but supplying Integer as the type argument to LinkedList is preferred, especially since you are using generics by supplying LinkedList as the type parameter to List already.
In your nested loop,
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
// ***** here *****
sorted.add(buckets.get(j).poll());
}
}
You look to be polling the wrong List.
Try changing
sorted.add(buckets.get(j).poll());
to:
sorted.add(buckets.get(i).poll());
Perhaps a cleaner more intuitive way to code this would be something like:
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (int j = 0; j < innerList.size(); j++) {
sorted.add(innerList.poll());
}
}
Although this may not work if the innerList has multiple items. Why not instead remove items safely with an iterator?
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (Iterator<Integer> iterator = innerList.iterator(); iterator.hasNext();) {
sorted.add(iterator.next());
iterator.remove(); // this guy is optional
}
}
Either that or simply use get(j)
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (int j = 0; j < innerList.size(); j++) {
sorted.add(innerList.get(j));
}
}
Although this isn't efficient use of a LinkedList
The item that you inserted into the ArrayList "sorted" is the item you took from the link list LinkedList.
But you never actually add any item to it. You simply just created a LinkedList and added it to your bucket list.
You need to add something into the temp list.
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
// Add something to the temp LinkedList
buckets.add(temp);
}
Hi I am stuck in a particular case
I have two arrays, ArrayA[] with 50 items and another ArrayB[] with 10 items.
I want to convert the values of the ArrayB[] (10 items) to be 1 if they match a value in ArrayA[] and 0 if they don't.
I have been trying various techniques for past 5 hours- would be great to get some guidance in what I can do to get this!
Thanks for any help!
If I understand you well, this is what you are looking for:
public static void method(int[] arrayA, int[] arrayB)
{
boolean match = false;
label: for(int i = 0; i < arrayA.length; i++)
for(int j = 0; j < arrayB.length; j++)
if(arrayA[i] == arrayB[j])
{
match = true;
break label;
}
int k = (match?1:0);
for(int i = 0; i < arrayB.length; i++)
arrayB[i] = k;
}
If not, please elaborate!
List l = Arrays.asList(arrayA);
for (int i = 0; i < arrayB.length; i++)
arrayB[i] = l.contains(arrayB[i]) ? 1 : 0;