This feature is supposed to add an element at the selected index and push all other in the array elements down. So, for instance, say I have the following array:
[0] = zero
[1] = one
[2] = two
if I add another element at index 0 called NEWZERO, the array has to look like this:
[0] = NEWZERO
[1] = zero
[2] = one
[3] = two
but currently I'm getting IndexOutOfBounds exception and it doesn't work.
P.S. I don't want to use the built-in ArrayList library, which automatically does it for you.
public void insert(int i, String s) {
if (array[i] == null) {
array[i] = s; //Need to add feature that instantly puts the element at the first available spot on the list.
} else {
for (int j = i; j < array.length; j++) { //Can't use >= i
array[j + 1] = array[j];
if (j == array.length - 1) {
break;
}
}
array[i] = s;
Try this
public void insert(int i, String s) {
String[] newArr = new String[array.length + 1];
for (int j = 0; j < array.length; j++) {
if(j < i){
newArr[j] = array[j];
} else if(j == i){ // '==' insted of '='
newArr[j] = s;
} else {
newArr[j+1] = array[i];
}
}
array = newArr;
}
Well, arrays are not dynamic, so if you have an array that has size 3 you cannot add anything to it unless you create a new array that has size of oldArray.length+1 and then populate it with new data.
public static int[] addAtIndex(int[] a, int index, int value) {
int[] newArr = new int[a.length + 1];
int temp;
for (int j = 0; j < a.length + 1; j++) {
if (j < index) {
newArr[j] = a[j];
} else if (j == index) {
//copy value at index to temp so that value added at specific index can be shifted right
temp = a[j];
newArr[j] = value;
newArr[j + 1] = temp;
} else {
newArr[j] = a[index];
index++;
}
}
return newArr;
}
Related
Lets say I have a class called "Sequence". This class has an instance variable private int[] tab.
There are also some methods to create this tab like those:
public Sequence() {
this.tab = fillAnArray(drawsNumber(5, 20));
}
private int drawsNumber(int min, int max) {
if (min > max) {
throw new IllegalArgumentException("Wrong range");
}
return new Random().nextInt(max - min + 1) + min;
}
public int[] fillAnArray(int size) {
int[] arr = new int[size];
arr[0] = 1;
for (int i = 1; i < arr.length; i++) {
arr[i] = drawsNumber(arr[i - 1], arr[i - 1] + 10);
}
return arr;
}
Now, I would like to create the method that accepts two Sequence objects as arguments and returns number of the same tab elements. So, I created method like this:
public int howManyCommonElements(Sequence c1, Sequence c2) {
int i = 0, j = 0;
int counter = 0;
while (i < c1.tab.length && j < c2.tab.length) {
if (c1.tab[i] == c2.tab[j]) {
++counter;
} else if (c1.tab[i] < c2.tab[j]) {
++i;
} else {
++j;
}
}
return counter;
}
How do I compare single elements like c1.tab[i], c2.tab[j]?
You have to compare every element of the 1st array with every element of the 2nd one. To do that you have to use 2 nested for cycles:
for (int i = 0; i < c1.tab.length; i++)
for (int j = 0; j < c2.tab.length; j++)
if (c1.tab[i] == c2.tab[j])
++counter;
If you have ordered elements (ASC), you can do like;
int i = 0, j = 0;
int counter = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] == arr2[j]) {
++i;
++j;
++counter;
} else if (arr1[i] < arr2[j]) {
++i;
} else {
++j;
}
}
I want to arrange the array such that even numbers are brought ahead. This is what I've done.
public int[] moveEvenToFront(int[] arr) {
arr[i - 1] = arr[i];
arr[i] = temp;
}
}
return arr;
}
}
This is what I have so far
Pretty simple. Just create a new array, then loop through the original twice. The first time, add the evens. The next time, add the odds. Looks like you were almost there:
public int[] moveEvenToFront(int[] arr) {
//declare a new array to populate with the result
int[] result = new int[arr.length];
int temp = 0;
//add the evens
for (int i = 0; i < result.length; i++) {
if (arr[i] % 2 == 0) {
result[temp] = arr[i];
temp++;
}
}
//add the odds
for (int i = 0; i < result.length; i++) {
if (arr[i] % 2 != 0) {
result[temp] = arr[i];
temp++;
}
}
//return
return result;
}
I am developing a simple program to print seat numbers, where the row are numbered from 1-5 and columns from a-e. the code i am using is as follows
public class JavaApplication5 {
public static void main(String[] args) {
int j =1,k;
int i;
char c;
String[] arr = new String[25];
for( i = 0;i < arr.length;i++)
{
while(j <= 5)
{
for(k = 97;k < 102; k++)
{
c = ((char)k);
arr[i] = j + "" + c;
System.out.println(arr[i]);
}
j++;
}
}
}
}
this displays desired result. but when I print an element outside the for loop I get the result as null like below
public static void main(String[] args) {
int j =1,k;
int i;
char c;
String[] arr = new String[25];
for( i = 0;i < arr.length;i++)
{
while(j <= 5)
{
for(k = 97;k < 102; k++)
{
c = ((char)k);
arr[i] = j + "" + c;
}
j++;
}
}
System.out.println(arr[6]);
}
how to solve this?
this will leave all elements as null
String[] arr = new String[25];
this will iterate until j == 5 so only until arr[5]
while(j <= 5) {
j++;
}
Therefore arr[6] is still null
Change
arr[j] = j + "" + c;
instead of
arr[i] = j + "" + c;
Now it works.
public static void main(String[] args) {
int j = 1, k;
int i;
char c;
String[] arr = new String[25];
for (i = 0; i < arr.length; i++) {
while (j <= 5) {
for (k = 97; k < 102; k++) {
c = ((char) k);
arr[j] = j + "" + c;
}
j++;
}
}
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
System.out.println(arr[4]);
System.out.println(arr[5]);
System.out.println(arr[6]); // null because your check j <= 5 in while loop
}
You can access the array elements normally outside of the loop. In your example, arr[6] is just null. The fault is not in the way you access it. (Although i cant see the bug yet ;))
The problem in your code is that you simply write 5 time on index 1, then 5 time on index 2 and so on.
So you never wrote on index 6.
Your code should be changed to code below:
String[] arr = new String[25];
int i = 0;
int j = 1;
while (j <= 5) {
for (k = 97; k < 102; k++) {
c = ((char) k);
arr[i++] = j + "" + c;
}
j++;
}
System.out.println(arr[6]);
Because your loops run 5*5 times, then your i index will never pass arr array length.
But you better control it like this to prevent your code from being error prone:
if(i < arr.length) {
arr[i++] = j + "" + c;
} else {
break;
}
I need to write an algorithm that will take an array of ints and find the k'th largest element in the array. The caveat here is that the runtime must be O(K*n) or better.
My teacher has made it clear this can be done with a modified bubble sort program, but I am unsure as to how I can modify the bubble sort without ruining it, as I would think it necessary to loop through every element of the array. Here is my code (just the shell of the program and an unmodified bubble sort):
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
for (int i = (A.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (sorted[j-1] < sorted[j])
{
temp = sorted[j-1];
sorted[j-1] = sorted[j];
sorted[j] = temp;
}
}
}
return sorted[k-1];
}
Figured it out:
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
for (int i = 0; i < A.length-1; i++)
{
for (int j = 0; j < A.length-i-1; j++)
{
if (sorted[j] > sorted[j+1])
{
temp = sorted[j];
sorted[j] = sorted[j+1];
sorted[j+1] = temp;
}
if(i == (k-1)) return A[A.length-i-1];
}
}
return sorted[A.length-k];
}
The the array has been sorted to the k-th largest element, it has found what it is looking for and can stop the sort and return.
I thought a modified bubble sort just exited early if the list was already sorted?
Wouldn't something like this suffice?
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
bool bSorted = TRUE;
for (int i = (A.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (sorted[j-1] < sorted[j])
{
temp = sorted[j-1];
sorted[j-1] = sorted[j];
sorted[j] = temp;
bSorted = FALSE;
}
}
if(bSorted)
break;
}
return sorted[k-1];
}
I have a class that implements an interface and I think when I try to insert an element into the array more than once the first insertions are forgotten. I really can't figure this one out. This is what I have:
public void insertElementAt(int index, E el)
throws IllegalArgumentException {
Object temp[] = new Object[data.length + 1];
for (int i = 0; i < data.length; i++) {
if (i == index){
temp[index] = el;
temp[i + 1] = data[i];
i++;
}
temp[i] = data[i];
}
data = temp;
if (index > data.length || index < 0) {
throw new IllegalArgumentException();
}
}
Then my test reports null instead of first at he last assertion.
#Test
public void testInsertToLeft() {
PriorityList<String> list = new ArrayPriorityList<String>();
list.insertElementAt(0, "First");
// Must shift array elements in this case
list.insertElementAt(0, "New First");
assertEquals("New First", list.getElementAt(0));
assertEquals("First", list.getElementAt(1));
}
You must do like this:
public void insertElementAt(int index, E el) throws IllegalArgumentException {
Object temp[] = new Object[data.length + 1];
for (int i = 0; i < data.length; i++) {
if (i >= index){
temp[i + 1] = data[i];
} else {
temp[i] = data[i];
}
}
temp[index] = el;
data = temp;
if (index > data.length || index < 0) {
throw new IllegalArgumentException();
}
}
To remove it:
public void removeElementAt(int index) throws IllegalArgumentException {
Object temp[] = new Object[data.length - 1];
for (int i = 0; i < temp.length; i++) {
if (i > index){
temp[i - 1] = data[i];
} else {
temp[i] = data[i];
}
}
data = temp;
if (index > data.length || index < 0) {
throw new IllegalArgumentException();
}
}
Try changing your for loop to either:
for (int i = 0; i < data.length; i++) {
if (i == index){
temp[index] = el;
temp[i + 1] = data[i];
i++;
}else{
temp[i] = data[i];
}
}
or
for (int i = 0; i < data.length; i++) {
if (i == index){
temp[index] = el;
temp[i + 1] = data[i];
i++;
continue;
}
temp[i] = data[i];
}
What is data.length when the list is empty? If it is empty at first insertion you will not enter the for loop but copy the temp array, it will go into the loop at next insertion with length 1. The first insertion will be skipped.
I would do this:
public static void insertElementAt(int index, E el)
throws IllegalArgumentException {
if (index > data.length || index < 0) {
throw new IllegalArgumentException();
}
Object temp[] = new Object[data.length + 1];
for (int i = index; i < data.length; i++) {
temp[i+1] = data[i];
}
temp[index] = el;
data = temp;
}
You should have the test for valid parameters first ("fail early"), and you can make good use of the JDK's utility methods do the lifting for you:
public static void insertElementAt(int index, E el) {
if (index > data.length || index < 0) {
throw new IllegalArgumentException();
}
data = Arrays.copyOf(data, data.length + 1);
System.arrayCopy(data, index, data, index + 1, data.length - index);
data[index] = el;
}
Also note you don't need to declare a throws, becauseIllegalArgumentException is an unchecked exception, so I removed it. Normally, one follows this pattern.