Print array in a loop with dynamic variable Java - java

I am trying to define an array that increased by one each time then print the result of an equation that the array is assigned to;
my code so far is
public class PrimeNumberCounter {
public static void main(String[] args) {
// Define integers
int a = 1;
final int b = 2;
final int c = 3;
// Define Array
int[] nth;
nth = new int[100];
//Set loop
for (a = 1; a < 100; a = a + 1) {
int d = a * b + c;
System.out.println(d);
}
}
}
The math function and loop work but I can't figure out how to publish the nth term.
So far I have read array's are the most suitable solution but after much messing around removed the print array part, and decided to ask for help.
Thanks All
EDIT: addition of original code (it's kinda silly hence why I didn't publish it 1st time
public class PrimeNumberCounter {
public static void main(String[] args) {
// Define integers
int a = 1;
final int b = 2;
final int c = 3;
// Define Array.
int[] nth;
nth = new int[100];
//Set loop
for (a = 1; a < 100; a = a + 1) {
nth[] = a * b + c;
System.out.println(nth);
}
}
}

Use some collection like a list instead of using array.
You can use an iterator to iterate over that list and update the iterator.

If I understood you correctly, you are not trying to increase the size of the array, what you are trying to do is increase a counter that iterates through the array and assigns the result of the d = a * b + c; equation to the ith element of the array. Then after all the elements in the array have been populated, you want to iterate through the array an print all the values. If that is the case you can modify your code as follows:
public class PrimeNumberCounter {
public static void main(String[] args) {
// Define integers
int a = 1;
final int b = 2;
final int c = 3;
//int d = 0; // not used
// Define Array assuming that its size is fixed to 100
int[] nth = new int[100];
// Set the assignment loop
for (a = 1; a <= nth.length; ++a) {
// array indexing starts at 0
nth[a - 1] = a * b + c;
}
// print loop
for (int i = 0; i < nth.length; ++i) {
System.out.printf("%d: %d\n", i + 1, nth[i]);
}
}
}
If you don't know the size of the array a priori you can use an ArrayList instead which can grow dynamically as mentioned in the comments and previous answer.
import java.util.List;
import java.util.ArrayList;
public class PrimeNumberCounter {
public static void main(String[] args) {
// Define integers
int a = 1;
final int b = 2;
final int c = 3;
// Some size N let's assume it's a 100 again
List<Integer> nth = new ArrayList<Integer>();
// Set the assignment loop
for (a = 1; a <= 100; ++a) {
// array indexing starts at 0
nth.add(a - 1, a * b + c);
}
// print loop
for (int i = 0; i < nth.size(); ++i) {
System.out.printf("%d: %d\n", i + 1, nth.get[i]);
}
}
}

Related

Pick a few random numbers in a specific range without duplicates

I want to pick 8 random integers in the range 0-7.
int one = (int) (Math.random()*0)+7;
int two = (int) (Math.random()*0)+7;
// ...
int eight = (int) (Math.random()*0)+7;
However, no duplicate numbers are allowed. How can I improve this code to establish this?
Follow the below snippet and change the maxLimit and noOfItems according to your preference to get desired result.
Here the Set contains unique integers under specified limit.
public class RandomIntegers
{
public static final Random random = new Random();
public static final int maxLimit = 8;
public static final int noOfItems = 8;
public static void main( String[] args )
{
Set<Integer> uniqueRandomIntegerSet = new HashSet< Integer >();
while(uniqueRandomIntegerSet.size() < noOfItems)
uniqueRandomIntegerSet.add( random.nextInt( maxLimit ) );
}
}
I'm not sure if this violates your requirements, but you could just go like this:
public static void main(String[] args) {
List<Integer> randomZeroToSeven = new ArrayList<>();
for (int i = 0; i <= 7; i++) {
randomZeroToSeven.add(i);
}
Collections.shuffle(randomZeroToSeven);
}
Alternatively, you can skip the shuffle and just grab a random element out of the list every time you want a random number from 0-7. EG:
public static void main(String[] args) {
List<Integer> zeroToSeven = new ArrayList<>();
for (int i = 0; i <= 7; i++) {
zeroToSeven.add(i);
}
System.out.println(zeroToSeven.get(new Random().nextInt(8)));
}
Another way is to fill up an array / collection with all possibilities and pick from those. Each picked item is removed from the allowed array and put into the output array until you have picked all items.
This way you skip double picks and the execution is linear.
Something like this:
int desiredSize = 8;
List<Integer> allowed = new ArrayList<>();
for (int i = 0; i < desiredSize; i++) {
allowed.add(i);
}
List<Integer> output = new ArrayList<>();
Random random = new Random();
while (output.size() < desiredSize) {
int index = random.nextInt(allowed.size());
output.add(allowed.get(index));
allowed.remove(index);
}
If you need to generate numbers from min to max (including both), you can write
random.nextInt(max - min + 1) + min
public static void main(String[] args) throws IOException {
HashSet<Integer>list=new HashSet();
Random random=new Random();
while(list.size()<8){
list.add(random.nextInt(7 - 0 + 1) + 0); // OR list.add(random.nextInt(8));
}
System.out.println(list);
}
There are only 8 integers from 0-7 and so what you are really asking is for the numbers from 0-7 in a random order.
The quickest way to do this both coding and execution is to shuffle a set of integers.
public class Test {
public static void main(String[] args){
List<Integer> list = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7);
Collections.shuffle(list);
for(int i : list){
System.out.println(i);
}
}
}
If you want to write a shuffle algorithm yourself you can do so by so swapping every item (bar the last) in an array with a random index. The reason you don't do the last is because it biases the outcome. See Fisher Yates Shuffle
Just because I couldn't resist here is a java implementation of Fisher Yates:
public class Test {
public static void main(String[] args){
Random rnd = new SecureRandom();
int[] arr = new int[]{0,1,2,3,4,5,6,7};
for(int i = 0; i < arr.length - 1; i++){
int swapIndex = rnd.nextInt(8);
int tmp = arr[i];
arr[i] = arr[swapIndex];
arr[swapIndex] = tmp;
}
System.out.println(Arrays.toString(arr));
}
}

Counting number of data swaps in Java bubble sort

I'm trying to count and output the number of swaps of data elements in a bubble sort method using Java. I'm a beginner, so am unsure how to overcome my issue: method is void and can't return anything, so what can I do to output the swaps?
in one doc, the sort method:
public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
//Bubble sort algorithm.
//Postcondition: list objects are in ascending order.
public void bubbleSort(T list[], int length)
{
//Initialize swap counter
int bubbleSwaps = 0;
for (int iteration = 1; iteration < length; iteration++)
{
for (int index = 0; index < length - iteration;
index++)
{
Comparable<T> compElem =
(Comparable<T>) list[index];
if (compElem.compareTo(list[index + 1]) > 0)
{
T temp = list[index];
list[index] = list[index + 1];
list[index + 1] = temp;
bubbleSwaps++;
}
}
}
}
}
In another, I use the method, and am looking to find a way to output bubbleSwaps:
public class numberSwapsReview{
public static void main(String [] args)
{
// define an Integer array of 1000 elements
Integer[] bubbleArray = new Integer[1000];
// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*1000)
for (int i = 0; i < bubbleArray.length; i++) {
bubbleArray[i] = (int)(Math.random() * 1000);
}
SearchSortAlgorithms<Integer> sortObject = new SearchSortAlgorithms<Integer>();
sortObject.bubbleSort(bubbleArray, 1000);
}
}
Since you are making an instance of the class, you could make bubbleSwaps class level then get the value after the sort
public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
//Initialize swap counter
int bubbleSwaps = 0;
//Bubble sort algorithm.
//Postcondition: list objects are in ascending order.
public void bubbleSort(T list[], int length)
{
for (int iteration = 1; iteration < length; iteration++)
{
for (int index = 0; index < length - iteration;
index++)
{
Comparable<T> compElem =
(Comparable<T>) list[index];
if (compElem.compareTo(list[index + 1]) > 0)
{
T temp = list[index];
list[index] = list[index + 1];
list[index + 1] = temp;
this.bubbleSwaps++;
}
}
}
}
public int getBubbleSwaps(){
return this.bubbleSwaps;
}
}
Here is the other class:
public class numberSwapsReview{
public static void main(String [] args)
{
// define an Integer array of 1000 elements
Integer[] bubbleArray = new Integer[1000];
// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*1000)
for (int i = 0; i < bubbleArray.length; i++) {
bubbleArray[i] = (int)(Math.random() * 1000);
}
SearchSortAlgorithms<Integer> sortObject = new SearchSortAlgorithms<Integer>();
sortObject.bubbleSort(bubbleArray, 1000);
sortObject.getBubbleSwaps();
}
}
You might use a Comparator instead of Comparable elements. With that (preferable as a wrapper around the normal comparator), you can compute in a field variable how many time was the result >0
One way would be to change the return type of your method as int and return the number of swaps you did. Then just call:
int nbswaps = sortObject.bubbleSort(bubbleArray, 1000);
If you can't modify the return type, you can
print the number of swaps in the method at the end
create an attribute named nbSwaps in your class (don't forget to reset it at each call of bubbleSort method) and then implement a getter to be able to get the value from your main
Also you may change the declaration of your class as class SearchSortAlgorithms<T extends Comparable<T>>.
Now you will be sure that the elements have to be comparable and you could get rid of Comparable<T> compElem = (Comparable<T>) list[index];.

Filling a int[] array

I must make a int array filled with 5000 numbers, and then take the value of each cell, which is a random number up to 1000, and multiply it by the square root of the cell index.
So far, my code is:
import java.util.*;
public class thousandArray{
public static void main (String args[]){
int numbers[] = new int[5000];
int r = 0 + (int)(Math.random()*1000);
double rt = numbers[r];
while(rt==numbers[r]){
r=0+(int)(Math.random()*1000);
double square = rt*Math.sqrt(numbers[r]);
System.out.println(square);
System.exit(0);
}
}
}
im pretty sure I did the code right, I cant figure out how to fill my array.
import java.util.*;
public class thousandArray{
public static void main (String args[]){
int numbers[] = new int[5000];
int r = 0 + (int)(Math.random()*1000);
double rt = numbers[r]; //you never assigned anything to numbers[r]
while(rt==numbers[r]){
r=0+(int)(Math.random()*1000);
double square = rt*Math.sqrt(numbers[r]);
System.out.println(square);
System.exit(0); //you exit the first time it loops
}
}
}
To fill an int array:
int[] numbers = new int[5000];
for (int i = 0; i < 5000; i++) {
numbers[i] = some_value;
}
To make the values be random, more or less as the problem states, you'd use:
numbers[i] = (int)(Math.random()*1000);
To multiply by the square root of the cell index:
numbers[i] = numbers[i] * (int)Math.sqrt(i);
Of course, that assumes that numbers should be an int array. It would make more sense for it to be a double array, in which case you'd remove the (int) casts.
public class ThousandArray {
public static void main (String args[]){
int MAX = 5000;
int numbers[] = new int[MAX];
for (int i = 0; i < MAX; i++) {
numbers[i] = (int)(Math.sqrt(i) * (Math.random()*1000));
}
}
}

Shifting and Re-organizing Arrays

I have an array, let's say: LRU_frame[] = {4,1,0,3}
I have a random() function that spits out a random number. If the random number n is contained in the array LRU_frame, then, n should be on LRU_frame[0] and everything else must be shifted down accordingly.
For example if random() gives me a 0, the new LRU_frame[] = {0,4,1,3}
Another example, if random() gives me a 3, the new LRU_frame[] = {3,4,1,0}
How do I do this for any Array size with any number of elements in it?
I know how to shift arrays by adding a new element on LRU_frame[0] but have no idea on how to re-organize the array like I need.
This is the code I have so far and let's assume char a is the random number(casted into char) to use and re-organize the array.
public static void LRU_shiftPageRef(char a) {
for (int i = (LRU_frame.length - 2); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
You have a good idea, you only need to find the position of the a element in the array and start the cycle from it, instead of LRU_frame.length.
int index = -1;
// find the positon of 'a' in the array
for (int i = 0; i <= (LRU_frame.length - 1); i++) {
if (LRU_frame[i] == a) {
index = i;
break;
}
}
// if it is present, do roughly the same thing as before
if (index > -1) {
for (int i = (index - 1); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
However if you can use ArrayLists it gets much easier.
// declaration
ArrayList<Integer> LRU_frame = new ArrayList<Integer>();
...
if (LRU_frame.contains(a)) {
LRU_frame.remove((Integer) a);
LRU_frame.add(0, a);
}
I think this could be the sort of thing you are after:
public static void LRU_shiftPageRef(char a) {
int index = indexOf(a);
if (index == -1) {
//not currently in array so create a new array 1 bigger than existing with a in newArray[0] or ignore depending on functionality required.
} else if (index > 0) {
//Set first entry as a and shift existing entries right
char insertChar = a;
char nextChar = LRU_frame[0];
for (int i =0; i < index; i++) {
LRU_frame[i] = insertChar;
insertChar = nextChar;
nextChar = LRU_frame[i+1];
}
LRU_frame[index] = insertChar;
} else {
//do nothing a is already at first position
}
}
public static int indexOf(char a) {
for (int i=0; i < LRU_frame.length; i++) {
if (LRU_frame[i] == a) {
return i;
}
}
return -1;
}
Use Arrays.sort(LRU_frame); to sort the entire array, or Arrays.sort(LRU_frame, fromIndex, toIndex)); to sort part of the array.
Arrays class has other useful methods like copyOfRange.

Need help passing an array with elements already stored into it as a parameter for a method (JAVA)

So here I have a piece of code that takes a string named key ("ALICE") and passes it into the method keyReader() to get the position of the alphabet of each index - to clarify A would be 1, L would be 12, I would be 9, C would be 3, and E would be 5. These numbers are stored into an array named keyArray[].
My problem is now using keyArray[] with these 5 elements that are stored in it and passing it into the method keyNumber() as a parameter in order change each number to base 27 and add it to a total which is keyNo in this case.
Any help and or suggestions are appreciated.
public class Problem2 {
public static void main(String[] args) {
String key = "ALICE"; //VARIABLE - Will be read from text file
String cipherThis = "JLMRSULTQTXLRCQQEBCHQFWWE"; //VARIABLE - Will be read from text file
int noKey = 0;
int[] keyArray = new int[5];
keyReader(key, keyArray); //reads the key
keyNumber(noKey, keyArray); //evaluates the keyNumber of keyReader
}
//Method for reading each letter of the key
private static void keyReader(String key, int[] keyArray) {
for (int x = 0; x < 5; x++) {
keyArray[x] = key.charAt(x) - 64;
}
}
//Method for evaluating the key number
private static void keyNumber(int noKey, int[] keyArray) {
int i = 0; //Counter for the numbers of the letters stored into the array using the keyReader() method
int k = 4; //Counter for the 5 letters of the key (4,3,2,1,0)
while (i < 5) {
while (k >= 0) {
noKey += Math.pow(27, k) * keyArray[i];
k--;
i++;
}
}
}
}
use Integer(Object Reference)array instead of int array (primitive). So u can get reference back and u can use it later for further processing.
Instead of using...
private static void keyNumber(int noKey, int[] keyArray) {
Try using...
private static int keyNumber(int[] keyArray) {
int noKey = 0;
//...
return noKey;
}
Which would be called using...
noKey = keyNumber(keyArray); //evaluates the keyNumber of keyReader
You should also consider doing the same thing with your keyReader, rather then passing it an array, have it return the result...
private static int[] keyReader(String key) {
int[] keyArray = new int[key.length()];
for (int x = 0; x < keyArray.length; x++) {
keyArray[x] = key.charAt(x) - 64;
}
return keyArray;
}
And call it using...
int[] keyArray = keyArray = keyReader(key); //reads the key
You shouldn't rely on magic numbers, but work to known values...
Instead of...
int k = 4; //Counter for the 5 letters of the key (4,3,2,1,0)
while (i < 5) {
while (k >= 0) {
You should be using...
int k = keyArray.length - 1; //Counter for the 5 letters of the key (4,3,2,1,0)
while (i < keyArray.length) {
while (k >= 0) {
instead...
In java all primitives, like ints are pass by value (ie. copied). What you want is to pass my reference (ie &). So Autobox the int using new Integer(someint) as an argument (should work) else its better to simply return the int (after the additions) from the keyNumber function.
public static void main (String [] args){
String key = "ALICE"; //VARIABLE - Will be read from text file
String cipherThis = "JLMRSULTQTXLRCQQEBCHQFWWE"; //VARIABLE - Will be read from text file
int noKey = 0;
int[] keyArray = new int[key.lenght];
keyReader(key, keyArray); //reads the key
keyNumber (new Integer(noKey), keyArray); //evaluates the keyNumber of keyReader
}
//Method for reading each letter of the key
private static void keyReader(String key, int[] keyArray) {
for (int x = 0; x < keyArray.length; x++){
keyArray[x] = key.charAt(x)-64;
}
}
//Method for evaluating the key number
private static void keyNumber(Integer noKey, int[] keyArray){
int i = 0; //Counter for the numbers of the letters stored into the array using the keyReader() method
int k = 4; //Counter for the 5 letters of the key (4,3,2,1,0)
while (i < 5){
while (k >= 0){
noKey += Math.pow(27, k)*keyArray[i];
k--;
i++;
}
}
}

Categories

Resources