I wrote a small program.
Сondition: "Given an array of size n. Insert an element with a zero value after each negative element of the array." I solved this task using 2 ArrayList arrays. I'm wondering if it's possible to get a solution using only 1 array?
Code of the program:
public class Task_108 {
public void Task108(){
System.out.println("Input size of array: ");
Scanner scn = new Scanner(System.in);
int sizeArr = scn.nextInt();
ArrayList<Integer> ArrIntNum = new ArrayList<>(sizeArr); // Declare array
Random rnd = new Random();
int val;
// Filling array random elements from -20 to 20
for(int i = 0; i < sizeArr; i++){
val = -20 + rnd.nextInt(41);
ArrIntNum.add(i, val);
}
// Output array on the screen
System.out.println(ArrIntNum.toString());
ArrayList<Integer> ArrWithZeroAftNegVal = new ArrayList<>(); // Declare once more array
// Adding zero after every negative number in array ArrIntNum and write in array ArrWithZeroAftNegVal
for(int i = 0; i < sizeArr; i ++){
if(ArrIntNum.get(i) < 0) {
ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
ArrWithZeroAftNegVal.add(0);
}
else
ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
}
// Output edited array on the screen
System.out.println(ArrWithZeroAftNegVal.toString());
}
}
A ListIterator works quite naturally, allow addition of elements on the same array:
ListIterator<Integer> i = ArrIntNum.listIterator();
while (i.hasNext()) {
Integer value = i.next();
if (value < 0) i.add(0);
}
Like this:
import java.util.ArrayList;
public class Task_108 {
public void Task108(){
System.out.println("Input size of array: ");
Scanner scn = new Scanner(System.in);
int sizeArr = scn.nextInt();
ArrayList<Integer> arrIntNum = new ArrayList<Integer>(sizeArr); // Declare array
Random rnd = new Random();
// Filling array random elements from -20 to 20
for(int i = 0; i < arrIntNum.size(); i++)
arrIntNum.add(-20 + rnd.nextInt(41));
// Output array on the screen
System.out.println(arrIntNum);
// Adding zero after every negative number in array ArrIntNum
for(int i = 0; i < sizeArr; i++) {
if(arrIntNum.get(i) < 0)
arrIntNum.add(i + 1, 0);
}
// Output edited array on the screen
System.out.println(arrIntNum);
}
}
I also simplified your code for you.
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I'm using this code:
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Matrix
{
public static void main(String[] args)
{
Scanner enter = new Scanner(System.in);
int[][] firstMatrix = new int[4][4];
int[][] secondMatrix = new int[4][4];
Random spin = new Random();
System.out.println("Please enter 16 numbers to populate the array: ");
for (int count = 0; count<firstMatrix.length;count++) // nested for for user input to populate 4x4 array
{
for (int count2 = 0; count2 < firstMatrix[count].length; count2++)
{
firstMatrix[count][count2] = enter.nextInt(); // populate array with user input
}
} // end array population
System.out.printf("The sum is: %d%n", sumMatrix(firstMatrix)); // call sumMatrix
System.out.println(firstMatrix[0][0]); // debug
for (int count3 = 0; count3<secondMatrix.length; count3++) // nested for to populate array with random numbers 1-100, row
{
for (int count4 = 0; count4<secondMatrix[count3].length; count4++) // column
{
secondMatrix[count3][count4] = 1 + spin.nextInt(100); // 100 inclusive, generate and populate array
}
}
System.out.println(secondMatrix[0][0]); // debug to show that it is properly printing the correct element
for (int i = 0; i<secondMatrix.length; i++)
{
for (int j = 0; j<secondMatrix[i].length; j++)
System.out.print(" " + secondMatrix[i][j]); // print the total array ( this process can be used to print the returned array )
}
System.out.println(); // debug
int arrayTotal = firstMatrix[0][0] + secondMatrix[0][0]; // debug
System.out.println("The element total is " + arrayTotal); // debug
System.out.println();
addMatrix(firstMatrix,secondMatrix); // call addMatrix
System.out.println("Programmed by Stephen Mills");
} // end main
public static int sumMatrix(int[][] array) // method to sum the elements of the array
{
int total = 0;
for (int number = 0; number<array.length; number++) // row
{
for (int number2 = 0; number2<array[number].length; number2++) // column
total += array[number][number2]; // sum of all elements
}
return total; // returns the sum
} // end sumMatrix
public static int[][] addMatrix(int[][] array1, int[][] array2) // improper method
{
int[][] thirdMatrix = new int[4][4];
for (int count4 = 0; count4<thirdMatrix.length; count4++)
{
for (int count5 = 0; count5<thirdMatrix[count4].length; count5++)
thirdMatrix[count4][count5] = array1[count4][count5]+array2[count4][count5];
}
System.out.println(Arrays.toString(thirdMatrix));
return thirdMatrix;
} // end addMatrix7
}
Most of the program works as intended but I'm getting this "[[I#3d4eac69, [I#42a57993, [I#75b84c92, [I#6bc7c054" output when trying to print my array. I've tried several methods, including simple println, toString, setting a variable equal to the method call, and I've tried putting the print statement in main first and then in the method second. Any ideas why this is happening?
If you want to print int elements of the 2d array thirdMatrix you can try this:
for(int[] simpleArray: thirdMatrix)
System.out.println(Arrays.toString(simpleArray));
The reason of your output: when you call
Arrays.toString(thirdMatrix)
you will call
String.valueOf(element)
foreach element of thirdMatrix. As elements of thirdMatrix are Array not primitive types, method
String.valueOf(Object obj)
will be called which return the hashcode of thirdMatrix elements(one-dimensional arrays).
I'm trying to create an Integer[] that is increased by a multiple of 10 for each loop. Once the Integer[] size is set I'd like it to fill up the array with random ints. I'm able to get the size of the array to increase, but the values stored within it are null.
To me this means the array is resizing correctly, but they elements aren't being assigned to anything. I'm trying a double for-loop, with the inner loop assigning the random values. If there is a better way to do this(which I'm sure there is b/c mine isn't running!) could you please help?
this is my creation of the Int[]
public class TimeComplexity {
Integer[] data;
public TimeComplexity()
{
Random random = new Random();
for (int N = 1000; N <= 1000000; N *= 10)
{
N = random.nextInt(N);
data = new Integer[N];
//checking to see if the random numbers were added.
//array size is okay but locations aren't taking a
//random number
System.out.println(Arrays.toString(data));
}
}
In case you're interested in the output for it my main class. (this isn't part of the question but if you have suggestions I'd love them!)
public class TimeComplexityApp {
private static int MAXSIZE = 1000000;
private static int STARTSIZE = 1000;
public TimeComplexityApp()
{
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
TimeComplexity time = new TimeComplexity();
System.out.println(time);
System.out.printf("%-6s %13s %13s\n\n\n","ARRAY","int","INTEGER");
for (int N = STARTSIZE; N <= MAXSIZE; N *= 10)
{
double d = 1.0;
System.out.printf("\n%-6d %15.2f %15.2f\n", N, d, d);
}
}
}
In the first source code that shows lack initialize the elements of array of integers.
data = new Integer [N]; only creates the array of integers of size N, lack include the elements in each cell of the array.
So, just need a loop to complete each element or cell array:
for (int i = 0; i <N; i ++)
data [i] = random.nextInt (N);
Now this array is complete and will not return NULL on each item.
On every iteration of your loop, you are creating a new array of random (int size) length. But you are never putting anything into it. The right way to do this is:
int[] vals = ...;
for (int i = 0; i < end - start; i++) {
if (vals.length < i; i++) {
//1. create new larger int[]
//2. copy the old array into the new array
//3. vals = yourNewArray
}
vals[i] = random.nextInt();
}
int[] drawNumbers = new int[10];//Array With 10 Random Numbers USED for DRAWN NUMBERS
String x = "Drawn Numbers: ";
List<Ticket> ticketWon ;
do{
//GENERATING 10 Random Numbers
for (int i = 0; i <= drawNumbers.length -1 ; i++) {
Random r = new Random();
drawNumbers[i] = r.nextInt(99) + 1;
x += drawNumbers[i] + " ";
}
}
I'm trying to generate 10 random numbers that must be random generated and Unique. My problem is that with Random r = new Random() there are times that replicated numbers are shown. How can i generate 10 random numbers from range 1 to 99 without replications?
Problem is for a Lottery System
I would like to use Collection.Shuffle but I'm not that sure how it should be implemented.
Here is an alternative way to achieve your desired result. We populate a list with values 1 to 99. Then we shuffle the list and grab the first 10 values:
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<100; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<10; i++) {
System.out.println(list.get(i));
}
}
You won't have to import/directly deal with Random, which is a plus. However, as pointed out by #Voicu (in the comments), shuffle does indeed utilize random:
public static void shuffle(List<?> list) {
if (r == null) {
r = new Random();
}
shuffle(list, r);
}
private static Random r;
You can broadly think of this problem as having a deck of cards numbered from 1 to 99, and you want to pick 10 of those cards. The solution would be to, programmatically, create that deck and then randomly select from that deck and remove from the deck.
We can model the deck as a List of Integers and populate that List with entries from 1 to 99 with something like this:
List<Integer> deck = new ArrayList<Integer>();
for( int i=1; i<=99; i++ ){
deck.add( i );
}
We then need to pick a random card between the 0th card (lists are numbered starting at 0) and the number of elements in the list:
int draw = r.nextRandom( deck.size() );
Integer card = deck.remove( draw );
And repeat that 10 times, doing something with the "card" (say, putting it into an array, or another list, or whatever:
int drawNumbers = new int[10];
for( int co=0; co<10; co++ ){
int draw = r.nextRandom( deck.size() );
Integer card = deck.remove( draw );
drawNumbers[co] = card;
}
Use Set<Integer>.
Set<Integer> set = new HashSet<Integer>();
int[] drawNumbers = new int[10];
Random r = new Random();
for(int i=0; i<10; i++)
{
drawNumbers[i] = r.nextInt(99) + 1;
while(set.contains(drawNumbers[i]))
drawNumbers[i] = r.nextInt(99) + 1;
set.add(drawNumbers[i]);
}
I'd generate random numbers and save them to a Set until I get 10 numbers. Then create a list from it, shuffle it, and then take numbers from it.
final int NUMBERS_TO_DRAW = 10;
Random r = new Random();
// Generate NUMBERS_TO_DRAW random numbers
Set<Integer> randoms = new HashSet<>();
while (randoms.size() < NUMBERS_TO_DRAW) {
randoms.add(r.nextInt(99) + 1);
}
// Now shuffle them:
List<Integer> shuffledRandom = new ArrayList<>(randoms);
Collections.shuffle(shuffledRandom);
EDIT:
As #MarkPeters noted in the comments, using a LinkedHashSet would eliminate the need to shuffle:
final int NUMBERS_TO_DRAW = 10;
Random r = new Random();
// Generate NUMBERS_TO_DRAW random numbers
LinkedHashSet<Integer> randoms = new LinkedHashSet<>();
while (randoms.size() < NUMBERS_TO_DRAW) {
randoms.add(r.nextInt(99) + 1);
}
It would be easier to use a list so you could check if it already contains the number and re-generate if it does.
List<Integer> drawNumbers = new ArrayList<Integer>();
Random r = new Random();
int newNumber = -1;
do
{
newNumber = r.nextInt(99) + 1;
} while(drawNumbers.contains(newNumber); //Make sure the number is not already in the list.
Then put this in a loop to repeat 10 times.
I am trying to solve a problem in Java as part of my assignment. The problem is as below:
The user enters ten numbers one by one upon prompting by the screen. The screen then assigns all the distinct value to an array and a similar array to hold the frequency of how many times those numbers have appeared.
I have done the below work, but seems I am stuck somewhere in assigning the frequencies and distinct values to the arrays:
import java.util.*;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
for (int k=0;k<10;k++)
{
count[k]=0;
distinct[k]=0;
}
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter number 0: ");
numbers[0]=input.nextInt();
count[0]=1;
distinct[0]=numbers[0];
int j=0;
for (int i = 1;i<10;i++)
{
System.out.print("Enter number "+i+": ");
numbers[i]=input.nextInt();
while(j<i)
{
if (distinct[j]==numbers[i])
count[j]=count[j]+1;
else
distinct[j+1]=numbers[i];
j++;
}
}
for (int k=0;k<10;k++)
{
System.out.println(distinct[k]+ " "+count[k]);
}
}
}
I know that it is not fair to ask someone to help me solve the problem. But any kind of hint will be helpful.
Thank you
are the numbers limited to 0-9? If so, I would simple do the assignment.
(please note you will assign the input to a variable called "input"):
numbers[0]=input;
count[input]++;
Also you can start your for loop in "0" to avoid the assignment prior to the for loop.
Just a hint.
Hope this helps!
the ideal data structure would be a HashMap
Steps:
1) initialize an array to store the numbers and for each input
2) check if a hashmap entry with key as the entered number already exists
3) if exists simply increase its count
4) else create new entry with key as the number and count as 1
so at the end your frequencies would be calculated
if you are forced to use 2 arrays
1) initialize two arrays
2) for each input loop the number array and check whether that number is already in the array
3) if so take the array index and increment the value of the frequency array with the same index
4) if not freq[index] = 1
A proper way of doing that would be:
public Map<Integer, Integer> getFrequencies(Iterable<Integer> numbers) {
Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
for(Integer number : numbers) {
if (frequencies.get(number) == null) {
frequencies.put(number, 0);
}
frequencies.put(number, frequencies.get(number) + 1);
}
return frequencies;
}
It returns a map number -> frequency.
Arrays are not a way to go in Java, they should be avoided whenever possible. See Effective Java, Item 25: Prefer lists to arrays.
I removed the Scanner object to write the code faster, just replace it with your code above and it should work.
int[] numbers = { 1, 2, 2, 2, 3, 3, 3, 1, 1, 2 };
int[] count = new int[10];
int[] distinct = new int[10];
count[0] = 1;
distinct[0] = numbers[0];
int disPos = 1; //Current possition in the distinct array
boolean valueInarray = false;
for (int i = 1; i < 10; i++) {
valueInarray = false;
for (int d = 0; d < i; d++) {
if (numbers[i] == distinct[d]) {
count[d] = count[d] + 1;
valueInarray = true;
break;
}
}
if (!valueInarray) {
distinct[disPos] = numbers[i];
count[disPos] = 1;
disPos++;
}
}
If you ABSOLUTELY HAVE TO use arrays.. here is a way to do it…
import java.util.Scanner;
import java.util.Arrays;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
int [] distinct1 = new int[1];
int distinctCount = 0;
boolean found = false;
Scanner input = new Scanner(System.in);
for (int i=0; i<10; i++) {
found = false;
System.out.print("Enter number " + i);
numbers[i]=input.nextInt(); //Add input to numbers array
for (int j=0; j<=distinctCount; j++)
{
if (distinct1[j] == numbers[i]){ // check to see if the number is already in the distinct array
count[j] = count[j] + 1; // Increase count by 1
found = true;
break;
}
}
if (!found) {
distinct[distinctCount] = numbers[i];
count[distinctCount] = 1;
distinctCount++;
distinct1 = Arrays.copyOf(distinct, distinctCount+1);
}
}
for (int j=0; j<distinctCount; j++)
System.out.println("The number " + distinct1[j] + " occurs " + count[j] + " times" );
}
}
I think this is what you need, correct me if I'm wrong...
import java.util.HashMap;
import java.util.Scanner;
public class JavaApplication10 {
public static void main(String[] args) {
// Initializing variables
int[] numbers = new int[10];
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
Scanner input = new Scanner(System.in);
// Getting the 10 inputs
for(int x=0; x<10; x++) {
// Asking for input
System.out.println("Enter number "+x+":");
numbers[x]=input.nextInt();
// If the table contains the number, add 1
// Otherwise: set value to 1
if(table.containsKey(numbers[x]))
table.put(numbers[x], table.get(numbers[x])+1);
else
table.put(numbers[x],1);
}
// Closing the reader
input.close();
// Get the highest and smallest number
int highest=0;
int smallest=0;
for(int i:table.keySet()) {
if(i>highest)
highest=i;
if(i<smallest)
smallest=i;
}
// For every value between the smallest and the highest
for (int x=smallest; x<=highest; x++) {
// Check if the frequency > 0, else continue
if(table.get(x)==null)
continue;
// Output
System.out.println(x+" is "+table.get(x)+" times in \'frequence\'");
}
}
}
This also handles with negative numbers, unlike the other's codes. If you don't want to use HashMaps let me know so I can create something with arrays.
Let me know if it (doesn't) works!
Happy coding (and good luck with your assignment) ;) -Charlie
I need to make a typical integer filled array with 10 random non repeating numbers from 0 to 20. Also, I need to be able to modify this so I can exclude some random numbers from 0 to 20.
How can I do this?
You can do this in three easy steps:
Build a list with all the candidate numbers you want
Use Collections.shuffle to shuffle that list
Use the n first elements of that shuffled list.
First build a list of size 20 with values 0,...,19
Then shuffle() it
And last - take the sublist containing first 10 elements.
This Method will work for you. It generate 10 unique random numbers from 0 to 20.
public static int[] getRandomArray(){
int randomCount =10;
int maxRandomNumber = 21;
if(randomCount >maxRandomNumber ){
/* if randomCount is greater than maxRandomNumber
* it will not be possible to generate randomCount
* unique numbers
**/
return null;
}
HashMap<Integer, Integer> duplicateChecker = new HashMap<Integer, Integer>();
int[] arr = new int[randomCount ];
int i = 0;
while(i<randomCount ){
// Generate random between 0-20, higher limit 21 is excluded
int random = new Random().nextInt(maxRandomNumber );
if(duplicateChecker.containsKey(random)==false){
duplicateChecker.put(random, random);
arr[i]=random;
i++;
}
}
return arr;
}
* Edited: To make the method deterministic. And Avoid the chance of infinite loop
public static int[] getRandomArray(){
int randomCount =10;
int maxRandomNumber = 21;
if(randomCount >maxRandomNumber ){
/* if randomCount is greater than maxRandomNumber
* it will not be possible to generate randomCount
* unique numbers
**/
return null;
}
ArrayList<Integer> arrayList = new ArrayList<Integer>();
// Generate an arrayList of all Integers
for(int i=0;i<maxRandomNumber;i++){
arrayList.add(i);
}
int[] arr = new int[randomCount ];
for(int i=0;i<randomCount;i++){
// Generate random between 0-20, higher limit 21 is excluded
int random = new Random().nextInt(arrayList.size());
// Remove integer from location 'random' and assign it to arr[i]
arr[i]=arrayList.remove(random);
}
return arr;
}
What about making an arraylist of numbers upto 20, and after each random number call you remove the number from the list and into the array.
example
Random r = new Random();
int[] myArray = new int[10];
ArrayList<Integer> numsToChoose = new ArrayList<Integer>();
int counter = 0;
for(int i = 0; i < 21; i++)
{
numsToChoose.add(i);
}
while(numsToChoose.size() > 11)
{
myArray[counter] = numsToChoose.remove(r.nextInt(numsToChoose.size()));
counter++;
}
That way it should only loop 10 times, I may be wrong though.
Hope it helps
EDIT: And in order to modify this to exclude certain numbers, you would just need a method that takes an array that contains said numbers as a parameter, and loop through it removing each number from the arraylist before you generate your random numbers.
Most of the other responses offer the Collections.shuffle method as a solution. Another way, which is theoretically faster is the following:
First lets build the list:
public class RandomWithoutReplacement {
private int [] allowableNumbers;
private int totalRemaining;
/**
* #param upperbound the numbers will be in the range from 0 to upperbound (exclusive).
*/
public RandomWithoutReplacement ( int upperbound ) {
allowableNumbers = new int[ upperbound ];
for (int i = 0; i < upperbound; i++) {
allowableNumbers[i] = i;
}
totalRemaining = upperbound;
}
}
Next lets consider what we need to do when we need to get the next number.
1) When we request another number, it must be chosen from any one of the available, uniformly.
2) Once it is chosen, it must not repeat again.
Here is what we can do:
First, choose a number at random from the allowableNumbers array.
Then, remove it from the array.
Then remove the number at the end of the array, and place it in the position of the number we are to return.
This ensures all of the 2 conditions we have placed.
public int nextRandom () {
//Get a random index
int nextIndex = (int) ( Math.random() * totalRemaining );
//Get the value at that index
int toReturn = allowableNumbers [ nextIndex ];
//Find the last value
int lastValue = allowableNumbers [ totalRemaining - 1 ];
//Replace the one at the random index with the last one
allowableNumbers[ nextIndex ] = lastValue;
//Forget about the last one
totalRemaining -- ;
return toReturn;
}
With that, your function is almost complete.
I would add a couple more things just in case:
public boolean hasNext () {
return totalRemaining > 0;
}
And at the beginning of the actual function:
public int nextRandom () {
if (! hasNext() )
throw new IllegalArgumentException();
// same as before...
}
That should be it!
Well, I could't help it not to post my solution which is storing a sequance of numbers into twice as many random locations first. Then compacts it into the resultting array.
int[] myRandomSet = generateNumbers(20, 10);
...
public int[] generateNumbers(int range, int arrayLenght){
int tempArray[];
int resultArray[];
int doubleLocations;
Random generator = new Random();
doubleLocations = range * 2;
tempArray = new int[doubleLocations];
resultArray = new int[arrayLenght];
for (int i=1; i<=range; i++){
if (i != 5 && i != 13){ //exclude some numbers
do{
r = generator.nextInt(doubleLocations);
}while(tempArray[r]!=0);
tempArray[r] = i; //enter the next number from the range into a random position
}
}
int k = 0;
for (int i=0; i<(doubleLocations); i++){
if(tempArray[i] != 0){
resultArray[k] = tempArray[i]; //compact temp array
k++;
if (k == arrayLenght) break;
}
}
return resultArray;
}