Java Search array for number - java

I have a project where I need to search an array of 50 elements and not only print those elements, which is figured out, but I need to find a number, boolean check = false, say 10 and if I do print a message box that I found it!
import java.util.*;
public class IT145_Homework_5_4 {
public static void main(String args[]) {
double alpha[] = new double[50];
boolean check = false;
// Initialize the first 25 elements of the array (int i=0; i<25; i++)
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
// Initialize the last 25 elements of the array (i=25; i<50; i++)
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
// Print the element of the array
System.out.println("The values are: ");
print(alpha);
}
// Print method to display the element of the array
private static void print(double m_array[]) {
for (int i = 1; i <= m_array.length; i++) {
System.out.print(m_array[i - 1] + " ");
if (i % 10 == 0)
System.out.print("\n");
}
}
}

public class IT145_Homework_5_4
{
public static void main(String args[])
{
double alpha[] = new double[50]; // all the values are whole numbers, why not make them of type int?
// Initialize the first 25 elements of the array (int i=0; i<25; i++)
for (int i = 0; i < 25; i++)
alpha[i] = i * i;
// Initialize the last 25 elements of the array (i=25; i<50; i++)
for (int i = 25; i < 50; i++)
alpha[i] = 3 * i;
// Print the element of the array
System.out.println("The values are: ");
print(alpha);
// Searches for value in array
double valueToFind = 100;
if(find(alpha, valueToFind))
System.out.println(valueToFind + " is in the array");
else
System.out.println(valueToFind + " is not in the array");
}
// Print method to display the element of the array
private static void print(double m_array[])
{
for (int i = 1; i <= m_array.length; i++)
{
System.out.print(m_array[i - 1] + "\t\t");
if (i % 10 == 0)
System.out.print("\n");
}
}
//Method to find element in array
private static boolean find(double m_array[], double valueToFind)
{
for(int i = 0; i < m_array.length; i++) //remember that arrays start with index 0
if(m_array[i] == valueToFind)
return true;
return false;
}
}

private static void print(double m_array[]) {
boolean check = false;
int result = 0;
for (int i = 1; i <= m_array.length; i++) {
System.out.print(m_array[i - 1] + " ");
if (i % 10 == 0)
System.out.print("\n");
if(m_array[i-1] == 10){
result = m_array[i - 1];
check = true;
}
}
if(check){
//Print message box with value stored in "result" variable
}
}

Related

Java How do i repeat sort until no swaps are done in bubblesort?

I am taking 10 elements and performing a bubble sort on them. I want to add an algorithm that repeats the sort until no swaps are needed to make this more efficient.
Essentially I want to:
repeat until no swaps done in a pass
For elements 1 to (n-1)
compare contents of element value 1 with the contents of the next value
if value 1 is greater than value 2
then swap the values
This is what I have done so far :
{
//create array
int[] iList = new int[10];
Scanner sc = new Scanner(System.in);
//takes in array input for 10 numbers
System.out.println("Enter a array of numbers ");
for(int i = 0; i< 10; i++ )
{
int num = i + 1;
System.out.println("Enter number " + num);
iList[i] = sc.nextInt();
}
//Bubble sorts the array
System.out.println("The array =");
for(int a = 0; a < iList.length; a++ )
{
for(int b = a+1; b < iList.length; b++)
{
if(iList[a] > iList[b])
{
int iTemp = iList[a];
iList[a] = iList[b];
iList[b] = iTemp;
}
System.out.println("Progress = " + Arrays.toString(iList) );
}
}
} ```
Here is my implementation :
public static void sort(int[] nums) {
boolean isSwapped;
int size = nums.length - 1;
for (int i = 0; i < size; i++) {
isSwapped = false;
for (int j = 0; j < size - i; j++) {
if (nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
isSwapped = true;
}
}
if (!isSwapped) break;
}
System.out.println("Sorted Array: " + Arrays.toString(nums));
}

Using for loop to find an element that appears multiple times in a random, unsorted array

My goal is to print out a user input value (and its corresponding index) if it appears 1 or more times in a random generated array of 50 integers. If I search the array for a value, and it happens to appear more than once, however, only one location of the element is printed, and then the if-else statement is executed. If I remove the break at the end of the third for loop, the whole thing falls apart. I've attached an image but here is the part of it that is giving me an issue. Apologies if the code is not clean, I'm very new.
public static void main(String[] args) {
System.out.println("IDS201 HW3:\n");
System.out.println("1. Generate 50 random integer unsorted list.\n");
Scanner stdin = new Scanner(System.in);
int[] randomNumbers = new int[50];
for(int index = 0; index < randomNumbers.length; index++) {
randomNumbers[index] = (int) (Math.random()*100);
}//end for
int count = 0;
for(int i = 0; i < randomNumbers.length; i++) {
System.out.print(randomNumbers[i] + ",");
count++;
if(count == 10) {
System.out.println();
count = 0;
}
}//end for
System.out.println("\nSearch value?");
int x = stdin.nextInt();
int i;
for(i = 0; i < randomNumbers.length; i++) {
if(randomNumbers[i] == x)
break;}
if (i != randomNumbers.length) {
System.out.println("\nFound " + x + " in array [" + i + "]");}
else {
System.out.println(x + " is not in the list");}
{int temp;
int size = randomNumbers.length;
for(i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(randomNumbers[i]>randomNumbers[j]){
temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
System.out.println("\nSmallest element of the array is: " + randomNumbers[0]);}
System.out.println("\n3. Sort the list:");
int size = randomNumbers.length;
for(i=0; i<size; i++)
{
for(int j=i+1; j<size; j++)
{
if(randomNumbers[i] > randomNumbers[j])
{
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
System.out.print("Now the Array after Sorting is :\n\n");
int count1 = 0;
for(i=0; i<size; i++)
{
System.out.print(randomNumbers[i]+ ",");
count++;
if(count == 10) {
System.out.println();
count = 0;
}
}
}
}
if statement in for loop
Implementing the comments to your question:
import java.util.Scanner;
public class NumCount {
private static final int RANDOM_NUMBER_COUNT = 50;
private static void display(int[] randomNumbers) {
int count = 0;
for (int i = 0; i < RANDOM_NUMBER_COUNT; i++) {
System.out.print(randomNumbers[i] + ",");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
}
private static int[] generateRandomNUmbers() {
int[] randomNumbers = new int[RANDOM_NUMBER_COUNT];
for (int index = 0; index < RANDOM_NUMBER_COUNT; index++) {
randomNumbers[index] = (int) (Math.random() * 100);
}
display(randomNumbers);
return randomNumbers;
}
private static int search(int[] randomNumbers, int x) {
int i;
int count = 0;
for (i = 0; i < randomNumbers.length; i++) {
if (randomNumbers[i] == x) {
System.out.println("\nFound " + x + " in array [" + i + "]");
count++;
}
}
return count;
}
private static int[] sort(int[] randomNumbers) {
int size = randomNumbers.length;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (randomNumbers[i] > randomNumbers[j]) {
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
return randomNumbers;
}
/**
* Start here.
*/
public static void main(String[] args) {
System.out.println("IDS201 HW3:\n");
System.out.println("1. Generate " + RANDOM_NUMBER_COUNT + " random integer unsorted list.\n");
int[] randomNumbers = generateRandomNUmbers();
System.out.print("\n2. Search value? ");
Scanner stdin = new Scanner(System.in);
int x = stdin.nextInt();
int count = search(randomNumbers, x);
if (count == 0) {
System.out.println(x + " is not in the list");
}
System.out.println("\n3. Sort the list:");
sort(randomNumbers);
System.out.print("Now the Array after Sorting is :\n\n");
display(randomNumbers);
}
}
Of-course there is no need to search for the smallest number because it will be the first element in the sorted array. Hence I removed that part of your code.

How to print the index number of an element in two dimensional arrays in java?

So this is the code, i displayed a multiple of 5 and then shuffled it.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class TwoDimensionalArrays {
public static void main(String[] args) {
This part is the display of multiple of 5 numbers up to 500.
int [][]table = new int[10][10];
int x = 5;
for(int i = 0; i < table.length; i++){
for(int j=0; j < table[i].length; j++){
table[i][j]= x;
x+=5;
System.out.print(table[i][j] + "\t");
}
System.out.println();
}
This part is the shuffled arrays using Math.random.
System.out.println("\nShuffled Arrays: \n");
int index1 = 0;
for(int a = 0; a < table.length; a++) {
for(int b = 0; b < table[a].length; b++) {
int il = (int)(Math.random()*table.length);
int jl = (int)(Math.random()*table[a].length);
int temp = table[a][b];
table[a][b] = table[il][jl];
table[il][jl] = temp;
System.out.print(table[a][b] + "\t");
}
System.out.println();
}
}
}
How can i print the index number of an element, for example, 40, from the shuffled arrays?
Please check the below answer. Here I added seperate for loops to print the shuffled array. Because in your current implementation after printing table[a][b] value, that value can be gain replaced by the randomly generated indexes. So Best way is print the shuffled array after completely shuffled it. Used Map<String, Integer> to keep the indexes with values. Please check the below code:
public static void main(String[] args) {
int[][] table = new int[10][10];
int x = 5;
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
table[i][j] = x;
x += 5;
System.out.print(table[i][j] + "\t");
}
System.out.println();
}
System.out.println("\nShuffled Arrays: \n");
Map<String, Integer> map = new HashMap<>(); //Hash map to keep indexes
//Shuffle the array
for (int a = 0; a < table.length; a++) {
for (int b = 0; b < table[a].length; b++) {
int il = (int) (Math.random() * table.length);
int jl = (int) (Math.random() * table[a].length);
int temp = table[a][b];
table[a][b] = table[il][jl];
table[il][jl] = temp;
}
}
//Print shuffled array
for (int a = 0; a < table.length; a++) {
for (int b = 0; b < table[a].length; b++) {
int value = table[a][b];
System.out.print(value + "\t");
//Insert indexes to hash map as key value pairs
String key = a + ", " + b;
if (value == 40 || value == 320 || value == 450) {
map.put(key, value);
}
}
System.out.println();
}
//Printing indexes
System.out.println("\nIndexes: \n");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getValue() + " [" + entry.getKey() + "]");
}
}
So the idea here is to check if value on random index is present in existing array(before shuffled), if yes then add the random entry into a map with value as newly assigned index in shuffled array, so this way once your shuffled array is ready, you have the completed map with all the details of each value and its index in shuffled array
public static void main(String [] args) {
int [][]table = new int[10][10];
Map<Integer,String> map = new HashMap<>();
int x = 5;
for(int i = 0; i < table.length; i++){
for(int j=0; j < table[i].length; j++){
table[i][j]= x;
x+=5;
System.out.print(table[i][j] + "\t");
}
System.out.println();
}
System.out.println("\nShuffled Arrays: \n");
int index1 = 0;
for(int a = 0; a < table.length; a++) {
for(int b = 0; b < table[a].length; b++) {
int il = (int)(Math.random()*table.length);
int jl = (int)(Math.random()*table[a].length);
int temp = table[a][b];
if(exists(table[il][jl], table)) {
map.put(table[il][jl], "["+a + "][" + b + "]");
}
table[a][b] = table[il][jl];
table[il][jl] = temp;
System.out.print(table[a][b] + "\t");
}
System.out.println();
}
System.out.println(map);
}
public static boolean exists(int value, int[][] tmp) {
List<int[]> list = Arrays.asList(tmp);
for(int[] arr: list){
if(Arrays.stream(arr).anyMatch(i -> i == value)) {
return true;
}
}
return false;
}
Hope this will help..!!

I am trying this simple sudoku

I am trying a simple sudoku program. i started by taking the values in a 3D
array and then copied them into a 1D array by using mr.serpardum's method.
i know that there is an error at the point where i am trying to find
duplicate elements,because even if i give same numbers as input the output
says "its a sudoku" but i can't to find it...apparently i can't add any
image coz i dont have enough credits
public class SecondAssignment {
#SuppressWarnings("unused")
public static void main(String[] args) throws IOException {
int i = 0, j = 0, k = 0;
boolean result = false;
int arr1[][];
arr1 = new int[3][3];
int arr2[];
arr2 = new int[9];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the elements in the sudoku block");
//getting elements into array
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr1[i][j] = Integer.parseInt(br.readLine());
}
}
//printing it in matrix form
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
System.out.print(arr1[i][j] + "\t");
}
System.out.println(" ");
}
//copying array1 elements into array 2
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr2[i * 3 + j] = arr1[i][j];
}
}
//finding duplicate elements
for (i = 0; i < arr2.length; i++) {
for (int m = i + 1; m < arr2.length; m++) {
if (arr2[i] == (arr2[m])) {
System.out.println("Not a sudoku");
//result = true;
} else {
System.out.println("Its a sudoku");
//result = false;
}
}
}
}
}
You can update your code to following
//finding duplicate elements
for( i = 0; i < arr2.length; i++){
for(int m = i+1; m < arr2.length; m++){
if(arr2[i] == (arr2[m])){
result = true;
break;
}
}
}
if(result){
System.out.println("\nNot a sudoku");
}
else{
System.out.println("\nIts a sudoku");
}
You should have used break as soon as the match was found.
This code just checks if duplicate element is present in the array (of size 9) or not.

Problems Sorting a two column array and outputting value frequency in Java

Here is the problem I have, I spent a long time toying with for loops and arrays and temp variables, and now my output is just a couple numbers.
/*
Write a program that reads numbers from the keyboard into an array of type int[].
You may assume that there will be 50 or fewer entries in the array. Your program
allows any number of numbers to be entered, up to 50. The output is to be a
two-column list. The first column is a list of the distinct array elements;
the second is the count of the number of occurrences of each element.
The list should be sorted on entries in the first column, largest to smallest.
For the array:
-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12
the output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
*/
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[][] twoColumn = new int[2][50];
int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
//gather user input to fill an array (up to 50 values);
System.out.println("Input up to 50 values.");
for (int i = 0; i < 50; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
/*System.out.println("Press 0 to stop, or 1 to continue.");
if (keyboard.nextInt() == 0) {
break;
}
else if (keyboard.nextInt() == 1){
continue;
}
else if (keyboard.nextInt() != 0 && keyboard.nextInt() != 1) {
System.out.println("You must enter 0 or 1. Now you must re-enter the value.");
i--;
}*/
}
// checking if each value occurs more than once, and assigning it a place
// in the two column array if it is unique.
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (i == 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace] = inputValues[i];
} else if (i > 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace + 1] = inputValues[i];
}
}
}
lastUsedSpace = -1;
//Sorting the first column of the two column array
for (int i = 0; i < twoColumn.length; i++) {
for (int j = 0; j < twoColumn.length; j++) {
if (twoColumn[0][i] < twoColumn[0][j + 1]) {
temp = twoColumn[0][j + 1];
twoColumn[0][j + 1] = twoColumn[0][i];
twoColumn[0][i] = temp;
}
}
}
// filling in the frequency column of the array
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (inputValues[i] == inputValues[j]) {
valueFrequency = valueFrequency + 1;
}
if (j <= inputValues.length - 1 && lastUsedSpace == -1) {
lastUsedSpace = 0;
twoColumn[1][0] = valueFrequency;
valueFrequency = 0;
} else if (j <= inputValues.length - 1 && lastUsedSpace > -1) {
twoColumn[1][lastUsedSpace + 1] = valueFrequency;
valueFrequency = 0;
}
}
}
//printing output
for (int i = 0; i < twoColumn.length; i++) {
System.out.println("Input Frequency");
System.out.println(twoColumn[0][i]+" "+twoColumn[1][i]);
}
}
}
}
there I tested and fixed it you should take out the -999 jazz if you want the user to have to go through the whole 50
import java.util.Arrays;
import java.util.Scanner;
public class swinging {
static Scanner keyboard = new Scanner(System.in);
static int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
public static void main(String[] args){
int j = 0;
for (; j < 50; j++) {
System.out.println("value #" + (j + 1) + ":");
inputValues[j] = keyboard.nextInt();
if(inputValues[j]==-999)break;
}
theValues= bubbleSort(Arrays.copyOf(inputValues, j));
for (int i = 0; i < theValues.length; i++) {
System.out.println("Input Frequency");
System.out.println(theValues[i]+" "+howMany[i]);
}
}
static int[] theValues;
static int[] howMany;
public static int[] bubbleSort(int[] Is ){
boolean switchedOne=true;
int temp;
howMany=new int[Is.length];
Arrays.fill(howMany,1);
int length=Is.length-1;
while(switchedOne){switchedOne=false;
for(int i=0;i<length;i++){
if(Is[i]>Is[i+1]){temp=Is[i];Is[i]=Is[i+1];Is[i+1]=temp;switchedOne=true;
temp=howMany[i];howMany[i]=howMany[i+1];howMany[i+1]=temp;}
if(Is[i]==Is[i+1]){Is=removeElement(Is,i+1);howMany=removeElement(howMany,i+1);howMany[i]++;length--;}
}
}
return Is;
}
public static int[] removeElement(int[] Is,int index){
for(int i=index;i<Is.length-1;i++){Is[i]=Is[i+1];}
return Arrays.copyOf(Is,Is.length-1);
}}
In case you are not playing with loops and wish to solve the problem on a higher-level, you could use a TreeMap and NavigableMap. See example below.
// ArrayGroupByCount.java
package com.geoloo.array;
import java.util.HashMap;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.TreeMap;
/*
* Description: Display occurence of entered numbers in descending order
* Sample input/output:
Input up to 50 values. 0 to exit
value #1:-12
value #2:3
value #3:-12
value #4:4
value #5:1
value #6:1
value #7:-12
value #8:1
value #9:-1
value #10:1
value #11:2
value #12:3
value #13:4
value #14:2
value #15:3
value #16:-12
value #17:0
map: {1=4, 2=2, 3=3, 4=2, -12=4, -1=1}
nmap: {4=2, 3=3, 2=2, 1=4, -1=1, -12=4}
*/
public class ArrayGroupByCount {
public static void main(String[] args) {
Integer input = 0;
Scanner keyboard = new Scanner(System.in);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
TreeMap<Integer, Integer> treemap = new TreeMap<Integer, Integer>();
System.out.println("Input up to 50 values. 0 to exit");
for (int i = 0; i < 50; i++) {
System.out.print("value #" + (i + 1) + ":");
input = (int)keyboard.nextInt();
if(input==0){
break;
}
int content = 0;
if(map.containsKey(input))
content = map.get(input);
map.put(input, content+1);
}
keyboard.close();
treemap.putAll(map);
NavigableMap<Integer, Integer> nmap=treemap.descendingMap();
System.out.println("map: "+map);
System.out.println("nmap: "+nmap);
}
}
package project2c;
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int valueAmount = 0;
int temp = 0;
int valueFrequency = 1;
//gather user input to fill an array (up to 50 values);
System.out.println("how many values would you like to process?");
valueAmount = keyboard.nextInt();
int[] inputValues = new int[valueAmount];
for (int i = 0; i < valueAmount; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
}
//sort values in descending order
for (int i = 0; i < inputValues.length - 1; i++) {
for (int j = 0; j < inputValues.length - 1; j++) {
if (inputValues[j + 1] > inputValues[j]) {
temp = inputValues[j + 1];
inputValues[j + 1] = inputValues[j];
inputValues[j] = temp;
}
}
}
//print out put
System.out.println();
System.out.println("Value Frequency");
for (int i = 0; i < inputValues.length - 1; i++) {
if (inputValues[i] == inputValues[i + 1]) {
valueFrequency = valueFrequency + 1;
} else if (inputValues[i] > inputValues[i + 1]) {
System.out.println(inputValues[i] + " " + valueFrequency);
valueFrequency = 1;
}
}
}
}

Categories

Resources