two dimensional arraylists and input/sorting - java

I am trying to add all the doubles between two <end> instances into an arraylist within an arraylist (at each index of <end> have the doubles between the <end>s, and so forth)
ArrayList<ArrayList<Double>> myArr = new ArrayList<ArrayList<Double>>();
int j = 0;
int nLine = 0;
while(scan.hasNext()) {
String line = scan.next();
//System.out.println(line);
if(!line.equals("<end>")) {
nLine = Double.valueOf(line);
ArrayList<Double> row = new ArrayList<Double>();
myArr.add(row);
row.add(j, nLine);
j=j++;
} else {
j=j++;
}
}
As it stands now the code is putting in a single double in a an array (as opposed to all of the ones between statements; thus the output looks like this:
[[1.4], [3], [15], [3.2], etc. etc.
where I want it to look like this:
[[1.4, 3, 15, 3.2], [5, 13.4], [954.3, etc....
The file it is scanning is essentially:
<end>
1.4
3
15
3.2
<end>
5
13.4
<end>
954.3
43 etc. etc. (infinitely)
My goal (eventually) is to tally how many doubles are in each arrayList index and make sure none of the doubles are exactly the same, and to make sure each of the row arrays have no more than 10 values in them.
So I have been stuck and any help is appreciated.
Thanks for any help.

ArrayList<ArrayList<Double>> myArr = new ArrayList<ArrayList<Double>>();
int nLine = 0;
ArrayList<Double> currArr = null;
while(scan.hasNext()) {
String line = scan.next();
if(!line.equals("<end>")) {
nLine = Integer.valueOf(line);
currArr.add(nLine);
} else {
if(currArr!=null) myArr.add(currArr);
currArr = new ArrayList<Double>();
}
}
if(currArr!=null) myArr.add(currArr);
In the middle of the code you're using Integer instead of Double. Not sure why so I left it. Code assumes the input always starts with <end>.

You could use a HashSet as a way to keep track of the duplicates (or better yet use an ArrayList of Sets instead to avoid the extra data structure)
Here's an example of generating a random # of ArrayLists without dups:
ArrayList<ArrayList<Integer>> myArr = new ArrayList<ArrayList<Integer>>();
HashSet<Integer> duplicates = new HashSet<Integer>();
Random random = new Random();
for(int x=0; x<3; x++) {
ArrayList<Integer> row = new ArrayList<Integer>();
myArr.add(row);
for(int y=0; y<3; y++) {
int randomInt = random.nextInt(100);
if(!duplicates.contains(randomInt)) {
row.add(0,randomInt);
duplicates.add(randomInt);
}
}
}
for(int i=0;i<myArr.size();i++)
{
System.out.println(myArr.get(i));
}

Related

How to display numbers less than 3 from an Array

I am supposed to write a program that accepts 6 user inputs and display numbers less than 3. I don't know what the problem is and I can't find help anywhere.
public class Apples {
public static void main(String [] args{
double [] numList = new double [6];
Scanner scan = new Scanner(System. in);
for (int i = 0; i<6; i++){
numList[i]=scan.nextDouble(); //user input
}
Arrays.sort(numList[i]); //sort user input
for (numList < 3)
System.out.println(numList);
}
}
}
I would to something like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i=0; i<6; i++) {
double number = scan.nextDouble();
if(number < 3.0) {
System.out.println(number);
}
}
}
So:
If it's just about printing, you don't need to store in an array the numbers, that you get from input.
You don't need sorting, you can just check if the number that you have currently scanned is smaller than 3 (or double 3.0).
The for(numList < 3) is not a correct Java syntax. You probably meant if(number < 3)
This may be due to copy/paste but there where quite some problems, let me show you one solution:
public static void main(String [] args){
double [] numList = new double [6];
Scanner scan = new Scanner(System. in);
// until here everything is fine
for (int i = 0; i<numList.length; i++){ // just a hint: use the array's length. Maybe you want to change the array one day and add 20 numbers to it..
numList[i]=scan.nextDouble(); // you forgot the . and it is called nextDouble() (capital D)
}
Arrays.sort(numList); // sorting is fine, just make sure you sort the whole array (not just one element)
for (int i = 0; i<numList.length; i++){ // here I assume you want to print every element smaller than 3, so you still need to iterate over the whole array (maybe the user inputs only twos
if(numList[i]<3){ // test if the number is smaller than 3
System.out.println(numList[i]); // and print it
}
}
}
if however you want to print only the 3 smallest elements of the array, then your approach was correct (though you still need to write out the whole for conditions:
for(int i=0; i<3;i++){
System.out.println(numList[i]);
}
The last for doesn't work like that. With a for you can iterate trough numbers like you did in the first one or through lists/arrays.
I didn't understood if you wanted the smallest 3 or the ones smaller than 3.
If you want the smallest 3 you can do this:
double smallList[] = new double[3]
for (int i=0;i<3;i++) {
smallList[i] = numList[i];
}
or if you want to print it one by one:
for (int i=0;i<3;i++) {
System.out.println(numList[i]);
}
if you want the ones that are smaller than 3 you'll have to do:
for (int i=0;i<numList.length;i++) {
if (numList[i]<3) {
System.out.println(numList[i]);
}
}
Two ways of printing them out.
double[] numList = new double[6];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
numList[i] = scan.nextDouble(); // user input
}
// then do
Arrays.stream(numList).filter(a -> a < 3).forEach(System.out::println);
// or
for (double n : numList) {
if (n < 3) {
System.out.println(n);
}
}

How to create an array with unique integers as elements [duplicate]

This question already has answers here:
Java Array of unique randomly generated integers
(10 answers)
Closed 5 years ago.
i want to create an array of 10000 unique random elements. Till now i only figure out how to create random integers and fill an array and finding the doubles and deleted them. But this decrease the size of the array which i dont want it.
So the question is how i can fill an array with unique integers as elements without decreasing the size of the array.
You could use this code. Usage of Set will eliminate duplicates and you are fetching random numbers until you get 10000 different random integers.
Set<Integer> numbers = new HashSet<>();
Random r = new Random();
while (numbers.size() < 10000) {
numbers.add(r.nextInt(100000));
}
Integer[] a = new Integer[numbers.size()];
a = numbers.toArray(a);
I found this great solution:
This solution doesn't need any Collection class.
public static int[] createRandomNumbers(int howMany) {
int n = howMany + 1;
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = i;
}
int [] result = new int[n];
int x = n;
SecureRandom rd = new SecureRandom();
for (int i = 0; i < n; i++) {
int k = rd.nextInt(x);
result[i] = a[k];
a[k] = a[x-1];
x--;
}
return result;
}
System.out.println(Arrays.toString(createRandomNumbers(10000)));
Reference: Best way to create a list of unique random numbers in Java
Hope it helps
Try this logic:
USE AN ARRAYLIST ENTIRELY, THEN CONVERT TO AN ARRAY AT THE END OF THE ENTIRE OPERATION.
Declare an arraylist
For every random number generated, check if the number already exists in the arraylist (using the .contains() method). If it does, repeat the process, else, move to the next number.
Code example:
Arraylist<Integer> arr = new Arraylist<>();
arr.add(generate()); //I included this line so that the arraylist won't be empty
//Note that the method *generate()* generates a new random number
for(int i = 0; i < 9999; i++){
int next = generate(); //the method that generates your number
if(arr.contains(next)){
i--; //The entire operation will be repeated for this index.
}
else{
arr.add(next); //Add the number to the arraylist
}
}
int[] finalArray = arr.toArray(); //Your final resultant array!
I hope this helps.. Merry coding!
You can use Set. This Collection that contains no duplicate elements.
Documentation https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Set<Integer> numbers = new HashSet();
do {
numbers.add(ThreadLocalRandom.current().nextInt());
} while(numbers.size() < 10000);

Move non repeating numbers from 2 arrays in new array

I want the numbers in the first array that do not repeat with the numbers in the second array to go to the third array
This is what I have done till now and it doesn`t work...please help
for(int i = 0; i < isir.length; i++)
{
for(int j = 0 ; j < isir2.length; j++)
{
if(isir[i] != isir[j])
{
for(int k = 0; k < sirdif1.length; k++)
{
sirdif1[k] = isir[i];
}
}
}
}
I am entering the numbers from console with Scanner function...
With using lists and steams:
Integer a1[] = {1,2,5,6,8};
Integer a2[] = {1,3,5,7,8};
List<Integer> result = new ArrayList<>();
// Add elements from first array which ist not in the second
Arrays.stream(a1).filter(_a -> !Arrays.asList(a2).contains(_a)).forEach(result::add);
// Add elements from second array which ist not in the first
Arrays.stream(a2).filter(_a -> !Arrays.asList(a1).contains(_a)).forEach(result::add);
result.forEach(System.out::println);
Output will be:
2
6
3
7
I'd probably use Sets for clarity.
public void test() {
Integer[] a1 = {1,2,3,4,5};
Integer[] a2 = {2,3,4};
// Treat them as Sets.
Set<Integer> s1 = new HashSet<>(Arrays.asList(a1));
Set<Integer> s2 = new HashSet<>(Arrays.asList(a2));
// Get the union of both.
Set<Integer> all = new HashSet<>(s1);
all.addAll(s2);
// Find the repeating ones.
Set<Integer> common = new HashSet<>(s1);
common.retainAll(s2);
// Non-repeating is.
Set<Integer> nonRepeats = new HashSet<>(all);
nonRepeats.removeAll(common);
System.out.println(nonRepeats);
}
I would suggest good naming conventions first..variables like sirdif1(i cant even imagine how this name was decided..) really make it hard for others to read/help
int a1[] ; // Initialize array1
int a2[] ; // Initialize array2
List<Integer> tempList = new ArrayList<Integer>();
for(int i = 0; i < a2.length; i++)
{
boolean found = false; // To be able to track if the int was found in both arrays
for(int j = 0; j < a1.length; j++)
{
if(a1[j].equals(a2[i]))
{
found = true;
break; // If it exist in both arrays there is no need to look further
}
}
if(!found ) // If the same is not found in both..
tempList.add(a2[i]); // .. add to temporary list
}
//Temporary array to combine both arrays;
int[] merged= new int[isir1.length + isir1.length];
//Copy isir1 into new temporary "merged" array;
System.arraycopy(isir1, 0, merged, 0, isir1.length);
//Copy isir2 into new temporary "merged" array;
System.arraycopy(isir2, 0, merged, isir1.length, isir2.length);
//Get the unique values of array "merged" and assign them to new array;
int[] sirdif1= IntStream.of(merged).distinct().toArray();

generating 50 random float arraylist value unique

I'm trying to write code that stores 50 randomly generated floating point numbers in an ArrayList. Use a regular for-loop to cycle through the values and remove any that are less than 0.5. Then use a for-each loop to print out the values that remain.
this is my code so far and I don't know where to go from here...
import java.util.ArrayList;
public class fiftyFloats {
public static void main (String [] args) {
//create a reference for the array list
ArrayList <Float> vals;
//reserve space for it in memeory
vals = new ArrayList <Float> (50);
for (int i = 0; i<vals.size(); i++){
i = new Float
}
for (Integer atPos: vals) {
System.out.println(vals.toString());
}
}
}
There are a few ways to do this depending on how you want to generate a "random" number.
java.util.Random has some functions that can be used, including "nextFloat" which returns a random values between 0 and 1 of the float type.
so
ArrayList <Float> vals = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < 50; i++) {
vals.add(rand.nextFloat());
}
Then it should be easy enough to loop through the list again and remove any number that doesn't meet your criterion. You don't need to reserve 50 spots up front in an ArrayList, that's one of the benefits of using it, that you can dynamically add to it.
Your loop as is won't work. You already defined "i" as an integer in your loop code, now you're trying to create a float with the same name. You can use "i" inside your loop, but it is going to be the "i" that you specified at "int i = 0;"
Overall it seems like you're very new and don't understand some core things about java, like how variables work. Consulting a tutor/teacher/basic text would probably helpy ou a lot.
To generate a random number you need to use the Random class.
NOTE - random.nextFloat() will only generate a number between 0.0 and 1 if you want to include larger numbers you will need to multiply it
The integer you are using to control the for loop cannot be reassigned to a float within the loop
You don't need to put arrayList.toString() in a loop
import java.util.ArrayList;
import java.util.Random;
public class fiftyFloats {
public static void main(String[] args) {
ArrayList<Float> vals = new ArrayList<Float>();
Float randomNum;
Random rand = new Random();
for (int i = 0; i < 50; i++) {
randomNum = rand.nextFloat();
if (randomNum > 0.5) {
vals.add(randomNum);
}
}
System.out.println(vals.toString());
}}
I think this is what you are trying to do here:
//create a reference for the array list
ArrayList<Float> vals;
//reserve space for it in memeory
vals = new ArrayList<Float>(50);
Random rand = new Random();
for (int i = 0; i < 50; i++) {
vals.add(rand.nextFloat());
}
for (Float val : vals) {
System.out.println(val.toString());
}
Some things to point out in your original code:
Float fl = new Float(2.2);
//create a reference for the array list
ArrayList<Float> vals;
// Here, you've set the _Capacity_, not the size.
vals = new ArrayList<Float>(50); // vals.size() => 0
// Based on above, you are essentially saying "never do these things"
// -> for (int i = 0; i < 0; i++)
for (int i = 0; i < vals.size(); i++) {
// this, if a valid expression, would have an incompatible type
// since i is of type int.
// if you were to use this, you would need to use a constructor such as
// new Float(1.2).
i = new Float
}
// In this enhanced loop, you are assigning a value from ArrayList vals
// to atPos, not the position. Since ArrayList is of type Float,
// atPos is a Float.
for (Integer atPos : vals) {
System.out.println(vals.toString());
}
Since the float values you need are not quoted between min and max then you can use nano time
Example:
List <Float> vals = new ArrayList <Float> (50);
for (int i = 0; i<vals.size(); i++){
vals.add (System.current/100.0f);
}**

Adding digits within an arraylist with a guideline

I'm a newbie coder and in need some help. Im trying to add the digits of a number together according to a number corresponding to how many digits I can use. Im using Eclipse Juno and using a separate text file for using my numbers. Though it isn't much This is what I have now:
public static void main(String[] args) throws IOException{
String token1 = "";
Scanner infile1 = new Scanner(new File("input.txt"));
ArrayList<String> temps = new ArrayList<String>();
//Adding Input files to the Arraylist
while(infile1.hasNext()){
token1 = infile1.next();
temps.add(token1);
}
infile1.close();
//Calling the Numbers from ArrrayList temps
for(int x = 0; x < temps.size(); x++) {
System.out.println(x + " " + temps.get(x));
for(x = 0; x < temps.size(); x++ ){
}
}
}
}
The numbers are
9678415 7,
9678415 6,
9678415 5,
9678415 4,
2678515 3,
Number to add, digits to use. The input.txt file does not have commas
Exactly how you do this is going to depend on what the data looks like in the file. You say it's not delimited by commas so I will have to assume they are separated by lines. You will need to separate the values within the strings and convert to int; so the below should do what you are attempting, if I understand the question. (full disclosure, it's been a little while since I've written in Java and I don't have a way to test this right now, make sure I haven't made any basic syntax errors)
ArrayList<Integer> totalArray = ArrayList<Integer>();
for(String tStr : temps){
int tempTotal = 0;
String[] numArray = tStr.split(" ");
for(int x = 0; x < Integer.parseInt(numArray[1]){
int y = Integer.parseInt(numArray[0].substring(x,x+1));
tempTotal += y;
}
totalArray.add(tempTotal);
}
There are probably better ways to get the highest value, but since I have been out of this for a little while, I'm just going to do it in the most basic way I can think of.
int highestValue = 0;
for (Integer x : totalArray){
if(highestValue<=x){
highestValue = x;
}
}
return highestValue;

Categories

Resources