I'm working on a Tower of Hanoi project for school which needs to ask the user how many disks there are and then it needs to create and then solve the tower with a visual included. How I decided to do it is by using 2D arrays and for the most part its working, my only problem is that I don't know how to move the disks while keeping it modular. Here is my code.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of disks");
int num = scan.nextInt();
int temp = num-(num-1);
int measure = num;
//initializing the towers
int[][] towers = new int[num][num];
for(int i = 0 ; i < num; i++)
{
for(int j=0; j <3; j++)
{
}
}
createRings(towers, num, temp);
moveDisk(towers,num);
}
// creating the rings
private static void createRings (int[][]towers, int num, int temp)
{
for(int i = 0; i<num; i++)
{
for(int j=0; j<3;j++)
{
towers[i][0] = temp;
}
temp = temp+1;
}
displayTower(towers, num);
}
// prints the array for display purposes
private static void displayTower (int[][] towers, int num)
{
for(int i = 0; i<num; i++)
{
for(int j = 0; j<3; j++)
{
System.out.print(towers[i][j]+"\t");
}
System.out.println();
}
}
//moves the numbers in the array that represents disks
private static void moveDisk(int[][]towers, int num)
{
System.out.println();
displayTower(towers, num);
}
Does anyone have any suggestions on what I could do?
I've changed your code a bit to make it more readable for me.
I changed the towers array. Now each tower is its own array inside the towers array (makes more sense IMHO).
Arrays in Java know their size. So you don't have to pass the length of the array as a parameter to every method.
I added a method getHighestIdx() which returns the index before the first 0 value in the array
I don't know, how the function moveDisk() was intended to work. I changed the declaration so that it makes sense to me. It now moves a disk from tower i to tower j
This should help you to implement the algorithm from the linked question.
Here is the changed code:
public static void main(String[] args) {
int numberOfRings = 6;
int[][] towers = new int[3][numberOfRings];
createRings(towers);
displayTowers(towers);
moveDisk(towers, 0, 2);
displayTowers(towers);
}
private static void createRings(int[][] towers) {
for (int j = 0; j < towers[0].length; j++) {
towers[0][j] = j + 1;
}
}
private static void displayTowers(int[][] towers) {
for (int i = 0; i < towers[0].length; i++) {
for (int j = 0; j < towers.length; j++) {
System.out.print(towers[j][i] + " ");
}
System.out.println("");
}
}
private static void moveDisk(int[][] towers, int fromIdx, int toIdx) {
int valToMove = towers[fromIdx][getHighestIdx(towers[fromIdx])];
towers[fromIdx][getHighestIdx(towers[fromIdx])] = 0;
towers[toIdx][getHighestIdx(towers[toIdx]) + 1] = valToMove;
}
private static int getHighestIdx(int[] tower) {
int i = 0;
while (i < tower.length && tower[i] != 0) {
i++;
}
return i - 1;
}
Okay, hopefully this makes more sense. I have an array hard coded with only 1s and 0s. I am trying to write a function that reads each element to see if it is a 0 or 1. If it is a 1, it will execute another function and then change that 1 to a 0 so that it is not read again. I have it printing simply as a placeholder for the other function I will be implementing later. I'm having trouble getting the findfirst1 function to check every element in the array. I have tried putting the incrementors for i and k in different places within the flow of the code but nothing I have tried gets me the correct output.
public static void main(String[] args)
{
int[][] testarray = {{1,0,0,0,0,0,0,1},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{1,0,0,0,0,0,0,1}};
findfirst1(testarray);
}
public static void findfirst1(int[][] array1)
{
int value = 0;
for(int i = 0; i < 6;i++)
{
for(int k = 0; k < 7;k++)
{
value = array1[i][k];
if(value == 1)
{
System.out.println(value);
array1[i][k] = 0;
}
else
{
System.out.println(value);
}
}
}
}
Okay, so after starting completely over and writing it all from scratch I figured it out. The array.length was right all along. I had trouble wrapping my head around it because I was so focused on the idea of the "image".
Edit: I just found an error where it wouldn't print the last line for array1, so I just added an extra row of 0s and it worked.
public class ChainCodeClass {
public static void main(String[] args)
{
int[][] array1 = {{0,1,0,0,0,0,0,0},{0,1,0,0,0,1,0,0},{0,1,1,1,0,0,1,0},
{0,0,0,1,1,0,0,1},{0,0,0,0,1,0,0,1},{0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,1,0}**,{0,0,0,0,0,0,0,0}**};
int[][] array2 = {{0,0,0,0,0,0,0,0},{0,1,1,1,1,0,1,0},{0,0,0,0,1,0,1,0},
{0,0,1,1,1,0,1,0},{0,0,1,0,0,0,1,0},{0,0,1,0,0,0,1,0},{0,0,0,0,0,0,1,1},
{0,0,0,0,0,0,0,0}};
System.out.print("First Image");
print(array1);
findfirst1(array1);
print(array1);
System.out.print("Second Image");
print(array2);
outline8(array2);
}
public static void findfirst1(int[][] array)
{
int value = 0;
for(int i = 0; i < array.length; i++)
{
for(int k = 0; k < array.length; k++)
{
value = array[i][k];
if(value == 1)
{
System.out.print(value + " ");
array[i][k] = 0;
}
else
{
System.out.println(value);
}
}
}
}
public static void print(int[][] array)
{
for(int i = 0; i < array.length; i++) // print function for the array using incrementors
{
System.out.print("\n");
for(int k = 0; k < array.length; k++)
{
System.out.print(array[i][k] + " ");
}
}
System.out.println();
}
}
I'm supposed to modify code that I've written for an assignment:
public class ToweringStrings2 {
public static final int H = 2; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}
public static void drawTowers(int H) {
for (int i = 1; i <= H; i++) {
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print("+");
}
System.out.println();
}
for (int k = 1; k <= H + 2; k++) {
System.out.print("#");
}
System.out.println();
}
}
so that it prints sequential numbers starting at 1, instead of +s. Currently, it prints:
This is what the new code is supposed to print:
and so on.
For some reason I'm just really stuck and can't figure it out.
You can create an extra variable to print and increment
Like that:
public class ToweringStrings2 {
public static final int H = 10; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}
public static void drawTowers(int H) {
int count = 1;
for (int i = 1; i <= H; i++) {
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print(count++ + " ");
}
System.out.println();
}
for (int k = 1; k <= H + 2; k++) {
System.out.print("# ");
}
System.out.println();
}
}
Step 1 - make it print a variable rather than a hard-coded string. Instead of System.out.print("+"), System.out.print(counter).
For this to work you need to have declared counter somewhere in the same scope as the statement: int counter = 0.
Run this. You'll see it print "0" where it used to print "+".
Step 2 - Now you need to make counter increase by one every time it prints.
Find the right place to add:
counter = counter + 1;
Run it and see it work.
Further notes
A more concise alternative to var = var + 1 is var++.
You can even do this at the same time as you use the value of a variable:
System.out.println(var++);
This can be used to express some algorithms very concisely -- but it can be confusing for beginners, so feel free to not use this technique until you're comfortable with the basics.
i'm trying to create a bubble sort but I there is something wrong with my code. The output is : 82345679. I would like it to be : 23456789.
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
int[] tab = {9,8,7,6,5,4,3,2};
int[] result = {9,8,7,6,5,4,3,2};
for (int i = 0; i < result.length; i++ ) {
if (i < result.length - 1 ) {
if (result[i] > result[i+1]) {
result = permute(result, i);
i = 0;
}
}
}
for (int i: result) {
System.out.print(i);
}
}
public static int[] permute (int[] tableau, int index) {
int temp;
temp = tableau[index];
tableau[index] = tableau[index+1];
tableau[index+1] = temp;
return tableau;
}
}
The issue is with the combination of i = 0 and i++ in the for loop. Whenever you go in the i = 0 branch, you end up restarting at 1 because of the i++. Resulting in always skipping the 8 after the first iteration where the 9 is moved to the end.
So, either restart at -1, or use a while loop and only increment in an else block. For example:
int i = 0;
while (i < result.length - 1) {
if (result[i] > result[i+1]) {
permute(result, i)
i = 0;
} else {
i++;
}
}
However, I would advise against the one-loop bubble sort, because the algorithm complexity is harder to see (it is still O(n^2), but with only one loop it can give the impression that it is O(n)).
You need two loops.
int swap;
for (int i = 0; i < ( result.length - 1 ); i++) {
for (int j = 0; j < result.length - 1; j++) {
if (result[j] > result[j+1]) {
swap = result[j];
result[j] = result[j+1];
result[j+1] = swap;
}
}
}
You need to have 2 loops in order to compare each number to the whole array..
example of bubble sorting
public static void bubbleSort(int[] numArray) {
int n = numArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numArray[j - 1] > numArray[j]) {
temp = numArray[j - 1];
numArray[j - 1] = numArray[j];
numArray[j] = temp;
}
}
}
}
Refer to this question
Sorting an Array of int using BubbleSort
Can be done with ONE loop (although it is not the usual way to present the bubble sort):
public static void main (String args[]) {
int[] tab = {9,8,7,6,5,4,3,2};
int i=1; // let's do the bubble sort again
while (i < tab.length) {
// loop invariant : t[0] <= t[1] .... <= t[i-1]
if (tab[i-1] < tab[i]) { // bubble here
swap(tab, i-1, i);
if (i>1) {
i = i-1; // one step to the left....
}
} else {
i = i +1; // one step to the right
}
}
for (int x: tab) {
System.out.print(x);
}
}
static void swap(int[] t, int i, int j) {
int x = t[i];
t[i] = t[j];
t[j] = x;
}
My program is as below:
package simplemirror;
public class simple {
public static void main (String arg[]){
for( int i = 1; i <= 3; i++ ){
for( int j = 0; j < i; j++ ){
System.out.print(i+"*");
}
System.out.println("");
}
}
}
Above program output is as below:
1*
2*2*
3*3*3*
I need output as below:
1
2*2
3*3*3
2*2
1
this code will work try this.............:)
public class simple {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n;
n=3;
for(int i=1;i<2*n;i++){
if(i<=n){
for(int j=1;j<i;j++){
System.out.print(i+"*");
}
System.out.println(i);
}
else{
for(int j=i+1;j<2*n;j++){
System.out.print(2*n-i+"*");
}
System.out.println(2*n-i);
}
}
}
}
try
public static void main(String[] args) {
int limit=5;
int rows=limit+(limit-1);
int center=(int) Math.ceil(((double)rows/2));
boolean centerReached=false;
for(int i=1;i<=limit&&i>0;){
for(int j=1;j<=i;j++){
System.out.print(i);
if(i==j)
continue;
System.out.print("*");
}
if(center==i)
centerReached=true;
if(centerReached)
i--;
else
i++;
System.out.println();
}
}
ouptut
1
2*2
3*3*3
4*4*4*4
5*5*5*5*5
4*4*4*4
3*3*3
2*2
1
EDIT:
It's been a while, and I have learned a few things.
You can use streams!
private static void print(int num) {
IntStream.concat(
IntStream.iterate(1, (i) -> ++i).limit(num),
IntStream.iterate(num - 1, (i) -> --i).limit(num).limit(num - 1))
.boxed()
.map(i -> Stream.generate(i::toString).limit(i).collect(Collectors.joining("*")))
.forEach(System.out::println);
}
Please don't ask such question here. Ans to your question may be looks like follows but once again don't ask such questions here.
public class simple {
public static void main (String arg[])
{
for( int i = 1; i <= 3; i++ ){
for( int j = 0; j < i; j++ ){
if(j== i-1)
{
System.out.print(i);
}
else
{
System.out.print(i+"*");
}
}
System.out.println("");
}
}
}