Bubble pop using boolean in java. - java

import java.util.*;
public class Zhangbubble
{
public static void main (String[] args)
{
int Bub[] = new int[6];
Random randy = new Random();
boolean Done = false;
for (int x=0; x<6; x++)
{
Bub[x] = randy.nextInt(100);
System.out.println (Bub[x]);
}
System.out.println ("This is the original array");
while (! Done)
{
Done = true;
for (int x = 0; x<Bub.length-1; x++)
{
if(Bub[x+1] > Bub[x])
{
int temp = Bub[x];
Bub[x] = Bub[x+1];
temp = Bub[x+1];
Done = false;
}
else
{
Done = false;
}
}
for(int x = 0; x<6; x++)
{
System.out.print(Bub[x]+" ");
}
}
}
}
So my programming teacher asked us to make a bubble sort in java using a boolean. His example shows the code in a while loop with for loops. This code is suppose to continuously sort until it has the numbers in the array organized from least to greatest. However, I'm really lost and I can't seem to figure out where I'm going wrong. Any help would be greatly appreciated!

The problem is in your switching algorithm. You are assigning temp twice.
int temp = Bub[x];
Bub[x] = Bub[x+1];
temp = Bub[x+1]; //Here should assign Bub[x+1] to temp
//Example: Bub[x+1] = temp
edit-Actually, there could be some improvement in the sorting algorithm itself, too. Personally, I like to do it this way:
public class Sort {
private static int[] array = { 3, 8, -1, 7, 0, 3 };
public static void main(String[] args) {
for(int i = 0; i < array.length - 1; i++) {
for(int j = i + 1; j < array.length; j++) {
if(array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for(int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}

this working
public static void main(String[] args) {
int Bub[] = new int[6];
Random randy = new Random();
boolean Done = false;
for (int x=0; x<6; x++)
{
Bub[x] = randy.nextInt(100);
System.out.println (Bub[x]);
}
System.out.println ("This is the original array");
while ( ! Done)
{
for (int x = 0; x<Bub.length-1; x++)
{
if(Bub[x+1] > Bub[x])
{
int temp = Bub[x];
Bub[x] = Bub[x+1];
Bub[x+1]=temp ;
Done = false;
}
else
{
Done = false;
}
}
for(int x = 0; x<6; x++)
{
System.out.print(Bub[x]+" ");
}
Done = true;
}
}

Related

How to make every index of 2D array a random integer?

`import java.util.Random;
public class Main {
public static void main(String[] args) {
int[][] board = new int[5][5];
int sNA = 5;
// new GUI();
sequenceMaker(board);
drawBoard(board);
}
//
public static void drawBoard(int[][] board2D) {
int m=1;
for(int i = 0; i < board2D.length; i++){
for(int j=0; j < board2D.length; j++){
System.out.print(board2D[i][j]+" ");
}
System.out.println();
}
}
public static void sequenceMaker(int[][] board2D) {
Random rand = new Random();
int m = 1;
int x = 0;
while(x < 24){
int columnRandom = rand.nextInt(5);
int rowsRandom = rand.nextInt(5);
x += 1;
if(board2D[columnRandom][rowsRandom] == 0) {
board2D[columnRandom][rowsRandom] = m;
m += 1;
}
else if(board2D[columnRandom][rowsRandom] == m) {
while(board2D[columnRandom][rowsRandom] == m) {
columnRandom = rand.nextInt(5);
rowsRandom = rand.nextInt(5);
board2D[columnRandom][rowsRandom] = m;
m+=1;
}
}
}
}
}`
This is what I wrote to this point, but the output doesn't include every index, maximally going to 15-16ish.
I tried a while loop, so that if another integer is in the place of randomally generated number, it generates those number once again. I don't know why my output is incomplete though.
I have solved my own question (I think).
What I have changed is that in the sequenceMaker() function, I have moved the x+=1 into the if statements. The code looks like this :
public static void sequenceMaker(int[][] board2D) {
Random rand = new Random();
int m = 1;
int x = 0;
while(x < 25){
int columnRandom = rand.nextInt(5); // random column
int rowsRandom = rand.nextInt(5); // random row
if(board2D[columnRandom][rowsRandom] == 0) {
board2D[columnRandom][rowsRandom] = m;
m += 1;
x += 1;
}
else if(board2D[columnRandom][rowsRandom] != 0) {
while(board2D[columnRandom][rowsRandom] == 0) {
columnRandom = rand.nextInt(5);
rowsRandom = rand.nextInt(5);
board2D[columnRandom][rowsRandom] = m;
m+=1;
x += 1;
}
}
}
}
I hope my mediocrity helped someone!
public static void sequenceMaker(int[][] board2D) {
//it will initialize your array with random integers
Random rand = new Random();
for(int i=0; i<board2D.length; i++){
for(int j=0; j < board2D[i].length; j++ ){
int randomNo = rand.nextInt(20); //you can change the bound as required
board2D[i][j] = randomNo;
}
}
}

how I can sort and find the duplication in the array and return if there is a duplication?

how I can sort and find the duplication in the array and return if there is a duplication?
I have an array with this code
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int r = input.nextInt();
int[] list = new int[r];
init(list);
static void init(int list[]) {
Random random = new Random();
for (int i = 0; i < list.length; i++) {
int n = (int) (Math.random() * 50 + 1);
list[i] = random.nextInt(50) + 1;
}
}
static void print(int list[]) {
for (int i : list) {
System.out.print(i + " ");
}
}
}
how can I sort it in another method and find the duplication
From you question I understand You want the duplicate items in an array.
Here is an example using naive approach. Please don't use it if you have very large array!!!
public static void main (String [] args) {
System.out.println("Hello world");
int [] myarray = {1,3,4,2,2,2,3};
int [] duplicates = findDuplicates(myarray);
System.out.println(Arrays.toString(duplicates));
}
private static int [] findDuplicates( int [] list) {
int [] countingArray = new int[1];
int n = 0;
for (int i = 0; i < list.length; i++) {
for (int j = i + 1 ; j < list.length; j++) {
if (list[i] == list[j]) {
boolean flag = true;
for (int k = 0; k < countingArray.length; k++) {
if ((countingArray[k] == list[i])) {
flag = false;
}
}
if (flag) {
if (n == countingArray.length) countingArray = resizeBy1(countingArray);
countingArray[n++] = list[i];
}
}
}
}
return countingArray;
}
private static int [] resizeBy1(int [] s) {
int [] newArray = new int[s.length +1];
for (int i = 0; i< s.length; i++) {
newArray[i] = s[i];
}
s = newArray;
return s;
}
If you want to know an advance approach please look at Finding repetition in array

How can I check if every single int in a randomly generated array is even and make it create another random array if it's not?

So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10.
Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers.
The problem right now is that I can't understand how to fix the last for and make it work properly with the boolean b that is supposed to restart the creation of the array.
import java.util.Scanner;
public class EvenArrayGenerator {
public static void main(String a[]) {
Boolean b;
do {
b = true;
int[][] Array = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
Array[i][j] = (int) (Math.random() * 11);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Array[i][j] % 2 != 0)
b = false;
}
}
} while (b);
}
}
public class ArrayGen {
private int[][] array = new int[4][4];
private int iterations = 1; // you always start with one iteration
public static void main (String[] args) {
ArrayGen ag = new ArrayGen();
ag.reScramble();
while(!ag.isAllEven()) {
ag.reScramble();
ag.iterations++;
}
// this is just a nice visualisation
for (int i = 0; i < 4; i++) {
System.out.print("[");
for (int j = 0; j < 4; j++) {
System.out.print(ag.array[i][j] +((j != 3)? ", " : ""));
}
System.out.print("]\n");
}
System.out.println(ag.iterations + " iterations needed to get all-even array.");
}
private void reScramble () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = (int)(Math.random() * 11);
}
}
}
private boolean isAllEven () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (array[i][j] % 2 == 1) {
return false;
}
}
}
return true;
}
}
I think this is a good solution. Refactoring your code into structured methods is never a bad idea. I hope this helps!
You are looping until you get an array that's all even. You should initialize b to be false, and update it to true in the (nested) for loop. Note that once's you've set it to false, there's no reason checking the other members of the array, and you can break out of the for loop.
Note, also, that using stream could make this check a tad more elegant:
b = Arrays.stream(arr).flatMapToInt(Arrays::stream).anyMatch(x -> x % 2 != 0)
What about generating random numbers up to 5 and double it? Then you don't have two check if they are even.
Instead of your last for loop:
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(Array[i][j] % 2!=0){
b=false;
break;
}
}
if(!b){
break;
}
}
if(!b){
break;
}
Alternatively, you could do an oddity check when you are generating the elements. Something like:
int element;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
do{
element = (int)(Math.random()*11);
}while(element % 2 !=0)
Array[i][j] = element;
}
}
That way you don't have to check the values, they will always be even.
This should work:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
anyOdd |= Array[i][j] % 2!=0;
}
}
} while(anyOdd);
}
}
As you can see, I just modified the condition from b to anyOdd, so if there is any odd number, it will iterate again.
Also, you can check it when you generate the random numbers, so you avoid a second loop:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
anyOdd |= array[i][j] % 2 != 0;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
} while(anyOdd);
}
}
public class EvenArrayGenerator {
public static void main(String a[]) {
int[][] arr = createAllEvenArray(4);
printArray(arr);
}
private static int[][] createAllEvenArray(int size) {
while (true) {
int[][] arr = createArray(size);
printArray(arr);
if (isAllEven(arr))
return arr;
}
}
private static int[][] createArray(int size) {
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
arr[i][j] = (int)(Math.random() * 11);
return arr;
}
private static void printArray(int[][] arr) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0)
System.out.print("\t");
System.out.format("%2d", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
private static boolean isAllEven(int[][] arr) {
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
if (arr[i][j] % 2 != 0)
return false;
return true;
}
}

Improve performance of reversing array

I am trying to solve question at Reverse Game
When I submit my code, in some of the testcases it is getting timeout.
I think problem may be in reverseSubArray() method but I am not sure how to improve performance here.
Following is my code:
public class ReverseGame
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int testCases = Integer.parseInt(scanner.nextLine());
int[] numberOFBalls = new int[testCases];
int[] ballNumberArray = new int[testCases];
for (int i = 0; i < testCases; i++)
{
numberOFBalls[i] = scanner.nextInt();
ballNumberArray[i] = scanner.nextInt();
}
for (int i = 0; i < testCases; i++)
{
process(numberOFBalls[i], ballNumberArray[i]);
}
scanner.close();
}
private static void process(int totalNumberOFBalls, int ballNumber)
{
int[] ballsArray = new int[totalNumberOFBalls];
int maximumNumberOnBall = totalNumberOFBalls - 1; // This is because
// balls are numbered
// from 0.
// As the first step is to reverse the Balls arrangement, So insert into
// ballsArray in descending order of index.
for (int i = 0; i < totalNumberOFBalls; i++)
ballsArray[i] = maximumNumberOnBall--;
for (int i = 1; i < totalNumberOFBalls; i++)
{
ballsArray = reverseSubArray(ballsArray, i);
}
int position = findPosition(ballsArray, ballNumber);
System.out.println(position);
}
private static int[] reverseSubArray(int[] a, int fromIndex)
{
int temp = 0, counter = 1;
int midIndex = (a.length - fromIndex) / 2;
for (int i = fromIndex; i < fromIndex + midIndex; i++)
{
temp = a[a.length - (counter)];
a[a.length - (counter)] = a[i];
a[i] = temp;
counter++;
}
/*
* System.out.println(); for (int i = 0; i < a.length; i++)
* System.out.print(a[i] + " ");
*/
return a;
}
private static int findPosition(int[] ballsArray, int ballNumber)
{
for (int i = 0; i < ballsArray.length; i++)
{
if (ballsArray[i] == ballNumber)
return i;
}
return 0;
}
}
The time complexity of your solution is O(n ^ 2). It is too slow for n = 10 ^ 5. So you need to use a better algorithm. Here is simple linear solution which uses the fact that we do not need to know the positions of all balls(we need only the k-th):
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int testsCount = in.nextInt();
for (int t = 0; t < testsCount; t++) {
int n = in.nextInt();
int k = in.nextInt();
// Simulates all rotations,
// but keeps track only of the k-th ball.
// It does not matter what happens to the others.
for (int i = 0; i < n; i++)
if (k >= i)
k = i + n - 1 - k;
out.println(k);
}
out.flush();
}
}
This solution has an O(n) time complexity and easily passes all test cases.
It is actually possible to find the positions of all balls in linear time, but it is not required here.

How to find the Odd and Even numbers in an Array?

Right now, I'm trying to find the odd and even numbers of an array. Here's the code of what I have so far. I know my findEvens() and findOdds() methods are messed up because they keep giving me off values whenever I try to print the final result. For example, if I try to find the odds of {1,5,8,3,10}, it gives me {5,3,0}. And if I try to find the evens of {2,5,8,7,19}, it gives me {2,8,0}. Anyone know why?
public class Scores {
private int[] numbers;
public Scores(int[] numbersIn) {
numbers = numbersIn;
}
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberEvens++;
}
}
int[] evens = new int[numberEvens];
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
evens[count] = numbers[i];
count++;
}
}
return evens;
}
public int[] findOdds() {
int numberOdds = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberOdds++;
}
}
int[] odds = new int[numberOdds];
int count = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] % 2 == 1) {
odds[count] = numbers[i];
count++;
}
}
return odds;
}
public double calculateAverage() {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return (double) sum / numbers.length;
}
public String toString() {
String result = "";
for (int i = 0; i < numbers.length; i++) {
result += numbers[i] + "\t";
}
return result;
}
public String toStringInReverse() {
String result = "";
for (int i = numbers.length - 1; i >= 0; i--) {
result += numbers[i] + "\t";
}
return result;
}
}
You're problem is in counting how many even numbers you have
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberEvens++;
}
}
this will always return a number that is half the size of the length of numbers because you're doing mod division on the number of elements in the array, not on the elements themselves. Add numbers[i] to the if statement
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
numberEvens++;
}
}
looks like you've got the same problem with odd count
'i' is used as conditional variable for looping. You should not divide this by 2. You have to divide the array element. like
if (numbers[i] % 2 == 0) {
numberEvens++;
}
then it should work. Thanks
Try This Code
import java.util.Scanner;
public class OddEven {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter number Elements in Array");
int n = s.nextInt();
int arr[] = new int[n];
System.out.println("enter Elements ");
for(int i=0; i<n; i++) {
arr[i]=s.nextInt();
}
int [] odd = filterOdd(arr);
try {
for(int i=0; i<n; i++) {
System.out.println("Odd" + odd[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {}
int [] even = filterEven(arr);
try {
for(int i=0; i<n; i++) {
System.out.println("Even" + even[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {}
}
public static int[] filterOdd(int[] a) {
int l = 0;
int j = 0;
for(int i=0; i<a.length; i++) {
if(a[i]%2==1) {
l++;
}
}
int k[]=new int[l];
for(int i=0; i<a.length; i++) {
if(a[i]%2==1) {
k[j] = a[i];
j++;
}
}
return k;
}
public static int[] filterEven(int[] a) {
int l = 0;
int j = 0;
for(int i=0; i<a.length; i++) {
if(a[i]%2==0) {
l++;
}
}
int k[] = new int[l];
for(int i=0; i<a.length; i++) {
if(a[i]%2==0) {
k[j] = a[i];
j++;
}
}
return k;
}
}
public class Array {
public static void main(String[] args) {
// TODO code application logic here
//Array declaration and value asign
int number[]=new int[]{1,2,3,4,5,6,7,8,9};
// for loop to move number
for(int p=0;p<number.length;p++)
{
// check number is even or odd??
if(number[p]%2==0)
System.out.println(number[p]+ " is Even number");
else
System.out.println( number[p]+" is odd umber");
}
}
}
Odd array one columns and another columns even array
public class OddEven {
public static void main(String[] args) {
int arr[]={1,2,3,4,5,6,7,8};
int ss[]=new int[10];
int odd[]=new int[10];
int i;
int k;
for( i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
{
ss[i]=arr[i];
System.out.print(""+ss[i]);
System.out.print(" ");
}
if((arr[i]%2)!=0)
{
odd[i]=arr[i];
System.out.print(""+odd[i]);
System.out.print(" ");
}else
{
System.out.println(" ");
}
}
}
}
========================================output==============================
1 2
3 4
5 6
7 8

Categories