Description: Given an array and a number, return a new array, with the value app
ID: 3690893 • Letter: D
Question
Description: Given an array and a number, return a new array, with the value appended to the end. Unlike yesterday's drill, the array you're appending to can be any size even empty! But if you write your loop correctly, your code won't care. Notice that this looks a lot like another one you're doing today? That's intentional. Two drills - same algorithm - different types. What do you need to change to make the second drill work, once you've completed the first? Input array -the old array val - the value to append Output: the new, longer arrayExplanation / Answer
/**
* returns a new int array value appended to the end
*
* @param array
* @param val
* @return
*/
int[] myMethod(int[] array, int val) {
int longArr[] = new int[array.length + 1];
for (int i = 0; i < array.length; i++) {
longArr[i] = array[i];
}
longArr[array.length] = val;
return longArr;
}
/**
* returns a new string array value appended to the end
*
* @param array
* @param val
* @return
*/
String[] myMethod(String[] array, String val) {
String longArr[] = new String[array.length + 1];
for (int i = 0; i < array.length; i++) {
longArr[i] = array[i];
}
longArr[array.length] = val;
return longArr;
}
/**
* returns a new array which deletes the 3rd(index:2) element from the array
*
* @param array
* @param val
* @return
*/
int[] myMethod(int[] array) {
int shortArr[] = new int[array.length - 1];
int count = 0;
for (int i = 0; i < array.length; i++) {
if (i != 2)
shortArr[count++] = array[i];
}
return shortArr;
}
/**
* returns a new array which deletes the index element from the array
*
* @param array
* @param val
* @return
*/
int[] myMethod(int[] array,int index) {
int shortArr[] = new int[array.length - 1];
int count = 0;
for (int i = 0; i < array.length; i++) {
if (i != index)
shortArr[count++] = array[i];
}
return shortArr;
}
/**
* returns the concatenation of str and val
*
* @param str
* @param val
* @return
*/
String concatStringInt(String str, int val) {
return str + val;
}
/**
* returns the concatenation of val and str
*
* @param str
* @param val
* @return
*/
String concatIntString(int val, String str) {
return val + str;
}
/**
* convert int to string
*
* @param val
* @return
*/
String int2String(int val) {
return "" + val;
}