I'm trying to decode a huffmann binary code tree with no success. Am using the following code:
public static int decodeTree(String str){
int length = str.length();
int num = 0;
int number = 0;
Node root = tree1.get(0);
String b;
// 0 left
// 1 right
for (int x = 0; x <tree1.size(); x++) {
Node curr = root;
while ((curr.isLeaf() == false) && num < length) {
if (str.charAt(num) == '0') {
curr = curr.Left();
num++;
}
else if (str.charAt(num) == '1') {
curr = curr.Right();
num++;
}
}
number = curr.getValue();
}
return number;
}
It should output:
10, 46, 200, 155, 50, 50, 23, 12, 18, 59, 40, 10, 200, 10, 40, 50, 46, 12, 18, 200, 46
It is currently outputting:
155, 46, 200, 200, 50, 91, 23, 12, 46, 200, 40, 200, 155, 50, 200, 68, 38, 50, 18, 200, 200
It is to return decimal numbers. It decodes some numbers correctly but in the wrong sequence. Do you have any idea what might be wrong?
I'm also uploading my Tree implementation:
public static String[] huffman(int[] histo){
//initial list of nodes
tree1 = new ArrayList<>();
for (int i = 0; i < histo.length; i++)
if(histo[i] != 0) {
tree1.add(new Node(histo[i], i));
}
//get weights until only root node is left out
while(tree1.size() > 1){
combine(tree1);
}
//recursively generate code for each node in the tree
//if the recursion finds a leaf node,
//it sets the correct element in the array to the code of the node
Node root = tree1.get(0);
String[] codage = new String[histo.length];
root.genCodeWord(codage);
return codage;
}
Further information:
This is how I'm trying to decode back:
String[] oneDConvertedBack1 = new String[oneD.length];
System.out.print("\n\nCONVERTED BACK:\n");
for(int i =0; i<oneD.length; i++)
Gray graycode = new Gray();
oneDConvertedBack1[i] = graycode.convertToBinaryCode(oneDGray[i]);
}
for(int i=0; i<oneD.length;i++)
System.out.print(oneDConvertedBack1[i]+ ", ");
int[] oneDConvertedBack2 = new int[oneD.length];
System.out.print("\n\nCONVERTED BACK:\n");
for(int i =0; i<oneD.length; i++) {
oneDConvertedBack2[i] = decodeTree(oneDBinary[i]);
}
The following are the constituents of the Nodes of the tree and its CodeWord method
public Node(Node left, Node right, int value){
l = left;
r = right;
v = value;
i = -1;
}
public void genCodeWord(String[] codes){
if(l != null && r != null){
l.setCodeWord("0"+getCodeWord());
l.genCodeWord(codes);
r.setCodeWord("1"+getCodeWord());
r.genCodeWord(codes);
}else{
codes[i] = getCodeWord();
}
}
Related
I'm trying to create a method that searches the volume array for the largest value and returns the value in the corresponding position of the note array.
Also, separately, how could I modify it so that it only plays the loudest note
import arb.soundcipher.*;
SoundCipher midi;
String[] note = {"C", "C#", "D", "D#", "E", "F", "F#",
"G", "G#", "A", "A#", "B"};
float[] volume = {80, 100, 75, 43, 40, 81, 100,
60, 90, 30, 75, 52};
float[] duration = {1.3, 2, 0.5, 3, 0.9, 1, 0.25,
0.6, 1.5, 3, 1.25, 2};
void setup() {
size(200,200);
midi = new SoundCipher(this);
int i = (int) random(note.length);
midi.playNote(MIDIValue(note[i]),volume[i],duration[i]);
}
float MIDIValue(String aNote) {
float noteMIDIValue = 0.0;
int i;
for (i =0; i < note.length && !note[i].equals(aNote) ; i++);
if(i < note.length) {
noteMIDIValue = i+60;
}
return noteMIDIValue;
}
traverse the volume array and keep track of maximum volume and id(index). And finally, return the note corresponding to the maximum element id (node[id]).
Method implementation ...
String findLargestVolumeNote() {
int maxId = 0;
float maxVol = volume[0];
// searching array for loudest volume
for(int i = 0; i < volume.length; i++) {
if(volume[i] > maxVol) {
maxId = i;
maxVol = volume[i];
}
}
return note[maxId]; // returning corrsponding note
}
I am wondering how I can change my objects individually when giving them a name (setName) seen below.
Code:
//textfield & labels
String[] arrLabelsKlanten = new String[] {"KlantID", "Gebruikersnaam", "Wachtwoord", "Voornaam", "Achternaam", "Straat", "Huisnummer", "Gemeente", "Email", "Telefoonnr"};
for (int i = 0; i < arrLabelsKlanten.length; i++)
{
if(i < 5)
{
lblLabelsKlanten = new ClassLabels.lblIngelogdAls(arrLabelsKlanten[i] + ":", 350, 510 + i * 50, 300, 50);
lblLabelsKlanten.setName(String.valueOf(i));
add(lblLabelsKlanten);
txtTextvakken = new ClassTextfields.txtAdmin(500, 515 + i * 50, 300, 30);
txtTextvakken.setName(String.valueOf(i));
add(txtTextvakken);
}else if (i >= 5)
{
lblLabelsKlanten = new ClassLabels.lblIngelogdAls(arrLabelsKlanten[i] + ":", 910, 260 + i * 50, 300, 50);
lblLabelsKlanten.setName(String.valueOf(i));
add(lblLabelsKlanten);
txtTextvakken = new ClassTextfields.txtAdmin(1050, 265 + i * 50, 300, 30);
txtTextvakken.setName(String.valueOf(i));
add(txtTextvakken);
}
}
}
Your strings are stored in an array named lblLabelKlanten, the valueOf(i) is your iterator, not the array.
lblLabelKlanten.setName(arrLabalKlanten[i]); should get you the String inside your array, and set the name of your object to the string value.
at least I think that is the question you are asking?
I'm having trouble getting the graphics to show up with my hangman program.
This is the code for my engine class:
public static void main(String[] args)
{
//hangman viewer stuff
//////////////////////////////////////////////////////////////
JFrame frame = new JFrame();
frame.setSize(200,375); //invoked the method setSize on the implicit parameter frame
frame.setTitle("Hangman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
HangmanComponent g = new HangmanComponent();
frame.add(g);
frame.setVisible(true);
///////////////////////////////////////////////////////////////
String wordd = JOptionPane.showInputDialog("Type in a word.");
int length = wordd.length();
String blank = "_ ";
String word2 = new String("");
int guesscount = 10;
ArrayList<String>answers=new ArrayList<String>(); //creates reference to empty structure that will contain references
char blanks[]=new char[wordd.length()]; //creates an array with the same number of terms as the length of the word
for (int i=0; i<length; i++)//fills the array with blanks corresponding to the length of the word
{
blanks[i] = '_';
}
HangmanComponent y = new HangmanComponent();
while (true)
{
String letter = JOptionPane.showInputDialog("Guess a letter! You have "+guesscount+" guesses."+"\n"+answers+"\n"+Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")); //Prints a space
char letterchar = letter.charAt(0); //converts string letter to char letterchar
int idx = 0;
boolean found = false;
answers.add(letter); //adds the string to the arraylist answers
while (idx >= 0 && idx < length) //idx is greater than or equal to 0 but less than the length of the word
{
//System.out.println("idx = " + idx);
idx = wordd.indexOf(letter, idx); //idx is the index of "letter" in "wordd" and finds all instances of the letter
//System.out.println("idx = " + idx + ", guesscount = " + guesscount);
if (idx != -1) //if idx is not -1 (the letter exists in the word)
{
found = true;
blanks[idx] = letterchar; //sets the term in the array equal to the letter
idx += 1; //idx=idx+1
}
else
{
guesscount=guesscount-1;
y.nextStage();
y.printStage();
frame.add(y);
frame.setVisible(true);
break;
}
}
if (found)
{
JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"You found a letter!"+"\n"+answers);
}
else
{
JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"That letter is not in the word! Guess again!"+"\n"+answers);
if (guesscount == 0)
{
JOptionPane.showMessageDialog(null, "Sorry, you're all out of guesses. The answer was '"+wordd+".' Thanks for playing!");
break;
}
}
char [] lettersArray = wordd.toCharArray(); //converts word to array of chars
if (Arrays.equals(blanks, lettersArray))//compares array of blanks to array of letters
{
JOptionPane.showMessageDialog(null, "You guessed the word! Thanks for playing!");
break;
}
}
}
and this is the code for my HangmanComponent class (with the graphics)
int stage=0;
public void nextStage()
{
stage++;
}
public void printStage()
{
System.out.println("Your stage number is:"+stage);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(5,BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
g2.setColor(Color.BLACK);
g.drawLine(50, 30, 50, 10);
g.drawLine(50, 10, 130, 10);
g.drawLine(130, 10, 130, 300);
g.drawLine(20, 300, 150, 300);
if (stage==1)
{
//draws the head
g2.setStroke(new BasicStroke(3,BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
Ellipse2D.Double head = new Ellipse2D.Double(25, 30, 50, 50);
g2.draw(head);
}
else if (stage==2)
{
//draws the body
g.drawLine(50, 80, 50, 180);
}
else if (stage==3)
{
//draws the left arm
g.drawLine(10, 150, 50, 100);
}
else if (stage==4)
{
//draws the right arm
g.drawLine(50, 100, 90, 150);
}
else if (stage==5)
{
//draws the left leg
g.drawLine(30, 250, 50, 180);
}
else if (stage==6)
{
//draws the right leg
g.drawLine(50, 180, 70, 250);
}
else if (stage==7)
{
//draws the left eye
Ellipse2D.Double lefteye = new Ellipse2D.Double(40, 50, 1, 1);
g2.draw(lefteye);
g2.fill(lefteye);
}
else if (stage==8)
{
//draws the right eye
Ellipse2D.Double righteye = new Ellipse2D.Double(58, 50, 1, 1);
g2.draw(righteye);
g2.fill(righteye);
}
else if (stage==9)
{
//draws the mouth
Arc2D.Double mouth = new Arc2D.Double(40.00, 50.00, 20.00, 20.00, 180.00, 190.00, Arc2D.OPEN);
g2.draw(mouth);
}
}
Right now, the hangman program runs perfectly fine, but the graphic is only added the first time the user inputs a wrong letter. How do I get the graphics to be inputted for every time a wrong letter is inputted?
I can't seem to figure out what my parameters should be for my method "public static int[][] sellSeatByPrice". I need to prompt the user for a price (of a seat), then figure out if that price is taken (if it = 0) and if not, assign it the value 0.
Below is my code, help please!
import java.util.Scanner;
/**
* Write a description of class A10_TheaterSeating here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class A10_TheaterSeating
{
public static void main(String args[])
{
System.out.println("***Welcome to the Ticket Choice App!***");
System.out.println();
int[][] theaterSeats = //set values in seating chart array
{
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{10, 10, 20, 20, 20, 20, 20, 20, 10, 10},
{20, 20, 30, 30, 40, 40, 30, 30, 20, 20},
{20, 30, 30, 40, 50, 50, 40, 30, 30, 20},
{30, 40, 50, 50, 50, 50, 50, 50, 40, 30}
};
int[][] seats = theaterSeats;
printArray(seats); //print the seating chart
System.out.println();
//Defining variables
String str = "";
String input = "";
while (!input.equalsIgnoreCase("Q"))
{
System.out.print("Select 'S' to pick a seat, 'P' choose a price or 'Q' to quit: ");
Scanner in = new Scanner(System.in);
input = in.next();
if (input.equalsIgnoreCase("S"))
{
System.out.print("Enter row and seat number desired: ");
int row = in.nextInt();
int seat = in.nextInt();
System.out.println();
sellSeatByNumber(seats, row, seat);
printArray(seats);
System.out.println();
}
else if (input.equalsIgnoreCase("P"))
{
System.out.print("Enter price of seat desired: ");
int price = in.nextInt();
System.out.println();
sellSeatByPrice(seats, row, seat, price);
printArray(seats);
System.out.println();
}
}
System.out.println();
System.out.println("Thank you for choosing the ticket choice app.");
System.out.println();
}
public static void printArray(int[][] currSeat)
{
final int ROWS = 9;
final int COLUMNS = 10;
for(int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLUMNS; j++)
{
System.out.print(currSeat[i][j] + "\t");
}
System.out.println();
}
}
public static int[][] sellSeatByNumber(int[][] seats, int row, int seat)
{
if (row <= 0 || row > 9)
{
if (seat <= 0 || seat > 10)
{
System.out.print("Please enter a valid row and seat: ");
}
}
if (seats[row][seat] == 0)
{
System.out.print("That seat is taken. Please select another seat: ");
}
else
{
seats[seats.length - row][seat - 1] = 0;
}
return seats;
}
public static int[][] sellSeatByPrice(int[][] seats, int row, int seat, int price)
{
if (seats[row][seat] = price)
{
seats[seats.length - row][seat - 1] = 0;
}
return seats;
}
}
Your parameters seem fine - the internal logic and syntax is incorrect.
Since you're using static methods, and passing along the seat matrix, that is okay - but you have to check that the values being passed in are inside the bounds of your matrix - or you will get exceptions on them.
For instance, you don't check the bounds in sellSeatByPrice(). You really should do that, or a bogus row/seat combination could blow your program up.
It's also the case that the comparison given is incorrect:
if (seats[row][seat] = price)
should really be
if (seats[row][seat] == price)
as = is assignment, and == is primitive comparison.
Furthermore, in sellSeatByNumber(), you can still run into issues since an out of bounds row/seat combo will still blow up. You do check the bounds - kudos - but you don't return anything if they're outside of those bounds. In all reality, an IllegalArgumentException should be raised if they're stepping out of bounds, or you can return the matrix unmodified (which may be more straightforward).
Let's say I got this map that prints out:
00000
00000
00000
How do I change the element in [0][0] into an X?
In other words, how to make it look like this using Screen input:
X0000
00000
00000
Considering Its an 2D Array of String Type...
arr[0][0] = "X";
Run this:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String[][] array = {{"0","0","0"},{"0","0","0"},{"0","0","0"}};
System.out.println("Before: ");
printArray(array);
array[0][0] = "x";
System.out.println("After: ");
printArray(array);
}
private static void printArray(String[][] array){
for(int i=0; i<array.length; i++){
for(int j=0; j<array[0].length; j++){
System.out.print(array[i][j]);
}
System.out.println("");
}
}
}
Or go here: http://ideone.com/2DQC1
In This example user k check array element value and change them
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
Scanner in = new Scanner(System.in);
int inputcol = 0;
int inputrow = 0;
int newnum = 0;
int uinput = 0;
int repeat = 1;
int[][] a = new int[][]{
{ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 },
{ 110, 120, 130, 140, 150, 160, 170, 180, 190, 200 },
{ 210, 220, 230, 240, 250, 260, 270, 280, 290, 300 },
{ 310, 320, 330, 340, 350, 360, 370, 380, 390, 400 },
{ 410, 420, 430, 0, 440, 450, 460, 470, 490, 500 }
};
while(repeat!=0)
{
System.out.println("Select Option:\n 1 for View Value:\n 2 for Replace Value: ");
uinput = in.nextInt();
//int b[][]={{1,3,4},{3,4,5}};
if(uinput==1)
{
System.out.println("Enter Row: ");
inputrow = in.nextInt();
System.out.println("Enter Cols:");
inputcol = in.nextInt();
System.out.println(a[inputrow][inputcol]);
}
else
if(uinput==2)
{
System.out.println("Enter Row: ");
inputrow = in.nextInt();
System.out.println("Enter Cols:");
inputcol = in.nextInt();
System.out.println("Enter New Number: ");
newnum = in.nextInt();
a[inputrow][inputcol] = newnum;
}
else
{
System.out.println("Check your input. ");
}
System.out.println("Want to repeat it? if yes press 1\n for exit press 0 ");
repeat = in.nextInt();
}
}
}