How would i go about converting the following 1d arrays into 2d arrays? I am kind of confused when working with 2d arrays.
[100, 101, 102, 200, 201, 202, 300, 301, 302] [232, 123, 102, 200, 321, 202, 300, 301, 302]
Another way would be to create a 2D array with the dimensions wished, then use an outer and inner for loop to transfer values. For example:
int k = 0
//array declarations
for (int i = 0...)
for (int j = 0...)
if (k < array1D.length)
array2D[i][j] = array1D[k];
k++
You can try this: 2D Array is nothing just an array of arrays, so you can put these two array into a 2D array, every element of a 2D array is an array.
int[] arr1 = {100, 101, 102, 200, 201, 202, 300, 301, 302};
int[] arr2 = {232, 123, 102, 200, 321, 202, 300, 301, 302};
int[][] array2D = new int[2][];
array2D[0] = arr1;
array2D[1] = arr2;
int[] x = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int [][]z = new int[4][4];
for (int i = 0, k=0; i < 4; i++)
for (int jl = 0; jl < 4; jl++)
z[i][jl] = x[k++];
for(int i=0;i<4;i++)
{
System.out.println();
for(int jl=0;jl<4;jl++)
{
System.out.print(z[i][jl]+" ");
}
}
Hope you have got answer to your problem.Happy coding
Related
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();
}
}
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
}
This program is a work in progress. In it, I created an array of ten objects with five pieces of different data types for each object. I need to find the highest score for q1 which I hoped to accomplish by creating a loop that would compare the variable highScore with each q1 data(8, 3, 10, 8, 9, 7.5, 8.5, 6, 7.5, 7) as the loop went through its cycles, however, I am getting an error message that says "The operator < is undefined for the argument type(s) double, ClassGrade" at the line that is second from the bottom. I don't understand why I am getting this error message, but i suspect that the reason i am getting it is that I am not correctly specifying the specific element that i am trying to access from each object. Any help on the matter would be greatly appreciated.
public class ClassGrade {
public String studentID;
public double q1;
public double q2;
public int mid;
public int finalExam;
public ClassGrade(String studentID, double q1, double q2, int mid, int finalExam)
{
// TODO Auto-generated constructor stub with a few modifications
}
public static void main(String[] args) {
System.out.println("this program works");
double highScore;
highScore = 0;
ClassGrade [] student = new ClassGrade[10];
student[0] = new ClassGrade ("A1", 8, 8.5, 84, 82);
student[1] = new ClassGrade ("B2", 3, 7, 0, 99);
student[2] = new ClassGrade ("C3", 10, 9.5, 92, 84);
student[3] = new ClassGrade ("D4", 8, 8, 89, 86);
student[4] = new ClassGrade ("E5", 9, 10, 83, 91);
student[5] = new ClassGrade ("F6", 7.5, 8.5, 88, 69);
student[6] = new ClassGrade ("G7", 8.5, 0, 81, 52);
student[7] = new ClassGrade ("H8", 6, 8.5, 79, 68);
student[8] = new ClassGrade ("I9", 7.5, 6, 72, 91);
student[9] = new ClassGrade ("J10", 7, 6.5, 58, 77);
for(int i=0; i<10; i++){
if (highScore < student[i])
highScore = student[i];
}
}
}
First, you need to assign your instance variables in you constructor.
You are comparing a double (highscore) with a ClassGrade (student[i]).
You need to create public methods in ClassGrade to return your desired properties.
Accessing an object's properties from an array is just the same way as from a single object. You fetch the object from the array and use '.' to access its public properties or methods. E.g:
array[i].method()
You are comparing the highscore with the actual object in the array, you are comparing a student with grade, so just make some small change - declare a method in your ClassGrade class like getQ1() and then access the q1 from the loop
This should work:
ClassGrade classGrade = (ClassGrade) student[i];
classGrade.method();
Each member of the array is still a ClassGrade, so all you need to do is check its q1 member like you would any other ClassGrade's q1.
for(int i=0; i<10; i++){
if (highScore < student[i].q1)
highScore = student[i].q1;
}
Just think about it as if the array index is part of the name, and it'll make more sense.
// Consider this:
studentZero = new ClassGrade("A1", 8, 8.5, 84, 82);
if (highScore < studentZero)
highScore = studentZero;
// studentZero is not a double. Therefore...
if (highScore < studentZero.q1)
highScore = studentZero.q1;
Alternatively, you can add a getter for q1, and use it.
int score = student[i].getQ1()
if (highScore < score)
highScore = score;
See here for an example of how to access a member of an object in an array:
So i have this slice of code that reads text from a csv file where nums[] goes throughout the file and stores the number of a said student, and grades[][] goes through and stores each of their grades:
Scanner sc = new Scanner(new FileReader("location.csv"));
String [][] stuff = new String [10][];
for(int i = 0; i<10; i++){
String line = sc.nextLine();
stuff[i] = line.split.(",");
}
int [][] grades = new int [10][10];
int [] nums = new int [10];
for(int x = 0; x<10; x++){
nums[x] = Integer.parseInt(stuff[x][0]);
System.out.println(nums[x]);
for(int y = 0; y<11; y++){
grades[x][y] = Integer.parseInt(stuff[x][y]);
}
}
The problem is that numbs works wonderfully, but grades cant store any value that is past the first column of data. If I set grades [x][y] = stuff[any number] [0] it will run, but if I try to go past 0 in the rows, I error terminate.
Part of data file:
1, 66, 82, 85, 87, 65, 80, 97, 75, 68, 72
2, 70, 63, 75, 62, 84, 65, 67, 95, 81, 96
3, 100, 98, 73, 78, 69, 75, 97, 66, 61, 90
4, 75, 62, 79, 78, 87, 73, 74, 76, 63, 84
5, 81, 90, 80, 66, 75, 96, 73, 77, 66, 87
Stack Trace:
java.lang.NumberFormatException: For input string: " 66"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
Fixed Code ( I apologize, I did not copy the code verbatim and included a few extra errors in it)
public static void main(String[] args)throws FileNotFoundException
{
Scanner sc = new Scanner(new FileReader("location.csv"));
String [][] values = new String [10][];
for(int i = 0; i<10; i++){
String line = sc.nextLine();
values[i] = line.split(",");
}
int [][] grades = new int [10][10];
int [] nums = new int [10];
for(int x = 0; x<10; x++){
nums[x] = Integer.parseInt(values[x][0]);
System.out.println(nums[x]);
for(int y = 0; y<10; y++){
grades[x][y] = Integer.parseInt(values[x][y+1].trim());
}
}
You aren't getting rid of the whitespace between tokens.
Make sure to clear it, preferably with String#trim()
Integer.parseInt(stuff[x][0].trim());
For the record, I'd also look to use better names than stuff.
Also, you're going to get an index out of bounds when you fix those other errors:
for( int y = 0; y < 11; y++ )
grades[x][y] = Integer.parseInt( stuff[x][y] );
All your array indexes go to 10, which in Java means 0 through 9. y here will go to 10, so boom out of bounds.
Considering the syntax errors pointed out in the comments, please in the future copy and paste the EXACT code you are using. It'll be no good if we are debugging different code than what you are actually using.
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();
}
}
}