Write a method called get which will return an element from the given index. Returns -1 if the index is out-of-bounds.
Write a method called remove which will remove an element from the given index. Returns -1 if the index is out-of-bounds. Data should be shifted accordingly during removal.
//This is the get method
public int get(int index){
if(index < 0 || index >= size) {
return -1;
}else {
return data[index];
}
}
//This is the remove method
public int remove(int index){
if(index < 0 || index >= size){
return -1;
}else {
for(int i = 0; i < size-1; i++) {
index[i] = index[i+1];
}
}
}
This is as far as I got. Not sure how to proceed with the code. I'd appreciate if someone could guide me through. Thank you!
So far, you have the right idea. I am going to assume based on your syntax, that you are using an array. Your get() method looks good, but you are missing some code from your remove() method.
public int remove(int index){
//check for out-of-bounds
if(index < 0 || index >= size) //assumes size is set to the size of the array
{
return -1; }
else
{
for(int i = index; i < size-1; i++){
data[i] = data[i+1]; }
data[size-1] = 0; //assuming the array contains numbers, if not replace '0' with null
}
}
You need to replace the following :
for(int i = 0; i < size-1; i++) {
index[i] = index[i+1];
}
with:
for(int i = index; i < size-1; i++) {
data[i] = data[i+1];
}
Start the loop with index
index[i] won't compile. Should be data[i] probably.
Note:
This will not delete the last element. You need to specifically check for it.
public class MyList<T> {
T[] items = (T[])new Object[10];
public int size() {
int counter=0;
for (int i = 0; i < items.length; i ++) {
if (items[i] != null) {
counter ++;
}
}
return counter;
}
public void remove(int t) {
for (int i = t; i < items.length-1; i++) {
items[i]=items[i+1];
}
items[items.length-1]=null;
items= Arrays.copyOf(items,size());
}
}
Related
Java says ''the type of the expression must be Array type but it resolved to Int"
I'm looking to do a nested For Loop for the solution, but any other more more elegant suggestions are also welcome.
public class ArraySearch {
public static int searchForItemInArray(int needle, int[] haystack) throws Exception {
for (int i = 0; i <= needle; i++) {
for (int j = 0; j < haystack.length; j++) {
if (needle[i] == haystack[j]) {
}
}
}
return -1;
}
}
needle is an Int variable so isn't part of an array.
The answer to fix the IF statement was needle == haystack[j]
If searching for an item in an arrray is actually what you want, then you don't need a nested for loop.
If the needle is the item that you are searching for and the haystack is the array, you need to parse the array one time, using only one for loop and check at each step if the current item is equal to the searched element.
public static int searchForItemInArray(int needle, int[] haystack) {
for (int i = 0; i < haystack.length; i++) {
if (needle == haystack[i]) {
// return the position of the item in the array.
return i;
}
}
return -1;
}
It looks like you are searching index of the needle it that array. If it is true, than your code can be as follows:
public static int searchForItemInArray(int needle, int[] haystack) throws Exception {
for (int i = 0; i <= haystack.length; i++) {
if (needle == haystack[j]) {
return i;
}
}
return -1;
}
This code prints the first occurence of element 'k' in the array properly but the question I'm doing wants me to print -1 if the element 'k' is entirely not present in the array. I know its easy but I'm just stuck and its frustatiting any help?
n = sc.nextInt();
k = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++) {
arr[i] = sc.nextInt();
}
for(int i=0;i<n;i++) {
if(arr[i]==k) {
System.out.println(i);
break;
}
}
Use Arrays#binarySearch:
int firstIndexOf(int[] sortedArray, int x) {
int p = Arrays.binarySearch(sortedArray, x);
if (p < 0) {
return -1;
}
while (p > 0 && sortedArray[p - 1] == x) {
--p;
}
return p;
}
Binary search splits the searched range in half repetively looking in which half to continue. It returns either the found position or the complement (~p) of the insert position.
int findOccurenceOfElemet(int[] a, int k) {
if(a.length == 0) {
return -1;
}
for(int i = 0; i < a.length; i++) {
if(a[i] == k) {
return i;
}
}
//return -1 if element not found
return -1;
}
What you are asking in the title, and what you are asking in the post body, are two different questions; however, if we will follow your question's body, that has nothing to do with binary search, and introducing boolean flag would get you what you are asking for:
boolean notFound = true;
for(int i=0; i<n; i++) {
if(arr[i] == k) {
System.out.println(i);
notFound = false;
break;
}
}
if(notFound) System.out.println("-1");
I'm implementing Insertionsort for university. My code works in theory, but my for-loop is executed only once instead of books.size() (which is 5, I've tested that). I tried it using the number 5, but it won't work and I'm kind of desperate because I can't seem to find the error.
Here is my code:
static void sort(LinkedList<Book> books)
{
int i;
for ( i = 0; i < books.size(); i++)
{
Book temp = books.get(i);
books.remove(i);
for (int j = 0; j < books.size(); j++) {
if (books.get(j).compareTo(temp) > 0) {
books.add(j, temp);
return;
}
}
books.add(temp);
}
}
The compareTo function of the Book-Class looks like the following:
public int compareTo(Book other)
{
int iAutor = autor.compareTo(other.getAutor());
if (iAutor != 0)
return iAutor;
else
{
int iTitel = titel.compareTo(other.getTitel());
if (iTitel != 0)
return iTitel;
else
{
if (this.auflage < other.getAuflage())
return -1;
else if (this.auflage > other.getAuflage())
return 1;
else
return 0;
}
}
}
Am I simply blind?
You need to swap return for break and fix the logic to avoid adding the book twice. There may be more elegant ways than this, but it should work:
int i;
for ( i = 0; i < books.size(); i++)
{
Book temp = books.get(i);
books.remove(i);
bool added = false;
for (int j = 0; j < books.size(); j++) {
if (books.get(j).compareTo(temp) > 0) {
books.add(j, temp);
added = true;
break;
}
}
if (!added) {
books.add(temp);
}
}
Well, I found out how to solve it, just if someone has the same problem (don't think that will happen, but it's a good habit I hope).
As #Klitos Kyriacou pointed out right, I had a twist in my thoughts about the process of Insertionsorting.
The solution is changing the loops in the following:
static void sort(LinkedList<Book> books) {
Book temp;
for (int counter = 0; counter < books.size(); counter++) {
temp = books.get(counter);
for (int position = 0; position < counter; position++)
{
if (temp.compareTo(books.get(position)) < 0)
{
books.remove(counter);
books.add(position, temp);
break;
}
}
}
}
I'm trying to write the remove method for Set but it doesn't work when I test it. Am I doing it wrong? the size doesn't reduce after I remove the element.
public class MySet<T> implements Set<T> {
private T[] arrayB;
private int elements;
#Override
public boolean remove(Object f) {
T h = (T) f;
for (T z : arrayB) {
if(z == h) {
z = null;
}
}
return true;
}
#Override
public int size() {
int count = 0;
for(int arr = 0; arr < arrayB.length; arr++){
if(arrayB[arr] != null) {
count++;
}
}
return count;
}
The test code is:
MySet<Integer> ints = new MySet<Integer>();
for (int i = 0; i < 100; i++) {
ints.add(i);
}
for (int i = 0; i < 100; i += 2) {
ints.remove(i);
}
}
Your size method relies on whether the element is null to decide whether to count it. Assuming that you are attempting to place a null in the array, you're doing it wrong. All you've done is assign null to z, which is just a local variable. The array is not changed.
You must use a traditional for loop and use an array access expression to assign null to the array element. You'll also want to call equals instead of using == to find the element.
for (int i = 0; i < array.length; i++)
{
if (array[i] != null && array[i].equals(h))
{
array[i] = null;
}
}
Depending on whether you want to remove all elements that match, or just the first one, you may consider adding a break statement inside the if.
Okay, this is probably going to come across as a really easy question, but honestly I'm new to coding and I've run up against a brick wall here. I need to insert a value into an array, shift the data to the right, and update the size of the array. The professor provided comments for us to structure our code around, and I've got most of it, but this last part is killing me. Can anyone help? Here's the code (the relevant portion is under //insert value and shift data...etc):
public class List {
// Declare variables
private int size = 0;
private int maxSize = 100;
private int[] data;
Scanner keyboard = new Scanner(System.in);
// constructors
public List() {
data = new int[maxSize];
}
public List(int maxSize) {
this.maxSize = maxSize;
data = new int[maxSize];
}
// methods
// Adds a value into the array and updates the size
public boolean add(int value) {
if (size == maxSize) {
System.out.println("Cannot add value since the list is full");
return false;
}
data[size] = value;
size++;
return true;
}
// add multiple values to the list obtained from the keyboard
public void addValues() {
// declare local variables
int count = 0;
System.out.println("Enter multiple integers separated by spaces");
String line = keyboard.nextLine();
Scanner scanLine = new Scanner(line);
try {
while (scanLine.hasNext()) {
data[size] = scanLine.nextInt();
count++;
size++;
}
} catch (ArrayIndexOutOfBoundsException aiobe) {
System.out.println("Only " + count + " values could be added before the list is full");
return;
} catch (InputMismatchException ime) {
System.out.println("Only " + count + " values could be added due to invalid input");
return;
}
}
// This will print all the elements in the list
public void print() {
System.out.println();
for (int i = 0; i < size; i++) {
System.out.print(data[i] + " ");
}
System.out.println();
}
// This methods returns the index of the key value if found in the list
// and returns -1 if the key value is not in the list
public int find(int key) {
for (int i = 0; i < size; i++) {
if (data[i] == key) {
return i;
}
}
return -1;
}
// This methods deletes the given value if exists and updates the size.
public boolean delete(int value) {
int index = find(value);
if (index == -1) {
System.out.println("The specified value is not in the list");
return false;
}
for (int i = index; i < size - 1; i++) {
data[i] = data[i + 1];
}
size--;
return true;
}
// This methods inserts the value at the given index in the list
public boolean insertAt(int index, int value) {
// validate index value and insertability
if (index < 0 || index > size || size == maxSize) {
System.out.println("Invalid index or list is already full");
return false;
}
// insert value and shift data to the right and update the size
return true;
}
// This method removes the value at given index and shifts the data as needed
public boolean removeAt(int index) {
if (index >= 0 && index < size) {
for (int i=index+1; i<size; i++)
data[i-1] = data[i];
size--;
return true;
}
return false;
}
// This method sorts the values in the list using selection sort
public void sort() {
int temp;
for (int j=size; j>1; j--) {
int maxIndex = 0;
for (int i=1; i<j; i++)
if (data[maxIndex] < data[i])
maxIndex = i;
temp = data[j-1];
data[j-1] = data[maxIndex];
data[maxIndex] = temp;
}
}
}
I apologize if the code is structured really horribly as well, by the way, I was unsure how to format it on this site so it looked right.
// insert value and shift data to the right and update the size
// I think the size is globally declared right?
size++;
for(int i=size - 1; i < 0; i--) {
data[i] = data[i - 1];
}
data[index] = value;
If you have a max size there will also be a check for size <= maxSize. Hope it helps
Think below answer should help. As there is already a size check, no need to check it again
public boolean insertAt(int index, int value) {
// validate index value and insertability
if (index < 0 || index > 5) {
System.out.println("Invalid index or list is already full");
return false;
}
// insert value and shift data to the right and update the size
for(int i=index;i<size;i++) {
data[++i] = data[i];
}
data[index] = value;
return true;
}
public boolean insertAt(int index, int value) {
// validate index value and insertability
if (index < 0 || index > size || size == maxSize) {
System.out.println("Invalid index or list is already full");
return false;
}
// insert value and shift data to the right and update the size
for (int i=size - 1; i > index; i--)
data[i+1] = data[i];
data[index] = value
size++;
return true;
}