I have to write a method called print() that prints out the results as follows;
Original:
-----------
|9|7|9|4|3|
-----------
Sorted:
-----------
|3|4|7|9|9|
-----------
My new code is as follows:
for(int i=0;i< intArray.length; i++)
{
if(i==intArray.length-1)
{
System.out.print("----\n");
}
else{
System.out.print("----");
}
}
for(int i=0;i< intArray.length; i++)
{
if(i==0)
{
System.out.println("| "+intArray[i]+" | ");
}
else if(i==intArray.length-1)
{
System.out.print(intArray[i]+" |\n");
}
else{
System.out.print(intArray[i]+" | ");
}
}
for(int i=0;i< intArray.length; i++)
{
if(i==intArray.length-1)
{
System.out.print("----\n");
}
else{
System.out.print("----");
}
}
Its almost perfect except one number is out of place and is displaying as follows:
Original:
| 3 |
2 | 9 | 9 | 6 |
Sorted:
| 2 |
3 | 6 | 9 | 9 |
Frequencies:
Original:
| 9 |
1 | 6 | 6 | 4 | 8 | 5 | 8 | 5 | 1 |
Sorted:
| 1 |
1 | 4 | 5 | 5 | 6 | 6 | 8 | 8 | 9 |
Frequencies:
Can somebody please tell me what the problem is as I can't figure it out. Thanks for all of your help in the comments
System.out.println appends a newline after the output, that is, after every array item in your code. You should use System.out.print instead. Also it looks like you are only printing the pipes at the end of the array, making it look something like
34799|
For the example output you need something like
public void print()
{
//no need for \n, println produces one at the end of the string
System.out.println("-------------------");
System.out.print("|");
for(int i=0;i< intArray.length; i++)
{
System.out.print(intArray[i] + "|");
}
System.out.print("\n-------------------\n");
}
There is no need of if-else, we can print the array with a simple for loop, e.g.:
int[] array = new int[]{1,2,3,4,5};
System.out.println("--------------");
System.out.print("|");
for(int element : array){
System.out.print(element + "|");
}
System.out.println("--------------");
update
Here's how it works:
First println() prints first dashed line.
Second print() before the for loop prints initial '|'
print() in the for loop prints element appended by '|'
There is no need to print the last '|' it is already done in the for loop.
Last println() prints dashed line after the array contents.
Related
why is the output 22212345?
Shouldn't it be: "43212345", because when we are keep adding the first values of the string onto the previous version of the string.
So everytime we increment k, we are going from 2,3,4 and adding it onto the previous version.
why is the output 22212345?
String str = "12345";
for (int k = 1; k <= 3; k++)
str = str.charAt(k) + str;
So everytime we increment k, we are going from 2,3,4 and adding it onto the previous version.
No, you're not. You're prefixing str with the char at k.
So, if we get a pen and piece of paper and desk check the code (why don't people desk check anymore 😓) you will see what's actually happening...
+---+-----------+---------+-----------------------+
| k | char at k | str | result (charAt + str) |
+---+-----------+---------+-----------------------+
| 1 | 2 | 12345 | 212345 |
| 2 | 2 | 212345 | 2212345 |
| 3 | 2 | 2212345 | 22212345 |
+---+-----------+---------+-----------------------+
This happends in each iteration:
first_loop_state: {
k : 1
initial_str : "12345";
str.charAt(k) : '2'
final_str : "212345"
}
second_loop_state:{
k : 2
initial_str : "212345";
str.charAt(k) : '2'
final_str : "2212345"
}
third_loop_state:{
k : 3
initial str : "2212345";
str.charAt(k) : '2'
final_str : "22212345"
}
I've been scratching my head over this for awhile now. I'm quite new to programming, so my code may not be that efficient, but it's killing me that I can't figure out what's going wrong.
The goal is to compare 'uScore' (the score of the game just played, where lower is better) to the sorted list of highscores stored in the array of objects 'records', using records[i].getName() to retrieve the score at that position. I then mark the position where 'uScore' is to be inserted using 'insertScoreHere', then shift everything below it in the array down by one place. I then set the value of the score at 'insertScoreHere' to uScore, and the name to 'uName' (player name from game just played).
public void sortWinners() {
for (int i = 0; i < 10; i++) {
if (uScore < records[i].getScore()) {
insertScoreHere = i;
i = 10; //this is terrible i know
}
}
for (int i = 9; i > insertScoreHere; i--) {
records[i] = records[i-1];
}
records[insertScoreHere].setName(uName);
records[insertScoreHere].setScore(uScore);
}
Now if the player name from the most recent game is 'sam', and his score is '8', and the array is empty to start with, this is what is happening (below is the array 'records'):
NAME: sam, SCORE: 8
NAME: sam, SCORE: 8
NAME: , SCORE: 0
NAME: , SCORE: 0
NAME: , SCORE: 0
NAME: , SCORE: 0
NAME: , SCORE: 0
NAME: , SCORE: 0
NAME: , SCORE: 0
NAME: , SCORE: 0
I've logged everything as much as I can, adding this to my code:
public void sortWinners() {
for (int i = 0; i < 10; i++) {
if (uScore < records[i].getScore()) {
insertScoreHere = i;
i = 10;
}
}
Log.v("ARRAY", "PLACE TO INSERT SCORE: " + insertScoreHere);
for (int i = 9; i > insertScoreHere; i--) {
Log.v("ARRAY", "BEFORE ITERATION I = " + i + ": " +
" | " + records[0].getScore() +
" | " + records[1].getScore() +
" | " + records[2].getScore() +
" | " + records[3].getScore() +
" | " + records[4].getScore() +
" | " + records[5].getScore() +
" | " + records[6].getScore() +
" | " + records[7].getScore() +
" | " + records[8].getScore() +
" | " + records[9].getScore());
records[i] = records[i-1];
Log.v("ARRAY", " AFTER ITERATION I = " + i + ": " +
" | " + records[0].getScore() +
" | " + records[1].getScore() +
" | " + records[2].getScore() +
" | " + records[3].getScore() +
" | " + records[4].getScore() +
" | " + records[5].getScore() +
" | " + records[6].getScore() +
" | " + records[7].getScore() +
" | " + records[8].getScore() +
" | " + records[9].getScore());
}
records[insertScoreHere].setName(uName);
records[insertScoreHere].setScore(uScore);
Log.v("ARRAY", "AFTER SORTING");
for (int i = 0; i < 10; i++) {
Log.v("ARRAY", "NAME: " + records[i].getName() + ", SCORE: " + records[i].getScore());
}
}
Here's an example of the result of the logging. Say we have a populated array (where duplicates have already occurred), e.g:
NAME: milfred, SCORE: 1
NAME: milfred, SCORE: 1
NAME: timmy, SCORE: 3
NAME: john, SCORE: 5
NAME: sam, SCORE: 7
NAME: dhshs, SCORE: 8
NAME: , SCORE: 0
NAME: , SCORE: 0
NAME: , SCORE: 0
NAME: , SCORE: 0
Now let's say the next game that is played has a score of '6' and a player name 'stringray'. This is what my logging returns:
PLACE TO INSERT SCORE: 4
BEFORE ITERATION I = 9: | 1 | 1 | 3 | 5 | 7 | 8 | 0 | 0 | 0 | 0
AFTER ITERATION I = 9: | 1 | 1 | 3 | 5 | 7 | 8 | 0 | 0 | 0 | 0
BEFORE ITERATION I = 8: | 1 | 1 | 3 | 5 | 7 | 8 | 0 | 0 | 0 | 0
AFTER ITERATION I = 8: | 1 | 1 | 3 | 5 | 7 | 8 | 0 | 0 | 0 | 0
BEFORE ITERATION I = 7: | 1 | 1 | 3 | 5 | 7 | 8 | 0 | 0 | 0 | 0
AFTER ITERATION I = 7: | 1 | 1 | 3 | 5 | 7 | 8 | 0 | 0 | 0 | 0
BEFORE ITERATION I = 6: | 1 | 1 | 3 | 5 | 7 | 8 | 0 | 0 | 0 | 0
AFTER ITERATION I = 6: | 1 | 1 | 3 | 5 | 7 | 8 | 8 | 0 | 0 | 0
BEFORE ITERATION I = 5: | 1 | 1 | 3 | 5 | 7 | 8 | 8 | 0 | 0 | 0
AFTER ITERATION I = 5: | 1 | 1 | 3 | 5 | 7 | 7 | 8 | 0 | 0 | 0
AFTER SORTING
NAME: milfred, SCORE: 1
NAME: milfred, SCORE: 1
NAME: timmy, SCORE: 3
NAME: john, SCORE: 5
NAME: stingray, SCORE: 6
NAME: stingray, SCORE: 6
NAME: dhshs, SCORE: 8
NAME: , SCORE: 0
NAME: , SCORE: 0
NAME: , SCORE: 0
And lastly, here at my data types:
String uName;
int uScore;
playerRecord records[] = new playerRecord[10];
playerRecord:
public class playerRecord {
private String name;
private int score;
public playerRecord(String input_name, int input_score) {
name = input_name;
score = input_score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public void setName(String set_name) {
name = set_name;
}
public void setScore(int set_score) {
score = set_score;
}
}
Populating playerRecord:
for (int i = 0; i < 10; i++) {
records[i] = new playerRecord("", (0));
}
I hope I've been able to illustrate the issue properly. If any other details are needed please let me know.
You are having issues with memory pointers. Your array of 10 scores is actually an array of 10 pointers to playerRecord objects. I know it doesn't look like it, but this is what is happening behind the scenes when you have an array of objects.
The two duplicated elements in the array, after executing the sort operation, are actually addressing the same piece of memory!
Let's say i=4; and insertScoreHere = 3.
records[i] = records[i-1];
# records[4] = records[3];
# BUT what actually happens here is records[4] is now pointing to the
# same piece of memory as records[3]. So then:
# records[4] => memory_address_x
# records[3] => memory_address_x
records[insertScoreHere].setName(uName);
records[insertScoreHere].setScore(uScore);
#so now this code: records[3].setName(uName); is actually modifying
#the same piece of memory as records[4].
Solution #1:
Swap the pointers around as you do the sort. I'm going to use the object at i==9 since that one gets wiped anyway.
public void sortWinners() {
for (int i = 0; i < 10; i++) {
if (uScore < records[i].getScore()) {
insertScoreHere = i;
i = 10; //this is terrible i know
}
}
# EDIT 1: lets save this record for reuse
playerRecord temp = records[9];
for (int i = 9; i > insertScoreHere; i--) {
records[i] = records[i-1];
}
# EDIT 2: change the record to point to a separate record
records[insertScoreHere] = temp;
# ^ this index now points to a separate record from records[i]
records[insertScoreHere].setName(uName);
records[insertScoreHere].setScore(uScore);
}
Solution #2:
Another way to avoid messing with memory pointers will be to copy the data from one record to another:
public void sortWinners() {
for (int i = 0; i < 10; i++) {
if (uScore < records[i].getScore()) {
insertScoreHere = i;
i = 10; //this is terrible i know
}
}
for (int i = 9; i > insertScoreHere; i--) {
records[i].setName(records[i-1].getName()); # EDIT 1 **
records[i].setScore(records[i-1].getScore());# EDIT 2 **
}
records[insertScoreHere].setName(uName);
records[insertScoreHere].setScore(uScore);
}
The problem comes about with these lines when you want to insert your new score
records[insertScoreHere].setName(uName);
records[insertScoreHere].setScore(uScore);
What this is actually doing is replacing the name and score of the playerRecord that is at that index. Which has also the same object which you have now shuffled to the next index (insertScoreHere + 1)
To show you this all you need to do is print the address of the player records in your array:
playerRecord#996db8, playerRecord#996db8, playerRecord#163006a, playerRecord#1be847c, ...
This is after I have called your sortWinners method once - you can see that the first two elements in the array reference the same object playerRecord#996db8
To fix this you just need to insert the new score at that index by calling this
records[insertScoreHere] = new PlayerRecord(uName, uScore)
You might also want to review the naming conventions for Java
I'm working on an implementation of the "Merge Numbers" game, seen here on the Play store: https://play.google.com/store/apps/details?id=com.ft.game.puzzle.cubelevels
The idea is that if I have a 2D array of cells, some of which are empty and others of which have numbers, and I place a given number into an empty cell, then if that number matches at least 3 of its neighbors, the neighbors are made empty and the cell value is incremented. A simple example:
| 1 | 2 | 3 | 4 |
| 3 | | 2 | |
| 1 | 2 | 3 | |
| | 2 | 1 | 4 |
If the next number (generated randomly by the game) is 2, and I place it into cell (1, 1) (where (0, 0) is the upper left cell), the new game board should look like this:
| 1 | | 3 | 4 |
| 3 | 3 | | |
| 1 | | 3 | |
| | 2 | 1 | 4 |
The newly-placed 2 is incremented to 3, and the neighboring cells with value of 2 have been cleared.
I'm having trouble figuring out how to do this. Here is my code so far:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[][] w = {{1, 2, 3, 4}, {3, 0, 4, 0}, {1, 2, 3, 0}, {0, 2, 1, 4}};
Scanner input = new Scanner(System.in);
System.out.println("Enter space for putting 1: ");
int a = input.nextInt();
int b = input.nextInt();
if (a == 1 && b == 1) {
w[1][1] = 1;
for (a = 0; a < w.length; a++) {
for (b = 0; b < w[0].length; b++) {
System.out.print(w[a][b] + " ");
}
System.out.print('\n');
}
System.out.println("Enter space for putting 4: ");
a = input.nextInt();
b = input.nextInt();
if (a == 1 && b == 3) {
w[1][3] = 4;
for (a = 0; a < w.length; a++) {
for (b = 0; b < w[0].length; b++) {
System.out.print(w[a][b] + " ");
}
System.out.print('\n');
}
}
}
}
}
How can I check to see if the neighbors of the newly-added number have the same value?
How can I increment the newly-added number?
I'm trying to print my 2D array to the console as if the array were co-ordinates on a chess board for example, my code looks like this:
public Piece[][] getBoardView() throws NoBoardDefinedException
{
System.out.println(Arrays.deepToString(board));
return board;
}
This currently prints the 2D array in one straight line across the console, can anyone suggest a way to change this into a board style format?
Try this.
for (Piece[] row : board)
System.out.println(Arrays.toString(row));
if this is the case then you would get likewise,
int chessboard [][] = {
{1,2,3},
{4,5,6},
{7,8,9}
};
for(int i = 0; i < chessboard.length ; i ++){
System.out.println();
for(int j = 0 ; j < chessboard[i].length ; j++){
System.out.print(" | " + chessboard[i][j] );
}
System.out.print(" |");
System.out.println();
}
OUT PUT :
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
How do I find the complexity in tilde notation of the following algorithm:
for (int j = 0; j < N; j++) {
for (int k = j + 1; k < N; k++) {
array[k] = array[j];
}
array[j] = k
}
I've made a table with how many times the inner for-loop loops if N = 9:
| j | # of loops |
|:-----------|------------:|
| 0 | 8 |
| 1 | 7 |
| 2 | 6 |
| 3 | 5 |
| 4 | 4 |
| 5 | 3 |
| 6 | 2 |
| 7 | 1 |
| 8 | 0 |
As you evaluate, the number of inner iterations decreases linearly from 8 down to 0, i.e. it is 4 on average, for a total of 4.9=36.
More generally, the average is (N-1)/2 and the total N.(N-1)/2.
Consequently, I(N) ~ N²/2, in terms of the iteration count.
In terms of memory accesses (R+W), it's the double: A(N) ~ N². (The extra access in the outer loop adds a negligible N contribution.)