Hey guys, am trying to write to do type casting in java, but i keep getting
run:
[(E,1), (H,1), (F,2), (G,2), (I,5), ( ,7)]
(H,1)
class datacompression.tuple
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to datacompression.tuple
at datacompression.Chap3.huffman(Chap3.java:79)
at datacompression.Chap3.histogram(Chap3.java:37)
at datacompression.Main.main(Main.java:18)
Java Result: 1
this the source code:
import java.util.ArrayList;
/**
*
* #author Cubearth
*/
public class Chap3 {
public static void huffman(ArrayList<tuple> list){
//creates an huffman tree
ArrayList<Node> huff = new ArrayList<Node>();
for(int i = 0; i<list.size(); i++){
huff.add(i, new Node(list.get(i), 2));
huff.get(i).setScore(list.get(i).getB());
}
System.out.println(huff.get(1).getData().toString());
System.out.println(huff.get(1).getData().getClass());
while(huff.size()>1){
String msg = ((tuple)(huff.get(0).getData())).getA()+ ((tuple)(huff.get(1).getData())).getA();
Node tmp = new Node(msg, 2);
tmp.setChild(huff.get(0), 1);
tmp.setChild(huff.get(1), 1);
tmp.setScore((huff.get(0).getScore()+huff.get(1).getScore()));
huff.set(0, tmp);
huff.remove(1);
sort2(huff);
}
System.out.println(huff);
Tree tmp = new Tree(huff.get(0));
tmp.print(2);
}
public static void sort2(ArrayList<Node> list){
//sort an arrayList of node, uesing insertion sort
int pos, min;
for(pos = 0; pos<list.size()-1; pos++){
min = pos;
for(int i = pos+1; i<list.size(); i++){
if(list.get(i).getScore()< list.get(pos).getScore())
min = i;
}
if(min!=pos){
swap2(list, pos, min);
}
}
}
public static void swap2(ArrayList<Node> list, int a, int b){
//swap two indexes of list
Node bucket = new Node(list.get(a).getData(), list.get(a).getNoc());
list.set(a, list.get(b));
list.set(b, bucket);
}
}
why my check for class in the huffman method comes up as a tuple(), but am unable to cast it as one?
well, initially huff.get(0).getData() might come as a 'tuple', but in this line:
huff.set(0, tmp);
you set it to be a String (as tmp is a String), so in the next iteration it will complain
Related
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;
}
}
im very confused as to why my queue is not working, i believe that there is a problem in the enqueue and dequeue methods. but im not sure, i am supposed to Implement the class with the initial array size set to 8. The array size will be doubled once the number of the elements exceeds the size. After an element is removed from the beginning of the array, you need to shift all elements in the array one position the left. Write a test program that adds 20 numbers from 1 to 20 into the queue and removes these numbers and displays them. here is my code
public class Queue {
private int[] elements;
private int size;
private int first;
private int last;
public static final int DEFAULT_CAPACITY = 8;
public Queue(){
this (DEFAULT_CAPACITY);
}
public Queue (int capacity){
elements = new int[capacity];
first = 0;
last = 0;
size = 8;
}
public void Enqueue(int v){ //fills queue and lengthens if necessary
if (last>=size){
int[] temp = new int[elements.length*2];
System.arraycopy(elements, 0, temp, 0, elements.length);
elements = temp;
}
elements[last]=v;
last++;
}
public int Dequeue(){
int output = elements[first];
System.out.print(output + " ");
while(last != 0){
for(int i = 0; i<last;i++){
elements[i]= elements[i-1];
}
last--;
}
return output ;
}
public boolean empty(){ // tests for empty queue
return last==first;
}
public int getSize(){
size=last;
return size;
}
}
and here is the tester class.
public class QueueTester {
public static void main(String[] args){
Queue q = new Queue();
q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3);
q.Enqueue(4);
q.Enqueue(5);
q.Enqueue(6);
q.Enqueue(7);
q.Enqueue(8);
q.Enqueue(9);
q.Enqueue(10);
q.Enqueue(11);
q.Enqueue(12);
q.Enqueue(13);
q.Enqueue(14);
q.Enqueue(15);
q.Enqueue(16);
q.Enqueue(17);
q.Enqueue(18);
q.Enqueue(19);
q.Enqueue(20);
while (q.empty()){
q.Dequeue();
while(last != 0){
for(int i = 0; i<last;i++){
elements[i]= elements[i-1];
}
last--;
}
Remove the while loop. If you're trying to make sure it's not dequeueing an empty queue have an if condition check to ensure that the size is > 0.
public int Dequeue(){
if (getSize() == 0) {
// throw an error or something
}
int output = elements[first];
System.out.print(output + " ");
for(int i = 0; i<last;i++){
elements[i]= elements[i-1];
}
last--;
return output ;
}
Additionally you need to print the output in your tester class, and I assume you want to dequeue while the queue is NOT empty:
while (!q.empty()){
System.out.println(q.Dequeue());
Mmm, think the algorithm you are using is not correct try referring this http://projectyogisha.com/implementing-queues/ , its in C though.
I have to call the method that takes an array list of parameter and moves the minimum value in front of the list. I keep getting an error int this line:
System.out.printf("Display numbers\n", myList.minInteger);
Here's the code:
import java.util.*;
public class MinToFront{
public static void main (String [] args){
MinToFront myList = new MinToFront();
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(8);
list.add(92);
list.add(4);
list.add(2);
list.add(17);
list.add(9);
myList.minToFront(list);
System.out.printf("Display numbers\n", myList.minInteger);
}// end of main
public static void minToFront (ArrayList<Integer> minInteger){
int result = 0;
int min = minInteger.get(0);
for (int i = 0; i < minInteger.size(); i++){
if (minInteger.get(i)< min) {
min = minInteger.get(i);
result = min;
}
}
minInteger.add(0, minInteger.remove(result));
}// end of method
}//end of class
First, writing "Display numbers" does not display numbers. It displays the sentence you just wrote. Second, do not create an instance if the class includes main().
Lastly, you should put brackets at the end of a method while calling it.
Here is your code, corrected:
public static void minToFront (ArrayList<Integer> minInteger)
{
int result = 0;
int min = minInteger.get(0);
for (int i = 0; i < minInteger.size(); i++)
{
if (minInteger.get(i)< min)
{
min = minInteger.get(i);
result = min;
}
}
minInteger.add(0, result);
minInteger.remove(result);
}// end of method
}//end of class
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm Java beginner, I have taken piece of code from online and trying the program on permutation. Im getting error as
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1.
Can anybody help to resolve this problem. Thank you.
// Permute.java -- A class generating all permutations
import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Permute implements Iterator {
private final int size;
private final Object [] elements; // copy of original 0 .. size-1
private final Object ar; // array for output, 0 .. size-1
private final int [] permutation; // perm of nums 1..size, perm[0]=0
private boolean next = true;
// int[], double[] array won't work :-(
public Permute (Object [] e) {
size = e.length;
elements = new Object [size]; // not suitable for primitives
System.arraycopy (e, 0, elements, 0, size);
ar = Array.newInstance (e.getClass().getComponentType(), size);
System.arraycopy (e, 0, ar, 0, size);
permutation = new int [size+1];
for (int i=0; i<size+1; i++) {
permutation [i]=i;
}
}
private void formNextPermutation () {
for (int i=0; i<size; i++) {
// i+1 because perm[0] always = 0
// perm[]-1 because the numbers 1..size are being permuted
Array.set (ar, i, elements[permutation[i+1]-1]);
}
}
public boolean hasNext() {
return next;
}
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
private void swap (final int i, final int j) {
final int x = permutation[i];
permutation[i] = permutation [j];
permutation[j] = x;
}
// does not throw NoSuchElement; it wraps around!
public Object next() throws NoSuchElementException {
formNextPermutation (); // copy original elements
int i = size-1;
while (permutation[i]>permutation[i+1])
i--;
if (i==0) {
next = false;
for (int j=0; j<size+1; j++) {
permutation [j]=j;
}
return ar;
}
int j = size;
while (permutation[i]>permutation[j]) j--;
swap (i,j);
int r = size;
int s = i+1;
while (r>s) { swap(r,s); r--; s++; }
return ar;
}
public String toString () {
final int n = Array.getLength(ar);
final StringBuffer sb = new StringBuffer ("[");
for (int j=0; j<n; j++) {
sb.append (Array.get(ar,j).toString());
if (j<n-1) sb.append (",");
}
sb.append("]");
return new String (sb);
}
public static void main (String [] args) {
for (Iterator i = new Permute(args); i.hasNext(); ) {
final String [] a = (String []) i.next();
System.out.println (i);
}
}
}
ArrayIndexOutOfBoundsException Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
As you have not posted any stack trace. Problem is unclear. But these links may help you.
oracle docs
stackoverflow
I want to crate a Heap structure that each node have 2 data , 1) string 2) int
so i think that each node must be a Class that's name is "heapNode" , but i have a trouble in swap method ,
please help me
import java.util.ArrayList;
public class MainHeap {
ArrayList<heapNode> heap;
MainHeap (){
new ArrayList<heapNode>();
}
public int getMin(){
return heap.get(0).data ;
}
private int parent(int pos) {
return pos / 2;
}
private void swap(int pos1, int pos2) {
heapNode temp =new heapNode();
temp = heap.get(pos1);
heap.get(pos1) = heap.get(pos2);
heap.get(pos2) = temp;
}
public void insert(int elem) {
int max = heap.size();
heap.get(max).data = elem ;
int current = heap.size() ;
while (heap.get(current).data < heap.get(parent(current)).data){
swap ( current , parent(current));
}
}
}
and this is my heapNode class
public class heapNode {
int data;
String fileName;
}
the swap method has error but i cant solve errors
Your swap code actually makes the objects point to different objects. It does not modify the positions in the arraylist itself. If using arraylist, you will have to remove an object from an index and set that object at a new index to swap or else you can use other data structure.
java.util.PriorityQueue<YourClass>