How do you create a mathematical sequence in Java? - java

I want to declare integers, while the program is running.
I run the program, and then I give it via System.in.println an integer and repeat this as long as I want.
I want the program to give those integers a name of a certain type for, for example a(i) or a[i], dunno, (it should be handy) and then a(i) represents the the i'th integer I gave the program.
My idea is then that I can use those elements by their name just like, if I had declared them in the first place.
For example add two integers together.
For example I defined a method add+, which waits for 2 integer and then adds them. For example I write:
add
a(2)
a(47)
(then I would get here the result.)
I don't think implementing the add function is difficult. However I don't know, how to let the program count the number of inputs or how to let it declare and use variables.

First: Welcome to programming java; it will be a long road.
Here are some hints:
Use a List<Integer> to hold the sequence of numbers entered by the user.
Actually instanciate a concreate List class, for example LinkedList<Integer>'. If you need to access the elements by index, use anArrayList`.\
Each time the user enters a number, create a new Integer and userList.add(newInteger);
Simple sample
List<Integer> userList = new LinkedList<Integer>();
for (index = 0; index < 9; ++index)
{
Integer newInteger = new Integer(index);
userList.add(newInteger);
}
for (Integer current : userList)
{
System.out.println(current);
}

Yeah, I am following the conversation.
I am just a bit frustrated, because I can't really write any interesting or practical java programs (yet), because my knowledge isn't that big yet.
First I tried to find out, if there was a way to add elements to array, because arrays seemed to me very useful, because each element of an array already has an address. I googled, and it seems that is not possible.
I might be able to use the idea with the list, but it seems to be that the length of the list has to have a limit and actually I wanted to avoid that.

Related

Count elements in array

I am trying to count an element in an array of objects.
long number = Stream.of(jobTitle).count();
System.out.println("There are " + number + " employees.");
What happens is that it will print out the message as many times as many employees have the same job title. Yet "number" stays always 1.
Any guiding would be much appreciated.
long number = Stream.of(jobTitle).count();
Counts the elements in a stream that contains one element.
It is not surprising that this operation always ends up with the exact same result.
Your code is equivalent to:
List<Whatever> titels = new ArrayList<>();
titels.put(oneEntry);
... print titels.size()
Long story short: that statement is nonsensical. What you probably meant was:
if (arbetstitel.equalsIgnoreCase(jobCount)){
g++;
or something alikw. Of course g is a rather bad name for a counter.
But the real answer here is: step back. Think what the problem is you intend to solve, and what the elements are you need to look at. The code you are showing here is simply not making (much) sense. I can't tell you how to fix it, because, as said: it is not clear what you try to achieve here.
A streamish way of counting:
long usersWithMatchingTitle = Arrays.stream(employees).filter(e -> e.getJobTitle().equalsIgnoreCase(jobTitleFromUser)).count();
Meaning: instead of manually iterating your array, you can turn the whole array into a stream, and then filter/count whatever you want to.
Please note: your code seems to only care about the first 30 elements in that array. If that is really what you want, you will need ...stream(employees).limit(30)...
You need to change the stream of command to define a proper Predicate for filter option.
Stream.of(employees).filter(e -> e.getJobTitle().equals(jobTitle)).count();

How can I add (+) an integer to an element in a 2-dimensional ArrayList?

I'm trying to add 1 to an integer in a 2-dimensional ArrayList.
I'm using the set() method with the element + 1 as the second argument, but the "+ 1" isn't working. When I retrieve the element, it defines it as an object, not an integer. How do I get around this?
Code:
ArrayList<ArrayList> inventoryList = new ArrayList(
Arrays.asList(new ArrayList<String>(), new ArrayList<Integer>()));
...
(inventoryList.get(1)).set(i, ((inventoryList.get(1)).get(i) + 1));
Error:
Main.java:47: error: bad operand types for binary operator '+'
(inventoryList.get(1)).set(i, ((inventoryList.get(1)).get(i) + 1));
^
My code is at this ideone page. This code is translated from python and I'm currently debugging it so don't worry about the other errors.
ArrayList<ArrayList> inventoryList = ...
You are using the raw variant of ArrayList for your inner lists, such an ArrayList indeed contains Objects instead of Integers. You shouldn't use those raw ArrayLists and instead use generic ones:
What is a raw type and why shouldn't we use it?
Looking at your code a bit more, it seems that inventoryList is supposed to contain two lists, one that contains the items you have (as strings) and one that contains how many you have (as integers) where you can find how many you have of the item at index i in the first list by looking in the second list at that same index i.
If that is correct there are multiple ways to fix this, indeed, casting the Objects to Integers works, but then you are still using raw types, which you probably shouldn't. To fix this you should just not keep the ArrayList<String> and the ArrayList<Integer> in the same list. You could just have:
ArrayList<String> inventoryItems = ...
ArrayList<Integer> inventoryItemCounts = ...
separately (you don't need a list if it always contains exactly 2 items, a list of strings and a list of integers). However a cleaner solution would be, as was suggested in the comments by user2418306, to use a map
Map<String, Integer> inventory = ...
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html, that way each string (item) in your inventory has exactly one corresponding integer (number you have of that item) and you don't have to get that by using the "at the same index" trick.
Looking at you code a bit though, I would say that more is going wrong with the inventory. You print your inventory using:
for (int i = 0; i < inventoryList.size(); i++){
System.out.println((inventoryList.get(1)).get(i) + " : " + (inventoryList.get(0)).get(i));
}
and you iterate through it in that way in other places as well. However, if i'm not misunderstanding anything, inventoryList.size() is always going to be 2 (the inventoryList contains 2 lists, one of strings and one of integer). To get the number of distinct items (strings) in your inventory you'd have to do inventoryList.get(0).size() (or inventoryList.get(1).size() because that is going to be the same). However, things will get easier if you chose a better datatype for your inventory. I would look into the mentioned Map. Using that, you easily get the correct number using inventory.size().
You can solve your problem by casting to Integer
inventoryList.get(1).set(i, (Integer) inventoryList.get(1).get(i)+1);
Of course first take a look on comments below your question to see how to properly init your list, so you wont need explicit cast.
The way it is declared, your lists are list of Object. You need to cast the result from second get() with (Integer), like:
inventoryList.get(1).set(i, (Integer)inventoryList.get(1).get(i)+1);
Note: There are unneeded ().

select odd/even elements of array using recursion

Am working on some programming homework and am a bit lost. The project is to select the even/odd elements of a listarray and store in another array. It is not the even numbers in each element, but the elements themselves so if an array had values "1,2,5,7,9" and returned the even elements it would give "1, 5, 9". Also have to use recursion. Would anyone be able to give me a starting point or some advice. Though about starting with 2 elements and taking 2nd element and then building up from that, but don't know how it would add on the 2nd pass
public static ArrayList<Integer> even(ArrayList<Integer> list)
ArrayList<Integer> evenlist = ListMethods.deepClone(tList);//make copy of list
if (evenlist.size()<=1) // The list is empty or has one element
{
// return null;// Return the list as is
}
if
(evenlist.size()==2)
{
//return right element
//call method again
//add to list
}
Psuedocode
int[] evens,odds;
function categorize(List<Integer> in,int idx)
if(idx>=in.length)
return
int cur = in[idx]
if(even), add to evens
else add to odds
categorize(in,idx+1)
This sounds similar to the homework I just completed, so if it is (And you're in my class!), I'll not tell you to use any terminology we haven't covered as I know it can be daunting trying to discover something new for practicals (beyond what we have to do).
First, set your exit condition. As you've already said, you have to create a new ArrayList out of the existing one. You are going to remove items from the existing ArrayList, storing the integers that are at even (or odd) indices, until the list is empty.
So your exit condition is:
if (evenList is Empty)
return evenList;
Then, work your way through the steps. I would advise determining if the Array you start with has an even of odd number of steps, something like this:
if (evenList has Even Elements)
int holderForIntsAtEvenElements = last evenList EVEN element
Note we start at the last element, so when you are coming OUT of the recursive method, this will be the last one added to your new ArrayList, and thus it'll be in numerical order. You might find this post interesting to do this: What does this boolean return mean?
We then want to remove the last element from the list and recursively call the method again.
Finally, when we hit our exit condition and start to come out, we want to add the ints we've been storing to them, e.g.:
evenList.add(holderForIntsAtEvenElements);
return evenList;
That doesn't solve one problem, which is what to do with the very first element if the list does NOT have an even number of elements - however, I'll let you try and solve that!
That's a good mix of code and pseudo code and will hopefully help to get you on the right track.
You could use a simple for loop like this:
for (int i = 0; i < list.size(); i += 2) {
System.out.println(list.get(i));
}
If you have to use recursion, here's an outline of the steps you might take. (I won't tell you exactly what to do because you haven't tried anything and it is like homework.)
Take first element and store it
Remove (new) first element from list
Call self

How do you (get around) dynamically naming variables?

I'm not sure if I'm using the right nomenclature, so I'll try to make my question as specific as possible. That said, I imagine this problem comes up all the time, and there are probably several different ways to deal with it.
Let's say I have an array (vector) called main of 1000 random years between 1980 and 2000 and that I want to make 20 separate arrays (vectors) out of it. These arrays would be named array1980, array1981, etc., would also have length 1000 but would contain 1s where the index in the name was equal to the corresponding element in main and 0s elsewhere. In other words:
for(int i=0; i<1000; i++){
if(main[i]==1980){
array1980[i]=1;
} else {
array1980[i]=0;
}
Of course, I don't want to have to write twenty of these, so it'd be good if I could create new variable names inside a loop. The problem is that you can't generally assign variable names to expressions with operators, e.g.,
String("array"+ j)=... # returns an error
I'm currently using Matlab the most, but I can also do a little in Java, c++ and python, and I'm trying to get an idea for how people go about solving this problem in general. Ideally, I'd like to be able to manipulate the individual variables (or sub-arrays) in some way that the year remains in the variable name (or array index) to reduce the chance for error and to make things easier to deal with in general.
I'd appreciate any help.
boolean main[][] = new boolean[1000][20];
for (int i=0; i < 1000; i++) {
array[i][main[i]-1980] = true;
}
In many cases a map will be a good solution, but here you could use a 2-dim array of booleans, since the size is known before (0-20) and continuous, and numerable.
Some languages will initialize an array of booleans to false for every element, so you would just need to set the values to true, to which main[i] points.
since main[i] returns numbers from 1980 to 2000, 1980-main[i] will return 1980-1980=0 to 2000-1980=20. To find your values, you have to add 1980 to the second index, of course.
The general solution to this is to not create variables with dynamic names, but to instead create a map. Exactly how that's done will vary by language.
For Java, it's worth looking at the map section of the Sun collections tutorial for a start.
Don Roby's answer is correct, but i would like to complete it.
You can use maps for this purpose, and it would look something like this:
Map<Integer,ArrayList<Integer>> yearMap = new HashMap<Integer,ArrayList<Integer>>();
yearMap.put(1980,new ArrayList<Integer>());
for (int i = 0; i < 1000; i++){
yearMap.get(1980).add(0);
}
yearMap.get(1980).set(999,1);
System.out.println(yearMap.get(1980).get(999));
But there is probably a better way to solve the problem that you have. You should not ask how to use X to solve Y, but how to solve Y.
So, what is it, that you are trying to solve?

Java: Sorting different types of arrays to one another

I need to sort an array based on the positions held in another array.
What I have works, but it is kinda slow, is there a faster/better way to implement this?
2 Parts:
Part1
int i = mArrayName.size();
int temp = 0;
for(int j=0;j<i;j++){
temp = mArrayPosition.get(j);
mArrayName.set(temp, mArrayNameOriginal.get(j));
}
In this part, mArrayPosition is the position I would like the mArrayName to be in.
Ex.
input:
mArrayName= (one, two, three)
mArrayPosition = (2,0,1)
output:
mArrayName= (three, one two)
Part 2
int k=0;
int j=0;
do{
if(mArrayName.get(k)!=mArrayNameOriginal.get(j)){
j++;
}else{
mArrayIdNewOrder.set(k, mArrayId.get(j));
k++;
j=0;
}
}while(k < mArrayName.size());
}
In this part, mArrayName is the reordered name array, mArrayNameOriginal is the original name array.
Ex.
mArrayName = (three, one, two)
mArrayNameOriginal = (one, two, three)
Now I want to compare these two arrays, find which entries are equal and relate that to a new array that has their rowId number in it.
Ex.
input:
mArrayId = (001,002,003)
output:
mArrayIdNewOrder = (003,001,002)
So then I will have mArrayIdNewOrder id's matching up with the correct names in mArrayName.
Like I said these methods work, but is there a faster/better way to do it? I tried looking at Arrays.sort and comparators but they only seem to sort alphabetically or numerically. I saw something like I can create my own rules inside the comparator but it would probably end up being similar to what I already have.
Sorry for the confusing question. I'll try to clear up any ambiguities if needed.
The best performance read I've found is Android's Designing For Performance doc. You are violating a couple of the "Android way" style of doing things that will help you.
You are using multiple internal getters inside each loop for what looks like a simple value. Redo this by accessing the fields directly.
For extra credit, post your performance comparison results! I'd love to see em!
You could use some form of tuple, some class to hold both id and name. You'll just to have a java.util.Comparator that compares it accordingly, both elements will move together and your code will be cleaner.
This data structure might be convenient for the rest of your program... if not, just take things off it again and you're done.
If your order indexes are compact, i.e. from index 0 to size - 1, then just use an array and create the updated list afterwards? About something like
MyArray[] array = new MyArray[size];
for(int j=0;j< size;j++) {
array[ mArrayPosition.get(j) ] = mArrayName.get(j);
}
// create ArrayList from array

Categories