so my program is supposed to access a text document then do all that jazz that currently works. The only problem that I can't figure out is how to shuffle the contents of an array without having them end up on top of each other. Both internets and multiple tries with random and for loops have been unfruitful. here is my code:
import java.io.*;
import java.util.*;
public class lab_6 {
public static void main(String[] args)throws FileNotFoundException {
Scanner input = new Scanner(System.in); //reads from keyboard
System.out.println("What is the name of your file. ");
String name = input.nextLine();
Scanner reader = new Scanner(new File(name));// Open text file
System.out.println("how many names are in your array");
int num = input.nextInt();
String[] names = new String[num];
for (int index = 0; index< names.length; index++)
{
names[index] = reader.nextLine();// Gets a line while there is one
}
System.out.println("\nOriginal List");
printList(names);
System.out.println("\nShuffled List");
shuffle(names);
printList(names);
System.out.println("\nSorted List");
Arrays.sort(names); // this is a built in method
printList(names);
System.out.println("What name are you looking for");
Scanner input1 = new Scanner(System.in); //reads from keyboard
String find = input1.nextLine();
int index = search(names,find);
if(index == -1)
System.out.println("The name was not there");
else
System.out.println(find+" was found at position "+index);
System.out.println("The average length of all the names is "+averageLength(names));
}
public static void printList(String[] array) // print the list of names numbered
{
for (int i=0; i<array.length; i++)
{
System.out.println((i+1)+") "+ array[i]);
}
}
public static void shuffle (String[] array) // mix-up the array
{
}
public static int search(String[] array, String find)
{
for(int i=0; i<array.length; i++) {
if (array[i].equals(find) ) return i;
}
return -1;
}
public static double averageLength(String[] array) //return the average length of the names
{
int sum=0;
for (int i=0; i<array.length; i++)
{
int l= array[i].length();
sum +=l;
}
int average = sum/(array.length);
return average;
}
}
String[] names = ...;
Collections.shuffle(Arrays.asList(names));
// done
Note that Arrays.asList() returns a modifiable (but fixed-length) list, backed by the array, and not a copy of the array. So the array will be shuffled.
Just use the Fisher-Yates shuffle (Knuth algorithm P):
private Random rand = new Random();
public static void shuffle(String[] array) { // mix-up the array
for (int i = array.length - 1; i > 0; --i) {
int j = rand.nextInt(i + 1);
String temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
See:
Knuth, D. 1969, 1998: Seminumerical Algorithms 1st & 3rd Eds. The Art of Computer Programming Series, Volume 2, p. 125.
Fisher, Ronald A.; Yates, Frank (1948) [1938]. Statistical tables for biological, agricultural and medical research (3rd ed.). London: Oliver & Boyd. pp. 26–27.
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
https://stackoverflow.com/a/1520212/636009
You can use the Collections class, with the shuffle method. The documentation is available here.
Example
int[] values = {1,2,3,4,5};
List<Integer> valuesList = Arrays.asList(values);
Collections.shuffle(valuesList);
// valuesList is shuffled.
Related
So I am trying to complete this code. The goal is to input an array of strings, then count the frequency of how often the words are found. For example:
input:
joe
jim
jack
jim
joe
output:
joe 2
jim 2
jack 1
jim 2
joe 2
An array must be chosen for Strings, and another array much be chosen for word frequency.
My code so far:
I am stuck into trying to implement this. The string method is set, but how am I going to count the frequency of words, and also assign those values to an array. Then print both side by side. I do know that once the integer array is set. We can simply do a for loop to print the values together such as. System.out.println(String[i] + " " + countarray[i]);
public class LabClass {
public static int getFrequencyOfWord(String[] wordsList, int listSize, String currWord) {
int freq = 0;
for (int i = 0; i < listSize; i++) {
if (wordsList[i].compareTo(currWord) == 0) {
freq++;
}
}
return freq;
}
public static void main(String[] args) {
LabClass scall = new LabClass();
Scanner scnr = new Scanner(System.in);
// assignments
int listSize = 0;
System.out.println("Enter list Amount");
listSize = scnr.nextInt();
// removing line to allow input of integer
int size = listSize; // array length
// end of assignments
String[] wordsList = new String[size]; // string array
for (int i = 0; i < wordsList.length; i++) { //gathers string input
wordsList[i] = scnr.nextLine();
}
for (int i = 0; i < listSize; i++) {
String currWord = wordsList[i];
int freqCount = getFrequencyOfWord(wordsList, listSize, currWord);
System.out.println(currWord + " " + freqCount);
}
}
}
int some_method(String[] arr, String word) {
int count = 0;
for (int i=0; i<arr.size(); i++) {
if (arr[i].equals(word)) count++;
}
return count;
}
Then in main method:
String[] array = ["joe", "jake", "jim", "joe"] //or take from user input
int[] countArray = new int[array.size()]
for (int i=0; i<array.size(); i++) {
countArray[i] = some_method(array, array[i])
}
System.out.println(array[0] + " " + countArray[0]);
Ouput:
joe 2
I want to store as many elements as desired by the user in an array. But how do I do it.
If I were to create an array, I must do so with a fixed size. Every time a new element is added to the array and the array becomes full, I want to update its size by '1'.
I tired various types of code, but it did not work out.
It would be of great help if someone could give me a solution regarding it - in code if possible.
Instead of using an array, use an implementation of java.util.List such as ArrayList. An ArrayList has an array backend which holds values in a list, but the array size is automatically handles by the list.
ArrayList<String> list = new ArrayList<String>();
list.add("some string");
You can also convert the list into an array using list.toArray(new String[list.size()]) and so forth for other element types.
On a low level you can do it this way:
long[] source = new long[1];
long[] copy = new long[source.length + 1];
System.arraycopy(source, 0, copy, 0, source.length);
source = copy;
Arrays.copyOf() is doing same thing.
You can create a temporary array with a size that is one element larger than the original, and then copy the elements of the original into the temp, and assign the temporary array to the new one.
public void increaseSize() {
String[] temp = new String[original.length + 1];
for (int i = 0; i < original.length; i++){
temp[i] = original[i];
}
original = temp;
}
You can change the size in various ways, but the same idea applies.
You can't. You can either create a new array and move the items to that array - Or you can use an ArrayList.
By using copyOf method in java.util.Arrays class String[] size will increment automatically / dynamically. In below code array size 0 after manipulation of using Arrays.copyOf the size of String array is increased to 4.
package com.google.service;
import java.util.Arrays;
public class StringArrayAutoIncrement {
public static void main(String[] args) {
String[] data = new String[] { "a", "b", "c", "d", "e" };
String[] array = new String[0];// Initializing array with zero
int incrementLength = 1;
for (int i = 0; i < data.length; i++) {
array = Arrays.copyOf(data, i + incrementLength);// incrementing array by +1
}
/**
* values of array after increment
*/
for (String value : array) {
System.out.println(value);
}
}
}
Output:
a
b
c
d
e
https://www.java2novice.com/java-arrays/array-copy/
int[] myArr = {2,4,2,4,5,6,3};
System.out.println("Array size before copy: "+myArr.length);
int[] newArr = Arrays.copyOf(myArr, 10);
System.out.println("New array size after copying: "+newArr.length);
You can also do myArr = Arrays.copyOf(myArr, 10);
In this case do, myArr = Arrays.copyOf(myArr, myAry.length+1);
u can use array list for that
here is example for array list of string
'import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex01 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Italian Riviera");
myArr.add("Jersey Shore");
myArr.add("Puerto Rico");
myArr.add("Los Cabos Corridor");
myArr.add("Lubmin");
myArr.add("Coney Island");
myArr.add("Karlovy Vary");
myArr.add("Bourbon-l'Archambault");
myArr.add("Walt Disney World Resort");
myArr.add("Barbados");
System.out.println("Stupid Vacation Resort Adviser");
System.out.println("Enter your name:");
String name = userInput.readLine();
Integer nameLength = name.length();
if (nameLength == 0)
{
System.out.println("empty name entered");
return;
}
Integer vacationIndex = nameLength % myArr.size();
System.out.println("\nYour name is "+name+", its length is " +
nameLength + " characters,\n" +
"that's why we suggest you to go to "
+ myArr.get(vacationIndex));
}
}'
similarly u can make array for integer,blooean and all kinds of data types
for more detail u can see this
http://www.anyexample.com/programming/java/java_arraylist_example.xml
Create list object, add the elements and convert that list object to array using list.toArray(new String[list.size()])
u can do it by this
import java.util.Scanner;
class Add
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
char ans='y';
int count=0;
while(ans!='N'||ans!='n')
{
int initial_size=5;
int arr[]=new int [initial_size];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
if(count>0)
{
System.out.print("enter the element u want to add in array: ");
arr[initial_size-1]=obj.nextInt();
}
System.out.print("Do u want to add element in array?");
ans=obj.next().charAt(0);
if(ans=='y'||ans=='Y')
{
initial_size++;
count++;
}
}
}
}
public class IncreaseArraySize {
public static void main(String[] args) {
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = 5;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println(" ");
System.out.println("Before increasing Size of an array :" + arr.length);
int arr2[] = new int[10];
arr = arr2;
arr2 = null;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
System.out.println("After increasing Size of an array : " + arr.length);
}
}
Use an ArrayList. The size it automatically increased if you try to add to a full ArrayList.
minGap(array); is not being recognized. I don't know what I have done wrong, but I am sure it is a super simple fix. Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added. Any hints?
package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {
public static void main(String args[]) {
int length;
Scanner input = new Scanner(System.in); //scanner to input any size array user wants
System.out.println("Please enter the numbers for the array.");
length = input.nextInt();
String[] array = new String[length];
for(int i = 0;i <length;i++) { //counter logic
System.out.println("How many integers are in the array?"+(i+1));
array[i] = input.nextLine();
}
System.out.println("Enter the numbers for the array (individually):");
for(int i = 0;i <length;i++) { //counter logic
System.out.print(array [i]);
array[i] = input.nextLine();
}
input.close();
minGap(array);
}
private static int minGap(int a[], int gapMin) {
int []gap = new int[a.length];
//a
for (int i=0;i<a.length-2;i++) {
if (gapMin>gap[i]) {
gapMin=gap[1];
}
}
return gapMin;
}
}
I believe you wanted a method to find the minimum gap. As such, you should not be passing that into the method. Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1]). So you could do,
private static int minGap(int a[]) {
int gapMin = Integer.MAX_VALUE;
int[] gap = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (gapMin > gap[i]) {
gapMin = gap[i];
}
}
return gapMin;
}
or (if you're using Java 8+)
private static int minGap(int a[]) {
return Arrays.stream(a).min().getAsInt();
}
Then you need to actually save that value or print it. That is, change
minGap(array);
to (just print it)
System.out.println(minGap(array));
And you need an array of int (not a String[]).
int[] array = new int[length];
for(int i = 0; i < length; i++) {
System.out.printf("Please enter integer %d for the array%n", i + 1);
array[i] = input.nextInt();
}
This is a program that takes these three arrays and sorts them using insertion sort and counting the number of comparisons and swaps performed for each array when sorted.
I'm now trying to test three other arrays that have been made on text files. The these three text files are just lists of numbers, the first text file is called "array4.txt" and its list of numbers contains 1 through 2000 in order.
The second file is called "array5.txt" and its list of numbers contains 2000 through 1 in descending order. Lastly, the third file is called "array6.txt" and its list of numbers contains a list of randomly mixed numbers from 1 to 2000, including 1 and 2000 with no repeats.
My goal is to read these files and put their values into an actual array and for my insertion sort method to read them, sort them, and count the number of comparisons and exchanges just as what I did with my first three arrays.
I'm very new to Java and don't know exactly how to do this.
import java.util.Scanner;
import java.io.*;
public class InsertionSort
{
public static void main(String args[]) throws IOException
{
int[] Array = {1,2,3,4,5,6,7,8,9,10};
int[] Array2 = {10,9,8,7,6,5,4,3,2,1};
int[] Array3 = {1,10,2,9,3,8,4,7,5,6};
System.out.println("Insertion Sort: ");
System.out.println();
System.out.println("Best Case Scenario: ");
printArray(Array);
insertionSort(Array);
System.out.println("Worst Case Scenario: ");
printArray(Array2);
insertionSort(Array2);
System.out.println("Average Case Scenario: ");
printArray(Array3);
insertionSort(Array3);
}
public static void insertionSort(int[] list)
{
int comps = 0, swaps = 0;
for(int i = 1; i < list .length; i++) {
int j = i;
// compare i with sorted elements and insert it
// sorted elements: [0..i-1]
while (j > 0 && list[j] < list[j - 1]) {
int temp = list[j];
list[j] = list[j - 1];
list[j - 1] = temp;
swaps++;
comps++; // loop condition true
j--;
}
comps++; // checking loop condition when false
}
//printArray(list);
System.out.println("Comparisons: " + comps
+ " Swaps: " + swaps);
System.out.println();
}
static void printArray(int[] array){
for(int i=0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
}
}
This is what I came up with. Hope it helps!
package com.company;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// Replace array.txt with the name of your txt file and your path
Scanner fileScanner = new Scanner(new File("array.txt"));
// Counter variable so we'll know the size of the array we'll need
int counter = 0;
// Iterate through the file counting the number of integers and incrementing the counter variable
while(fileScanner.hasNextInt()){
counter++;
fileScanner.nextInt();
}
// Reset the scanner to the beginning of the txt file
fileScanner = new Scanner(new File("array.txt"));
// Scan each integer into the array
int [] array = new int[counter];
for (int i = 0; i < array.length; ++i) array[i] = fileScanner.nextInt();
}
}
Here you go:
public void getIt() {
List<Integer> ints = new ArrayList(); //temporary holder
try (Scanner scanner = new Scanner("filename.txt")) { //open a scanner that will scan our file
scanner.forEachRemaining(line -> { //iterate through each line in our file
String[] numberStrings = line.split(","); // the comma is your presumed delimeter IF one exists
for (int x = 0; x < numberStrings.length; x++) { // loop through each item separated by a comma on each line
ints.add(Integer.parseInt(numberStrings[x])); // turn this string into an int and add it to your list
}
});
}
Integer[] integerArray = ints.toArray(new Integer[ints.size()]); //transform our list into an array
}
If it's only one number per line you don't need the for loop or the line.split inside of the forEachRemaining
I want to store as many elements as desired by the user in an array. But how do I do it.
If I were to create an array, I must do so with a fixed size. Every time a new element is added to the array and the array becomes full, I want to update its size by '1'.
I tired various types of code, but it did not work out.
It would be of great help if someone could give me a solution regarding it - in code if possible.
Instead of using an array, use an implementation of java.util.List such as ArrayList. An ArrayList has an array backend which holds values in a list, but the array size is automatically handles by the list.
ArrayList<String> list = new ArrayList<String>();
list.add("some string");
You can also convert the list into an array using list.toArray(new String[list.size()]) and so forth for other element types.
On a low level you can do it this way:
long[] source = new long[1];
long[] copy = new long[source.length + 1];
System.arraycopy(source, 0, copy, 0, source.length);
source = copy;
Arrays.copyOf() is doing same thing.
You can create a temporary array with a size that is one element larger than the original, and then copy the elements of the original into the temp, and assign the temporary array to the new one.
public void increaseSize() {
String[] temp = new String[original.length + 1];
for (int i = 0; i < original.length; i++){
temp[i] = original[i];
}
original = temp;
}
You can change the size in various ways, but the same idea applies.
You can't. You can either create a new array and move the items to that array - Or you can use an ArrayList.
By using copyOf method in java.util.Arrays class String[] size will increment automatically / dynamically. In below code array size 0 after manipulation of using Arrays.copyOf the size of String array is increased to 4.
package com.google.service;
import java.util.Arrays;
public class StringArrayAutoIncrement {
public static void main(String[] args) {
String[] data = new String[] { "a", "b", "c", "d", "e" };
String[] array = new String[0];// Initializing array with zero
int incrementLength = 1;
for (int i = 0; i < data.length; i++) {
array = Arrays.copyOf(data, i + incrementLength);// incrementing array by +1
}
/**
* values of array after increment
*/
for (String value : array) {
System.out.println(value);
}
}
}
Output:
a
b
c
d
e
https://www.java2novice.com/java-arrays/array-copy/
int[] myArr = {2,4,2,4,5,6,3};
System.out.println("Array size before copy: "+myArr.length);
int[] newArr = Arrays.copyOf(myArr, 10);
System.out.println("New array size after copying: "+newArr.length);
You can also do myArr = Arrays.copyOf(myArr, 10);
In this case do, myArr = Arrays.copyOf(myArr, myAry.length+1);
u can use array list for that
here is example for array list of string
'import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex01 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Italian Riviera");
myArr.add("Jersey Shore");
myArr.add("Puerto Rico");
myArr.add("Los Cabos Corridor");
myArr.add("Lubmin");
myArr.add("Coney Island");
myArr.add("Karlovy Vary");
myArr.add("Bourbon-l'Archambault");
myArr.add("Walt Disney World Resort");
myArr.add("Barbados");
System.out.println("Stupid Vacation Resort Adviser");
System.out.println("Enter your name:");
String name = userInput.readLine();
Integer nameLength = name.length();
if (nameLength == 0)
{
System.out.println("empty name entered");
return;
}
Integer vacationIndex = nameLength % myArr.size();
System.out.println("\nYour name is "+name+", its length is " +
nameLength + " characters,\n" +
"that's why we suggest you to go to "
+ myArr.get(vacationIndex));
}
}'
similarly u can make array for integer,blooean and all kinds of data types
for more detail u can see this
http://www.anyexample.com/programming/java/java_arraylist_example.xml
Create list object, add the elements and convert that list object to array using list.toArray(new String[list.size()])
u can do it by this
import java.util.Scanner;
class Add
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
char ans='y';
int count=0;
while(ans!='N'||ans!='n')
{
int initial_size=5;
int arr[]=new int [initial_size];
arr[0]=1;
arr[1]=2;
arr[2]=3;
arr[3]=4;
arr[4]=5;
if(count>0)
{
System.out.print("enter the element u want to add in array: ");
arr[initial_size-1]=obj.nextInt();
}
System.out.print("Do u want to add element in array?");
ans=obj.next().charAt(0);
if(ans=='y'||ans=='Y')
{
initial_size++;
count++;
}
}
}
}
public class IncreaseArraySize {
public static void main(String[] args) {
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = 5;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println(" ");
System.out.println("Before increasing Size of an array :" + arr.length);
int arr2[] = new int[10];
arr = arr2;
arr2 = null;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
System.out.println("After increasing Size of an array : " + arr.length);
}
}
Use an ArrayList. The size it automatically increased if you try to add to a full ArrayList.