How to remove element from a raw array - java

I have a program that will push pop and display, but I cannot pop the pushed numbers in my program probably I can't delete the element of that array. This is my code so far:
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Class2 {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out
.print("1.)Push\n2.)Pop\n3.)Display\n4.)Exit\n\nChoose Item :");
int x = Integer.parseInt(in.readLine());
int[] a = new int[10];
int b = 0;
int i = 0;
do
{
switch (x) {
case 1:
System.out.print("Enter Push number :");
int v = Integer.parseInt(in.readLine());
a[b] = v;
b += 1;
System.out.print("Item push :" + v + "\n");
System.out
.print("1.)Push\n2.)Pop\n3.)Display\n4.)Exit\n\nChoose Item :");
x = Integer.parseInt(in.readLine());
if (x == 3) {
for (i = 0; i < b; i++) {
System.out.print(a[i] + " ");
}
}
break;
case 2:
System.out.print("Enter Pop Number :");
int c = Integer.parseInt(in.readLine());
if (c == a[i]) {
}
System.out.print("Item Pop :" + c + "\n");
System.out
.print("1.)Push\n2.)Pop\n3.)Display\n4.)Exit\n\nChoose Item :");
x = Integer.parseInt(in.readLine());
if (x == 3) {
for (i = 0; i < b; i++) {
System.out.print(a[i] + " ");
}
}
break;
case 4:
break;
}
} while (x == 1 || x == 2);
}
}

First of all, if you want to change the elements of an array, then you should not use an array.
If you really don't want to use containers, then you could allocate dynamically a new array without the element you want to remove (not so a good idea probably because of bad performance and wasted memory).
This could be the method that returns the new array:
public static int[] removeElementAt(int [] array, int index){
if(index > 0 && index < array.length){
int [] newArray = new int[array.length - 1];
for(int i=0; i<index; i++)
newArray[i] = array[i]; // copying elements
for(int i=index+1; i<array.length; i++)
newArray[i-1] = array[i];
array = newArray;
}
return array;
}
This is just a simple example:
myArray = Class.removeElementAt(myArray, 5); // removes 6. element
You could also use the function removeElement from the API ArrayUtils, something like this:
array = ArrayUtils.removeElement(array, element)
Another alternative would be to convert your array to a list, remove the element, and then convert it back to an array: not so a good idea, because you could use directly an ArrayList.
So, the idea is to use dynamic containers when you want to modify the content, otherwise use a normal raw array.

you can use below code and it might solve your issue.
int brr[]= new int [a.length-1];
int j=0;
for(;j<a.length;j++)
{
if(c== a[j])
{
break;
}
else{
brr[j]=a[j];
}
}
for(j=j+1;j<a.length;j++)
{
brr[j-1] =a[j];
}
in display show brr array.

When you push 2, 5, and 6 you have a queue with 3 items in it:
a[0] == 2
a[1] == 5
a[2] == 6
When you pop 2, you want to remove it from the array. To do this, you need to copy everything after where 2 was popped from into the position above, so that you end up with:
a[0] == 5
a[1] == 6
The code for this would look something like:
int popPosition = findPopPosition();
for(int i = popPosition + 1; i < MAX; i++)
a[i - 1] = a[i];
b--; // Decrease effective queue size
Where findPopPosition() would need to find the index that 2 is at, so it would return 0 in this example.
Or, alternatively, the user could input the pop position directly (so pop element 0) instead of specifying what value they want to pop. That's probably more useful.

Not all test cases have been handled, but a sample working program as per your requirements.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ArrayDemo {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Array Max Capacity");
int maxSize = Integer.parseInt(br.readLine().trim());
int[] array = new int[maxSize];
int arrayCount = 0;
int choice = 0;
do {
System.out.println("\n1.Insert\n2.Delete\n3.Display\n4.Exit");
choice = Integer.parseInt(br.readLine().trim());
switch (choice) {
case 1:
boolean insertTrue = insertElement(br, maxSize, array,
arrayCount);
if (insertTrue) {
arrayCount++;
}
break;
case 2:
System.out.println("Enter Element to delete");
int delElement = Integer.parseInt(br.readLine().trim());
int numOccurrence = getOccurrenceCount(array, arrayCount,
delElement);
int newArrayCount = arrayCount - numOccurrence;
if (numOccurrence == 0) {
System.out.println("No Such Element to delete");
} else {
array = deleteElement(array, arrayCount, delElement,
newArrayCount,maxSize);
}
arrayCount =newArrayCount;
break;
case 3:
displayArray(array, arrayCount);
break;
case 4:
System.out.println("Exiting");
break;
default:
System.out.println("Invalid Choice, Exiting");
choice = 4;
}
} while (choice >= 1 && choice <= 3);
}
private static int[] deleteElement(int[] array, int arrayCount,
int delElement, int newArrayCount,int maxSize) {
int newArray[] = new int[newArrayCount];
int index=0;
for (int i = 0; i < arrayCount; i++) {
if (array[i] != delElement) {
newArray[index] = array[i];
index++;
}
}
resetArray(array, maxSize);
for(int i=0;i<newArrayCount;i++){
array[i]=newArray[i];
}
return array;
}
private static int[] resetArray(int[] array,int maxSize){
for(int i=0;i<maxSize;i++){
array[i]=0;
}
return array;
}
private static int getOccurrenceCount(int[] array, int arrayCount,
int delElement) {
int numOccurrence = 0;
for (int i = 0; i < arrayCount; i++) {
if (array[i] == delElement) {
numOccurrence++;
}
}
return numOccurrence;
}
private static void displayArray(int[] array, int arrayCount) {
if (arrayCount == 0) {
System.out.println("No Elements to Display");
} else {
System.out.println("Array is");
for (int i = 0; i < arrayCount; i++) {
System.out.print(array[i] + " ");
}
System.out.println("\n");
}
}
private static boolean insertElement(BufferedReader br, int maxSize,
int[] array, int arrayCount) throws IOException {
if (arrayCount < maxSize) {
System.out.println("Enter Element for Insertion");
array[arrayCount] = Integer.parseInt(br.readLine().trim());
return true;
} else {
System.out.println("Max Limit Reached, Insertion not possible");
return false;
}
}
}

Related

Magic Square in Java: Why always prints: Magic Squares cannot be created?

In the code below i try to read a file with the size of a 2d array and the numbers for each cell. Then the program must find a number that can be added in the cell with a zero value in magic array. All this in order to create magic squares based on the initialized magic array with the elements of the external file. The problem is that i always get the message "magic squares cannot be created" even when the if statement in next_successor method get true from all the arguments? where is the problem? i got really stuck any help will be appreciated!
so i think the main problem is with the methods:
next_successor
check_row
check_column
check_diagonals
The rules that i have to follow in order to create the methods are:
In order for current_number to be inserted into magic[row,column], the following checks (by check_row(), check_column() and check_diagonals()) should be made:
For each of the row, column, and possibly main diagonals (in the case of row=column or row=N-column-1) to which position magic[row,column] belongs, and for each current_number that does not has yet been inserted into the magic square (according to the value used[current_number-1]), we perform the following checks to decide whether current_number can be inserted into magic[row,column]:
Suppose (in the row or column or main diagonal where the position magic[row,column]) is located after the number current_number is placed in the position magic[row,column], m positions have been filled, so there are N-m empty positions left to be filled.
Let 𝑠 be the sum of the numbers already in the row or column or main diagonal (including current_number).
Let 𝑎 be the sum of the 𝑁−𝑚 smallest numbers (from 1 to N*N) not yet entered into the magic square (according to the table used) and 𝑏 the sum of the 𝑁−𝑚 largest numbers not yet entered (similarly) . If 𝑚=𝑁 then 𝑎=𝑏=0.
Let 𝐶 be the magic constant. If 𝑠+𝑎>𝐶 or 𝑠+𝑏<𝐶, for some row or column or main diagonal to which magic[row, column] belongs, then current_number cannot be inserted into position magic[row,column ], i.e. the respective check_row(), check_column() and check_diagonals() will return false, otherwise they will all return true.
the txt external file has the following elements:
6
0 0 13 0 20 0
0 15 0 0 0 12
8 0 2 0 31 0
0 14 0 7 0 1
28 0 0 0 0 0
0 0 6 0 0 21
import java.io.*;
import java.util.*;
public class MainSolver{
static ArrayList<MagicSquare> stuckAL;
static Stack<MagicSquare> stuckST;
static LinkedList<MagicSquare> stuckLL;
static int datastructure;
static int N = 0;
static int[][] input;
public static void main() throws IOException {
//THE PROGRAM READS THE EXTERNAL FILE
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
System.out.println("Enter data structure to use: (arraylist, stack, queue, linkedlist): ");
System.out.println("1: arraylist");
System.out.println("2: stack");
System.out.println("3: queue");
System.out.println("4: linkedlist");
datastructure = sc.nextInt();
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
N = fileScanner.nextInt();
input = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
input[i][j] = fileScanner.nextInt();
}
}
MagicSquare.size = N;
MagicSquare ms = new MagicSquare();
for(int i=0; i<N ;i++){
for(int j=0; j<N ;j++){
ms.set_cell(i,j,input[i][j]);
if (ms.magic[i][j] != 0) {
ms.used[ms.magic[i][j]-1] = true;
}
}
}
ms.check_used();
//PRINTING THE INPUT AND MAGIC ARRAY
System.out.println("Size of array from file: "+N);
ms.display(input);
System.out.println();
System.out.println("Size of array from MagicSquare object: "+ms.N);
ms.display(ms.magic);
fileScanner.close();
//IT STARTS THE INITIALIZATION OF DATASTRUCTURES & START THE SEARCH OF SUCCESSORS
initialize_search(ms,datastructure);
search(datastructure);
}
//THIS PART OF CODE NEEDS TO STAY AS IT IS. CAN'T MAKE CHANGES
static void initialize_search(MagicSquare ms, int datastructure) {
switch (datastructure) {
case 1:
case 2:
stuckAL = new ArrayList();
stuckAL.add(ms);
break;
case 3:
stuckST=new Stack();
stuckST.push(ms);
break;
case 4:
stuckLL=new LinkedList();
stuckLL.add(ms);
break;
default:
break;
}
}
//THIS PART OF CODE NEEDS TO STAY AS IT IS. CAN'T MAKE CHANGES
static void search(int datastructure) {
MagicSquare current = null, next;
switch (datastructure) {
case 1:
System.out.println("Search using ArrayList as a Stack");
break;
case 2:
System.out.println("Search using ArrayList as a Queue");
break;
case 3:
System.out.println("Search using Stack as a Stack");
break;
case 4:
System.out.println("Search using LinkedList as a Queue");
break;
default:
break;
}
boolean empty_frontier=false;
while (!empty_frontier) {
if (datastructure == 1) {
current = stuckAL.get(stuckAL.size()-1);
stuckAL.remove(stuckAL.size()-1);
}
else if (datastructure == 2) {
current = stuckAL.get(0);
stuckAL.remove(0);
}
else if (datastructure == 3)
current = stuckST.pop();
else if (datastructure == 4)
current = stuckLL.removeFirst();
current.initialize_successors();
while((next=current.next_successor()) != null)
{
if (next.numbers == N*N)
{
System.out.println("SOLUTION FOUND ");
System.out.println("==============");
next.display(next.magic);
return;
}
else switch (datastructure) {
case 1: ;
case 2: stuckAL.add(next);
break;
case 3: stuckST.push(next);
break;
case 4: stuckLL.addLast(next);
break;
}
}
switch (datastructure) {
case 1:
if (stuckAL.isEmpty())
empty_frontier=true;
break;
case 2:
if (stuckAL.isEmpty())
empty_frontier=true;
break;
case 3:
if (stuckST.isEmpty())
empty_frontier=true;
break;
case 4:
if (stuckLL.isEmpty())
empty_frontier=true;
break;
}
}
System.out.println("MAGIC SQUARES CANNOT BE CREATED");
}
}
class MagicSquare {
public static int size;
public int N;
public int C;
public int[][] magic;
public boolean[] used;
public int numbers;
public int row;
public int column;
public int current_number;
//THIS CONSTRUCTOR WITHOUT ARGUMENTS INITIALIZE N and C, the magic array and the numbers variable with zeros, as well as the used array with false values.
public MagicSquare() {
this.N = size;
C = N*((N*N+1)/2);
magic = new int[N][N];
used = new boolean[N*N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
magic[i][j] = 0;
}
}
for (int i = 0; i < used.length; i++) {
used[i] = false;
}
numbers = 0;
row = 0;
column = 0;
current_number = 0;
}
//THIS CONSTRUCTOR creates a copy of the object (mainly regarding the N, C, magic, numbers and used variables)
public MagicSquare(MagicSquare ms) {
N = ms.N;
C = ms.C;
magic = new int[N][N];
used = new boolean[N*N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
magic[i][j] = ms.magic[i][j];
}
}
for (int i = 0; i < used.length; i++) {
used[i] = ms.used[i];
}
numbers = ms.numbers;
row = ms.row;
column = ms.column;
current_number = ms.current_number;
}
//METHOD THAT IS CALLED TO FILL EACH CELL OF MAGIC ARRAY WITH NUMBER FROM EXTERNAL FILE
public void set_cell(int row, int col, int number){
if (number>=1 && number<=N*N && row>=0 && row<N*N && col>=0 && col<N*N && magic[row][col]==0){
magic[row][col] = number;
numbers++;
}
}
//METHOD THAT: "initializes" the process of constructing the "successors" of a MagicSquare object. As a successor we characterize a new object, which is in principle the same as its "parent" (with regard to the fields magic, numbers and used), but has an additional position of the magic square filled in in a valid way. The initialize_successors() method will practically give as values to the row and column fields the row and column of the next null of the magic table, while in addition it will initialize the value of the current_number field (eg, to 0).
public void initialize_successors() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (magic[i][j] == 0) {
row = i;
column = j;
current_number = 0;
return;
}
}
}
}
//METHOD THAT: each time it is called it will find the next value of current_number that can be placed in magic[row,column], construct an object that is a copy of the current object, but with the current_number in magic[row,column], and will return it. If no next value of current_number is found that can be inserted into magic[row, column], it will return null. In order for the current value of current_number to be inserted in the magic[row, column] position, this value must not already be used in the magic square (checked via the used table), and the methods check_row(), check_column() and check_diagonals() to return true.
public MagicSquare next_successor() {
MagicSquare successor;
while (current_number < N*N) {
current_number++;
if (!used[current_number-1] && check_row() && check_column() && check_diagonals()) {
successor = new MagicSquare(this);
successor.magic[row][column] = current_number;
successor.used[current_number-1] = true;
successor.numbers++;
/*if(column == N-1) {
successor.row++;
successor.column = 0;
}
else {
successor.column++;
}*/
System.out.println("next successor returns successor!");
return successor;
}
//break;
}
System.out.println("next successor returns null!");
return null;
}
//METHOD THAT: returns true if current_number is consistent with the row numbers of magic[row,column], otherwise returns false.
public boolean check_row(){
int sum = current_number;
int m = numbers;
int emptyPositions = N - m;
int a = getSumOfSmallestElementsNotUsed();
int b = getSumOfLargestElementsNotUsed();
System.out.println();
System.out.println("current number being tested in row: "+current_number);
for (int i = 0; i < N; i++) {
if (magic[row][i] != 0) {
sum += magic[row][i];
}
}
System.out.println("sum of numbers in row: "+sum);
if (sum + a > C || sum + b < C) {
System.out.println("row gives false!");
return false;
}
System.out.println("row gives true!");
return true;
}
//METHOD THAT: returns true if current_number is consistent with the column numbers of magic[row,column], otherwise returns false.
public boolean check_column(){
int sum = current_number;
int m = numbers;
int emptyPositions = N - m;
int a = getSumOfSmallestElementsNotUsed();
int b = getSumOfLargestElementsNotUsed();
System.out.println("current number being tested in column: "+current_number);
for (int i = 0; i < N; i++) {
if (magic[i][column] != 0) {
sum += magic[i][column];
}
}
System.out.println("sum of numbers in column: "+sum);
if (sum + a > C || sum + b < C) {
System.out.println("column gives false!");
return false;
}
System.out.println("column gives true!");
return true;
}
//METHOD THAT: which will return true if current_number is consistent with the numbers of each of the two main diagonals of the magic square, provided that magic[row,column] belongs to one or the other or both of the main diagonals of the magic square respectively, otherwise it will return false.
public boolean check_diagonals(){
int sum = current_number;
int m = numbers;
int emptyPositions = N - m;
int a = getSumOfSmallestElementsNotUsed();
int b = getSumOfLargestElementsNotUsed();
System.out.println("current number being tested in diagonals: "+current_number);
if (row == column) { //main diagonal
for (int i = 0; i < N; i++) {
if (magic[i][i] != 0) {
sum += magic[i][i];
}
}
} else if (row == N-column-1) { //other diagonal
for (int i = 0; i < N; i++) {
if (magic[i][N-i-1] != 0) {
sum += magic[i][N-i-1];
}
}
}
System.out.println("sum of numbers in diagonal: "+sum);
if (sum + a > C || sum + b < C) {
System.out.println("diagonals gives false!");
return false;
}
System.out.println("diagonals gives true!");
return true;
}
//METHOD THAT: calculate the sum of the 2 first empty elements of used array and therefore the smallest
public int getSumOfSmallestElementsNotUsed(){
int sum = 0;
int count = 0;
for (int i = 0; i < used.length; i++) {
if (!used[i]) {
sum += (i + 1);
count++;
}
if (count == 2) {
break;
}
}
System.out.println("sum of 2 smallest elements: "+sum);
return sum;
}
//METHOD THAT: calculate the sum of the 2 last empty elements of used array and therefore the largest
public int getSumOfLargestElementsNotUsed(){
int sum = 0;
int count = 0;
for (int i = used.length - 1; i >= 0; i--) {
if (!used[i]) {
sum += (i + 1);
count++;
}
if (count == 2) {
break;
}
}
System.out.println("sum of 2 largest elements: "+sum);
return sum;
}
public boolean isComplete() {
return numbers == N*N;
}
public void display(int array[][]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
public void check_used(){
int i,j;
int k=0;
for(i=0; i<magic.length; i++){
for(j=0; j<magic[i].length; j++){
System.out.println("POSITION IN USED ARRAY: "+k+" WITH VALUE: "+used[k]+" FROM POSITION IN MAGIC ARRAY: "+i+","+j+" WITH VALUE: "+magic[i][j]);
k++;
}
}
}
}
What do you think this computes?
this.N = size;
C = N*((N*N+1)/2); // C = 108
The size is 6 for your problem.
So you will need the values 1 thru 36 inclusive.
let max = N*N. So the sum of 1 thru 36 is max*(max+1)/2.
divide by N to get the col or row sum and you ((max*(max+1))/2)/N = 111.
or (N*(max+1))/2)
in your case is should have been (N*(N*N+1))/2.
The issue was that. (N*N+1) is 37. Then you divide by 2 which drops the fraction (int arithemetic). You need to first multiply by N and then divide by 2.

unable to sort or print out array

I got a task to write the methods to 1. take information in and save it into array, 2. to copy the array(only with previously given arguments) and 3. to sort the array to be in descending order. it seems to me like i got the first 2 parts working but i have been stuck on the third method for 2 days without any progress. i am still learning java so i'm pretty sure i have made a dumb mistake somewhere. thanks in advance.
import java.util.*;
public class RevisionExercise {
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(realArray, tempArray);
setArray(realArray);
printArray(realArray);
}
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int i;
for (i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
tempArray[i] = reader.nextInt();
if (tempArray[i] == 0) {
return tempArray[i];
}
}
return i;
}
private static int[] copyInfo(int[] realArray, int[] tempArray)
{
int targetIndex = 0;
for( int sourceIndex = 0; sourceIndex < tempArray.length; sourceIndex++ )
{
if( tempArray[sourceIndex] != 0 )
tempArray[targetIndex++] = tempArray[sourceIndex];
}
realArray = new int[targetIndex];
System.arraycopy( tempArray, 0, realArray, 0, targetIndex );
return realArray;
}
public static int[] setArray(int[] realArray)
{
int temp = 0;
for (int i = 0; i <realArray.length; i++) {
for (int j = i+1; j <realArray.length; j++) {
if(realArray[i] >realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
return realArray;
}
public static void printArray(int[] realArray ) {
System.out.println("\nOrdered array: ");
for(int i = 0; i < realArray .length; i++) {
System.out.println(realArray [i]);
}
}
}
the output i'm getting looks like this.
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
while it should look like this:
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
9
8
6
5
3
You made a mistake in calculating the total numbers entered by the user. Your function always return 0. So change it to something like this:
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int totalNumbers = 0;
for (int i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
int number = reader.nextInt();
if (number != 0) {
totalNumbers++;
tempArray[i] = number;
} else {
break;
}
}
return totalNumbers;
}
Chage the sort function to this:
public static void setArray(int[] realArray) {
int temp = 0;
for (int i = 0; i < realArray.length; i++) {
for (int j = i+1; j < realArray.length; j++) {
// Use < for descending order and > for ascending order
if(realArray[i] < realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
}
Your main program
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(tempArray, realArray, amountOfNumbers);
setArray(realArray);
printArray(realArray);
}
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int totalNumbers = 0;
for (int i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
int number = reader.nextInt();
if (number != 0) {
totalNumbers++;
tempArray[i] = number;
} else {
break;
}
}
return totalNumbers;
}
private static void copyInfo(int[] tempArray, int[] realArray, int size) {
for( int sourceIndex = 0; sourceIndex < size; sourceIndex++ )
{
realArray[sourceIndex] = tempArray[sourceIndex];
}
}
public static void setArray(int[] realArray) {
int temp = 0;
for (int i = 0; i < realArray.length; i++) {
for (int j = i+1; j < realArray.length; j++) {
if(realArray[i] < realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
}
public static void printArray(int[] realArray ) {
System.out.println("\nOrdered array: ");
for(int i = 0; i < realArray.length; i++) {
System.out.println(realArray [i]);
}
}
To begin with, in the askInfo method, the size of the realArray will always be 0, since amountOfNumbers is the return of
if (tempArray[i] == 0) {
return tempArray[i];
}
because your condition is tempArray[i] == 0, hence you are always returning 0. Then your copyInfo method is returning an array but you have nothing receiving the returned array. I would suggest changing your copyInfo method to
private static int[] copyInfo(int[] tempArray)
{
// same
int [] realArray = new int[targetIndex];
// same
}
and your main method to
public static void main(String[] args) {
//same
int[] realArray = new int[amountOfNumbers];
realArray = copyInfo(tempArray);
// same
}
General remark: Each of your methods returns an array but you never use this return value.
There are 2 modifications necessary to fix your code:
Keep the value of the method output:
realArray=copyInfo(realArray, tempArray);
So you put the result of the copy in the realArray variable.
You expect the askInfo method to return the number of entered numbers but in fact you return the value of the last entered number.
So instead of return tempArray[i]; you have to return i;

Generating 10 random numbers without duplicate with fundamental techniques

my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!
You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.
Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...
Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.
I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}
Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}
This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}
public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}
Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}

How to find the most frequent digit in a number string?

/*I am a beginner in programming.As a part of an assignment, I have to find the most frequent digit in a number string.Though my code gets compiled, it doesn't give me the correct results.Please help me with this.
*/
import java.util.*;
public class program
{
public int test(String number)
{
int freq0,freq1,freq2,freq3,freq4,freq5,freq6,freq7,freq8,freq9;
freq0=0;
freq1=0;
freq2=0;
freq3=0;
freq4=0;
freq5=0;
freq6=0;
freq7=0;
freq8=0;
freq9=0;
for (int i =0; i<number.length();i++)
{
switch (number.charAt(i))
{
case 48: freq0++;
break;
case 49: freq1++;
break;
case 50: freq2++;
break;
case 51: freq3++;
break;
case 52: freq4++;
break;
case 53: freq5++;
break;
case 54: freq6++;
break;
case 55: freq7++;
break;
case 56: freq8++;
break;
case 57: freq9++;
break;
}
}
List<Integer> hope = new ArrayList<Integer>();
hope.add(freq0);
hope.add(freq1);
hope.add(freq2);
hope.add(freq3);
hope.add(freq4);
hope.add(freq5);
hope.add(freq6);
hope.add(freq7);
hope.add(freq8);
hope.add(freq9);
int temp=0;
for (int j=0; j<(hope.size());j++)
{
if (temp<hope.get(j))
{
temp=hope.get(j);
}
}
return temp;
}
}
//this class is called by another main class.I am writing it's code too.
public class checker
{
public static void main ( String args [])
{
int inputs[] = {1234, 11, 144, 97764 };
int outputs[] = {1, 1, 4, 7};
for(int i=0; i<inputs.length; i++) {
int input=inputs[i];
int oracle_output=outputs[i];
program p = new program();
String input_string = "" + input;
int output = p.test(input_string);
if(output==oracle_output) {
System.out.println("test passed for " + input);
} else {
System.out.println("test failed for " + input);
}
}
}
}
What you could do is just use a simple array.
long number = 12345612;
int []frequency = new int[10];
while(number > 0)
{
int digit = number % 10;
number /= 10;
frequency[digit] ++;
}
for(int i = 0; i < 10; ++i)
System.out.println(frequency[i]);
If it is a String.
String str = "12342352397235823050237238523";
int []frequency = new int[10];
for(int i = 0; i < str.length(); ++i)
{
int digit = str.charAt(i) - '0';
frequency[digit] ++;
}
for(int i = 0; i < 10; ++i)
System.out.println(frequency[i]);
To get the maximum occuring digit.
int maxFrequency = 0;
int index = 0;
for(int i = 0; i < 10; ++i){
if(frequency[i] > maxFrequency){
maxFrequency = frequency[i];
index = i;
}
}
System.out.println("The highest occuring digit is " + index + " occuring " + maxFrequency + " times(s)");
The mistake in your program was that you're not considering the digit which repeated many times, you're taking into account the number of times only. And hence you get only the frequency not the digit.
Like it is said in the comment, the code can be made simpler (and more readable)
However, the answer to your question is this: the return value (temp) is the frequency of the most frequent digit, instead of the digit itself (which is j, you hust need to "remember" it)
Here is more readable and simpler code:
import java.util.ArrayList;
import java.util.List;
public class MostFrequentDigits1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long number = 12345612;
String str = "12342352397235823050237238523";
getMostFrequentDigitWInNumber(number);
getMostFrequentDigitInString(str);
}
public static void getMostFrequentDigitWInNumber(long number) {
List<Integer> list = new ArrayList<Integer>();
int[] frequency = new int[10];
int mostFrequentVal = 0;
while (number > 0) {
int digit = (int) (number % 10);
number /= 10;
frequency[digit]++;
if (frequency[digit] > mostFrequentVal) {
mostFrequentVal = frequency[digit];
}
}
for (int j = 0; j < frequency.length; j++) {
if (frequency[j] == mostFrequentVal) {
list.add(j);
}
}
System.out.println("most frequent digits in Number:" + list);
}
public static void getMostFrequentDigitInString(String str) {
List<Integer> list = new ArrayList<Integer>();
int mostFrequentVal = 0;
int[] frequency = new int[10];
for (int k = 0; k < str.length(); k++) {
char c = str.charAt(k);
int ind = Integer.valueOf(String.valueOf(c));
frequency[ind]++;
if (frequency[ind] > mostFrequentVal) {
mostFrequentVal = frequency[ind];
}
}
for (int j = 0; j < frequency.length; j++) {
if (frequency[j] == mostFrequentVal) {
list.add(j);
}
}
System.out.println("most frequent digits in string:" + list);
}
}

How can I convert this to work with array lists instead of arrays?

This code takes a random sampling of numbers, plugs them into an array, counts the odd numbers, and then lets the user pick an integer to see if it matches. This works great now with just arrays, but I want to convert it to work with ArrayLists. What's the easiest way to do this?
import java.util.Scanner;
import java.util.Random;
public class ArrayList {
public static void main(String[] args) {
// this code creates a random array of 10 ints.
int[] array = generateRandomArray(10);
// print out the contents of array separated by the delimeter
// specified
printArray(array, ", ");
// count the odd numbers
int oddCount = countOdds(array);
System.out.println("the array has " + oddCount + " odd values");
// prompt the user for an integer value.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find in the array:");
int target = input.nextInt();
// Find the index of target in the generated array.
int index = findValue(array, target);
if (index == -1) {
// target was not found
System.out.println("value " + target + " not found");
} else {
// target was found
System.out.println("value " + target + " found at index " + index);
}
}
public static int[] generateRandomArray(int size) {
// this is the array we are going to fill up with random stuff
int[] rval = new int[size];
Random rand = new Random();
for (int i = 0; i < rval.length; i++) {
rval[i] = rand.nextInt(100);
}
return rval;
}
public static void printArray(int[] array, String delim) {
// your code goes here
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i < array.length - 1)
System.out.print(delim);
else
System.out.print(" ");
}
}
public static int countOdds(int[] array) {
int count = 0;
// your code goes here
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 1)
count++;
}
return count;
}
public static int findValue(int[] array, int value) {
// your code goes here
for (int i = 0; i < array.length; i++)
if (array[i] == value)
return i;
return -1;
}
}
I rewrite two of your functions,maybe they will useful for you.
public static List<Integer> generateRandomList(int size) {
// this is the list we are going to fill up with random stuff
List<Integer> rval = new ArrayList<Integer>(size);
Random rand = new Random();
for (int i = 0; i < size; i++) {
rval.add(Integer.valueOf(rand.nextInt(100)));
}
return rval;
}
public static int countOdds(List<Integer> rval) {
int count = 0;
for (Integer temp : rval) {
if (temp.intValue() % 2 == 1) {
count++;
}
}
return count;
}

Categories

Resources