From a linked list to an array (Function) - java

I'm trying to give a function a list and make an array which contains the value of the nodes of the list (Not complicated). There it is:
public class MainClass {
public static int[] makeListIntoArray(Node<Integer> n) {
int[] arr1 = new int [countSizeOfList(n)];
for(int i = 0; i < countSizeOfList(n); i++) {
arr1[i] = n.getValue();
n = n.getNext();
}
return arr1;
}//EndOfFunction
public static int[] finalFunction2(Node<Integer> n) {
if(n == null) return ifListIsEmpty(n);
return makeListIntoArray(n);
}
public static int[] ifListIsEmpty(Node<Integer> n) {
Node<Integer> n2 = new Node<Integer>(999);
int[] arr1 = new int [countSizeOfList(n2)];
int i = 0;
arr1[i] = n2.getValue();
return arr1;
}
public static void main(String[] args) {
Node<Integer> n1 = new Node<Integer>(5);
Node<Integer> n2 = new Node<Integer>(4);
Node<Integer> n3 = new Node<Integer>(3);
Node<Integer> n4 = new Node<Integer>(5);
Node<Integer> n5 = new Node<Integer>(1);
n1.setNext(n2);
n2.setNext(n3);
n3.setNext(n4);
n4.setNext(n5);
System.out.println(finalFunction2(n1));
}//Main
}//Class
Thing is that it prints "[I#7960847b" beside of the actual array... fixes?
Any fixes?

If you want to insert a value into array then there should be an index especially a static one. You cannot simply assign it to arr1 like your do for primitive types.
For example, arr1[0] = n.getValue() is valid but not arr1 = n.getValue();
public static int[] makeListIntoArray(Node<Integer> n) {
int[] arr1 = new int [countSizeOfList(n)];
int idx=0;
while(n != null) {
arr1[idx++] = n.getValue();
n = n.getNext();
}
return arr1;
}//EndOfFunction

If you're using Java's built-in LinkedList data structure you can simply use the following to convert from LinkedList to array:
Integer[] array = list.toArray(new Integer[list.size()]);
So for the situation you're describing all you would need for the function is:
import java.util.LinkedList;
public class MainClass {
public static int[] makeListIntoArray(LinkedList<Integer> list) {
Integer[] arr = list.toArray(new Integer[list.size()]);
int[] intArr = Arrays.stream(array).mapToInt(Integer::intValue).toArray();
// Above line converts the wrapper Integer[] to int[] if you need that
return intArr;
}
}
You can find more info about LinkedList's toArray() method here.

If you want to keep the linked list but also want to access the elements in O(1), you can create an array of Nodes.
public class MainClass {
public static Node<Integer>[] makeListIntoArray(Node<Integer> n) {
Node<Integer>[] arr1 = new Node<Integer> [countSizeOfList(n)];
int i=0;
while(n != null) {
arr1[i] = n;
n = n.getNext();
++i;
}
return arr1;
}//EndOfFunction
}//Class

Related

Can't figure out how to return an array

Find all pairs with a given sum
Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class pair {
long first, second;
public pair(long first, long second)
{
this.first = first;
this.second = second;
}
}
class GFG {
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while(t-->0)
{
StringTokenizer stt = new StringTokenizer(br.readLine());
long N = Long.parseLong(stt.nextToken());
long M = Long.parseLong(stt.nextToken());
long X = Long.parseLong(stt.nextToken());
long A[] = new long[(int)(N)];
long B[] = new long[(int)(M)];
String inputLine[] = br.readLine().trim().split(" ");
for (int i = 0; i < N; i++) {
A[i] = Long.parseLong(inputLine[i]);
}
String inputLine1[] = br.readLine().trim().split(" ");
for (int i = 0; i < M; i++) {
B[i] = Long.parseLong(inputLine1[i]);
}
Solution obj = new Solution();
pair [] answer = obj.allPairs(A, B, N, M, X);
int sz = answer.length;
if(sz==0)
System.out.println(-1);
else{
StringBuilder output = new StringBuilder();
for(int i=0;i<sz;i++){
if(i<sz-1)
output.append(answer[i].first +" "+ answer[i].second + ", ");
else
output.append(answer[i].first +" "+ answer[i].second);
}
System.out.println(output);
}
}
}
}
// } Driver Code Ends
//User function Template for Java
/*
class pair {
long first, second;
public pair(long first, long second)
{
this.first = first;
this.second = second;
}
}
*/
class Solution {
public pair[] allPairs( long A[], long B[], long N, long M, long X) {
//MY CODE STARTS FROM HERE
ArrayList<Long> list = new ArrayList<>();
HashSet<Long> set = new HashSet<>();
for(long i : A){
set.add(i);
}
for(int i=0;i<M;i++){
if(set.contains(X-B[i])){
list.add(X-B[i]);
list.add(B[i]);
}
}
long arr[] = new long[list.size()];
for(int i=0;i<arr.length;i++){
arr[i] = list.get(i);
}
return arr;
}
}
I am getting this error:
prog.java:101: error: incompatible types: long[] cannot be converted to pair[]
return arr;
^
1 error
How can I correctly return the answer?
Before I get into the answer, it is very important to use descriptive variable names when writing your code. They might make sense to you, but people like me who aren't you, and possible even you in the future, have a hard time understanding what A, B, M, N, etc mean.
The reason you are getting this error is because your function allPairs() has a return type of pair[], but you're trying to return long[]. It's a bit hard to understand what you're trying to do because of your variable names, but it seems like when you find a result that you desire you are adding the first and second results separately into an array of longs, which also undermines the point of your pair class. Here's an idea of what it should probably look like instead:
class Solution {
public pair[] allPairs( long A[], long B[], long N, long M, long X) {
//MY CODE STARTS FROM HERE
ArrayList<pair> list = new ArrayList<>();
HashSet<Long> set = new HashSet<>();
for(long i : A){
set.add(i);
}
for(int i=0;i<M;i++){
if(set.contains(X-B[i])){
list.add(new pair(X-B[i], B[i]));
}
}
pair arr[] = new pair[list.size()];
arr = list.toArray(arr);
return list.toArray();
}
}
in your define method return type is pairs, but actually return a long[], it must be compile error
you should modify the Solution as follow
class Solution {
public pair[] allPairs( long A[], long B[], long N, long M, long X) {
//MY CODE STARTS FROM HERE
ArrayList<Long> list = new ArrayList<>();
HashSet<Long> set = new HashSet<>();
for(long i : A){
set.add(i);
}
for(int i=0;i<M;i++){
if(set.contains(X-B[i])){
list.add(X-B[i]);
list.add(B[i]);
}
}
pair arr[] = new pair[list.size()];
for(int i=0;i<arr.length;i++){
arr[i]=new pair(X-B[i], B[i]);
}
return arr;
}
}

How to save permutation in a Set Java

I have this method that prints my permutations of a Set I'm giving with my parameters. But I need to save them in 2 separate sets and compare them. So, for instance I have [5,6,3,1] and [5,6,1,3], by adding them in two separate BST, I can compare them by using the compareTo function to check whether their level order is the same. But I am having trouble with saving these permutations from my method into a set in my main. Does anyone know how to save these into a set?
What I have now:
import edu.princeton.cs.algs4.BST;
import java.util.*;
public class MyBST {
public static void main(String[] args) {
int size = 4;
BST<Integer, Integer> bst1 = new BST<Integer, Integer>();
BST<Integer, Integer> bst2 = new BST<Integer, Integer>();
Random r = new Random();
Set<Integer> tes = new LinkedHashSet<>(size);
Stack<Integer> stack = new Stack<>();
while (tes.size() < size) {
tes.add(r.nextInt(10));
}
System.out.println(tes);
System.out.println("possible combinations");
Iterator<Integer> it = tes.iterator();
for (int i = 0; i < tes.toArray().length; i++) {
Integer key = it.next();
bst1.put(key, 0);
}
combos(tes, stack, tes.size());
}
}
and here is the method I use:
public static void combos(Set<Integer> items, Stack<Integer> stack, int size) {
if (stack.size() == size) {
System.out.println(stack);
}
Integer[] itemz = items.toArray(new Integer[0]);
for (Integer i : itemz) {
stack.push(i);
items.remove(i);
combos(items, stack, size);
items.add(stack.pop());
}
}
And this is the output:
I'm not sure if I understood your idea but maybe this will help:
Yours combos method will return set of all permutations (as Stacks)
...
for (int i = 0; i < tes.toArray().length; i++) {
Integer key = it.next();
bst1.put(key, 0);
}
Set<Stack<Integer>> combos = combos(tes, stack, tes.size()); //there you have set with all Stacks
}
}
public static Set<Stack<Integer>> combos(Set<Integer> items, Stack<Integer> stack, int size) {
Set<Stack<Integer>> set = new HashSet<>();
if(stack.size() == size) {
System.out.println(stack.to);
set.add((Stack) stack.clone());
}
Integer[] itemz = items.toArray(new Integer[0]);
for(Integer i : itemz) {
stack.push(i);
items.remove(i);
set.addAll(combos(items, stack, size));
items.add(stack.pop());
}
return set;
}

Method in Java for creating an array with arbitrary number of dimensions

Is it possible in Java to create a method that return an array with the number of dimensions passed by parameter?
Here is the code I have so far:
public static Object buildMultiDimensionalArray(int numDimensions) {
if (numDimensions==1) {
return new int[1];
}
if (numDimensions==2) {
return new int[2][2];
}
if (numDimensions==3) {
return new int[3][3][3];
}
if (numDimensions==4) {
return new int[4][4][4][4];
}
if (numDimensions==5) {
return new int[5][5][5][5][5];
}
if (numDimensions==6) {
return new int[6][6][6][6][6][6];
}
// and so on...
return null;
}
But this works only for dimensions up to 6.
Is it possible to make this method work for any number of dimensions?
import java.lang.reflect.*;
import java.util.*;
public static Object nArray(int n) {
int[]dim = new int [n];
Arrays.fill(dim, n);
return Array.newInstance(int.class,dim);
}
Such many-dimension array is rarely seen in code. Maybe you could try one dimension array with the tuple(d1, d2 ...) mapped to the 1-d array index, the same power. for example, to visit the 2-nd row and 3-rd column of a[6][8], mapped to (2 * 8 + 3) 1-d array a[48]
You could return a single-dimension array with an explicit capacity and parse it as if it were a multidimensional array.
#SuppressWarnings("unchecked")
public static <T> T[] buildMultiDimensionalArray(int dimensions, Class<T> clazz) {
return (T[]) Array.newInstance(clazz, dimensions * dimensions);
}
class nArray {
int[] dims;
int[] mults;
int[] vals;
nArray(int ... d) {
int sum = 1;
int len = d.length;
dims = new int[len];
mults = new int[len];
for (int i=len-1; i>=0; i--) {
dims[i]=d[i];
mults[i] = sum;
sum*=d[i];
}
vals = new int[sum];
}
void set(int v, int ... d) {
int index = 0;
for (int i=0; i<d.length; i++) {
//if(d[i]>=dim[i]){throw new IndexOutOfBoundsException(); / NullPointerException } ???
index+=d[i]*mults[i];
}
vals[index] = v;
}
int get(int ... d) {
int index = 0;
for (int i=0; i<d.length; i++) {
// throw exception ?
index+=d[i]*mults[i];
}
return vals[index];
}
}
https://pastebin.com/k0hqcu5Y

Java Calculate all possible combinations of given int array

I am trying to construct a program that would take an array of int({1,2,3} and a length value and calculate all possible combinations of this array.
For example:
int[] arr= new char[] {0,1};
int[] tes = new int[3];
possiblecomb(2, arr,tes,0);
This will output:
00
10
01
11
But i keep getting a Stack overflow error when i try to call the possiblecomb in the for loop
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
// Create an arr to work with
int[] test = new int[] {0,1};
int[] tes = new int[3];
// Find all possible combinations of this arr in the string size of 3
possiblecomb(3, test,tes,0);
}
public static void possiblecomb(int maxLength, int[] nums, int[] curr,int end) {
// If the current array has reached it's maximum length
if(end == maxLength) {
System.out.println(Arrays.toString(curr));
// Else add each number from the numbs to new array and process these new arrays again
} else {
for(int i = 0; i < nums.length; i++) {
int[] oldCurr = curr.clone();
curr[end]= nums[i];
possiblecomb(maxLength,nums,curr,end++);
curr = oldCurr.clone();
}
}
}
}
Try moving your recursive call outside of the for.
You are using the for in order to copy contents.
Your end variable will eventually increment above max lenght, and your (==) comparison won't be a stopper.
Take the example where num.Length = 2 and end is 2 :
You will call your function once with end = 3 which will stop and print inside the recursive call, and next, when i == 1 your end will be 4 and the recursive call won't break.
If you want to avoid the infinite recurssion with your current code in order to better debug with output, put the break condition
if (end>=maxLength)
As #MichaelCMS said you never stop the recursion, hence a stack overflow.
If you don't mind using Lists instead of arrays this is a solution:
import java.util.*;
public class Program {
private static List<List<Integer>> combinations(List<Integer> list, int maxLength) {
return combinations(list, maxLength, new ArrayList(), new ArrayList());
}
private static List<List<Integer>> combinations(List<Integer> list, int length, List<Integer> current, List<List<Integer>> result) {
if (length == 0) {
List<List<Integer>> newResult = new ArrayList<>(result);
newResult.add(current);
return newResult;
}
List<List<List<Integer>>> res3 = new ArrayList<>();
for (Integer i : list) {
List<Integer> newCurrent = new ArrayList<>(current);
newCurrent.add(i);
res3.add(combinations(list, length - 1, newCurrent, result));
}
List<List<Integer>> res2 = new ArrayList<>();
for (List<List<Integer>> lst : res3) {
res2.addAll(lst);
}
return res2;
}
public static void printCombinations(List<Integer> list, int maxLength) {
List<List<Integer>> combs = combinations(list, maxLength);
for (List<Integer> lst : combs) {
String line = "";
for (Integer i : lst) {
line += i;
}
System.out.println(line);
}
}
public static void main(String[] args) {
List<Integer> l = Arrays.asList(0, 1);
printCombinations(l, 2);
}
}
That gives you:
00
01
10
11

My code is not Compiling

I have the following code, but is not compiling, any suggestions? It keeps giving an error on line 11.
import java.util.ArrayList;
public class ListArray {
public static ArrayList<Integer> getList(int a, int b, int[] array){
ArrayList<Integer> list = new ArrayList<Integer>();
if(a == b){
list = null;
}
if(a > b){
list = null;
}
for(int i = a; i <= b - 1; i++){
list =(i + 1);
}
return list;
}
}
From what I can tell you are trying to create a method which will create an
ArrayList<Integer> which is populated with the integers between a+1 and b ( as you have i+1 with i starting at a and ending at b-1, which shifts your values to a+1-b)
You are attempting to assign your ArrayList list to an int value, which is not allowed. I believe you meant to add each value instead.
You should use the add method from ArrayList
import java.util.ArrayList;
public class ListArray {
public static ArrayList<Integer> getList(int a, int b, int[] array){
ArrayList<Integer> list = new ArrayList<Integer>();
if(a == b){
list = null;
}
if(a > b){
list = null;
}
for(int i = a; i <= b - 1; i++){
list.add(i + 1);
}
return list;
}
}
You cannot assign an int to an ArrayList-typed variable, which you actually do at line list =(i+1);.
The compilation error message should be clear enough. What is it saying?

Categories

Resources