Create a Stream using Scanner - arrays

This is usually how I accept an Array from a user. I ask for the size, then loop and populate the Array.
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
int[] numbers = new int[N];
for (int n=0; n<N; n++){
numbers[n] = scan.nextInt();
}
I have been trying to learn java 8 and I noticed that the Random class has a method now to create a stream. It is pretty easy now to declare a n-sized array with random numbers.
int[] randomNumbers = new Random().ints().limit(N).toArray();
What I have been trying to do is create an array doing something similar with either streams or lambda expressions but for user input. What I tried doing is creating an IntStream, map the values to Scanner#nextInt, then create an array.
int[] numbers = new IntStream().map(x -> scan.nextInt()).limit(N).toArray();
What I can do is something like this:
int[] numbers = new int[N];
Arrays.fill(numbers, 0);
numbers = Arrays.stream(numbers).map(x -> scan.nextInt()).toArray();
System.out.println(Arrays.toString(numbers));
But that still feels a bit redundant. Filling the array with some arbitrary number only to replace it in the next line.

Due to the way, the current implementation handles limit(…)s, it’s more efficient to create a stream using:
IntStream.range(0, N).map(i -> scan.nextInt())
which will be more efficient when using toArray() as well as for parallel processing despite creating an otherwise unused value with the range operation. Further, this creates an ordered stream which maintains the element order.
So when using,
int[] numbers = IntStream.range(0, N).map(i -> scan.nextInt()).toArray();
it benefits from knowing the array size in advance.

Use IntStream.generate:
int[] numbers = IntStream.generate(() -> scan.nextInt()).limit(N).toArray();
As mentionned in the comments, this generates an unordered stream. If you want it to be ordered, you can use:
IntStream.range(0, N).map(i -> scan.nextInt()).toArray();

Related

How would I convert the data type int[] to the data type int

I have set up an array to randomize 5 different numbers in one class. In a different class I have prompted a user to guess the random number, and must reference the number each time to determine whether they have guessed correctly or not. My issue is that the numbers being randomized are in the data type int[], and I need to compare them to the data type int. When trying to reference the randomized numbers I get the error "Type mismatch: cannot convert from int[] to int". Any advice on how I would do that?
Class diceNumGen
final static int ARRAY_SIZE = 5;
public static int[] randNumArray = new int [ARRAY_SIZE];
public static int[] randNums(){
for(int i=0; i < randNumArray.length; i++) {
randNumArray[i] = (int) (Math.random()*12);
System.out.println(randNumArray);
}
return randNumArray.clone();
}}
Class Bet
static Bet bet = new Bet();
diceNumGen newClassObj = new diceNumGen();
int secondArray = diceNumGen.randNumArray;
//Set Turns variable where turns = 5
public int turnsToGo = 5;
//Set up the bet() method
public void bet() {
//Sets up the options as an array to be on the JOptionPane, each are numbered 0, 1, and 2 respectively
String[] options = {"Guess below 7", "Guess 7", "Guess above 7"};
welcome here, I'm newcomer too, this is my first answer.
I assume that you are using java, because of keywords, it is good to define the programming language in the question or tags to get better responses.
the first thing about your code is you don't need a whole class for generating an array, an ordinary function like this would be OK too:
static int[] randomGen(int len){
java.util.Random rand = new java.util.Random();
int[] randoms = new int[len];
for (int i = 0; i < len; i++) {
randoms[i] = rand.nextInt(12);
}
return randoms;
}
the next thing is, please indent your code, un-indented code (or badly indented code) will confuse the reader.
and about your question, at the first point why are you creating random array with the size of 5? if you just need one random number, just create one random number (with your Math.random() or better, nextInt(12) in Random class)
if user have 5 chances to guess same number you don't need 5 random numbers. just use this:
int randomNumber = (int) (Math.random() * 12);
or if you want user to guess 5 separate numbers, you need a for loop to iterate this random array per user guess.
Good luck in learning java.

Fill a 3d array with stream in java

My current code is like:
double[][][] result = new double[1000][][];
for (int i = 0; i < result.length; i++){
result[i] = somemethod();
}
Now I want to use stream to do the same thing. I did a lot of research, but cannot find an answer to fill the first dimension with the return value of another method.
For your task, the 3D nature of the array is irrelevant. You can replace double[][] with X in your mind and follow the same generic steps, you would do when producing the array X[]:
X[] array = IntStream.range(0, size).mapToObj(i -> somemethod()).toArray(X[]::new);
Using double[][] for X and 1000 for size yields:
double[][][] result
= IntStream.range(0, 1000).mapToObj(i -> somemethod()).toArray(double[][][]::new);
If somemethod() is expensive, but has no interference (so multiple concurrent calls are safe), you can use .parallel() with the stream. You could also use
double[][][] result = new double[1000][][];
Arrays.parallelSetAll(args, i -> somemethod());
in that case.

Finding the amount of different elements at array

We have an array at size n. How we can find how many different types of elements we have at n and what is the amount of each one?
For example: at {1,-5,2,-5,2,7,-5,-5} we have 4 different types, and the array of the amounts will be: {1,2,1,4}.
So my questions are:
How we can find how many different elements there is at the array?
How we can count the amount if each one?
Now, I try to solve it at Omega(n), I try a lot but I didn't find a way. I try to solve it with hash-tables.
You are trying to get frequency of an element in an array.
Initialize a Hash where every new key is initialized with value 0.
Loop through array and add this key to hash and increment the value.
In JavaScript:
hash = {};
a = [1,-5,2,-5,2,7,-5,-5];
for(var i = 0; i < a.length; ++i) {
if(hash[a[i]] === undefined)
hash[a[i]] = 0
hash[a[i]] = hash[a[i]] + 1;
}
console.log(hash.toSource());
The syntax and specific data structures you use will vary between languages, but the basic idea would be to store a running count of the number of instances of each value in an associative data structure (HashMap, Dictionary, whatever your language calls it).
Here is an example that will work in Java (I took a guess at the language you were using).
It's probably bad Java, but it illustrates the idea.
int[] myArray = {1,-5,2,-5,2,7,-5,-5};
HashMap<Object,Integer> occurrences = new HashMap<Object,Integer>();
for (int i=0;i<myArray.length;i++)
{
if (occurrences.get(myArray[i]) == null)
{
occurrences.put(myArray[i],1);
}
else
{
occurrences.put(myArray[i],occurrences.get(myArray[i])+1);
}
}
You can then use your HashMap to look up the distinct elements of the array like this
occurrences.keySet()
Other languages have their own HashSet implementations (Dictionaries in .NET and Python, Hashes in Ruby).
There are different approaches to solve this problem.The question that asked here might be asked in different ways.Here the the simple way to do it with std::map which is available in STL libraries.But remember it will be always sort by key.
int arr[]={1,-5,2,-5,2,7,-5,-5};
int n=sizeof(arr)/sizeof(arr[0]);
map<int,int>v;
for(int i=0;i<n;i++)
{
if(v[arr[i]])
v[arr[i]]++;
else
v[arr[i]]=1;
}
map<int,int>::iterator it;
for(it=v.begin();it!=v.end();++it)
cout<<it->first<<" "<<it->second<<endl;
return 0;
it will show output like
-5 4
1 1
2 2
7 1
I suggest you read about 'Count Sort'
Although i am not sure i understood correctly what you actually want to ask. Anyway, i think you want to:
1.) Scan an array and come up with the frequency of each unique element in that array.
2.) Total amount of unique elements
3.) all that in linear computational time
I think, what you need is Counting Sort. See algo on wiki.
You can obviously skip the sorting part. But you must see how it does the sorting (the useful part for your problem). It, first, calculates a histogram (array of size nominally equal to the number of unique elements in you original array) of frequency of each key. This works for integers only (although you can always sort other types by putting integer pointers).
So, every index of this histogram array will correspond to an element in your original array, and the value at this index will correspond to the frequency of this element in the original array.
For Example;
your array x = {3, 4, 3, 3, 1, 0, 1, 3}
//after calculation, you will get
your histogram array h[0 to 4] = {1, 2, 0, 4, 1}
i hope that is what you asked

J2ME - Storing ints in an array or similar

I am currently writing an app for a card game in j2me, I have used random number generator to create 5 random ints that will be stored in an array or similar to represent the players hand of cards (as each number represents a corresponding card in the pack)
At the moment, the following card creates the random numbers
int n = 0;
Random r = new Random();
while(n<5) {
int i = r.nextInt(52);
System.out.println( i);
n++;
I have tried to use a vector to store the 5 i values but I could not get this working, I was hoping for any suggestions of what I should consider using for storing i which will be accessible during gameplay.
Thanks Guys! :-) x
I dont see why you cant use Vector to store the values.
try this..
int n = 0;
**Vector<int> name = new Vector<int>();**
Random r = new Random();
while(n<5) {
int i = r.nextInt(52);
System.out.println( i);
**name.set(i, n);**
n++;
}
if this code was in a method, you can pass in the vector as a reference, so you can store the values.

How to do a simple random sort of values within an array

I need to sort these values randomly in an array.
int [] d = new int[26];
d[0]=1;
d[1]=5;
d[2]=10;
d[3]=25;
d[4]=50;
d[5]=75;
d[6]=100;
d[7]=200;
d[8]=300;
d[9]=400;
d[10]=500;
d[11]=750;
d[12]=1000;
d[13]=2000;
d[14]=3000;
d[15]=4000;
d[16]=5000;
d[17]=7500;
d[18]=10000;
d[19]=25000;
d[20]=50000;
d[21]=100000;
d[22]=250000;
d[23]=500000;
d[24]=750000;
d[25]=1000000;
Assuming you are writing this in C++ you can use random_shuffle function template from the Standard library. http://www.cppreference.com/wiki/algorithm/random_shuffle
If you want to write your own function, simply take two random indices and swap their values. Put that in a loop and do it as many times as think necessary for the array to be well shuffled (I would say a number of times equal to two times the number of elements in the array).
In psudo-code (since you haven't indicated the language)
NUMBER_OF_SHUFFLES = 2;
for(ix = 0; ix < NUMBER_OF_SHUFFLES * myArray.length; ix++)
index1 = random(myArray.length)
index2 = random(myArray.length)
temp = index1
myArray[index1] = myArray[index2]
myArray[index2] = temp
There are more sophisticated ways of doing it as well. Check out this discussion: An Efficient way of randomizing an array - Shuffle code
If it's java you may use
Arrays.shuffle(d);

Resources