Sort one dimensional array into two dimensional - java

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;
}

Related

Compare and count in two arrays not in same order - Java

I need to count how many of the same digits are in the code vs. guess.
If code = [1, 2, 5, 6] and guess = [4, 1, 3, 2], it should return 2.
I can't directly change the parameter arrays, so I first created new arrays, sorted, then looped through to find how many are the same in both. The issue is that it returns 4 no matter what.
public static int digits(int[] code, int[] guess) {
int[] sortedCode = new int[code.length];
int[] sortedGuess = new int[guess.length];
int digits = 0;
for (int i = 0; i < code.length; i++) {
sortedCode[i] = code[i];
sortedGuess[i] = guess[i];
}
Arrays.sort(sortedCode);
Arrays.sort(sortedGuess);
for (int i = 0; i < code.length; i++) {
if (sortedGuess[i] == sortedCode[i]) {
digits++;
}
}
return digits;
As #Icarus mentioned in the comments, "you're comparing index to index when you should compare index to every index".
public static int getCorrectDigits(int[] code, int[] guess) {
int correctDigits = 0;
if (code.length != guess.length) {
throw new IllegalArgumentException("Different lengths");
}
for (int x = 0; x<code.length; x++){
for (int y = 0; y<guess.length; y++){
if (code[x] == guess[y]){
correctDigits++;
}
}
}
return correctDigits;
}
You can also convert the traditional for loop to an enhanced for loop.
for (int j : code) {
for (int i : guess) {
if (j == i) {
correctDigits++;
}
}
}

Java how to copy values from 2D array to regular array row by row

I have the 2D array and printed them out backward. What I am trying to achieve is to copy each line of printed row to a regular array. Is it possible to do that?
Integer[][] testList;
testList = new Integer[][]{{1,2,3},{4,5,6},{7,8,9}, {10,11,12}};
for (int i = 0; i < testList.length; i++) {
for (int j = testList[i].length-1; j >=0; j--) {
System.out.print(testList[i][j] + " ");
}
System.out.println();
}
This will copy any size 2D array of ints.
int[][] testData = { { 1, 2, 3 },{}, null, { 4, 5, 6, 7 },null,{ 8, 9 },
{ 10, 11, 12 } };
int[] result = copy2DArrays(testData);
System.out.println(Arrays.toString(result));
prints
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
First, compute size of result array. This also handles null rows.
if a null row is encountered, replace with an empty array for copy phase.
Allocate the return array of computed size
Then for each row
iterate thru the row, copying the value to result array indexed by k
When done, return the resultant array.
public static int[] copy2DArrays(int[][] array) {
int size = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
// replace null row with empty one
array[i] = new int[]{};
continue;
}
size += array[i].length;
}
int k = 0;
int[] result = new int[size];
for (int[] row : array) {
for (int v : row) {
result[k++] = v;
}
}
return result;
}
Another, simpler option is using streams.
stream the "2D" array
only pass nonNull rows
flatten each row into a single stream
then gather them into an array.
int[] array = Arrays.stream(testData)
.filter(Objects::nonNull)
.flatMapToInt(Arrays::stream)
.toArray();
You can create a new array and then copy the values into it:
for (int i = 0; i < testList.length; i++) {
int[] copy = new int[testList[i].length];
int copyIndex = 0;
for (int j = testList[i].length-1; j >=0; j--) {
System.out.print(testList[i][j] + " ");
copy[copyIndex++] = testList[i][j];
}
}
The Arrays class gives you a lot of nifty features:
public static void main(String[] args) {
Integer[][] testList = new Integer[][]{{1,2,3},{4,5,6},{7,8,9}, {10,11,12}};
int max = 0;
for (Integer[] row : testList) {
max = Math.max(max, row.length);
}
Integer[][] copy = new Integer[testList.length][max];
for (int i = 0; i < testList.length; i++) {
copy[i] = Arrays.copyOf(testList[i], copy[i].length);
}
for (int i = 0; i < testList.length; i++) {
System.out.println("Source " + i + ": " + Arrays.toString(testList[i]));
System.out.println("Copy " + i + ": " + Arrays.toString(copy[i]));
}
}

Java sorting program, getting a confusing output

public static void main(String[] args) throws Exception {
// declarations
int i, z, x, greatest;
int[] array = { 2, 3, 4, 55, 6 };
int[] copyarray = { 0, 0, 0, 0, 0 };
int zz;
greatest = array[0];
for (zz = 0; zz < 5; zz++) {
for (x = 0; x < 5; x++) {
if (array[x] > greatest) {
greatest = array[x];
}
}
copyarray[zz] = greatest; // this will contain the sorted array
// part of the nested loop
for (z = 0; z < 5; z++) {
if (greatest == array[z]) {
array[z] = 0;
}
}
}
// not part of the nested loop
for (i = 0; i < 5; i++) {
System.out.println("sorted array: " + copyarray);
}
}
Output:
sorted array: [I#1a16869
sorted array: [I#1a16869
sorted array: [I#1a16869
sorted array: [I#1a16869
sorted array: [I#1a16869
This is just a basic little program and I'm trying to get the logic right. I can't improve it or make it into a class or method because I'm not even getting the output right.
If you are trying to use your own algorithm, i would suggest you try using IDE and debug the code.
If you want to use algorithm that JDK provides, you could use:
Arrays.sort(array);
Regarding the output, you are trying to print array and array is an object without toString implementation in java. Hence you should change your print statement to :
System.out.println("sorted array: "+Arrays.toString(copyarray));//without surrounding for loop to get what its after each step of sorting elements.
Or if you want to keep your for loop then you could use index based access to array like:
System.out.print(copyarray[i] + " ");
Actually, none of the answers here are right.
The heart of the problem is that you are not re-initializing the variable greatest for each iteration. It is set to array[0]; in the beginning and it is never changed again. This should go inside the loop.
public static void main(String[] args) throws Exception {
// declarations
int i, z, x, greatest;
int[] array = { 2, 3, 4, 55, 6 };
int[] copyarray = { 0, 0, 0, 0, 0 };
int zz;
// greatest = array[0]; <---- Don't do it here
for (zz = 0; zz < 5; zz++) {
greatest = array[0]; // <--- Initialize greatest here and not before the loop
for (x = 0; x < 5; x++) {
if (array[x] > greatest) {
greatest = array[x];
}
}
copyarray[zz] = greatest; // this will contain the sorted array
// part of the nested loop
for (z = 0; z < 5; z++) {
if (greatest == array[z]) {
array[z] = 0;
}
}
}
// not part of the nested loop
for (i = 0; i < 5; i++) {
System.out.println("sorted array: " + copyarray[i]);
}
}
As a side note, you are printing the array incorrectly, you should use copyarray[i] and not copyarray.
Whit these two changes, here's the output:
sorted array: 55
sorted array: 6
sorted array: 4
sorted array: 3
sorted array: 2
You are printing the reference not the value
use:
for(int i = 0; i < copyarray.length; i++ ) {
System.out.println("Value : " + copyarray[i]);
}
i would also recommend using Arrays.sort(array);
just write
private int[] values = { 9,2,5,3,1,7,0 };
public void printSorted() {
Arrays.sort(values);
for(int i = 0; i < values.length; i++) {
System.out.println("Value: " + values[i]);
}
}

Issue in incrementing index in array

Question:
You have an array of positive and negative integers, print all subsetsum which is equal to zero.
I have implemented only a simple test case here and the exception I get is ArrayIndexOutOfBoundsException.
Please help why the value is not incremented.
package app;
public class Array1
{
public static void subset(int p[])
{
int u = 0;
int s[] = new int[p.length];
if (p[0] < 0)
for (int i=0;i<p.length;i++)
{
for (int j = 0; j < p.length; j++) {
int k = p[i] + p[j];
if (k == 0)
{
System.out.println(p[i]);
System.out.println(p[j]);
s[u] = p[i];
u++; // Why u value is not incremented?
System.out.println(s[u]);
s[u] = p[j];
u++; // Why u value is not incremented?
System.out.println(s[u]);
}
}
}
for(int i = 0; i < s.length; i++)
System.out.println(s[i]);
}
public static void main(String s[])
{
subset(new int[] {-1, -2, -3, -4, 4, 3, 2, 1});
}
}
The problem is, int s[]=new int[p.length]; as the number of pairs can be more that (input array length itself) is the reason you get ArrayIndexOutOfBoundsException.
You can use a dynamic list for this purpose:
List<Integer> s = new ArrayList<Integer>();
// s.add(<elem>); // no need for variable u - increment :)

How to remove duplicates from a list using an auxiliary array in Java?

I am trying to remove duplicates from a list by creating a temporary array that stores the indices of where the duplicates are, and then copies off the original array into another temporary array while comparing the indices to the indices I have stored in my first temporary array.
public void removeDuplicates()
{
double tempa [] = new double [items.length];
int counter = 0;
for ( int i = 0; i< numItems ; i++)
{
for(int j = i + 1; j < numItems; j++)
{
if(items[i] ==items[j])
{
tempa[counter] = j;
counter++;
}
}
}
double tempb [] = new double [ items.length];
int counter2 = 0;
int j =0;
for(int i = 0; i < numItems; i++)
{
if(i != tempa[j])
{
tempb[counter2] = items[i];
counter2++;
}
else
{
j++;
}
}
items = tempb;
numItems = counter2;
}
and while the logic seems right, my compiler is giving me an arrayindexoutofbounds error at
tempa[counter] = j;
I don't understand how counter could grow to above the value of items.length, where is the logic flaw?
You are making things quite difficult for yourself. Let Java do the heavy lifting for you. For example LinkedHashSet gives you uniqueness and retains insertion order. It will also be more efficient than comparing every value with every other value.
double [] input = {1,2,3,3,4,4};
Set<Double> tmp = new LinkedHashSet<Double>();
for (Double each : input) {
tmp.add(each);
}
double [] output = new double[tmp.size()];
int i = 0;
for (Double each : tmp) {
output[i++] = each;
}
System.out.println(Arrays.toString(output));
Done for int arrays, but easily coud be converted to double.
1) If you do not care about initial array elements order:
private static int[] withoutDuplicates(int[] a) {
Arrays.sort(a);
int hi = a.length - 1;
int[] result = new int[a.length];
int j = 0;
for (int i = 0; i < hi; i++) {
if (a[i] == a[i+1]) {
continue;
}
result[j] = a[i];
j++;
}
result[j++] = a[hi];
return Arrays.copyOf(result, j);
}
2) if you care about initial array elements order:
private static int[] withoutDuplicates2(int[] a) {
HashSet<Integer> keys = new HashSet<Integer>();
int[] result = new int[a.length];
int j = 0;
for (int i = 0 ; i < a.length; i++) {
if (keys.add(a[i])) {
result[j] = a[i];
j++;
}
}
return Arrays.copyOf(result, j);
}
3) If you do not care about initial array elements order:
private static Object[] withoutDuplicates3(int[] a) {
HashSet<Integer> keys = new HashSet<Integer>();
for (int value : a) {
keys.add(value);
}
return keys.toArray();
}
Imagine this was your input data:
Index: 0, 1, 2, 3, 4, 5, 6, 7, 8
Value: 1, 2, 3, 3, 3, 3, 3, 3, 3
Then according to your algorithm, tempa would need to be:
Index: 0, 1, 2, 3, 4, 5, 6, 7, 8, ....Exception!!!
Value: 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 5, 6, 7, 8, 6, 7, 8, 7, 8, 8
Why do you have this problem? Because the first set of nested for loops does nothing to prevent you from trying to insert duplicates of the duplicate array indices!
What is the best solution?
Use a Set!
Sets guarantee that there are no duplicate entries in them. If you create a new Set and then add all of your array items to it, the Set will prune the duplicates. Then it is just a matter of going back from the Set to an array.
Alternatively, here is a very C-way of doing the same thing:
//duplicates will be a truth table indicating which indices are duplicates.
//initially all values are set to false
boolean duplicates[] = new boolean[items.length];
for ( int i = 0; i< numItems ; i++) {
if (!duplicates[i]) { //if i is not a known duplicate
for(int j = i + 1; j < numItems; j++) {
if(items[i] ==items[j]) {
duplicates[j] = true; //mark j as a known duplicate
}
}
}
}
I leave it to you to figure out how to finish.
import java.util.HashSet;
import sun.security.util.Length;
public class arrayduplication {
public static void main(String[] args) {
int arr[]={1,5,1,2,5,2,10};
TreeSet< Integer>set=new TreeSet<Integer>();
for(int i=0;i<arr.length;i++){
set.add(Integer.valueOf(arr[i]));
}
System.out.println(set);
}
}
You have already used num_items to bound your loop. Use that variable to set your array size for tempa also.
double tempa [] = new double [num_items];
Instead of doing it in array, you can simply use java.util.Set.
Here an example:
public static void main(String[] args)
{
Double[] values = new Double[]{ 1.0, 2.0, 2.0, 2.0, 3.0, 10.0, 10.0 };
Set<Double> singleValues = new HashSet<Double>();
for (Double value : values)
{
singleValues.add(value);
}
System.out.println("singleValues: "+singleValues);
// now convert it into double array
Double[] dValues = singleValues.toArray(new Double[]{});
}
Here's another alternative without the use of sets, only primitive types:
public static double [] removeDuplicates(double arr[]) {
double [] tempa = new double[arr.length];
int uniqueCount = 0;
for (int i=0;i<arr.length;i++) {
boolean unique = true;
for (int j=0;j<uniqueCount && unique;j++) {
if (arr[i] == tempa[j]) {
unique = false;
}
}
if (unique) {
tempa[uniqueCount++] = arr[i];
}
}
return Arrays.copyOf(tempa, uniqueCount);
}
It does require a temporary array of double objects on the way towards getting your actual result.
You can use a set for removing multiples.

Categories

Resources