This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Android (method for checking an arrays for repeated numbers?)
I've just asked a question and got a few answers and i was very happy to, but there were very complicated answers, I'm quite new to android so can some one maybe give me some example code or some think explained not the complicated. I've tried there code and tried to make sense of it but i cant.
here is the question....
could any one help me. i am making an app, and in the java, numbers are send to a int array and i need to check if any of the numbers in the array repeated and if there are to call a method or something like that. Is there a method to check this or something similar? or would i have to do it using loops and if statements, which i have tried but is getting a bit long and confusing. Any advice would be great, thanks.
int test[] = {0,0,0,0,0,0,0}; (The Array)
(A method to check if any of the arrays numbers are repeated)
First don't make double topic.
Second you are searching for a Java answer not related to Android.
I think that maybe it's better if you first learn java (or other language like).
I would store the items in a Set if you do not want them to repeat. If add returns false then you have a repeating number
Set uniqueItems = new HashSet();
for(int i=0;i<test.length;i++)
if(!uniqueItems.add(test[a]))
System.out.println("The item is already in the set");
First, sort the array. Then search through the array comparing each node to the node on either of it's sides. Or you could store the data in a Set which cannot have duplicates.
Arrays.asList(test).contains(valueYouWantCheck).
If you want to find out for each and every value in test array, Yes I think you need to loop the array.
Related
This question already has answers here:
Sort a parallel array using Arrays.sort()
(5 answers)
Closed 6 years ago.
I have the following problem:
I have two arrays of a different data type, e.g.
byte[] a = {2,5,3};
long[] b = {2,0,1};
And I want b to get sorted and the entries in a must be changed respectively, s.t. I get
byte[] a = {5,3,2};
long[] b = {0,1,2};
I've seen that most people do that with a Comparator but that doesn't seem to work with different data types. I am looking for an efficient solution as the array lengths will be very large. However, a has only two different entries 0 and 1 (but I still want to keep it as byte to have the option for more entries) and all pairs (0,x) are already sorted (that means if I only pick pairs where the first entry is a 0 then it is already sorted). The same holds also for pairs (1,x'), but the entries in b are not completely sorted. I hope my problem got clear. I am happy for any suggestions.
Thank you very much in advance!
Edit: Apparently this question: Sort a parallel array using Arrays.sort() is very similar. However I wasn't able to reproduce any working example. Does anyone have a full working example?
I would try to solve your problem if you tagged your question c, but in java your problem description shows, that you're missing a class.
public class MyClass implements Comparable {
private byte;
private long;
//getters setters
//compare method according to your requirements.
}
Then you'll have MyClass[] which you will be able to sort.
And in case you want to stick to your problem, simply implement a sort algorithm, sort one of your arrays and when only you perform a swap, swap elements in the second array too.
For a class assignment I have to compare different lists' performance with one another's using UUID.randomUUID().toString() to insert a few thousand random strings in a list and record how long it takes with the nanoTime() method. I just can't recall how to set the amount of calls to my add method for my list to a certain number, or how to do it with the UUID.randomUUID(), at least.
newbieList.add(UUID.randomUUID().toString());
is what I have, which just inserts one random string, of course.
I know this is a simple question probably but I couldn't find any answers Googling or here, so help would be appreciated! Thanks.
Just put it in a for loop. A for loop is used for repeating stuff when you know at the beginning how often you want to repeat.
See this answer to a related question for lots of examples for various for loops.
I am trying to convert a section of code from using an ArrayList of custom objects to a regular array.
Previous my definition was
ArrayList<Room> rooms = new ArrayList<Room>();
Which I have now changed to
Room[] rooms;
Previously I used the below line to add items to the array list
rooms.add(new Room(1,1,30,false,true,true,false));
But I am now struggling to find the way I should simply add individual items to the array throughout code.
I think you are best sticking with an arrayList here, but just to give you a bit more light on it.
To do what you are trying to do, you will have to keep a index integer which will just point to the current position in the array, then when you add you can increment this and add the new object into the next poisition.
When you get to the maximum size of your array, you will need to expand it.
You will find that there has been questions on expanding an array which have been asked already and you can find the answers here:
Expanding an Array?
If you can live with a fixed-size array, that gives you at least a slight chance of success. If not, you can't beat ArrayList and if your mission is to succeed without reimplementing it, then it is an impossible mission.
You should really give more insight into the exact rationale for rewriting your code like that, it would give us some chance to properly help you.
I can recommend:
Use Arraylist as Long you Need to insert Elements. Once th Array is final Convert to Array.
If you need to increase the size of the array when adding another element, you have to construct another array with the size of the old array +1.
Afterwards, you would copy the contents of the old array over to the new array (the bigger array).
This question already has answers here:
Java - IndexOutOfBoundsException: Index: 1, Size: 0
(1 answer)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
I've got a very annoying problem with some code throwing an IndexOutOfBoundsException and I really cannot understand why. The logcat points to the "addTimetableItem" of the following code which ill explain more on:
if(sortedFridayTimes.size()>0){
insertDay("Friday");
for(int i=1; i<sortedFridayTimes.size()+1;i++){
addTimetableItem(sortedFridayTimes.get(i));
}
}
"sortedFridayTimes" is an ArrayList containing my own "Timetable Entry" objects which I have sorted into order already. First the size is checked to see if there are any objects and if there is then "insertDay" runs which creates a new textview for a title and adds it to the layout (This works fine..).
Inside the for loop the idea is to then add all the objects from the arraylist into the layout. Now I know that the "addTimetableItem" code works as ive tested it already, but my problem is that i cant seem to get the last object out of the arraylist. If I declare the for loop to only run for
"i<sortedFridayTimes.size()"
then the program runs fine but I don't get the last entry in the arraylist which I know exists because I've debugged and watched my variables. On adding the "+1" as shown above I now get the IndexOutOfBoundsException and I really don't know why. As I've said, I've debugged and I know that an entry exists in the arraylist where I'm trying to point to, but it just crashes. I can provide more code if needs be, but does anyone have any ideas please?
You should accept #Tim's or #Graham's answer, this is just an addendum. They're correct about your size()+1 going past the end of the array.
If you're having difficulty using indexes to properly get everything out of the list, you can also try using a for-each loop (depending on the version of the Android SDK you're using). I'm assuming sortedFridayTimes is a list of class TimetableItem since you don't specify.
So this:
if(sortedFridayTimes.size()>0){
insertDay("Friday");
for(int i=1; i<sortedFridayTimes.size()+1;i++){
addTimetableItem(sortedFridayTimes.get(i));
}
}
Becomes this:
if(!sortedFridayTimes.isEmtpy()){
insertDay("Friday");
for(TimetimeItem item : sortedFridayTimes){
addTimetableItem(item);
}
}
A little cleaner if you don't actually need to use i anywhere.
i<sortedFridayTimes.size()+1
You are looping past the last element in the array. Why the +1?
If there are N elements in the array, then the elements are from indexes 0 through to N-1.
So it should be:
for(int i=0; i<sortedFridayTimes.size(); i++) {
The last loop in your for loop runs:
sortedFridayTimes.get(sortedFridayTimes.size())
This will always be out of bounds, because the elements are zero indexed.
For example, if the array size is "5", then you cannot access index "5", because the 5 elements in the array are 0,1,2,3,4.
I have an array that created 5 objects. Each object has two strings and a int. Lets call the int "number". How can i add up the "number's" of each object into a final number, assume that the numbers change so i cannot simply just put 5 + 3 etc.. For example
Question question[] = new Question[5];
public Constructor()
{
String1 = "null";
Sting2 = "null";
number = 0;
}
SO i have five objects that look like this, they all have a different value. Number refers to a score, So if the user does something right, the number will be added to a variable, i need to know how to add up the 5 variables when i execute the 5 objects in something like.
for (i=0; i < Question.length; i++)
{
object.dostuff
}
Many things have to happen first:
Initialize the array: seems you got that one covered.
Initialize objects within the array: Make sure every cell of your array actually contains a question instance (or to be more precise: a reference to a Question instance).
Iterate over the array: here your loop seems to go over the class (Question, with capital Q) but you need to iterate over the array (question with a small q). Piece of advice, since the variable question here represents an array of question it would make more sense if you make your name plural (questions) to help illustrate that this is an array. Basic rule is to make the name as explicit as possible, so questionArray would be an even better name. Past a certain point it's a question of taste. Rule of thumb is that if you have to look at the declaration of the variable then it's probably not named correctly.
access methods, properties etc of the objects: when iterating over the array you need to access the right index (questions[i]) then access the members of this object (questions[i].doStuff). If you aim for OOP (which I assume is the point here) then you may want to make the obvious operations as functions of your Question class. Then simply call this function with the proper parameter (questions[i].setNumber(i)). It all depends on what you need it to do.
Hope this helps (if this is a homework related question you should tag it as such, that would maximize your chance to get help here).
Don't use Question.length, use question.length
Add an accessor method and a method to increment the scores.
use map to extract the numbers from the list of tuples then use reduce to accumulatively sum the numbers.
list=[("1 this is sentence 1","1 this is sentence 2",1),("2 this is sentence 1","2
this is sentence 2",2),("3 this is sentence 1","3 this is sentence 2",3)]
numbers=map(lambda x: x[2],list)
result=reduce(lambda x,y: x+y,numbers)
print(result)
output:
6