determining how many times each integer appears in the input (array) - java

it keeps repeating regardless of whether it's been already calculated or not. You can see the example output. it already calculated the occurrence of 1, but when it sees 1 again, it will calculate it again!
public class SortingInLinearTime {
public static int[][] howMany(int[] n){
// Makes a double array list where the second value is occurrence of the first value.
int[][] a = new int[n.length][2];
int counter = 0;
for(int i = 0; i != n.length; i++){
for(int j = 0; j != n.length; j++) {
if(n[i] == n[j]){
counter++;
}
}
a[i][0] = n[i];
a[i][1] = counter;
counter = 0;
}
// printer helper function
for(int i = 0; i != n.length; i++){
System.out.print(a[i][0] + " occurs ");
System.out.println(a[i][1] + " times");
}
return a;
}
public static void main(String[] args) {
int[] testArray = {1, 2, 3, 1, 2, 3, 4};
System.out.print(howMany(testArray));
}
}
output:
1 occurs 2 times
2 occurs 2 times
3 occurs 2 times
1 occurs 2 times
2 occurs 2 times
3 occurs 2 times
4 occurs 1 times
[[I#15db9742

In the first loop with i, you are recounting the same values again and again.
1 appears when i = 0 and when i = 3 as well. you once counted for 1 when i == 0 and recounted again at i == 3 in array n.
However, I believe the best solution for your problem could be achieved by changing your data structure from int[][] to an hashmap.

You're making this way harder than it needs to be both by looping over the array twice and by using an array to store your result. Try this:
public class SortingInLinearTime {
public static Hashtable<Integer, Integer> howMany(int[] n){
Hashtable<Integer, Integer> toRet = new Hashtable<Integer, Integer>();
for (int i = 0; i < n.length; i++) {
if (!toRet .containsKey(n[i])) {
toRet.put(n[i], 1);
} else {
toRet.put(n[i], toRet.get(n[i]) + 1);
}
}
return toRet;
}
public static void main(String[] args) {
int[] testArray = {1, 2, 3, 1, 2, 3, 4};
Hashtable<Integer, Integer> counts = howMany(testArray);
Set<Integer> keys = counts.keySet();
for(Integer key : keys){
System.out.println(key + " occurs " + counts.get(key) + " times.");
}
}
}
This has several advantages. It will not break if you pass an array with large numbers, like {1, 11, 203, 203}, which your current implementation cannot handle. It does not use extra space by declaring an array with many elements that you do not need. Most important, it works.

Convert your array to list using Arrays.asList() and then use the collections api to get the count.
Collections.frequency(Collection c, Object o)
Updated with the implementation
import java.util.AbstractList;
import java.util.Collections;
import java.util.List;
public class SortingInLinearTime {
public static int[][] howMany( int[] n){
// Makes a double array list where the second value is occurrence of the first value.
int[][] a = new int[n.length][2];
for(int i = 0; i < n.length; i++){
int count = Collections.frequency(asList(n), n[i]);
a[i][0] = n[i];
a[i][1] = count;
}
// printer helper function
for(int i = 0; i < n.length; i++){
System.out.print(a[i][0] + " occurs ");
System.out.println(a[i][1] + " times");
}
return a;
}
public static List<Integer> asList(final int[] is)
{
return new AbstractList<Integer>() {
public Integer get(int i) { return is[i]; }
public int size() { return is.length; }
};
}
public static void main(String[] args) {
int[] testArray = {1, 2, 3, 1, 2, 3, 4};
System.out.print(howMany(testArray));
}
}

Related

Rotate and return the ArrayList<Integer> in java

here in below program i am defining ArrayList of size 7 [1,2,3,4,5,6,7] and and rotating right by 3 places but when i print the numbers1 list it gives me my expected answer numbers: [5, 6, 7, 1, 2, 3, 4] but when i return this ArrayList and then print it, it gives me this answer numbers: [2, 3, 4, 5, 6, 7, 1] why is that please explain.
package QAIntvSprint;
import java.util.ArrayList;
import java.util.Scanner;
public class RotateArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
ArrayList<Integer> numbers = new ArrayList<>();
for (int i = 0; i < n; i++) {
numbers.add(sc.nextInt());
}
rotateArray(numbers, k);
ArrayList<Integer> ans = rotateArray(numbers, k);
for (Integer x : ans) {
System.out.print(x + " ");
}
}
static ArrayList<Integer> rotateArray(ArrayList<Integer> numbers, int k) {
for (int i = 0; i < k; i++) {
numbers.add(0, numbers.get(numbers.size() - 1));
numbers.remove(numbers.size() - 1);
}
ArrayList<Integer> numbers1 = numbers;
System.out.println("numbers: " + numbers1.toString());
return numbers1;
}
}
output
You are running your function twice:
rotateArray(numbers, k); // first
ArrayList<Integer> ans = rotateArray(numbers, k); // second
So the numbers are shifted by 6 instead of 3 positions
Besides, your function does not create a new copy of the array
You return a reference to the same array
ArrayList<Integer> numbers1 = numbers; // copies a reference to an object, not the object itself
return numbers1; // returns the original link
So i suggest refactoring your code like this:
public class RotateArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
ArrayList<Integer> numbers = new ArrayList<>();
for (int i = 0; i < n; i++) {
numbers.add(sc.nextInt());
}
// the function will modify the ArrayList by reference, it will change
rotateArray(numbers, k);
for (Integer x : numbers) {
System.out.print(x + " ");
}
}
static void rotateArray(ArrayList<Integer> numbers, int k) {
for (int i = 0; i < k; i++) {
numbers.add(0, numbers.get(numbers.size() - 1));
numbers.remove(numbers.size() - 1);
}
}
}
That's because your function rotateArray changes your numbers ArrayList you give it as parameter. So basically it changes the List (numbers) in your main method. And because you call the method two times, the array gets rotated in sum 6 times (like you see in your final output)
If you don't want to change the ArrayList you give in as a parameter, you should do something like
ArrayList<Integer> newList = new ArrayList(numbers);
as first in you rotateArray method and then rotate this list.
here
ArrayList<Integer> ans = rotateArray(numbers, k);
rotates
numbers, returned by the previous line
Delete
rotateArray(numbers, k);

Method that takes an integer input n and rotates an array n spaces

The my goal is to take a user's input and rotate the array however many times based off of their integer input. At first I was trying to get the array to reverse just to see it shift but I have a few errors in my function that won't let me compile.
Edit: I know I used list instead of using arr. I was looking at an example and accidentally typed it in.
Here is my code:
import java.util.Scanner;
public class Project1P2 {
public static void main(String[] args) {
int[] arr1 = {2,4,6,8,10,12};
int[] arr2 = shift(arr1);
Scanner input = new Scanner(System.in);
System.out.print("Here is the Array: " + arr1);
System.out.println("Enter a number to shift array: ");
int n = input.nextInt();
}
public static int[] shift(int[] arr) {
int[] arrShiftDone = new int[list.length];
for (int i = 0, j = arrShiftDone.length - 1; i < list.length; i++, j--) {
arrShiftDone[j] = list[i];
}
return arrShiftDone;
}
}
You need to fix a couple of things:
shift method never gets called from the main method, which means it won't do anything to the array
shift method should have another argument for the number of places to shift, say n
In shift method, you are using list whereas the argument is declared as arr
Below is an example method that shifts the array:
public static int[] shift(int[] arr, int n) {
if(n > arr.length)
n = n%arr.length;
int[] result = new int[arr.length];
for(int i=0; i < n; i++){
result[i] = arr[arr.length-n+i];
}
int j=0;
for(int i=n; i<arr.length; i++){
result[i] = arr[j];
j++;
}
return result;
}
The compilation error is because the variable list is unknown. Should be using the argument arr instead of list inside the method shift(int[] arr).
You can use Arrays.stream(int[],int,int) method twice to get two streams with the specified ranges of the array: near and far, then swap them and concat back into one stream, and thus get a shifted array:
public static int[] shiftArray(int[] arr, int n) {
return IntStream
.concat(Arrays.stream(arr, n, arr.length),
Arrays.stream(arr, 0, n))
.toArray();
}
public static void main(String[] args) {
int[] arr1 = {2, 4, 6, 8, 10, 12};
System.out.println("Source array: " + Arrays.toString(arr1));
System.out.println("Enter a number: ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] arr2 = shiftArray(arr1, n % arr1.length);
System.out.println("Shifted array: " + Arrays.toString(arr2));
}
Output:
Source array: [2, 4, 6, 8, 10, 12]
Enter a number:
3
Shifted array: [8, 10, 12, 2, 4, 6]
See also: Place positive numbers before negative
Your mistake is that in your shift method you are using list, it should be arr. I have updated it below. I have also included the shift method.
Edited to include negative shifts.
public static void main(String[] args) {
int[] arr1 = {2, 4, 6, 8, 10, 12};
int[] arr2 = reverseArray(arr1);
Scanner input = new Scanner(System.in);
System.out.println("Here is the Array: " + Arrays.toString(arr1));
System.out.print("Enter a number to shift array: ");
int n = input.nextInt();
int[] arr3 = shiftArray(arr1, n);
System.out.println("Here is the shifted Array: " + Arrays.toString(arr3));
}
public static int[] reverseArray(int[] arr) {
int[] arrShiftDone = new int[arr.length];
for (int i = 0, j = arrShiftDone.length - 1; i < arr.length; i++, j--) {
arrShiftDone[j] = arr[i];
}
return arrShiftDone;
}
public static int[] shiftArray(int[] arr, int shift) {
int[] arrShiftDone = new int[arr.length];
shift = shift % arr.length;
if (shift < 0) {
shift = arr.length + shift;
}
for (int i = 0 + shift, j = 0; j < arr.length; i++, j++) {
if (i >= arr.length) {
arrShiftDone[j] = arr[i - arr.length];
} else {
arrShiftDone[j] = arr[i];
}
}
return arrShiftDone;
}

Two Sum LeetCode Java Questions

I am attempting a Java mock interview on LeetCode. I have the following problem:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
I was attempting to implement a recursive solution. However, I am receiving errors upon trying to run my code.
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] sumnums = nums.clone();
//int[2] sol = {0,1};
int[] sol = new int[]{0,1};
sol = new int[2];
int j=sumnums.length;
int t=target;
for(int i=0;i<sumnums.length;i++){
if ((sumnums[i]+sumnums[j])==t){
sol[0]=i;
sol[1]=j;
//return sol;
}
}
j=j-1;
twoSum(sumnums,t);
return sol;
}
}
Error(s):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Solution.twoSum(Solution.java:12)
at __DriverSolution__.__helper__(__Driver__.java:8)
at __Driver__.main(__Driver__.java:54)
It appears to me the error may have to do with the following line of code:
if ((sumnums[i]+sumnums[j])==t){
Therefore, I am wondering if this is a syntax related error. I am attempting to check to see if two numbers add up to a different number.
Since this is a naive attempt at a recursive solution, I am happy to take any other criticism. But I am mostly concerned with getting my attempt at this problem to work and run with all testcases.
Thanks.
METHOD 1. Naive approach: Use two for loops
The naive approach is to just use two nested for loops and check if the sum of any two elements in the array is equal to the given target.
Time complexity: O(n^2)
// Time complexity: O(n^2)
private static int[] findTwoSum_BruteForce(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
return new int[] {};
}
METHOD 2. Use a HashMap (Most efficient)
You can use a HashMap to solve the problem in O(n) time complexity. Here are the steps:
Initialize an empty HashMap.
Iterate over the elements of the array.
For every element in the array -
If the element exists in the Map, then check if it’s the complement (target - element) also exists in the Map or not. If the complement exists then return the indices of the current element and the complement.
Otherwise, put the element in the Map, and move to the next iteration.
Time complexity: O(n)
// Time complexity: O(n)
private static int[] findTwoSum(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (numMap.containsKey(complement)) {
return new int[] { numMap.get(complement), i };
} else {
numMap.put(nums[i], i);
}
}
return new int[] {};
}
METHOD 3. Use Sorting along with the two-pointer sliding window approach
There is another approach which works when you need to return the numbers instead of their indexes. Here is how it works:
Sort the array.
Initialize two variables, one pointing to the beginning of the array (left) and another pointing to the end of the array (right).
Loop until left < right, and for each iteration
if arr[left] + arr[right] == target, then return the indices.
if arr[left] + arr[right] < target, increment the left index.
else, decrement the right index.
This approach is called the two-pointer sliding window approach. It is a very common pattern for solving array related problems.
Time complexity: O(n*log(n))
// Time complexity: O(n*log(n))
private static int[] findTwoSum_Sorting(int[] nums, int target) {
Arrays.sort(nums);
int left = 0;
int right = nums.length - 1;
while(left < right) {
if(nums[left] + nums[right] == target) {
return new int[] {nums[left], nums[right]};
} else if (nums[left] + nums[right] < target) {
left++;
} else {
right--;
}
}
return new int[] {};
}
Why not use a HashMap? Here is how it will work. We will iterate through the array and check if the target - nums[i] exists in the map. If not, we will store Key, Value as the number and its index respectively i.e K = nums[i], V = i
Here is how it will work:
Consider nums = [2, 7, 11, 15], target = 9
We will start iterating the array
First comes 2. Here we will check ( 9 - 2 ) i.e 7 does not exist in the hashmap, so we will store 2 as key and its index 0 as its value
Then, comes 7. Here we will check ( 9 - 7 ) i.e 2 which exists in the map and so we will return the index of 2 and index of 7 i.e returning [ 0, 1 ]
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++)
{
if(map.containsKey(target - nums[i]))
{
return new int[] {map.get(target-nums[i]),i};
}
else
map.put(nums[i],i);
}
return new int[] {-1,-1};
}
As you mentioned
First comes 2. Here we will check ( 9 - 2 ) i.e 7 does not exist in the hashmap
actually 7 does exist in the HashMap right
nums = [2, 7, 11, 15], target = 9
public static int[] twoSum(int[] nums, int target) {
int[] sumnums = nums.clone();
//int[2] sol = {0,1};
int[] sol = new int[]{0,1};
sol = new int[2];
int j=sumnums.length; // Every recursion j will be initialized as sumnums.length instead of J-1
int t=target;
for(int i=0;i<sumnums.length;i++){
// if ((sumnums[i]+sumnums[j])==t){
// Remember that Java arrays start at index 0, so this value(sumnums[j]) is not exist in the array.
if ((sumnums[i]+sumnums[j-1])==t){
sol[0]=i;
sol[1]=j;
return sol;
}
}
j=j-1;
twoSum(sumnums,t);
return sol;
}
One of the many possible solutions:
public class TwoSumIndex {
public static void main(String... args) {
int[] arr = {2, 7, 11, 15, 9, 0, 2, 7};
System.out.println(findTwoSums(arr, 9));
}
private static List<List<Integer>> findTwoSums(int[] arr, int target) {
Set<Integer> theSet = Arrays.stream(arr).mapToObj(Integer::valueOf).collect(Collectors.toSet());
List<Integer> arrList = Arrays.stream(arr).mapToObj(Integer::valueOf).collect(Collectors.toList());
List<Pair<Integer, Integer>> theList = new ArrayList<>();
List<Integer> added = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
int a = target - arr[i];
if (theSet.contains(a) && added.indexOf(i) < 0) { // avoid duplicates;
Integer theOther = arrList.indexOf(a);
theList.add(new Pair(i, theOther));
added.add(i);
added.add(theOther);
}
}
return theList.stream().map(pair -> new ArrayList<>(Arrays.asList(pair.getKey(), pair.getValue())))
.collect(Collectors.toList());
}
}
There are several things you need to know:
duplicates in the input array are allowed;
un-ordered array in the input is allowed;
no index pair duplicate in the output;
time complexity is theoretically O(N^2) but actually will be much lower since theSet.contains(a) O(logN) will filter out all failed indexes and then do the index duplicate O(N) checking, so the actual time complexity should be O(NlogN);
The output for the demo:
[[0, 1], [4, 5], [6, 1], [7, 0]]
I use the simpler approch
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices= new int[2];
int len=nums.length;
for(int i=0; i<len; i++){
for(int j=i+1; j<len;j++){
if((nums[i]+nums[j])==target){
indices[0] = i;
indices[1] = j;
return indices;
}
}
}
return null;
}
}
Complete code for beginners
//Predefined values
import java.util.Arrays;
public class TwoSum {
public static void main(String args[]) {
Solution solution = new Solution();
int target = 9;
int num[] = {2, 7, 11, 15};
num = solution.twoSum(num, target);
System.out.println(Arrays.toString(num));
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int result[] = new int[2];
int sum;
for (int i = 0; i + 1 < nums.length; i++) {
// adding the alternate numbers
sum = nums[i] + nums[i + 1];
if (sum == target) {
result[0] = i;
result[1] = i + 1;
return result;
}
}
return null;
}
}
************************************************************************
//User-defined
import java.util.Arrays;
import java.util.Scanner;
/**
*
* #author shelc
*/
public class TwoSum {
public static void main(String[] args) {
Solution solution = new Solution();
Scanner scanner = new Scanner(System.in);
int n;
System.out.print("Enter the number of elements : ");
n = scanner.nextInt();
int array[] = new int[10];
System.out.println("Enter the array elemets : ");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
int target;
System.out.println("Enter the target : ");
target = scanner.nextInt();
int nums[] = solution.twoSum(array, target);
System.out.println(Arrays.toString(nums));
}
}
class Solution {
public int[] twoSum(int nums[], int target) {
int result[] = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if ((nums[i] + nums[j]) == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return null;
}
}
public static int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];
int arrIndex =0;
for(int i =0; i<nums.length; i++){
for(int j = 0;j<nums.length-1;j++){
if( i!=j) {// don't check to itself
if (nums[i] + nums[j] == target) {
arr[arrIndex] = i;
arr[arrIndex + 1] = j;
break;
}
}
}
}
Arrays.sort(arr);
return arr;
}

Method that creates new array only from the even numbers in Java

I am trying to create method that creates new array only from the even numbers from another array. However, I do not understand why I have the right length (only with the number of the even numbers) of my output array, but I have 0s instead of the actual numbers.
I know that the problem is simple, but right now I am stuck with it.
import java.util.*;
public class test{
public static int [] myMethod(int []arr){
int [] temp;
int howManyEven = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]%2==0){
howManyEven++;
}
}
temp = new int [howManyEven];
int evenNum = 0;
for(int i=0;i<temp.length;i++){
boolean even = false;
for(int j=0;j<arr.length;j++){
if(arr[j]%2==0){
even = true;
evenNum = arr[j];
}
}
if(!even){
temp[i]=evenNum;
}
}
return temp;
}
public static void main (String[]args){
int [] myArray = {5,5,8,9,7,4,4,2,3};
System.out.println(Arrays.toString(myMethod(myArray)));
}
}
In the second part of your myMethod, where there is nested for loop, your outer loop should iterate over arr. It can be simplified to below
temp = new int [howManyEven];
int j = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]%2 == 0) {
temp[j++] = arr[i];
}
}
Better you can use java collections and finish the work in single loop
public static Integer[] myMethod(int []arr){ //notice the return type is Integer[] instead of int[]
List<Integer> evens = new ArrayList<Integer>();
for(int a : arr) {
if(a%2 == 0) {
evens.add(a);
}
}
return evens.toArray(new Integer[evens.size()]);
}
Look again at this:
if(!even){
temp[i]=evenNum;
}
I think you will notice yourself what's wrong.
Instead of processing the information twice for even numbers, you can create a List of integers which are 'even' and return that, or convert into primitive int[] and return that.
public static int[] myMethod(int[] arr) {
List<Integer> even = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==0){
even.add(arr[i]);
}
}
int []result = new int[even.toArray().length];
Iterator it = even.iterator();
int count=0;
while(it.hasNext()){
result[count++]=(int)it.next();
}
return result;
}
public static void main(String[] args) {
int[] myArray = {5, 5, 8, 9, 7, 4, 4, 2, 3};
System.out.println(Arrays.toString(myMethod(myArray)));
}
output
run:
[8, 4, 4, 2]
BUILD SUCCESSFUL (total time: 0 seconds)
The easiest way would be myMethod should create a temparory list which collects the even numbers from the input array and then convert it to an output array containing only the even elements which should be returned to the caller
Working Example
public static void main(String... str) {
// results array has only even numbers
Integer[] results = myMethod(new int[]{5, 5, 8, 9, 7, 4, 4, 2, 3});
for(int i=0;i<results.length;i++)
System.out.println(results[i]); // print each even number
}
static Integer[] myMethod(int[] inputArray) {
List<Integer> temp = new ArrayList<Integer>();
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] % 2 == 0) {
temp.add(inputArray[i]);
}
}
return temp.toArray(new Integer[5]);
}
Hope this code clarifies you well.

Sort one dimensional array into two dimensional

private double[] myNumbers = {10, 2, 5, 3, 6, 4};
private double[][] result;
private double[][] divideNumbers(double[] derp) {
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
//System.out.println(result[0] +" "+ result[1]);
return result;
}
I'm trying to sort the one dimensional array in to a matrix, where numbers between 4 - 8 are in one, and all other numbers are in the other.
1) You're not initializing result[][]. You will get a NullPointerException.
Either loop through myNumbers, count the number of values for each category, and create result[][], or push your values into an ArrayList<Double>[2] and use List.toArray() to convert back to an array.
2) result[][] is declared outside your method. While technically valid, it's generally poor form if there is not a specific reason for doing so. Since you're already returning double[][] you might want to declare a double[][] inside your function to work with and return.
I'm not following exactly what you want, but this should allow your code to work.
class OneDimToTwoDim {
public static void main(String[] args) {
// declare myNumbers one dimensional array
double[] myNumbers = {10, 2, 5, 3, 6, 4};
// display two dimensional array
for (int x = 0; x < myNumbers.length; x++) {
System.out.print("[" + myNumbers[x] + "] "); // Display the string.
}
// pass in myNumbers argument for derp parameter, and return a two dimensional array called resultNumbers
double[][] resultNumbers = OneDimToTwoDim.divideNumbers(myNumbers);
System.out.println(); // Display the string.
System.out.println(); // Display the string.
for (int x = 0; x < resultNumbers.length; x++) {
for (int y = 0; y < resultNumbers[x].length; y++) {
System.out.print("[" + resultNumbers[x][y] + "] "); // Display the string.
}
System.out.println(); // Display the string.
}
}
private static double[][] divideNumbers(double[] derp) {
// declare result to be returned
double[][] result = new double[2][derp.length];
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
return result;
}
}
Your result array isn't initialized. Are you getting null pointer exceptions? Is that the problem?
private static double[] myNumbers = {10, 2, 5, 3, 6, 4};
private static double[][] result = new double[2][myNumbers.length];
private static double[][] divideNumbers(double[] derp) {
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
result[0] = Arrays.copyOfRange(result[0],0,k);
result[1] = Arrays.copyOfRange(result[1],0,j);
return result;
}

Categories

Resources