I have an assignment that requires me to make ordered string list objects.
i currently have 2 ordered string lists, each with 7 string values in them.
im trying to create a method that merges list myList and yourList into a combined list combinedList.
here is what i have so far.
public boolean merge(OrderedStringList myList, OrderedStringList yourList){
int index;
String value;
for (index = 0;index < numUsed; index++){
value = myList.storage[index];
combinedList.insert(value);
}
for (index = 0;index < numUsed; index++){
value = yourList.storage[index];
combinedList.insert(value);
}
}
i declare the object combinedList in my main, and it doesnt recognize it in my orderedStringList.class
the insert function will insert strings into alphabetical order.
If you declared the combinedList inside your main function, it is accessible only inside the main function.
What you should do is create the combinedList inside the above function and return the result to the calling function i.e. your main function.
Where exactly is combinedList declared? Perhaps you should declare it outside outside your method so that all the methods can access it.
public class Merger {
private OrderedStringList combinedList; // This is a field
private int numUsed;
public static void main(){
new Merger().merge(new OrderedStringList(),new OrderedStringList());
}
public boolean merge(OrderedStringList myList, OrderedStringList yourList){
int index;
String value;
for (index = 0;index < numUsed; index++){
value = myList.storage[index];
combinedList.insert(value);
}
for (index = 0;index < numUsed; index++){
value = yourList.storage[index];
combinedList.insert(value);
}
return false;
}
}
class OrderedStringList {
public String[] storage;
public void insert(String value) {
// TODO Auto-generated method stub
}
}
Found out how to fix my problem. I just called the insert function based on the amount of strings that were in each list, and added them to the new combined list.
public boolean merge(OrderedStringList myList, OrderedStringList yourList) {
boolean result = false;
int index;
for (index = 0; index < myList.numUsed; index++) {
Insert(myList.storage[index]);
result = true;
}
for (index = 0; index < yourList.numUsed; index++) {
Insert(yourList.storage[index]);
result = true;
}
return result;
}
Related
I have a Model Class something like this:
public class Model {
String title, tag;
public Model() {
}
public Model(String title, String tag) {
this.title = title;
this.tag = tag;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
So I have ArrayList<Model> arr; according to my Model class
so, I want to get the Index of the tag for example -
//Let Suppose I have ArrayList Like this.
arr.add(new Model("SKYFALL","Action"));
arr.add(new Model("CASINO ROYALE","Thriller"));
//and so on.........
For example, I want the index of which have a Action tag.
I did something like this -
int index = arr.indexOf("Action");
but its index is always -1
To get Indexes of Object which contains provided tag. There can be multiple Model which has the same tag available.
public static void main(String[] args) {
ArrayList<Model> arr =new ArrayList<>();
arr.add(new Model("SKYFALL","Action"));
arr.add(new Model("CASINO ROYALE","Adventure"));
arr.add(new Model("CASINO ROYALE","Thriller"));
arr.add(new Model("CASINO ROYALE","Adventure"));
List<Integer> indexesByTag = getIndexesByTag(arr, "Adventure");;
System.out.println(indexesByTag);
// [1, 3]
}
Method to get Indexes of Objects which has provided tag available so need to return List<Integer>.
public static List<Integer> getIndexesByTag(ArrayList<Model> arr, String action){
IntStream intStream = IntStream.range(0, arr.size());
return intStream.boxed()
.map(index -> {
if(arr.get(index).getTag().equals(action)){
return index;
}
return -1;
})
.filter(index -> index!=-1)
.collect(Collectors.toList());
}
Other way without stream:
public static List<Integer> getIndexesByTag(ArrayList<Model> arr, String action){
List<Integer> indexes = new ArrayList<>();
for (int index = 0; index < arr.size(); index++) {
if(arr.get(index).getTag().equals(action)){
indexes.add(index);
}
}
return indexes;
}
You are finding the index wrong, your array list is of the array of object(Model class) while you find the index using a string.
You need to provide the object to find the index
Model actionModel = new Model("SKYFALL","Action")
arr.add(actionModel);
arr.add(new Model("CASINO ROYALE","Thriller"));
To find index
int index = arr.indexOf(actionModel);
Edit:
You can run a loop on the array list to find the index of an item
for (int i = 0; i < arr.size; i++) {
if (arr.get(i).getTag().eqauls("Action")){
index = i;
break;
}
}
If you check the indexOf method code from java library (which internally calls indexOfRange method), it return the index by making the equals method call on object.
int indexOfRange(Object o, int start, int end) {
Object[] es = elementData;
if (o == null) {
for (int i = start; i < end; i++) {
if (es[i] == null) {
return i;
}
}
} else {
for (int i = start; i < end; i++) {
if (o.equals(es[i])) {
return i;
}
}
}
return -1;
}
In your code equals will be called on Model class object with "Action" string. Which will definitely fail the equality check.
As the solution either override the equals method to return true if either tag or title matched. But I would say that won't be a good solution because equals method should follow some contracts.
So alternatively correct should be use of Streams API here.
arr.add(new Model("SKYFALL","Action"));
arr.add(new Model("CASINO ROYALE","Thriller"));
String toMatch = "Action";
OptionalInt indexOpt = IntStream.range(0, arr.size())
.filter(i -> toMatch.equals(arr.get(i).tag))
.findFirst();
System.out.println(indexOpt.orElse(-1)); // 0 Index
Edited:
If you are using older version of Java (before Java 8), you can use normal for loop as below:
int matchedIndex = -1;
for(int i = 0; i < arr.size() ; i++) {
if(arr.get(i).getTag().equals(toMatch)) {
matchedIndex = i;
break;
}
}
So here if matchedIndex value after iteration is -1, that means there was no match. Else you will get the matched index.
As an example we're combing through the permutations of the integer 123456789. Inspired by Heap's algorithm, we have the following
public static ArrayList<String> comb(char[] seq, int n, ArrayList<String> box){
if(n == 1){
if (isSquare(Integer.valueOf(String.valueOf(seq)))) {
box.add(String.valueOf(seq));
}
} else {
for(int i=0; i<n; i++){
comb(seq,n-1, box);
int j;
if ((n%2)==0) {
j = i;
} else {
j = 0;
}
char temp = seq[n-1];
seq[n-1] = seq[j];
seq[j] = temp;
}
}
return box;
}
In the present case we're interested whether a particular permutation is a square of an integer. Realised by
public static boolean isSquare(int n) {
if ((n%10)==2 || (n%10) ==3 || (n%10)==7 || (n%10) == 8) {
return false;
} else if ( (Math.sqrt(n)) % 1 ==0) {
return true;
} else {
return false;
}
}
However, to be able to use comb I must initialise an empty array outside of the method. What should I do to avoid inducing the need for global variable? I would still like to obtain a box with all solutions. I realise my error is in the parametrisation of comb .
Create a function that "wraps" the original recursive function, provides it with every parameter it needs and creates copies of objects if necessary:
Let's say you renamed your comb(...) function to combRecursive(...) for the sake of convenient naming.
public static ArrayList<String> comb(char[] seq, int n){
char[] seqCopy = Arrays.copyOf(seq, seq.length);
return combRecursive(seqCopy, n, new ArrayList());
}
I was attempting to write some code for a program in BlueJ (Java) that lists bags and adds and removes items from those bags, that sort of thing. Then I got stuck in the first class; I couldn't get to add an item to the bag properly as you can notice below in the addItem() method; it keeps adding String s to every null element in the array rather the first encountered. Any help would be tremendously appreciated.
Best wishes & many thanks,
Xenos
public class Bag1 {
private String[] store; // This is an array holding mutlitple strings.
public Bag1(int storageCapacity) {
store = new String[storageCapacity];
} // That was the primitive array constructor.
public boolean isFull() {
boolean full = true;
for(int i = 0; i < store.length; i++) {
if(store[i] == null) {
full = false;
}
}
return full;
} // The method above checks if the bag is full or not, and returns a boolean value on that basis.
public void add(String s) {
for(int i = store.length; i >= 0; i--) {
if(store[i] == null) {
store[i] = s;
}
}
}
}
You should exit the loop after finding the first empty spot :
public void add(String s)
{
for(int i=store.length-1; i>=0; i--) { // note the change in the starting index
if(store[i]==null) {
store[i] = s;
break;
}
}
}
I am trying to create a find method, that will check every entry in my PhoneDirectory, and return the position of the name that matches the name given in the parameter. This is what currently have:
private String find(String name) {
for (DirectoryEntry x : theDirectory) {
if (x.getName().equals(name)) {
return x.getName();
}
}
return null;
}
However I will be calling my find function from within other methods that don't necessarily want the name returned, but instead the number attached to the name, (each DirectoryEntry has a name and a telno).
Any help regarding how to return the position of the array instead of just the matching name, would be much appreciated.
you can take a couter to count the postion
private int find(String name) {
int i = 0;
for (DirectoryEntry x : theDirectory) {
if (x.getName().equals(name)) {
return i;
}
i++;
}
return -1; // returning -1 if not found
}
or you can use normal for loop instead of foreach
private String find(String name) {
int k=0;
for (DirectoryEntry x : theDirectory) {
if (x.getName().equals(name)) {
k++;
return x.getName();
}
}
//k will give you pos
return null;
}
If you want the position in the array, use a regular loop instead of a foreach loop.
for (int i=0;i<theDirectory.length;i++) {
DirectoryEntry x = theDirectory[i];
if (x.getName().equals(name)) {
return i;
}
}
Depending on the type of your theDirectory-field you could use an own counter up to its length:
private int find(String name) {
for (int i = 0; i < theDirectory.length(); i++) {
DirectoryEntry x = theDirectory[i]; //If it is an Array; for Lists use get etc...
if (x.getName().equals(name)) {
return i;
}
}
return -1;
}
Why not to avoid reinventing the wheel and use Guava instead:
private int find(String name) {
return Iterables.indexOf(theDirectory, new Predicate<DirectoryEntry>() {
public boolean apply(DirectoryEntry de) {
return de.getName().equals(name);
}
});
}
I'm using the Arrays.sort method to sort an array of my own Comparable objects. Before I use sort the array is full, but after I sort the array and print it to System nothing is printing out. EDIT. the array prints nothing at all. not empty line(s), just nothing.
here is the code for my method which uses sort :
public LinkedQueue<Print> arraySort(LinkedQueue<Print> queue1)
{
Print[] thing = new Print[queue1.size()];
LinkedQueue<Print> newQueue = new LinkedQueue<Print>();
for(int i = 0; i <queue1.size(); i++)
{
Print ob = queue1.dequeue();
thing[i] = ob;
System.out.println(thing[i]); //printing works here
}
Arrays.sort(thing);
for(int j = 0;j<thing.length-1;j++)
{
System.out.println(thing[j]); //printing does not work here
newQueue.enqueue(thing[j]);
}
return newQueue;
}
and here is the class for the Comparable object called Print.
public class Print implements Comparable<Print>
{
private String name;
private int numPages,arrivalTime,startTime,endTime;
public Print(String n, int p, int time, int sTime, int eTime)
{
name = n;
numPages = p;
arrivalTime = time;
startTime = sTime;
endTime = eTime;
}
public int getPages()
{
return numPages;
}
public int compareTo(Print other)
{
if(this.getPages()<other.getPages())
return -1;
else if(this.getPages()>other.getPages())
return 1;
else
return 0;
}
public String toString()
{
return name+"("+numPages+" pages) - printed "+startTime+"-"+endTime+" minutes";
}
}
Your last for loop doesn't print the last element in the array. If the array has only one element, it won't print anything at all. Change to:
for (int j = 0; j < thing.length; j++) //clean code uses spaces liberally :)
{
System.out.println(thing[j]);
newQueue.enqueue(thing[j]);
}
or (if supported by the JDK/JRE version used):
for (Print p : thing)
{
System.out.println(p);
newQueue.enqueue(p);
}
I hope the problem is this part of code
for(int i = 0; i <queue1.size(); i++)
{
Print ob = queue1.dequeue();
thing[i] = ob;
System.out.println(thing[i]); //printing works here
}
replace the above with
for(int i = 0; !queue1.isEmpty() ; i++)
{
Print ob = queue1.dequeue();
thing[i] = ob;
System.out.println(thing[i]); //printing works here
}