My practice problem says to"this method returns an array that has the elements of the specified
// array of Objects, with the Object at the specified index removed.
// the returned array should be smaller by one and have all elements
// in the same relative location to each other. YOU MAY NOT USE
// A LIST :)
Object[] remove(int index, Object[] arr){"
I have come up with this so far, and I'm not entirely sure it works. Can you guys please take a look and give me some feedback on how to fix it so I can do this "remove" properly.
public static remove(int index, Object[] arr){
int counter = 0;
int temp = 2;
int[] arr = {1, 2, 3, 4};
int[] second = new int[arr.length-1];
for(int i=0; i< arr.length;i++){
if(i != temp){
second[counter] = arr[i];
counter ++;
}
//return second;
}
public static Object[] remove(int index, Object[] array) {
Object[] newArray = new Object[array.length - 1];
for (int i = 0; i < array.length; i++) {
if (index > i) {
newArray[i] = array[i];
} else if(index < i) {
newArray[i - 1] = array[i];
}
}
return newArray;
}
You would have to copy over all elements, besides for the one at index, into a new array and return that.
Related
I have this question that I have been tackling for a while.
"The method should return an array containing the elements that are divisible by a certain number" in this case the target which is 5.
Here is my solution
public static int[] Divisible(int[] array, int target){
int[] answer = new int[array.length];
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0){
answer[i] = array[i];
}
}
return answer;
}
assuming my input is
int[] input = {5,3,6,10};
my output will be [5,0,0,10].
My desired output should be [5,10].
please, How do I get rid of the zeros
The basic idea is to fill the answer array from the bottom, and then truncate it to exactly the size you need.
int j = 0;
for (int i=0; i<array.length; i++) {
if (array[i] % target == 0){
answer[j++] = array[i];
}
}
return Arrays.copyOf(answer, j);
Arrays is a standard Java utility class.
If you're not allowed to use the Arrays utility class then the last line can be replaced by:
int[] answer2 = new int[j];
for (int i=0; i<j; i++)
answer2[i] = answer[i];
return answer2;
This feels a little clunky to me but it satisfies the apparent requirements to use simple arrays.
you can do like this
public static int[] Divisible(int[] array, int target){
List<Integer> list = new ArrayList<>();
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0){
list.add(array[i]);
}
}
int[] ints = new int[list.size()];
for (int i = 0; i < ints.length; i++) {
ints[i] = list.get(i);
}
return ints;
}
Two options:
you can use an ArrayList internally, as that can grow dynamically (you just keep adding the values you are interested in, done). If you have to return an array, you can easily do that based on your filled list.
when going only with arrays you can simply do 2 passes: first create that large array and fill it. Then count the non zero entries! Create a new array with the smaller length, and then copy over all non zero elements manually.
I have used the method stated by #GhostCat but it made me change the code entirely. This is my new code
public static Object[] Divisi(int[] array, int target){
ArrayList<Integer> answer = new ArrayList<>();
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0){
answer.add(array[i]);
}
}
return answer.toArray();
}
This gave me the desired answer but how else can i do this without converting to object
The shortest and the most quickest way to go about this is, you can change the array to an ArrayList and then use .toArray() method to get it back as a primitive array when returning.
public static Integer[] Divisible(int[] array, int target){
List<Integer> answer = new ArrayList<>();
for (int i = 0; i<array.length; i++){
if (array[i] % target == 0) {
answer.add(array[i]); // pushing to list only if the number is divisible
}
}
return answer.toArray(new Integer[0]); // converting the list to an array before returning
}
If you want a list of unique numbers use Set instead of a List.
Set<Integer> answer = new HashSet<>();
Instead of using the primitive int, I have conformed to using Integer instead.
Here is my solution.
public static Integer[] divisible(Integer[] array, int target) {
int j = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
if (array[i] % target == 0) {
j++;
list.add(array[i]);
}
}
Integer answer[] = new Integer[j];
answer = list.toArray(answer);
return answer;
}
You should use a separate counter for the result array and keep incrementing the counter if the number is divisible by the target.
Something like this :
int[] result=new int[array.length];
int resultindex=0; //create a separate counter
for(int i=0;i<array.length;i++)
{
if(array[i]%target==0)
{
result[resultindex]=array[i];
++resultindex; //update the counter
}
}
I'm making a class that deletes an element at a specific position in an Integer array. It runs perfectly the first 2 times, but then for some reason it decides that the ArrayIndexOutOfBoundsException should be thrown.
my code:
public class Arraydeletion {
public static int[] delete (int[] a, int delValPos){
int[] newArray = new int[a.length-1];
for (int i = 0; i < newArray.length; i++) {
if(a[i]!=a[delValPos]){ //<--- ArrayIndexOutOfBoundsException points here
newArray[i] = a[i];
}
else if(a[i] == a[delValPos]){
newArray[i] = a[delValPos+=1];
}
}
return newArray;
}
}
You never check that delValPos is a valid index within the input array a. Your method must validate it before doing anything else, and throw an exception if an invalid delValPos is supplied.
Working code would look like this :
public class Arraydeletion {
public static int[] delete (int[] a, int delValPos){
if (delValPos < 0 || delValPos >= a.length)
throw new SomeException(); // TODO decide which exception to throw
int[] newArray = new int[a.length-1];
int index = 0;
for (int i = 0; i < a.length; i++) {
if (i!=delValPos) {
newArray[index] = a[i];
index++;
}
}
return newArray;
}
}
This makes the code much simpler. It copies all the elements except a[delValPos] to the output array. Note that you can't use the same index i for reading elements from the input array and writing elements to the output array, because after you pass the deleted element, each i'th element in the input array would be written to the (i-1)'th place in the output array.
I tested your code and i retrieve outOfBoundException only if delValPos == a.length, so you can check this before loop.
However your code is pretty strange, it seems you want to clone an array except for one element in a certain position, if so this will work better:
public static int[] delete (int[] a, int delValPos){
int delValPos = 0;
int[] a = {1,2,3,4,5,6,7,8,9};
int[] newA = new int[a.length - 1];
if(a.length > delValPos) {
for(int i = 0 ; i < newA.length ; i++) {
if(delValPos < i && delValPos != 0) {
newA[i] = a[i];
}
else
newA[i] = a[i + 1];
}
}
return newA;
}
ok I have this code that someone helped with me
public void add(int index, E element)
if (index < 0 || index >= mList.length){
throw new IndexOutOfBoundsException(); // check if index is ok.
}
Object[] temp = new Object[mList.length + 1]; // create the new array into temp.
for (int i = 0, j = 0; j < temp.length; ++i, ++j){ // loop into the array by comparing the first array to the second array's index i&j
if ( i == index ) { // check if i is valid
temp[index] = element; // insert element into the array
--i; // decrement original array to cancel out j temp array
} else {
temp[j] = mList[i]; //
}
}
mList = temp;
}
Now I need to
public E remove(int index)
Do I need to create a temp array again?
I know there are two arrays, do I just do a for loop on the current array which is temp?
If you want to do it in a way similar to your add, then yes, you need a temp array.
public E remove(int index) {
Object[] temp = new Object[mList.length + 1];
for (int i = 0; j < mList.length; ++i) {
if(i<index) temp[i]=mList[i];
if(i>index) temp[i-1]=mList[i];
//N.B. not added if i == index
}
mList = temp;
}
To sum it up, you don't remove the element from the array, you just don't add it to the new one.
If you want a better solution, you should take a look at System.arraycopy() and Arrays.copyOf(). Give it a try and if you have difficulties don't shy away from asking.
If you are not forced to use arrays, I'd suggest you use Collections. For instance a List would suit your needs very well.
So I know how to get the size of a combination - factorial of the size of the array (in my case) over the size of the subset of that array wanted. The issue I'm having is getting the combinations. I've read through most of the questions so far here on stackoverflow and have come up with nothing. I think the issue I'm finding is that I want to add together the elements in the combitorial subsets created. All together this should be done recursively
So to clarify:
int[] array = {1,2,3,4,5};
the subset would be the size of say 2 and combinations would be
{1,2},{1,3},{1,4},{1,5},{2,3},{2,4},{2,5},{3,4},{3,5},{4,5}
from this data I want to see if the subset say... equals 6, then the answers would be:
{1,5} and {2,4} leaving me with an array of {1,5,2,4}
so far I have this:
public static int[] subset(int[] array, int n, int sum){
// n = size of subsets
// sum = what the sum of the ints in the subsets should be
int count = 0; // used to count values in array later
int[] temp = new temp[array.length]; // will be array returned
if(array.length < n){
return false;
}
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < n; j++) {
int[] subset = new int[n];
System.arraycopy(array, 1, temp, 0, array.length - 1); // should be array moved forward to get new combinations
**// unable to figure how how to compute subsets of the size using recursion so far have something along these lines**
subset[i] = array[i];
subset[i+1] = array[i+1];
for (int k = 0; k < n; k++ ) {
count += subset[k];
}
**end of what I had **
if (j == n && count == sum) {
temp[i] = array[i];
temp[i+1] = array[i+1];
}
}
} subset(temp, n, goal);
return temp;
}
How should I go about computing the possible combinations of subsets available?
I hope you will love me. Only thing you have to do is to merge results in one array, but it checks all possibilities (try to run the program and look at output) :) :
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
int n = 2;
subset(array, n, 6, 0, new int[n], 0);
}
public static int[] subset(int[] array, int n, int sum, int count, int[] subarray, int pos) {
subarray[count] = array[pos];
count++;
//If I have enough numbers in my subarray, I can check, if it is equal to my sum
if (count == n) {
//If it is equal, I found subarray I was looking for
if (addArrayInt(subarray) == sum) {
return subarray;
} else {
return null;
}
}
for (int i = pos + 1; i < array.length; i++) {
int[] res = subset(array, n, sum, count, subarray.clone(), i);
if (res != null) {
//Good result returned, so I print it, here you should merge it
System.out.println(Arrays.toString(res));
}
}
if ((count == 1) && (pos < array.length - 1)) {
subset(array, n, sum, 0, new int[n], pos + 1);
}
//Here you should return your merged result, if you find any or null, if you do not
return null;
}
public static int addArrayInt(int[] array) {
int res = 0;
for (int i = 0; i < array.length; i++) {
res += array[i];
}
return res;
}
You should think about how this problem would be done with loops.
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] + array[j] == sum) {
//Add the values to the array
}
}
}
Simply convert this to a recursive code.
The best way I can think to do this would be to have each recursive call run on a subset of the original array. Note that you don't need to create a new array to do this as you are doing in your code example. Just have a reference in each call to the new index in the array. So your constructor might look like this:
public static int[] subset(int[] array, int ind, int sum)
where array is the array, ind is the new starting index and sum is the sum you are trying to find
CodingBat > Java > Array-1 > reverse3:
Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.
public int[] reverse3(int[] nums) {
int[] values = new int[3];
for (int i = 0; i <= nums.length - 1; i++) {
for (int j = nums.length-1; j >= 0; j--) {
values[i] = nums[j];
}
}
return values;
}
I can't get this to work properly, usually the last int in the array, becomes every single int in the new array
You don't want a two-level loop. Just have one loop:
for(int i = 0, j = nums.length - 1; i < nums.length; i++,j--) {
values[i] = nums[j];
}
or, alternately, just don't track j sepearately, and do this:
for(int i = 0; i < nums.length; i++) {
values[i] = nums[nums.length - 1 - i];
}
Unless this is a homework, why not just use Apache ArrayUtils'
ArrayUtils.reverse(nums)
Never re-invent the wheel :)
The length of the input int[] is fixed at 3? Then it doesn't get any simpler than this.
public int[] reverse3(int[] nums) {
return new int[] { nums[2], nums[1], nums[0] };
}
See also:
CodingBat/Java/Array-1/reverse3
Note that Array-1 is "Basic array problems -- no loops." You can use a loop if you want, but it's designed NOT to be solved using loops.
Firstly, while creating new array give it size of old array.
Next, when you're reversing an array, you don't need two loops, just one:
int length = oldArray.length
for(int i = 0; i < length; i++)
{
newArray[length-i-1] = oldArray[i]
}
You only want a single loop, but with indices going both ways:
public int[] reverse(int[] nums) {
int[] back = new int[nums.length];
int i,j;
for (i=0,j=nums.length-1 ; i<nums.length ; i++,j--)
back[i] = nums[j];
return back;
}
public int[] reverse3(int[] nums) {
int rotate[]={nums[2],nums[1],nums[0]};
return rotate;
}
This code gives correct output:-
public int[] reverse3(int[] nums) {
int[] myArray=new int[3];
myArray[0]=nums[2];
myArray[1]=nums[1];
myArray[2]=nums[0];
return myArray;
}
I got this with Python.. So you can get the idea behind it
def reverse3(nums):
num = []
for i in range(len(nums)):
num.append(nums[len(nums) - i - 1])
return num
In your code, for each value of i, you are setting target array elements at i to value in "nums" at j. That is how you end up with same value for all the elements at the end of all iterations.
First of all, very bad logic to have two loops for a simple swap algorithm such as :
public static void reverse(int[] b) {
int left = 0; // index of leftmost element
int right = b.length-1; // index of rightmost element
while (left < right) {
// exchange the left and right elements
int temp = b[left];
b[left] = b[right];
b[right] = temp;
// move the bounds toward the center
left++;
right--;
}
}//endmethod reverse
or simplified:
for (int left=0, int right=b.length-1; left<right; left++, right--) {
// exchange the first and last
int temp = b[left]; b[left] = b[right]; b[right] = temp;
}
Why go through all this pain, why dont you trust Java's built-in APIs and do something like
public static Object[] reverse(Object[] array)
{
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
return list.toArray();
}
public int[] reverse3(int[] nums) {
int[] values = new int[nums.length];
for(int i=0; i<nums.length; i++) {
values[nums.length - (i + 1)]=nums[i];
}
return values;
}