Making a nested for loop into a single for loop - java

I had an assignment to create an array of random number from 10-100.
Then I need to sout all the numbers not listed in the array.
I did the assignment with a nested for loops, to cross reference the arrays, then I changed all the found numbers in the array into -1. Finally I printed out the elements in the array that were not -1.
My professor told me that is it possible for me to do this assignment with only one for loop and there is no need to do a nested for loop. and make the computer run 10,000 times instead of just 100.
Is that possible? If so how?
Thank you.
package assignment.pkg1;
import java.util.Random;
public class Assignment1 {
static Random ran = new Random();
public static void main(String[] args) {
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = (ran.nextInt(90)) + 10;
}
InversingArray(arr);
}
public static void InversingArray(int[] randomArray) {
int[] fullArray = new int[100];
for (int i = 0; i < 100; i++) {
fullArray[i] = i;
}
for (int i = 0; i < 100; i++) {
for (int j = 1; j < 100; j++) {
if (randomArray[j] == fullArray[i]) {
fullArray[i] = -1;
}
}
}
System.out.println("These numbers are not in randomArray: ");
for (int i = 0; i < 100; i++) {
if (fullArray[i] != -1) {
System.out.println(fullArray[i]);
}
}
}

In your code you create an array to hold the possible values. If you think about it, the array index will always be equal to the number stored in the array.
fullArray[i] = i;
This is redundant.
What you are being asked to do is determine which numbers have been used: a boolean test. This means that you should have an array of boolean that is initially false (the default value of booleans in java) and is flipped to true when an equal integer is flipped to true.
Something like
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = (ran.nextInt(90)) + 10;
}
// ba starts with all false values
boolean ba[] == new boolean[90]; // note that the instructor said 10-100
for(int i=0; i<90; i++) {
ba[arr[i]] = true;
// lets assume arr[0] == 45
// ba[arr[0]] is the same as ba[45]
// ba[45] = true; will set that bucket of the boolean array to true
}
System.out.println("These numbers are not in randomArray: ");
for (int k = 0; k < 10; k++) {
System.out.println(k);
}
for (int j = 0; j < 90; j++) {
if (!ba[j]) { // shorthand for ba[j]==false
System.out.println(j+10); // The array starts at a base of 10
}
}
Be aware (probably the point of the exercise) that you are working with an array [0..90] that represents the numbers [10..100].

The nested loop currently looks like this:
for (int i = 0; i < 100; i++) {
for (int j = 1; j < 100; j++) {
if (randomArray[j] == fullArray[i]) {
fullArray[i] = -1;
}
}
}
But we know, that fullArray[i] is always the same as i.
So you can rewrite it to:
for (int j = 1; j < 100; j++) {
int i = randomArray[j];
fullArray[i] = -1;
}
Or even shorter:
for (int j = 1; j < 100; j++) {
fullArray[randomArray[j]] = -1;
}

Related

How to generate unique chars when populating a 2D array?

How do I make it so that when I output the grid when I run the code, no two numbers or letters will be the same? When I currently run this code I could get 3x "L" or 2x "6", how do I make it so that they only appear once?
package polycipher;
import java.util.ArrayList;
public class Matrix {
private char[][] matrix = new char[6][6];
private int[] usedNumbers = new int[50];
{for(int x = 0; x < usedNumbers.length; x++) usedNumbers[x] = -1;}
private final char[] CIPHER_KEY = {'A','D','F','G','V','X'};
private final String validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public Matrix() {
int random;
for(int i = 0; i < CIPHER_KEY.length; i++) {
for(int j = 0; j < CIPHER_KEY.length; j++) {
validation: while(true) {
random = (int)(Math.random()*validChars.length()-1);
for(int k = 0; k < usedNumbers.length; k++) {
if(random == usedNumbers[k]) continue validation;
else if(usedNumbers[k]==-1) usedNumbers[k] = random;
}
break;
}
matrix[i][j] = validChars.split("")[random].charAt(0);
}
}
}
public String toString() {
String output = " A D F G V X\n";
for(int i = 0; i < CIPHER_KEY.length; i++) {
output += CIPHER_KEY[i] + " ";
for(int j = 0; j < CIPHER_KEY.length; j++) {
output += matrix[i][j] + " ";
}
output += "\n";
}
return output;
}
}
This should be much faster than validating each random choice:
Store your valid chars into an array;
char[] valid = validChars.toCharArray();
Shuffle the array;
shuffle(valid)
Go through the positions in the matrix, storing the elements in the same order they appear in the shuffled array.
assert (CIPHER_KEY.length * CIPHER_KEY.length) <= valid.length;
int k = 0;
for (int i = 0; i < CIPHER_KEY.length; i++) {
for (int j = 0; j < CIPHER_KEY.length; j++) {
matrix[i][j] = valid[k++];
}
}
Use a set and generate a new random if the old random number is in the map:
Pseudocode:
Set<Integer> set = new HashSet<Integer>();
for () {
int random = (int)(Math.random()*validChars.length()-1);
//Your code for validation here (move it to a function)
while (!set.contains(random)){
int random = (int)(Math.random()*validChars.length()-1);
//Your code for validation here (move it to a function)
}
//If we exit this loop it means the set doesn't contain the number
set.add(random);
//Insert your code here
}

How to dynamically control the for-loop nested level?

I am implementing some algorithm, in which the number of loop nested levels is determined by the input.
For example, if the input is 2-dimensional, then there two nested for-loops, as below:
for(int i=0; i<N; i++) {
for(int j=i+1; j<N; j++) {
if(table[i][j] == -1) {
for(int c=0; c<C; c++) {
int ii = table[i][c];
int jj = table[j][c];
sort(ii, jj);
if((T[ii][jj] != -1 && T[ii][jj] < l)) {
T[i][j] = l;
break;
}
}
}
}
}
If the input is 3-dimensional, then it would be something like below:
for(int i=0; i<N; i++) {
for(int j=i+1; j<N; j++) {
for(int k=j+1; k<N; k++) {
if(table[i][j][k] == -1) {
for(int c=0; c<C; c++) {
int ii = table[i][c];
int jj = table[j][c];
int kk = table[k][c];
sort(ii, jj, kk);
if((T[ii][jj][kk] != -1 && T[ii][jj][kk] < l)) {
T[i][j][k] = l;
break;
}
}
}
}
}
If there are only these two case, then I can write two versions of nested for-loops. But the dimensions of input could be any value between 2 and N. In this case, how to control the nested loop level dynamically, or is there any alternative to go around of this?
The only real way to do this is to use recursion.
You write a method containing a single for loop, each time around the loop if it needs to go deeper then the method calls itself with the right settings for that nested loop to be run.
Recursion is already been explained here. However, there is another solution as well. Using only one big loop containing a tiny inner loop.
int n = ...;
int dim = ...;
// Raise n to the power of dim: powN = n^dim
long powN = 1;
for (int i = 0; i < dim; ++i) powN *= n;
int[] indices = new int[dim];
for (long i = 0; i < powN; ++i)
{
// Calculate the indices
long bigI = i;
for (int k = 0; k < dim; ++k)
{
indices[k] = bigI % n;
bigI /= n;
}
// Now all your indices are stored in indices[]
}
I was suggesting something like this :
public static void recursiveLoop(int N, int level, int a){
if (level<0)
return;
for (int i=a; i<N; i++){
System.out.println("Level is : "+ level+ " i: "+i );
recursiveLoop(N,level-1,i+1);
}
}
You may explain what you really want to do.
If the Outer for loops are doing nothing but controlling a count, then your Nested for loops are simply a more complicated way of iterating by a count that could be handled by a Single for loop.
like:
for (x = 0; x < 8; x++) {
for (y = 0; y < 10; y++) {
for (z = 0; z < 5; z++) {
DoYourStuffs();
}
}
}
Is equivalent to:
for (x = 0; x < 8*10*5; x++) {
DoYourStuffs();
}

Java Array of unique randomly generated integers

public static int[] uniqueRandomElements (int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[j] = (int)(Math.random()*10);
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
return a;
}
I have a method above which should generate an array of random elements that the user specifies. The randomly generated integers should be between 0 and 10 inclusive. I am able to generate random integers but the problem I have is checking for uniqueness. My attempt to check for uniqueness is in my code above but the array still contains duplicates of integers. What am I doing wrong and could someone give me a hint?
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[j] = (int)(Math.random()*10); //What's this! Another random number!
}
}
}
You do find the duplicate values. However, you replace it with another random number that may be a duplicate. Instead, try this:
for (int i = 0; i < size; i++) {
a[i] = (int)(Math.random()*10);//note, this generates numbers from [0,9]
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
i--; //if a[i] is a duplicate of a[j], then run the outer loop on i again
break;
}
}
}
However, this method is inefficient. I recommend making a list of numbers, then randomizing it:
ArrayList<Integer> a = new ArrayList<>(11);
for (int i = 0; i <= 10; i++){ //to generate from 0-10 inclusive.
//For 0-9 inclusive, remove the = on the <=
a.add(i);
}
Collections.shuffle(a);
a = a.sublist(0,4);
//turn into array
Or you could do this:
ArrayList<Integer> list = new ArrayList<>(11);
for (int i = 0; i <= 10; i++){
list.add(i);
}
int[] a = new int[size];
for (int count = 0; count < size; count++){
a[count] = list.remove((int)(Math.random() * list.size()));
}
It might work out faster to start with a sequential array and shuffle it. Then they will all be unique by definition.
Take a look at Random shuffling of an array, and at the Collections.shuffle function.
int [] arr = [1,2,3,.....(size)]; //this is pseudo code
Collections.shuffle(arr);// you probably need to convert it to list first
If you have a duplicate you only regenerate the corresponding number once. But it might create another duplicate. You duplicate checking code should be enclosed in a loop:
while (true) {
boolean need_to_break = true;
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
need_to_break = false; // we might get another conflict
a[j] = (int)(Math.random()*10);
}
}
if (need_to_break) break;
}
But make sure that size is less than 10, otherwise you will get an infinite loop.
Edit: while the above method solves the problem, it is not efficient and should not be used for large sized arrays. Also, this doesn't have a guaranteed upper bound on the number of iterations needed to finish.
A better solution (which unfortunately only solves second point) might be to generate a sequence of the distinct numbers you want to generate (the 10 numbers), randomly permute this sequence and then select only the first size elements of that sequence and copy them to your array. You'll trade some space for a guarantee on the time bounds.
int max_number = 10;
int[] all_numbers = new int[max_number];
for (int i = 0; i < max_number; i++)
all_numbers[i] = i;
/* randomly permute the sequence */
for (int i = max_number - 1; i >= 0; i--) {
int j = (int)(Math.random() * i); /* pick a random number up to i */
/* interchange the last element with the picked-up index */
int tmp = all_numbers[j];
all_numbers[j] = a[i];
all_numbers[i] = tmp;
}
/* get the a array */
for (int i = 0; i < size; i++)
a[i] = all_numbers[i];
Or, you can create an ArrayList with the same numbers and instead of the middle loop you can call Collections.shuffle() on it. Then you'd still need the third loop to get elements into a.
If you just don't want to pay for the added overhead to ArrayList, you can just use an array and use Knuth shuffle:
public Integer[] generateUnsortedIntegerArray(int numElements){
// Generate an array of integers
Integer[] randomInts = new Integer[numElements];
for(int i = 0; i < numElements; ++i){
randomInts[i] = i;
}
// Do the Knuth shuffle
for(int i = 0; i < numElements; ++i){
int randomIndex = (int)Math.floor(Math.random() * (i + 1));
Integer temp = randomInts[i];
randomInts[i] = randomInts[randomIndex];
randomInts[randomIndex] = temp;
}
return randomInts;
}
The above code produces numElements consecutive integers, without duplication in a uniformly random shuffled order.
import java.util.Scanner;
class Unique
{
public static void main(String[]args)
{
int i,j;
Scanner in=new Scanner(System.in);
int[] a=new int[10];
System.out.println("Here's a unique no.!!!!!!");
for(i=0;i<10;i++)
{
a[i]=(int)(Math.random()*10);
for(j=0;j<i;j++)
{
if(a[i]==a[j])
{
i--;
}
}
}
for(i=0;i<10;i++)
{
System.out.print(a[i]);
}
}
}
Input your size and get list of random unique numbers using Collections.
public static ArrayList<Integer> noRepeatShuffleList(int size) {
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < size; i++) {
arr.add(i);
}
Collections.shuffle(arr);
return arr;
}
Elaborating Karthik's answer.
int[] a = new int[20];
for (int i = 0; i < size; i++) {
a[i] = (int) (Math.random() * 20);
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
a[i] = (int) (Math.random() * 20); //What's this! Another random number!
i--;
break;
}
}
}
int[] a = new int [size];
for (int i = 0; i < size; i++)
{
a[i] = (int)(Math.random()*16); //numbers from 0-15
for (int j = 0; j < i; j++)
{
//Instead of the if, while verifies that all the elements are different with the help of j=0
while (a[i] == a[j])
{
a[i] = (int)(Math.random()*16); //numbers from 0-15
j=0;
}
}
}
for (int i = 0; i < a.length; i++)
{
System.out.println(i + ". " + a[i]);
}
//Initialize array with 9 elements
int [] myArr = new int [9];
//Creating new ArrayList of size 9
//and fill it with number from 1 to 9
ArrayList<Integer> myArrayList = new ArrayList<>(9);
for (int i = 0; i < 9; i++) {
myArrayList.add(i + 1);
}
//Using Collections, I shuffle my arrayList
Collections.shuffle(myArrayList);
//With for loop and method get() of ArrayList
//I fill my array
for(int i = 0; i < myArrayList.size(); i++){
myArr[i] = myArrayList.get(i);
}
//printing out my array
for(int i = 0; i < myArr.length; i++){
System.out.print(myArr[i] + " ");
}
You can try this solution:
public static int[] uniqueRandomElements(int size) {
List<Integer> numbers = IntStream.rangeClosed(0, size).boxed().collect(Collectors.toList());
return Collections.shuffle(numbers);
}

2-dimensional array in Java

Assume you are given an int variable named nPositive and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that compute the number of all the elements in the entire 2-dimensional array that are greater than zero and assign the value to nPositive.
Code:
for(int i=0; i<a2d.length; i++){
int nPositive;
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive = a2d[i][j];
}
}
}
It has a compilation error. Why?
The iiner cycle is incorrect:
for(int j=0; j<a2d[i].length; j++){
You didn't initialize nPositive.
// make nPositive a global variable
int nPositive = 0;
for(int i=0; i<a2d.length; i++){
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive += a2d[i][j]; // add the value into nPositive as you go through the array
}
}
}
I tested it and find that,There is no any compilation error in your code...
for(int j=0; j<a2d[a2d.length-1].length; j++){//
let the length is a2d[10][10]
on statement a2d[a2d.length-1].length ,is equal a2d[10-1].length ,is equal a2d[9].length=>10
your algo is working fine for me ,i found no any error
here's my test code
public class A2dTest {
public static void main(String[] arr) {
int[][] a2d = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a2d[i][j] = (int) (Math.random() * 100) + 1000000;// all positives
}
}
for (int i = 0; i < a2d.length; i++) {
int nPositive = 0;
for (int j = 0; j < a2d[a2d.length - 1].length; j++) {
if (a2d[i][j] > 0) {
nPositive = a2d[i][j];
System.out.println("nPositive=" + nPositive);
}}
}
}
}
I believe this is one of the questions on codeLab. You just need to properly initialize nPositive at 0 and increment it for every positive integer. That's all they're looking for involving the output. So your code needs to be:
nPositive = 0;
for (int i = 0; i < a2d.length; i++)
{
for (int j = 0; j < a2d[i].length; j++)
{
if (a2d[i][j] > 0)
{
nPositive++;
}
}
}

How do i complete this question with 2-dimensional array in java?

Hey guys, im working through the Introduction to Programming in Java book and one of the exercises is this:
Empirical shuffle check. Run
computational experiments to check
that our shuffling code works as
advertised. Write a program
ShuffleTest that takes command-line
arguments M and N, does N shuffles of
an array of size M that is initialized
with a[i] = i before each shuffle, and
prints an M-by-M table such that row i
gives the number of times i wound up
in position j for all j. All entries
in the array should be close to N/M.
Now, this code just outputs a block of zeros...
public class ShuffleTest2 {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int [] deck = new int [M];
for (int i = 0; i < M; ++i)
deck [i] = i;
int [][] a = new int [M][M];
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
a[i][j] = 0 ;
for(int n = 0; n < N; n++) {
int r = i + (int)(Math.random() * (M-i));
int t = deck[r];
deck[r] = deck[i];
deck[i] = t;
for (int b = 0; b < N; b++)
{
for (int c = 0; c < M; c++)
System.out.print(" " + a[b][c]);
System.out.println();
}
}
}
}
}
}
What am i doing wrong? :(
Thanks
So a is like a history? As you are now it is always filled with zeroes just like you initialized, you never assign to it! After the "shuffling" for loop you need to set
A[i][POSITION] = CARD_VALUE
Meaning that after i-th shuffle, card CARD_VALUE is in position POSITION. I don't want to give you all the specifics, but it will take another for loop, and the nested for-loop for printing needs to be independent of any other loop, occuring when everything else is done.
Looks like you have a few things concerning the for-loops that you need to look over carefully. Trace the program flow manually or with a debugger and you'll notice that some of those braces and code blocks need to be moved.
--TRY THIS--
public class ShuffleTest2 {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int [] deck = new int [M];
int [][] a = new int [M][M];
for (int i = 0; i < M; i++) { //initialize a to all zeroes
for (int j = 0; j < M; j++) {
a[i][j] = 0 ;
}
}
for(int i = 0; i < N; i++) //puts the deck in order, shuffles it, and records. N times
{
for (int j = 0; j < M; j++) //order the deck
deck[j] = j;
for(int j = 0; j < M; j++) { //shuffle the deck (same as yours except counter name)
int r = j + (int)(Math.random() * (M-j));
int t = deck[r];
deck[r] = deck[j];
deck[j] = t;
}
for(int j = 0; j < M; j++) //record status of this deck as described
{
int card_at_j = deck[j]; //value of card in position j
a[card_at_j][j]++; //tally that card_at_j occured in position j
}
} //big loop ended
for (int b = 0; b < M; b++) //print loop. a is MxM, so limit of N was wrong.
{
for (int c = 0; c < M; c++)
{
System.out.print(" " + a[b][c]);
System.out.println();
}
} //print loop ended
} //main() ended
} //class ended

Categories

Resources