How do I replace duplicate numbers in an integer array? - java

My question is a very basic one. To give a bit of background, I was given an assignment to write a program that stored 100 unique (i.e no repeats)values into an array and displayed them. I thought I was on the right track earlier, but when I did a test run, all I keep getting is an "out of bounds error." Eclipse tells me it's in the method "checkDouble" but I can't seem to find what's wrong. Can anyone here help me out?
public class exercise2 {
/*#author Paolo
* #param hundredVal array to store values
* #param input random number generator from 1-100
*/
public static int[] hundredVal = new int[100];
public static int n = (int) (Math.random()*100+1);
public static void main(String[] args) {
storeVal();
}
/*
* This method is meant to take 100 random values
* from 1-100 and store them into the array hundredVal
*/
private static void storeVal() {
for (int i = 0; i < hundredVal.length; i++){
hundredVal[i] = (int) (Math.random()*100+1);
if(!checkDouble(hundredVal)){
printVal();
}
}
}
//This method is meant to test if there are any repeated values
public static boolean checkDouble (int[] hundredVal){
for (int i = 0; i < hundredVal.length; i++){
for (int j = 0; i < hundredVal.length; j++){
if (hundredVal[i] == hundredVal [j] && i != j){
return true;
}
}
}
return false;
}
//this just prints out the numbers on the console.
private static void printVal(){
for (int i =0; i < hundredVal.length; i++){
System.out.println(hundredVal[i]);
}
}
}
I don't want anyone to solve the whole assignment for me. I just want to know what is causing the out of bounds error to occur.

class exercise2{
public static int[] hundredVal = new int[100];
public static int n = (int) (Math.random()*100+1);
public static void main(String[] args) {
storeVal();
printVal();
}
private static void storeVal() {
for (int i = 0; i < hundredVal.length; i++){
hundredVal[i] = (int) (Math.random()*100+1);
}
if(!checkDouble(hundredVal)){
printVal();
}
}
public static boolean checkDouble (int[] hundredVal){
for (int i = 0; i < hundredVal.length; i++){
for (int j = 0; j < hundredVal.length; j++){
if (hundredVal[i] == hundredVal [j] && i != j){
return true;
}
}
}
return false;
}
private static void printVal(){
for (int i =0; i < hundredVal.length; i++){
System.out.println(hundredVal[i]);
}
}}

You can go with appropriate java collection - in your case LinkedHashSet should do the job. It's a Set (contains unique values) and it's ordered. It's almost always better to go with collections instead of arrays.

Related

Java Methods and Arrays

I am just starting out in Java and I have searched through the internet for several hours and cannot seem to find something to help me on an assignment. I have an array and I need to write a method for it. It seems easy but I cannot seem to connect the two together. I understand the methods but we did not go over using them with arrays so I am totally confused. If there is a similar answer on here, please point me in the right direction.
Thank you for your time.
Question:
Write a method which takes in an integer from the user between 1 and 10 and determines if that number is part of the randomly generated array. It must have a method signature of (int []) and return a boolean.
public class ArrayExample {
public int [] createRandomArray() {
int size = (int) (Math.random() * 10) + 1;
int[] array = new int [size];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10 ) + 1;
}
return array;
}
public static void main(String [] args) {
}
}
It will be something like below:
public class ArrayExample {
public static int [] createRandomArray() {
int size = (int) (Math.random() * 10) + 1;
int[] array = new int [size];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10 ) + 1;
}
return array;
}
private static boolean checkForNumInArray(int[] randomArrayInput){
//your logic goes here
// ask user for input number - Scanner/BufferedReader
//search for that number in array - Loops
// if found return true, otherwise return false - if-else
}
public static void main(String [] args) {
int[] randomArray = createRandomArray();
boolean isPresent = checkForNumInArray(randomArray);
}
}
You can go through the code to have understanding
public class ArrayExample {
public int [] createRandomArray() {
int size = (int) (Math.random() * 10) + 1;
int[] array = new int [size];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10 ) + 1;
}
return array;
}
public int getUserInput() {
//Take input from user and check it is between 1 and 10.
}
public boolean search(int[] arr, int input) {
// Use some searching algorithm. Linear search will suit as the array is randomly generated.
// if input is present in array return true else return false.
}
public static void main(String [] args) {
int input = getUserInput();
boolean result = search(createRandomArray(), input);
//Print a message based on result.
}
}
In the main method you simply have to iterate the loop of integers from one to ten and check if it is present in the array you have created.
public static void main(String[] args) {
int arr[] = createRandomArray();
for(int i=0;i<=10;i++) {
if(Arrays.binarySearch(arr, i) == 0) { System.out.println("yes"); }
}
}

Tower of Hanoi using 2D arrays issue

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;
}

Method to rotate the specified row of a 4x4 array initialised with integers 0-15?

Basically I have a 2D puzzle which is represented as a 4x4 integer array. The Array is initialised with integers 0..15 I have to Implement the method:
public static void play(int[][] puzzle)
method should take as its argument a 4x4 integer array that represents the puzzle after it has been scrambled. The method should be implemented using a loop that repeatedly:
1.Prints the current state of the puzzle
2.Asks the player to enter a rotation command
3.Performs the rotation requested by the player
The loop should terminate once the puzzle is back in its original unscrambled state which means it has to be back to the original Puzzle in order of the numbers 0 to 15.
The program should display a congratulation message when this happens.
The program should include user input validation.
Whenever the user input is invalid, the program should print the warning Invalid input!
User input is valid if it is in the form of one of the two commands row or column rotation.
The template of the Puzzle is :
public class Puzzle {
public static final int N = 4;
public static final int NUMBER_OF_ROTATIONS = 5;
public static void main(String[] args) {
int[][] puzzle = new int[N][N];
reset(puzzle);
test(puzzle);
reset(puzzle);
scramble(puzzle);
System.out.println("### Testing puzzle game play\n");
play(puzzle);
}
public static void print(int[][] puzzle) {
for (int[] row : puzzle) {
for (int elem : row) {
System.out.printf("%4d", elem);
}
System.out.println();
}
System.out.println();
}
public static void test(int[][] puzzle) {
System.out.println("### Testing reset method\n");
print(puzzle);
System.out.println("### Testing rotate methods\n");
print(puzzle);
for (int i = 0; i < N; i++) {
System.out.println("### rotateColumn(" + i + ")\n");
rotateColumn(puzzle, i);
print(puzzle);
System.out.println("### rotateRow(" + i + ")\n");
rotateRow(puzzle, i);
print(puzzle);
}
reset(puzzle);
System.out.println("### Testing random rotations\n");
print(puzzle);
for (int i = 0; i < 5; i++){
randomRotation(puzzle);
print(puzzle);
}
}
public static void reset(int[][] puzzle) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
puzzle[i][j] = i * N + j;
}
}
public static void scramble(int[][] puzzle) {
for (int i = 0; i < NUMBER_OF_ROTATIONS; i++) {
randomRotation(puzzle);
}
}
public static void rotateRow(int[][] arr, int row) {
for (int i= arr.length-1; i>0; i--) {
int r= (int) (Math.random() * (i+1)); int[] c = arr[i];
arr [i] = arr[r];
arr[r] = c;
}
}
// TODO: Implement method as specified in assignment brief
public static void rotateColumn(int[][] arr, int column) {
}
// TODO: Implement method as specified in assignment brief
public static void randomRotation(int[][] puzzle) {
}
// TODO: Implement method as specified in assignment brief
static void play(int[][] puzzle) {
}
}
As you can see, I have tried to implement the rotating the row method but after I run it, the whole array gets changed instead of a specified row. Can someone please show me what I am doing wrong? Thank you :).
Try this:
public static void rotateRow(int[][] arr, int row) {
int newCurrent = arr[row][arr.length - 1];
int nextCurrent;
for (int currentIndex = 0; currentIndex < arr.length; currentIndex++) {
nextCurrent = arr[row][currentIndex];
arr[row][currentIndex] = newCurrent;
newCurrent = nextCurrent;
}
}
I tested it out and it works great as far as I can tell.

How to remove duplicates from array using for loop

In this code I have found duplicates from an array and I want to remove them. The output then will be unique generated numbers. I am required to use math.random and modulo. Anyone have any clues? I tried to store them in an array but then the original array has 0's and 0 is part of my domain for the random number generation (from 0 to 52).
public class Decks {
public static void main(String[] args) {
generate();
}
public static void generate() {
int deckOfCard[] = new int[52];
for (int counts = 0; counts < 52; counts++) {
deckOfCard[counts] = (int) (Math.random() * 51);
}
for (int i = 0; i < deckOfCard.length - 1; i++) {
for (int j = i + 1; j < deckOfCard.length; j++) {
if ((deckOfCard[i] == (deckOfCard[j])) && (i != j)) {
System.out.println("DUPLICATE " + deckOfCard[i]);
}
}
}
for (int count = 0; count < deckOfCard.length; count++) {
System.out.print("\t" + deckOfCard[count]);
}
}
Why dont you try using HashSet instead of arrays ? As you know sets only store unique values so you wont have any duplicates.
You must validate the numbers generated during the random number generation like this:
import java.util.Random;
public class Decks {
public static void main(String[] args) {
Random myRandom = new Random();
int[] num = new int[53];
boolean[] check = new boolean[53];
int all = 0;
int ranNum;
while (all < 53) {
ranNum = myRandom.nextInt(53);
if (!check[ranNum]) {
check[ranNum] = true;
num[all] = ranNum;
all++;
}
}
for (int i = 0; i < 53; i++) {
System.out.println(num[i]);
}
}
}
I suggest not including number 0 because it does not exist in a real deck of cards (ACE being the lowest having the number value of 1). I just included it right here because in my understanding, 0 is included in your desired output.
Considering time complexity, you can sort them first, which at best case takes nlogn time, and then use O(1) to find duplicated elements out.

Null Pointer Exception - Printing 2d array

I'm having an issue with attempting to print a 2 dimensional array, I continually get a nullpointer exception at the first for loop in printArray(), and at printArray(). I do know what a nullpointerexception means, I'm just having a hard time understanding why I'm getting it. I've ran into this problem before while trying to print an array and it'd be great for me to finally figure this out.
import java.lang.*;
import java.util.*;
public class Board {
int N = 3;
static int [][] unittest;
//construct a board from an N-by-N array of blocks
//(where blocks[i][j] = block in row i, column j)
public Board(int[][] blocks){
blocks = new int[N][N]; //creates array of size N
//generates random numbers 0 inclusive to # exclusive
//Random r = new Random(); uses blocks[i][j] = r.nextInt();
for (int i = 0; i < blocks.length; i++){
for (int j = 0; j < blocks[i].length; j++){
blocks[i][j] = randInt(0,9);
}
}
unittest = blocks.clone();
}
//generates random numbers in a range
private static int randInt( int min, int max){
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
//board size N
public int size(){
return 0; //placeholder
}
//number of blocks out of place
public int hamming(){
return 0; //placeholder
}
//sum of manhattan distances between blocks and goal
public int manhattan(){
return 0;
}
//is this board the goal board?
public boolean isGoal(){
return true; //placeholder
}
//is the board solvable?
public boolean isSolvable(){
return true; //placeholder
}
//does this board equal y?
//Object because can only take objects
//does it use Comparable?
public boolean equals(Object y){
return true; //placeholder
}
//all neighboring boards
public Iterable<Board> neighbors(){
Stack<Board> placeholder = new Stack<Board>();
return placeholder;
}
//string representation of the board
public String toString(){
return "placeholder";
}
//unit test
private static void printArray(){
for (int i = 0; i < unittest.length; i++){ //**NULL POINTER EXCEPTION
for (int j = 0; j < unittest[i].length; j++){
System.out.print(unittest[i][j]);
if (j < unittest[i].length - 1){
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String[] args){
//prints out board
printArray(); //**NULL POINTER EXCEPTION
}
}
The problem lies in the test condition of printArray() function:
for (int i = 0; i < unittest.length; i++)
Here, unitest is a null object and when you try to apply length method on it, its throwing and exception.
Basically, you are not initializing the unittest object (2D array in your case). You can do something like this to avoid the exception:
private static void printArray(){
if(unittest == null)
System.out.println("its NULL");
else{
for (int i = 0; i < unittest.length; i++){ //**NULL POINTER EXCEPTION
for (int j = 0; j < unittest[i].length; j++){
System.out.print(unittest[i][j]);
if (j < unittest[i].length - 1){
System.out.print(" ");
}
}
System.out.println();
}
}
}
Hope it helps :)
static int [][] unittest;
is null when you call it
you have never initialized the array, nor put anything into it
Beyond initializing the array you have an off by one error
public Board(int[][] blocks){
blocks = new int[N][N]; //creates array of size N
//generates random numbers 0 inclusive to # exclusive
//Random r = new Random(); uses blocks[i][j] = r.nextInt();
for (int i = 0; i < blocks.length; i++){ <----------------- blocks length should be blocks.length-1
for (int j = 0; j < blocks[i].length; j++){ <---------------------also blocks [i].length - 1
blocks[i][j] = randInt(0,9);
}

Categories