add values to double[] arraylist - java

I have the following array
ArrayList<double[]> db_results = new ArrayList<double[]>();
and I would like to add values like this
db_results.add(new double[] {0,1,2});
but in a loop like this
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
db_results.add(new double[] {val});
}
obviously this is adding a new array each time with the single value... so how do I get it to add all into one array?

double[] nums = new double[3];
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
nums[i] = val;
}
db_results.add(nums);

Create the double[] first, add the numbers to it, and add that array to the List.
(The variable should likely be declared as a List, btw, not an ArrayList, unless you're specifically passing it to something that explicitly expects an ArrayList.)

With something like that :
max = 3;
double[] doubles = new double[max];
for ( int i = 0 ; i < max; ++i)
{
double val = Double.parseDouble(i);
doubles[i] = val;
}
db_results.add(doubles);

import java.util.Scanner;
class DarrayEx2
{
public static void main(String args[])
{
int a[][]=new int[3][3];
int r,c,sumr;
Scanner s=new Scanner(System.in);
for(r=0;r<a.length;r++)
{
for (c=0;c<a.length ;c++ )
{
System.out.println("enter an element");
a[r][c]=s.nextInt();
}
}
for(r=0;r<a.length;r++)
{
sumr=0;
System.out.println("elements in a["+r+"] row is");
for (c=0;c<a[1].length ;c++ )
{
System.out.println(" "+a[r][c]);
sumr = sumr+a[r][c];
}
System.out.println(" = "+sumr);
System.out.println(" ");
}
}
}
source : http://www.exceptionhandle.com/portal/java/core-java/part-12-arrays.htm

Related

Java Deque (Finding the max number of unique integers from subarrays.)

I was trying to solve a HackerRank problem on Java Deque. My code passed all the cases apart from the ones which have 100,000 inputs.
Problem: In this problem, you are given N integers. You need to find the maximum number of unique integers among all the possible contiguous subarrays of size M.
--->So we wre given N integers, and need to find the number of "unique integers" in each contagious subarray(of size M). And then print the maximum number of those "unique Integers".
link: https://www.hackerrank.com/challenges/java-dequeue/problem
My Code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque deque = new ArrayDeque<>();
HashSet<Integer> set = new HashSet<>();
int n = in.nextInt();
int m = in.nextInt();
int max=0;
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.add(num);
set.add(num);
if(i>=m-1){
if(set.size()>max)max=set.size();
Integer removed=(Integer)deque.removeFirst();
set.remove(removed);
set.add((Integer)deque.peek());
}
}
System.out.println(max);
}
Please tell me where my code went wrong.
What is the point of this line?
set.add((Integer)deque.peek());
I don't see anything in your code that is slow. I just wonder how you can keep track of unique numbers by using a set, given that a set only tells you if there is such a number (but not how many occurrences of the same number there are). And you don't want to keep scanning the deque to see if the number being removed is the last one.
I don't think this is great/fast code, but it seems to pass the test-cases. I keep a count of how many of each integer there is in the window by using a map (and use some of your code).
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque<Integer> deque = new ArrayDeque<>();
HashMap<Integer, Integer> counts = new HashMap<>();
int n = in.nextInt();
int m = in.nextInt();
int max = 0;
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.add(num);
int count = counts.getOrDefault(num, 0);
counts.put(num, ++count);
if (i >= m - 1) {
if (counts.size() > max) max = counts.size();
Integer removed = deque.removeFirst();
int removing = counts.get(removed);
removing--;
if (removing == 0) {
counts.remove(removed);
} else {
counts.put(removed, removing);
}
}
}
System.out.println(max);
}
}
Just wanted to share how I solved it in case it helps.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque deque = new ArrayDeque();
Set<Integer> integers = new HashSet<>();
int n = in.nextInt();
int m = in.nextInt();
long result = 0;
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.add(num);
integers.add(num);
if (deque.size() == m) {
long currentSize = integers.size();
if (currentSize > result) {
result = currentSize;
}
Integer removed = (Integer) deque.pollFirst();
if (!deque.contains(removed)) {
integers.remove(removed);
}
}
}
System.out.println(result);
}
We can optimize the space a little bit by avoiding the hashmap all together, but it seems like Hackerrank does not care about that. Any how I am putting my solution here which can solve this problem by using using a map.
private int countUniqueNumsInSubarrays(int[] nums, int m) {
Deque<Integer> deque = new LinkedList<>();
int maxUniqueCount = 0;
for (int i = 0; i < nums.length; i++) {
// if deque's left entry is outside the window then pop it out
while (!deque.isEmpty() && i - deque.peekFirst() >= m) {
deque.removeFirst();
}
// this will make sure that the deque only contains unique numbers,
// this is essentially helps us avoid that extra hash map
while (!deque.isEmpty() && nums[deque.peekLast()] == nums[i]) {
deque.removeLast();
}
deque.addLast(i);
if (i >= m - 1) {
maxUniqueCount = Math.max(maxUniqueCount, deque.size());
}
}
return maxUniqueCount;
}
import java.io.*;
import java.util.*;
import java.util.stream.Stream;
public class Solution {
public static void main(String[] args) {
var sc = new Scanner(System.in);
var split = sc.nextLine().split(" ");
int n = Integer.parseInt(split[0]);
int m = Integer.parseInt(split[1]);
if (!(1 <= n && n <= 100_000)) {
System.exit(0);
}
if (!(1 <= m && m <= 100_000)) {
System.exit(0);
}
if (!(m <= n)) {
System.exit(0);
}
split = sc.nextLine().split(" ");
sc.close();
int maxNumUniqueInt = 0;
HashSet<Integer> dist = new HashSet<>();
Deque<Integer> deque = new ArrayDeque<>();
int[] arr = Stream.of(split).mapToInt(Integer::parseInt).toArray();
for (int i = 0; i < m; i++) {
deque.addLast(arr[i]);
dist.add(arr[i]);
}
int num = dist.size();
if (maxNumUniqueInt < num) {
maxNumUniqueInt = num;
}
for (int i = m; i < n; i++) {
deque.addLast(arr[i]);
dist.add(arr[i]);
int remove = deque.removeFirst();
if (!deque.contains(remove)) {
dist.remove(remove);
}
num = dist.size();
if (maxNumUniqueInt < num) {
maxNumUniqueInt = num;
}
// System.out.println(i + " | " + deque + " | " + dist + " | " + maxNumUniqueInt);
}
System.out.println(maxNumUniqueInt);
}
}
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque<Integer> deque = new ArrayDeque<>();
int n = in.nextInt();
int m = in.nextInt();
int maxUnique = 0;
Map<Integer, Boolean> uniqSet = new HashMap<>();
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.addLast(num);
uniqSet.put(num, true);
if(deque.size() == m){
// int uniqueSize = new HashSet<>(deque).size();
int uniqueSize = uniqSet.size();
maxUnique = Math.max(maxUnique, uniqueSize);
int x = deque.removeFirst();
if(!deque.contains(x)){
uniqSet.remove(x);
}
}
}
in.close();
System.out.println(maxUnique);
}
}

Max of a list of strings in Java

I have data in the form of
String[] values = {"4,8", "1,6", "7,8", "1,5"}
where I have to find the max of the second element and if there are more than two of the max ("4,8" and "7,8"), find the one with the min of the first. So the output of values should be a string "4,8"
I am new to JAVA and I am not sure how exactly to go about this. I tried to use string split and something like
int[] num = new int[values.length];
int[] num2 = new int[values.length];
for (int i = 0; i<values.length; i++){
String[] test = values[i].split(",");
int nummed = Integer.parseInt(test[0]);
int nummed2 = Integer.parseInt(test[1]);
num[i] = nummed;
num2[i] = nummed2;
//System.out.println(test[0]);
//System.out.println(test[1]);
}
but it is quickly becoming very complicated and I would need to know the index or maybe filter out data to find the min of the first item.
This should be enough
class Main {
public static void main(String args[]) {
String[] values = {"4,8", "1,6", "7,8", "1,5"}; // try {"4,8", "1,6", "7,8", "1,5", "1,9"}
int right = Integer.MIN_VALUE;
int left = Integer.MAX_VALUE;
for (int i = 0; i<values.length; i++){
String[] test = values[i].split(",");
int nummed = Integer.parseInt(test[0]);
int nummed2 = Integer.parseInt(test[1]);
if (nummed2 >= right) {
if (right != nummed2) {
left = Integer.MAX_VALUE;
}
right = nummed2;
if (nummed < left) {
left = nummed;
}
}
}
System.out.println(left + "," + right);
}
}
public class StringManipulation {
public static void main(String args[]) {
System.out.println(output());
}
private static String output() {
String[] values = {"4,8", "1,6", "7,8", "1,5"};
int max = Integer.MIN_VALUE;
int first = Integer.MAX_VALUE;
for(int i = 0; i < values.length; i++) {
String[] arr = values[i].split(",");
if(Integer.parseInt(arr[1]) >= max){
max = Integer.parseInt(arr[1]);
first = Integer.parseInt(arr[0]) < first ? Integer.parseInt(arr[0]):first;
}
}
return (first) + "," + (max);
}
}
There could be multiple approaches to this problem. Given my understanding of the question, this is one of the simplest solutions.
Here's a solution that makes use of the fluent Comparator api, stream api and BigDecimals:
String[] values = {"4,8", "1,6", "7,8", "1,5"};
// create a custom comparator
Comparator<BigDecimal> comparator = Comparator
// first, comparing only the right side - the remainders
.comparing((BigDecimal num) -> num.remainder(BigDecimal.ONE))
// then, comparing the left side - the decimal part
.thenComparing(num -> num.setScale(0, RoundingMode.DOWN));
// find the max value using java stream api
Arrays.stream(values)
// replace commas with dots
.map(num -> num.replace(',', '.'))
// map values to bigdecimal
.map(BigDecimal::new)
// find the max element by our custom comparator
.max(comparator)
// print if an element is found (if the array was not empty)
.ifPresent(System.out::println);
Continuing with your solution, Tested. Works as expected, It was hard to type it all on mobile though.
public static void main(String arg[])
{
String[] values = {"4,8", "1,6", "7,8", "1,5","2,8"};
int[] num = new int[values.length];
int[] num2 = new int[values.length];
for (int i = 0; i<values.length; i++){
String[] test = values[i].split(",");
int nummed = Integer.parseInt(test[0]);
int nummed2 = Integer.parseInt(test[1]);
num[i] = nummed;
num2[i] = nummed2;
//System.out.println(test[0]);
//System.out.println(test[1]);
}
int max=0;
int min=0;
for(int i=0;i<num2.length;i++)
{
if(num2[i]>max) {
max =num2[i];
min=num[i];
}
else if(num2[i]==max)
min = min>=num[i]?num[i]:min;
}
System.out.println(min+","+max);
}
}

Array Guessing game - How to set and get an array?

I am trying to create a guessing game where the user enters a name and is
prompted to pick a number 5 times. I am trying to store the numbers in an array and use set and get methods to print out the attributes of the array. I have achieved this for the name but I am unable to set and get the array.
import java.util.Scanner;
public class StudentStore
{
private String n1;//store's the player's name
//private int [] s10; //stores the player's score
private int i;
private int noOfPlayers = 5;
private int[] s10 = new int[noOfPlayers];
Scanner kboardIn = new Scanner(System.in);
private int index;
int newInt = 0;
public StudentStore(String n1, int [] s10, int i )
{
this.n1 = n1;
this.s10[i] = s10[i];
this.setName(n1);
//this.i = i;
this.setScore(s10,i);
//this.index = index;
// PlayerScore.incNumberScores();
}
public void setScore( int []s10, int i)
{
//takes an integer score, sets variables and checks topScore
this.s10[i] = s10[i];
//this.checkAndSetTopScore();
}
public int [] getScore()
{
return this.s10;
}
public void setName(String n1)
{
this.n1 = n1;
}
public String getName()
{
return this.n1;
}
}
import java.util.Scanner;
public class StudentTester
{
public static void main(String args[])
{
Scanner kboardIn = new Scanner(System.in);
int noOfStudents;
System.out.print("Enter the number of students: ");
noOfStudents = kboardIn.nextInt();
//int[] noOfStudents;
//noOfStudents = new int[100];
StudentStore[] student1 = new StudentStore[noOfStudents];
//int s1 = 0;
int noOfPlayers = 5;
int[] s10 = new int[noOfPlayers];
//s10 = 0;
String n1 = "something";
int i = 0;
for (int index = 0; index < student1.length; index++)
student1[index] = new StudentStore(n1, s10, i);
for (int index = 0; index <= student1.length; index++)
{
System.out.print("What is name of student no "+(index+1)+" ?");
n1 = kboardIn.next();
student1[index].setName(n1);
System.out.print("What is mark for student no "+(index+1)+" ?");
for(i=0; i < noOfPlayers; i++)
{
s10[i] = kboardIn.nextInt();
student1[index].setScore(s10, i);
System.out.println("This is it" + s10[i]);
}
System.out.println(student1[index].getScore( ));
System.out.println(student1[index].getName());
System.out.println(index);
System.out.println(s10[index]);
System.out.println(i);
//System.out.println(s10[]);
}
for (int index = 0; index < student1.length; index++)
System.out.println("\nTotal Mark for " + student1[index].getName()+ " is\t" + student1[index].getScore());
}
}
It seems like you want to know how to loop over arrays. This is how you could achieve it:
String[] strings = {"hi","yo","test"};
for(String s : strings){
System.out.println(s);
}
System.out.println(student1[index].getScore()); you are getting the array, but printing an array will not give stored values in array. You should iterate over the array and print seperatly all values.
Thanks for the reply's. In the program System.out.println(student1[index].getScore()) is not printing a number. It is printing [I#137c6OD. I am not sure how to iterate over the array, but I will look up how to do it. Thanks a lot

NullPointerException from array created in a method

I'm currently doing a simple university project about the arrays.
In my project I initialize and fill an array by using a method called "setArray", but when the program returns on the main method in which I try to print the array's content, it returns a NullPointerException.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num[] = null;
String command;
setArray(in, num);
for(int i = 0; i < num.length ; i++)
{
System.out.println(num[i]);
}
}
private static void setArray(Scanner in, int[] num)
{
System.out.println("Type the array size: ");
int dim = in.nextInt();
num = new int[dim];
System.out.println("Size: " + num.length);
System.out.println("Type the numbers' variability: ");
int var = in.nextInt();
int ran;
for(int i = 0; i < num.length ; i++)
{
ran = (int) (Math.random() * var);
num[i] = ran;
System.out.println(num[i]);
}
}
Have a look at this question about whether Java is Pass By Reference
Your code would be better off like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num[] = null;
String command;
num = setArray(in);
for(int i = 0; i < num.length ; i++)
{
System.out.println(num[i]);
}
}
private static int[] setArray(Scanner in)
{
System.out.println("Type the array size: ");
int dim = in.nextInt();
int[] numToReturn = new int[dim];
System.out.println("Size: " + numToReturn.length);
System.out.println("Type the numbers' variability: ");
int var = in.nextInt();
int ran;
for(int i = 0; i < numToReturn.length ; i++)
{
ran = (int) (Math.random() * var);
numToReturn[i] = ran;
System.out.println(numToReturn[i]);
}
return numToReturn;
}
if you see your code you are declaring a local variable num in your setArray(scanner in,int[] num) method which is not visible in main function nor it is same as that you declared in main function .
The variable array num in the main function is different from that in setArray() function.

not storing text data into java array using scanner

My code is just printing out the last number from the list I create in a different program.
I need help storing the data into an array so I can sort it after.
edit: I need to take data from a file which is 'numbers.txt' and store it into an array.
public static void main(String[] args) throws Exception {
int numberArray = 0;
int[] list = new int[16];
File numbers = new File("numbers.txt");
try (Scanner getText = new Scanner(numbers)) {
while (getText.hasNext()) {
numberArray = getText.nextInt();
list[0] = numberArray;
}
getText.close();
}
System.out.println(numberArray);
int sum = 0;
for (int i = 0; i < list.length; i++) {
sum = sum + list[i];
}
System.out.println(list);
}
}
Correction in the code.
1.) Inside while loop, list[0] = numberArray;, will keep adding elements on the same index 0, so lat value will override. SO something like list[i] = numberArray; will work, and increement i inside while loop. Take care of ArrayIndexOutOfBound Exception here.
public static void main(String[] args) throws Exception {
int numberArray = 0;
int[] list = new int[16];
File numbers = new File("numbers.txt");
int i =0;
// Check for arrayIndexOutofBound Exception. SInce size is defined as 16
try (Scanner getText = new Scanner(numbers)) {
while (getText.hasNext()) {
numberArray = getText.nextInt();
list[i] = numberArray;
i++;
}
getText.close();
}
System.out.println(numberArray);
int sum = 0;
for (int i = 0; i < list.length; i++) {
sum = sum + list[i];
}
System.out.println(list);
}
}

Categories

Resources