How to fill in the gaps in each array element? - java

If I have an array like this
int[] array = {2,4,6,8,11};
how to print the gaps between each array element?
Gaps = 3 5 7 9 10
This is my program but the output is always 5 it doesn't print the other gaps is there any method rather than hash set? thank you
`
import java.util.HashSet;
import java.util.Set;
public class test {
public static void main(String[] args) {
int[] array = {2,4,6,8,11};
Set<Integer> set = new HashSet<>();
for(int m : array) {
if( set.add(m));
}//for
for(int i = 1 ; i < set.size() ;i++) {
if(!set.contains(i)) {System.out.println("Gaps = " + set.size()); }
}
}
}
`

In the following solution, I've fixed the logic errors you have made. There are other efficient ways to solve this problem.
import java.util.HashSet;
import java.util.Set;
public class test {
public static void main(String[] args) {
int[] array = {2,4,6,8,11};
Set<Integer> set = new HashSet<>();
for(int m : array) {
if( set.add(m));
}//for
for(int i = 1 ; i < (2* set.size()) + 1 ;i++) {
if(!set.contains(i)) {System.out.println(i); }
}
}
}

Related

Rounding off an arraylist to an integer array

I've been trying with this problem but couldn't wrap my head around it..
"Create a java method int [] roundoff (ArrayList input) that returns a new integer array containing all the input doubles correctly rounded off to integers."
This is where I got so far:
package javaProblem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class TowMethods {
public static int[] roundOff(ArrayList<Double> input) {
int [] iL=new int[input.size()];
for (double i:iL) {
//input.get(i);
int n=(int) Math.round(i) ;
iL[n]=n;
}
System.out.print(Arrays.toString(iL));
return (iL);
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Double> input1 = new ArrayList<Double>();
input1.add(2.3);
input1.add(1.3);
input1.add(3.35);
/* for (int i = 0; i < 3; i++) {
double num = keyboard.nextDouble();
input.add(num);
}*/
int[] iList = roundOff(input1);
System.out.println(Arrays.toString(iList));
}
}
for (int i = 0; i < input.size(); i++) {
iL[i] = (int)(Math.round(input.get(i)));
}
Instead of your loop in roundOff method
Please try to use meaningful names when you name your variables. Also inside the roundOff method instead of the foreach loop use a classic for loop and don't iterate through the freshly created integer array but over the ArrayList which you take as a parameter.
Here is the possible solution:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class TowMethods {
public static int[] roundOff(ArrayList<Double> inputs) {
int [] integers=new int[inputs.size()];
for (int i=0; i < inputs.size(); i++) {
integers[i] = (int) Math.round(inputs.get(i));
}
return integers;
}
public static void main(String[] args) {
// Scanner keyboard = new Scanner(System.in);
ArrayList<Double> inputs = new ArrayList<Double>();
inputs.add(2.3);
inputs.add(1.3);
inputs.add(3.35);
/*
for (int i = 0; i < 3; i++) {
double num = keyboard.nextDouble();
inputs.add(num);
}
*/
int[] iList = roundOff(inputs);
System.out.println(Arrays.toString(iList));
}
}
If you want to take the user input just uncomment the commented lines in the main method.
Use Math.rint() which properly rounds to the next int value.
double [] dbls = {2.4, 8.8, 22.23, 97.6};
int[] ints = new int[dbls.length];
for (int i = 0; i < dbls.length; i++) {
ints[i] = (int)Math.rint(dbls[i]);
}
System.out.println(Arrays.toString(dbls));
System.out.println(Arrays.toString(ints));
Prints
[2.4, 8.8, 22.23, 97.6]
[2, 9, 22, 98]

Declaring List before for loop in java

Below program gives output : 4 4 4 4 4
package HelloWorld;
import java.util.List;
import com.google.common.collect.Lists;
public class HelloWorld {
public static void main(String args[]) {
List<Product> productList = Lists.newArrayList();
**Product product = new Product();**
for (int i = 0; i < 5; i++) {
product.setId("id:" + i);
productList.add(product);
}
// Printing values
for (int i = 0; i < productList.size(); i++) {
System.out.println(productList.get(i).getId());
}
}
}
This is because Product is declared outside the loop.
But see another program :
package HelloWorld;
import java.util.List;
import com.google.common.collect.Lists;
public class HelloWorld {
public static void main(String args[]) {
**List<String> list = Lists.newArrayList();**
for(int i=0;i<5;i++){
list.add(""+i);
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
This gives output : 0 1 2 3 4
May i know why is it printing 0 1 2 3 4 even if the list is declared out side the for loop? I expected it to print 4 4 4 4 4
product is defined outside the for loop, so each time you are doing product.setId("id:" + i); you are overriding the id of the same instance and adding it again to the list. Create the product instance inside the loop
List<Product> productList = Lists.newArrayList();
for (int i = 0; i < 5; i++) {
Product product = new Product();
product.setId("id:" + i);
productList.add(product);
}
In your first example, you only instantiate one Productobject and add that 4 times to your list. However, each time - just before you add it, you overwrite the Id value with the current value of i. Ultimately that will become 4.
In your second example you add a new String object in every pass through of the loop and thus don't overwrite the already set value.

Displaying a shuffled integer array in java

sorry I'm really new to all of this. I know this is a stupid/easy question, but how would I display the shuffled array after i've set it all up. I have my code below and made the class that creates the array and has the algorithm for shuffling the integers inside the array. But I can't figure out how to display the shuffled array. Heres my code below:
My main:
package lab4b;
import java.util.Scanner;
public class Lab4B {
public static void main(String[] args) {
Shuffler test = new Shuffler(15);
test.Shuffle();
test.display();
}
}
and my Shuffle class:
package lab4b;
import java.security.SecureRandom;
public class Shuffler {
private static final SecureRandom randomNumbers = new SecureRandom();
private int [] data;
public Shuffler (int size){
data = new int [size];
for(int i = 0; i<data.length;i++){
data[i]= i+1;
}
}
public void Shuffle(){
int temp;
for(int first = 0; first<data.length; first++){
int second = randomNumbers.nextInt(data.length);
temp = data[first];
data[first] = data[second];
data[second] = temp;
}
}
public void display()
{
for(int counter =0; counter<data.length; counter++ ){
System.out.print(data[counter]+ " ");
}
System.out.println();
}
}
In this loop you are reset the value of the dataarray
for(int counter =0; counter<data.length; counter++ ){
// data[counter] = counter + 1; - do not do this
System.out.print(data[counter]+ " ");
}

How to call an ArrayList

I'm trying to append all of numbers that the program generates, into an array.
I used ArrayList method. However i can't manage program to read arr elements.
import java.util.Random;
import java.util.ArrayList;
public class Numbers {
public ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
System.out.println(arr);
return arr;
}
}
Furthermore; i'm trying all generated numbers to be read via another method.
(That part is the following)
How can the program read all generated numbers?
double [] numbers= StdIn.getNumbers(); // Stuck at here.
Is it possible to calling getNumbers method like that?
You can read it directly by creating the array list of type double:
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;
public class Numbers {
public ArrayList<Double> getNumbers() {
Random getNum = new Random();
ArrayList<Double> arr = new ArrayList<Double>(1000);
int size = 1000;
for (int i = 0; i < size; i++) {
double gauss = getNum.nextGaussian() * 15 + 70;
arr.add(gauss);
}
return arr;
}
public static void main(String[] args) {
Numbers number = new Numbers();
ArrayList<Double> arr = number.getNumbers();
System.out.println(arr);
}
}
You can call from other class as bellow
import java.util.Random;
import java.util.ArrayList;
public class PrintArray {
public static void main(String args[]){
ArrayList<Double> arrelements=OtherClass.getNumbers();
java.util.Iterator<Double> iterator = arrelements.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
class OtherClass{
public static ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
System.out.println(arr);
return arr;
}
}
You can iterate through the ArrayList to read numbers from your ArrayList.
import java.util.Random;
import java.util.ArrayList;
import javax.swing.text.html.HTMLDocument.Iterator;
public class PrintArray {
public static void main(String args[]){
ArrayList<Double> arrelements=getNumbers();
java.util.Iterator<Double> iterator = arrelements.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
public static ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
System.out.println(arr);
return arr;
}
}
You might think of something like that:
Initiate on object of your class and call the function
public class Numbers {
public ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
return arr;
}
public static void main(String[] args) {
Numbers n = new Numbers();
List<Double> numbers = n.getNumbers();
for (Double number : numbers) {
System.out.println(number);
}
}
}
Numbers class
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public final class Numbers {
private Numbers() {}
public static List<Double> getArrayListOfNumbers() { // ArrayList
List<Double> numbers = new ArrayList<>();
for(double d : getArrayOfNumbers()) {
numbers.add(d);
}
return numbers;
}
public static double[] getArrayOfNumbers() { // Array
Random random = new Random();
double[] numbers = new double[1000];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = random.nextGaussian() * 15 + 70;
}
return numbers;
}
}
Test Drive:
import java.util.List;
public class TestDrive {
public static void main(String[] args) {
// Printing arrayList numbers
List<Double> arrayListOfNumbers = Numbers.getArrayListOfNumbers();
arrayListOfNumbers.stream().forEach(System.out::println);
// Printing certain arrayList object
System.out.println("\nArrayList #7: " + arrayListOfNumbers.get(7));
}
}
Extra info:
Usually when there's need for fixed size/length (total values/objects), arrays are used (in your case it's 1000).
While ArrayList is a collection implementing interface List, which is used when there's no need for fixed size/length or when there's need for size/length flexibility.

Is there a way to test if a matrix line is made of precise values?

I tried the following program but it doesn't print what it should.
I'm sure that the way I check the array is correct but when I put it in a "if" tester the program doesn't give me results
import java.util.Arrays;
public class 3Dmatrix {
public static void main(String[] args) {
int [][][] cube;
cube = new int [2][2][2];
cube [0][0][0] = 4;
cube [0][0][1] = 2;
if (cube [0] [0] == new int[]{4, 2}) {
System.out.println("cat");
}
}
}
Use the Arrays.equals method. Here you go, this works and returns True:
import java.util.Arrays;
public class scratch
{
public static void main(String[] args)
{
int[][][] cube;
cube = new int[2][2][2];
cube[0][0][0] = 4;
cube[0][0][1] = 2;
int[] test = new int[]{4, 2};
for (int i = 0; i < test.length; i++)
System.out.println(cube[0][0][i] + " " + test[i]); //Printing test
if (Arrays.equals(cube[0][0], new int[]{4, 2})) //Returns true
System.out.println("YES");
else
System.out.println("NO");
}
}
Output: http://ideone.com/l2q7i6

Categories