How to add each element into a queue - java

How do I add each element into an arrayqueue? Basically, if I have an array of queues where each index is an arrayqueue that holds the 1s, 10s, 100s, etc. place of a corresponding 6 digit number in another index of array a. For example, if a[1] is 123456 then how can I make the code below hold arr[1] 654321? I've posted a question similar to this before but I'm just trying to get this right.
public static void radixSort(int[] a) {
//Create an array of 10 empty array queues
Queue[] arr = new Queue[a.length];
for (int i = 0; i < arr.length; i++)
arr[i] = new ArrayQueue();
for (int place = 1; place <= 100000; place *= 10) {
for (int i = 0; i < a.length; i++) {
arr[i].add(selectDigit(a[i],place));
// System.out.println("i: " + i + " a[i]: " + a[i] + " place: " + place + " digit: " + selectDigit(a[i],place));
}
}
// for (int i = 0; i < arr.length; i++)
// System.out.print(arr[i].remove()+ " ");
//for (int j = 0; j < arr.length; j++)
// a[j] = (Integer) arr[j].remove();
}

This tutorial might help:
http://www.sourcecodesworld.com/articles/java/java-data-structures/Radix_sort.asp
It seems a good walk through.

Related

Fibonacci Sequence using Array in Java

I want to get the fibonacci sequence entered by the user in array. The task given to me was "Ask the user for 2 integer input which will be taken for first and second array elements of size 10 array."
Here is my code.
int limit = 10;
int[] fib = new int[limit];
fib[0] = 0;
fib[1] = 1;
for (int j = 1; j < 2; j++)
{
System.out.print("Enter number " + "[" + j + "]: ");
num[j] = reader.nextInt();
num[j] = fib[j+1] + fib[j+2];
System.out.println("");
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++ )
{
System.out.print(fib[j] + " ");
System.out.print("");
}
I badly need help for this one, been searching for solution for hours and still don't get it.
I'll just make some corrections to your code and explain them:
int limit = 10;
int[] fib = new int[limit];
// fib[0] = 0;
// fib[1] = 1;
// The two lines above are wrong. Even though the real fibonacci sequence starts
// with 0 and 1, the question asks for the first two terms to come from user
// inputs. Instead, you can initialize them below:
// In your old code, you had "j = 1; j < 2; j++". However, that only loops once.
// So, have your condition to be j <= 2 instead: (I'm assuming that you want 1
// and 2 and not zero-based because it should print out "Enter number [1]:" and
// "Enter number [2]:"
for (int j = 0; j < 2; j++) // Not "j < 2"
{
System.out.print("Enter number " + "[" + j + "]: ");
fib[j] = reader.nextInt(); // not num[j] = ..., it's fib[j] = ...
// num[j] = fib[j+1] + fib[j+2];
// You don't need this ^^^
System.out.println("");
}
// Now you need to fill in the array:
for (int j = 2; j < limit; j++)
{
fib[j] = fib[j - 1] + fib[j - 2];
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++)
{
System.out.print(fib[j] + " ");
System.out.print("");
}
You have a number of mistakes here. Try to answer the following things:
What is the purpose of num variable here? You are using it to take input (num[j] = reader.nextInt();), then you are using it to store the Fibonacci sequence as well (num[j] = fib[j+1] + fib[j+2];)!!!
The first loop is only running one time. Assuming that your calculations are correct (which is not in this case!), it will have values for the first fibonacci number only.
Finally when you are printing the Fibonacci numbers, you are not using the num variable! Why?
Anyway, here is a solution to your problem. But, it will not help you unless you understand the logic behind it and you know which line is doing what!!!
int limit = 10;
int[] fib = new int[limit];
for (int j = 0; j < 2; j++)
{
System.out.print("Enter number " + "[" + j + 1 + "]: ");
fib[j] = reader.nextInt(); // These are the first two fibonacci numbers provided by the user
System.out.println("");
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++ )
{
if( j > 1 ) // You only calculate from the third Fibonacci, as the first two were given by user
{
fib[j] = fib[j-1] + fib[j-2];
}
System.out.print(fib[j] + " ");
System.out.print("");
}

Printing two dimensional array in Java

I'm trying to figure out what's wrong with my code for printing the two dimensional array
int[][] container = new int [3][6];
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <== 6; j++) {
System.out.print(contianer[i][j] + " ");
}
}
System.out.println();
<==is not an operator.
Array start from 0 to length - 1
you have a typo in your variable inside the for
System.out.println();must be executed inside the first for not outside.
int[][] container = new int [3][6];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
System.out.print(container[i][j] + " ");
}
System.out.println();
}

Printing for value of ArrayList Integer

I'm working on a small game that essentially has piles of coins, and you must take some coins from a pile then the program prints out the resulting piles in the format:
Pile 1: ****
Pile 2: *****
Pile 3: **
I have an array list that store all these values like so:
List<Integer> coins = new ArrayList<>();
[4,5,2]
But I can't figure out how to get it to properly print the *'s.
How can I write this code to print out a * for each value in an element. IE 4 *'s if the element value is 4?
Here is my current method:
static void printGameState(){
for(int i = 0; i <= coins.size()-1; i++){
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j <= coins.indexOf(i); j++){
System.out.print("*");
}
}
}
Instead of using this condition:
j <= coins.indexOf(i);
Use this condition:
j < coins.get(i);
Try it:
for(int i = 0; i <= coins.size()-1; i++) {
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j < coins.get(i); j++) {
System.out.print("*");
}
System.out.println();
}
You'll get:
Pile 1: ****
Pile 2: *****
Pile 3: **
You should be using < instead of <=. Also, you should be able to use get(i) to take the value at index i.
static void printGameState(){
for(int i = 0; i < coins.size(); i++){
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j < coins.get(i); j++){
System.out.print("*");
}
}
}
You could also make it a bit cleaner by forming another method to print * such as:
public void ast(int n){
for(int i=0; i<n; i++){
System.out.print("*");
}
}
Then the contents of printGameState loop would be
int k = i+1;
System.out.print("Pile " + k + ": ");
ast(coins.get(i));
You have to look at the values of the different stacks by accessing the array coins[i] instead of using the number of stacks as stack height:
static void printGameState(){
for(int i = 0; i < coins.size(); i++) {
// Build the coin stack
String coinStack = "";
for(int j = 0; j < coins.get(i); j++) {
coinStack += "*";
}
// And output it
System.out.println("Pile " + (i + 1) + ": " + coinStack);
}
}

How to multiply the elements of a column in a 2D array in Java?

i have a 2D array 3X5 and i need the to multiply each element in column one, and so forth. This is what ive attempted without any luck. the result is not correct. i tried storing each column into an array and multiply each element from that array but i get the same results.
edit: yes i am aware there is no multiplication in this code, that is because it yields an incorrect product.
for(int j = 0; j < 5; j++){
double v = 0.0;
double[] ex = new double[3];
double volumeBox1 = 0.0;
for(int i = 0; i < 3; i++){
v = d[i][j];
System.out.println(v);
for(int z = 0; z < 3; z++){
ex[z] = v;
}
}
System.out.println("The volume of box " + (j+1) + " is: " + volumeBox1);
I will assume your matrix is 5 x 3, which is more logical and convenient than 3 x 5 for this use case :
for (int i = 0 ; i < d.length ; j++) {
double vol = 1;
for (int j = 0 ; j < d[i].length ; j++) {
vol *= d[i][j];
}
System.out.println("The volume of box " + (j + 1) + " is: " + vol);
}
This can of course be done with a 3 x 5 matrix but I think it makes less sense to iterate on the columns :
for (int j = 0 ; j < d[0].length ; j++) {
double vol = 1;
for (int i = 0 ; i < d.length ; i++) {
vol *= d[i][j];
}
System.out.println("The volume of box " + (j + 1) + " is: " + vol);
}

sum of columns in a 2 dimensional array

static double [][] initialArray = {{7.432, 8.541, 23.398, 3.981}, {721.859, 6.9211, 29.7505, 53.6483}, {87.901, 455.72, 91.567, 57.988}};
public double[] columnSum(double [][] array){
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[i].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: "+sum);
index++;
}
return temp;
}
public static void main(String[] args) {
arrayq test = new arrayq();
test.columnSum(initialArray);
}
I want to get the sum of all the columns, but I keep getting an outofbounds exception. This is the output I get:
Index is: 0 Sum is: 817.192
Index is: 1 Sum is: 471.18210000000005
Index is: 2 Sum is: 144.7155
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at NewExam.arrayq.columnSum(arrayq.java:11)
Your outer for loop condition is giving you problems. Here's your loop: -
for (int i = 0; i < array[i].length; i++)
Now, when i reaches the value 3, you are trying to access array[3].length. This will throw you IndexOutOfBounds exception.
Since the size of every internal arrays are same, you can change your loop to: -
for (int i = 0; i < array[0].length; i++)
Or, even better, just store the array[0].length in some variable before hand. But that will not make much of a difference.
I would also suggest you to use a better way to calculate the sum of columns. Avoid iterating over rows first. Keep the iteration a normal one probably like this: -
public double[] columnSum(double [][] array){
int size = array[0].length; // Replace it with the size of maximum length inner array
double temp[] = new double[size];
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
temp[j] += array[i][j]; // Note that, I am adding to `temp[j]`.
}
}
System.out.println(Arrays.toString(temp));
return temp; // Note you are not using this return value in the calling method
}
So, you can see that how your problem is highly simplified. What I did is, rather than assigning the value to the array, I added the new value of array[i][j] to the existing value of temp[j]. So, gradually, the value of array[i][j] for all i's (rows) gets summed up in temp[j]. This way you don't have to use confusing iteration. So, just add the above code to your method, and remove the old one.
This method will also work fine, even if you have jagged-array, i.e., you inner arrays are not of same size. But just remember to define the size of temp array carefully.
Also note that, I have used Arrays.toString(temp) method to print the array.
Problem with your code is when it tries to fetch arr[3].length as there does not exist simple solution like sum = sum+arr[i][j] where i refers to row and j refers to column.
int row = arr.length;
int col = arr[0].length;
for(int j = 0; j < cols; j++)
{
int sum = 0;
for(int i = 0; i < rows; i++)
{
sum = sum + input[i][j];
}
}
for (int i = 0; i < array[i].length; i++)
for(int i=0;i<size;i++)
i & size must never be change in the loop
So close. The problem is that you are using array[i].length in your for loop. I changed it from array[i].length to array[0].length and your problem is gone. You need j there but you don't actually HAVE it yet.
You COULD do something like this although there isn't really any point if you know how you are going to get your array. Differently sized lists still would break the code for calculating sum though, you'd have to change that as well.
for (int i = 0, j = 0; i < initialArray[j].length; i++) {
for (; j < initialArray.length; j++) {
System.out.println(i + " " + j);
}
j = 0;
}
And here is your modified program.
public class Main {
static double[][] initialArray = { { 7.432, 8.541, 23.398, 3.981 }, { 721.859, 6.9211, 29.7505, 53.6483 }, { 87.901, 455.72, 91.567, 57.988 } };
public double[] columnSum(double[][] array) {
int index = 0;
double temp[] = new double[array[index].length];
for (int i = 0; i < array[0].length; i++) {
double sum = 0;
for (int j = 0; j < array.length; j++) {
sum += array[j][i];
}
temp[index] = sum;
System.out.println("Index is: " + index + " Sum is: " + sum);
index++;
}
return temp;
}
public static void main(String[] args) {
new Main().columnSum(initialArray);
}
}
for index = 3, i is also equal with 3 and you have array[i].length in your code, but array have 3 item so you get Exception on array[3].length expression
try it
public double[] columnSum(double [][] array){
double temp[] = new double[array[0].length];
for (int i = 0; i < array[0].length; i++){
double sum = 0;
for (int j = 0; j < array.length; j++){
sum += array[j][i];
}
temp[i] = sum;
System.out.println("Index is: " + i + " Sum is: "+sum);
}
return temp;
}

Categories

Resources