So I'm trying to write a recursive method to sum an arraylist of integers and create a client to test it.
My Class is:
import java.util.ArrayList;
public class SumArray
{
public static int ArraySum(int[]arrayList, int sum, int size)
{
sum = sum + arrayList[size];
size--;
while(size >= 0)
{
return ArraySum(arrayList, sum, size);
}
return sum;
}
}
My Client is:
import java.util.ArrayList;
public class ArraySumClient
{
public static void main()
{
System.out.print("The sum of the array is: ");
SumArray r = new SumArray();
int[] myList = new int[5];
myList[0] = 1;
myList[1] = 2;
myList[2] = 3;
myList[3] = 4;
int size = myList.length-1;
System.out.println(r.ArraySum(myList, 0, size));
}
}
These both compile and work. However, I'm trying to figure out a way for the user to input the size of the array and the numbers in the array instead of my inputting the array size and numbers inside the client.
you can use java scanner to take input from cmd prompt
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
You could try using an ArrayList instead of an array. It would let you dynamically add as many items as needed:
public static void main() {
List<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);
myList.add(3);
myList.add(4);
// compute sum
int sum = 0;
for (Integer value : myList) {
sum += value;
}
System.out.println("The sum is " + sum);
}
Using this approach, you would not need to ask how many items the user intends to add.
As #Satya suggested, you could read input from the command line as command line argument and extract them as:
Integer[] array = Stream.of(args).map(Integer::parseInt).toArray(size -> new Integer[size]);
You do not want to pass the length of the array to the method ArraySum which, I suppose you are doing because you are not able to remove an element from the array. One way of doing this is by using Arrays.copyOf() using which you could copy a part of the array as another array.
I think it is always good to use List of theses situations.
Related
This question already has answers here:
Scramble each digit of the int a and print out the biggest possible integer
(4 answers)
Closed 2 years ago.
For example, if someone inserts 34603, the output would be 64330. I've started this problem already but I can not think of a solution that works. Also, since this is an assignment, my instructor told me that arrays are not allowed. Here is what I have thus far:
public class loops{
loops(){}
public void biggest(int a){
String as = Integer.toString(a);
int index=0;
int asl = as.length();
while(index<asl){
String num1 = as.substring(index);
String num2 = as.substring((index+1));
int con1 = Integer.parseInt(num1);
int con2 = Integer.parseInt(num2);
if(con1<con2){
System.out.println("con2: "+con2);
}
if(con1>con2){
System.out.println("con1: "+con1);
}
System.out.println("added: "+con1+" "+con2);
index++;
}
}
public static void main(String []args){
loops x = new loops();
x.biggest(4583);
}
}
I would appreciate any and all help/hints, for I am truly lost on this one.
It should be reasonably obvious that the largest possible result is obtained by arranging the digits in descending order. One of the easier and more efficient ways of doing that would be with a counting sort, but the usual forms of that involve using arrays or array-equivalents to accumulate the counts.
So standard Counting Sort is out, along with all standard sort routines aimed at rearranging sequences of items. But you can still take your inspiration from Counting Sort. For example, figure out how many 9 digits are in the input, and form a number from that many 9s. Then figure out how many 8s and append them. Then how many 7s, etc. "Appending" digits to a number can be done arithmetically, so the whole procedure can be done without an array or array equivalent, even if we consider Strings to be array equivalents (as we should).
Details are left as the exercise they are intended to be.
I won't answer the question directly for you but suggest some ideas to help you.
you need to sort the integers in place - ie no arrays/no lists.. just iterate over the integer as a string which you're doing correctly, and progressively swap values so that you end up with a sorted numerical value.
thinking of various sort algorithms, quicksort, mergesort, bubble sort, etc. you effectively pick one of these algorithms and try to implement it.
start with the basic examples for integers to sort and iteratively develop your code to successively generate the correct answer... as test cases try:
no number at all... null
then the empty string ""
then a single digit, so a number 0-9
Next two digits both in order, then out of the sort order
then 3 digits in/out of order
Once you've implemented for 3 digits you should be able to generate your solution for any number of digits.
Note: if you use Integer as the input data type, you will be limited to being able to take a maximum integer value of Integer.MAX_VALUE (which isn't that large). Try to treat the input argument as a String and the individual digits as integers for the comparison (which you are already doing), this way you'll be able to process a much larger input.
import java.util.ArrayList;
import java.util.Collections;
public class loops{
loops(){}
public void biggest(int a){
String as = Integer.toString(a);
int index=0;
int index2=1;
int asl = as.length();
ArrayList<Integer> lista = new ArrayList<Integer>();
while(index<asl){
String num1 = as.substring(index,index2);
int con1 = Integer.parseInt(num1);
lista.add(con1);
index++;
index2++;
}
//order list
Collections.sort(lista);
Collections.reverse(lista);
System.out.println(lista);
//concatenate numbers
}
public static void main(String []args){
loops x = new loops();
x.biggest(34603);
}
}
**anything consult back. **
Ok, I came up with this. It's not the prettiest solution, I recognize that, but it DOES work. Have a look:
public class loops{
public int a,b,c,d,e,f,g,h,i,j;
public loops(){}
public void biggest(int a){
String as = Integer.toString(a);
int index=0;
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
f = 0;
g = 0;
h = 0;
i = 0;
j = 0;
int asl = as.length();
while(index<asl){
String num3 = as.substring(index,(index+1));
int con3 = Integer.parseInt(num3);
if(con3==9){a++;}
if(con3==8){b++;}
if(con3==7){c++;}
if(con3==6){d++;}
if(con3==5){e++;}
if(con3==4){f++;}
if(con3==3){g++;}
if(con3==2){h++;}
if(con3==1){i++;}
if(con3==0){j++;}
index++;
}
for(int z=0;z<a;z++){
System.out.print("9");
}
for(int y=0;y<b;y++){
System.out.print("8");
}
for(int x=0;x<c;x++){
System.out.print("7");
}
for(int w=0;w<d;w++){
System.out.print("6");
}
for(int v=0;v<e;v++){
System.out.print("5");
}
for(int u=0;u<f;u++){
System.out.print("4");
}
for(int t=0;t<g;t++){
System.out.print("3");
}
for(int s=0;s<h;s++){
System.out.print("2");
}
for(int r=0;r<i;r++){
System.out.print("1");
}
for(int q=0;q<j;q++){
System.out.print("0");
}
public static void main(String []args){
loops x = new loops();
x.biggest(45683408);
}
}
If arrays aren't allowed, then I don't think strings should be allowed either:
static void biggest(int n)
{
long counts=0;
for(; n>0; n/=10)
{
counts += 1L<<((n%10)*4);
}
long result=0;
for (long digit=9; digit>=0; --digit)
{
for(long rep=(counts>>(digit*4))&15; rep>0; --rep)
{
result = result*10 + digit;
}
}
System.out.println(result);
}
I am trying to find the third largest element of an array by sorting it through treeset in a decreasing order, but some of the test cases fail for certain input values and most of it pass for certain input values.
My code:
// { Driver Code Starts
import java.util.Scanner;
import java.util.*;
import java.io.*;
class ThirdLargestElement
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
long n =sc.nextLong();
Long arr[] = new Long[(int)n];
for(long i=0;i<n;i++)
arr[(int)i] = sc.nextLong();
GfG g = new GfG();
System.out.println(g.thirdLargest(arr));
t--;
}
}
}// } Driver Code Ends
class GfG
{
long thirdLargest(Long a[])
{
// Your code here
if(a.length<3)
return -1;
else{
TreeSet<Long> ts=new TreeSet<Long>(new myComparator());
for(long i:a)
ts.add(i);
ArrayList<Long> al=new ArrayList<Long>(ts);
return al.get(2);
}
}
}
class myComparator implements Comparator{
public int compare(Object obj1,Object obj2){
Long a=(Long) obj1;
Long b=(Long) obj2;
if(a<b)
return 1;
else if(a>b)
return -1;
else
return 0;
}
}
The testcase it failed:
Link to the question where you can run the code
Please explain why this code failed to pass the given test case.
Try This one
class GfG {
long thirdLargest(Long a[]) {
Arrays.sort(a);
List<Long> numbers = Arrays.asList(a);
Collections.reverse(numbers);
return numbers.size() >= 3 ? numbers.get(2) : -1;
}
}
You can directly add elements to TreeSet and get third largest number using stream,
while(t>0)
{
long n =sc.nextLong();
TreeSet<Long> ts=new TreeSet<>(Comparator.comparingLong(Long::longValue).reversed());
for(long i=0;i<n;i++)
ts.add(sc.nextLong());
long thirdLast = ts.stream()
.limit(3)
.skip(2)
.mapToLong(e->e)
.findAny().orElse(0l);
System.out.println(thirdLast);
t--;
}
The question states:
the function thirdLargest ... takes two argument. The first argument is the array a[] and the second argument is the size of the array (n).
Although the question states that the array is...
an array of distinct elements
the test cases indicate that we are dealing with an array of integers.
Personally, I don't see the need for the second method parameter, because in java an array is an object and has a length member. So my implementation below only takes one parameter, namely an array of int. Maybe the people at geeksforgeeks.org simply converted a question that was originally for the C language to java, since, in C, it is difficult to determine the size of any array.
Each element in a TreeSet must be an object, so we need to convert the elements in the int array to Integer objects. Autoboxing will do this automatically, nonetheless my code below contains an explicit conversion. So in the method I create a TreeSet. Since class Integer implements interface Comparable, the default TreeSet constructor is sufficient. I add all the elements of the int array to the TreeSet, then obtain a descending iterator and then iterate to the third element returned by the iterator, which is the value that the method needs to return.
int thirdLargest(int[] arr) {
int third = -1;
if (arr != null && arr.length > 2) {
TreeSet<Integer> set = new TreeSet<Integer>();
for (int elem : arr) {
set.add(Integer.valueOf(elem));
}
Iterator<Integer> iter = set.descendingIterator();
if (iter.hasNext()) {
iter.next();
if (iter.hasNext()) {
iter.next();
if (iter.hasNext()) {
third = iter.next().intValue();
}
}
}
}
return third;
}
Of-course, if you want to ignore the conditions imposed by the original question, you could get the third largest element using the stream API
IntStream.of(2, 4, 1, 3, 5)
.boxed()
.sorted(Collections.reverseOrder())
.collect(Collectors.toList()).get(2)
This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 9 years ago.
I have this assignment:
Print 5 random integer between 1-52 with no duplicate using if/else.
Here's my code so far. It prints some numbers, but it sometimes prints duplicates.
import java.util.Random;
public class RandomCards {
public static void main(String[] args) {
Random randomCards = new Random();
int card;
for (int x = 1; x <= 5; x++) {
card = randomCards.nextInt(52) + 1;
}
if (card != randomCards) // if the value of card is not equal, proceed
{
System.out.print(card + " ");
} else {
return card; // if the value are the same get random integers again
}
}
}
public static void main(String args[]) {
Random randomNumber = new Random();
// Set stores only Unique values
Set<Integer> cards = new HashSet<Integer>();
// Iterate over to generate random numbers
while (cards.size() < 5) {
int r = randomNumber.nextInt(52) + 1;
cards.add(r);
}
for(Integer card : cards) {
System.out.println(card);
}
}
You can use this
Random randomCards = new Random();
int[] card={0,0,0,0,0};
while(card[card.length-1] == 0) {
int temp=randomCards.nextInt(52);
for(int j=0;j< card.length ; j++){
if(card[j] == 0){
card[j] = temp;
break;
}
}
}
for(int j=0;j< card.length ; j++){
System.out.println(card[j]);
}
It's not clear what you're asking, but I note from your code that you don't have any duplicate detection. You need to save each value that you generate and check for duplicates when you create a new one. I suggest creating a Set<Integer> to hold your generated values, calling add() for each new card, and checking contains() to see whether a new value has already been selected. You'd want to change your loop condition to something like cards.size() < 5 as well.
Finally, note that your use of return card is incorrect and will result in a compile-time error. return is used to end a method and send a value back to where it was called from; the main method (which is always void) has no return value, and ending the method wouldn't make sense there anyway. It looks like some code may have been copied and pasted from a version where drawCard() was its own method. Instead, just keep looping until you find 5 unique cards (such as by using the size() method I mentioned earlier).
Maybe this?
Random rand = new Random();
// ArrayList to store non-duplicate cards.
ArrayList<Integer> cards = new ArrayList<Integer>();
// Iterate over to generate random numbers
while (cards.size() < 5)
{
int r = rand.nextInt(52) + 1;
if (!cards.contains(r))
cards.add(r); // Only add if there is no such number in list
}
Hope this helps.
Hope this would be of any help.
It comprises of separate methods for computation, setting the lower and upper bound and printing the list when it has 5integers in it. Using TreeSet solves your problem of duplicates. Here it goes,
package com.project.stackoverflow;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;
public class RandomGenerator {
public TreeSet<Integer> compute() {
TreeSet<Integer> generatedList = new TreeSet<Integer>();
Scanner s = new Scanner(System.in);
System.out.println("Enter the lower bound for checking random numbers:");
long lowBound = s.nextLong();
System.out.println("Enter the upper bound for checking random numbers:");
long topBound = s.nextLong();
Random randomNumbers = new Random();
for (int i = 0; i < topBound; i++) {
if (generatedList.size()==5) {
break;
}
else {
generatorFunc(lowBound, topBound,randomNumbers,generatedList);
}
}
return generatedList;
}
public void generatorFunc(long lowBound,long topBound,Random randomNumbers, TreeSet <Integer> generatedList) {
long limit = topBound - lowBound;
long part = (long)(limit * randomNumbers.nextDouble());
int randomNum = (int) (part + lowBound);
generatedList.add(randomNum);
}
public void printList() {
TreeSet<Integer> testListVals = compute();
System.out.println("New" + testListVals);
}
public static void main(String[] args) {
RandomGenerator obj = new RandomGenerator();
obj.printList();
}
}
If your problem is just about the duplicates, then you can store each random number generated in an array, and for every successive call to nextint(), check if it already exists in the array of stored values, and till it does, call nextint() again for that iteration itself, else store it in the array and go to next iteration.
public class LotteryNumbers {
private ArrayList <Integer> numbers;
public LotteryNumbers() {
this.numbers = new ArrayList <Integer> ();
this.drawNumbers();
}
public ArrayList <Integer> numbers() {
return this.numbers;
}
public void drawNumbers() {
Random random = new Random ();
int counter = 0;
while (counter < 7) {
this.numbers.add(random.nextInt(39) + 1);
counter++;
}
}
This is a class used for printing 7 numbers from 1..39.
It does that job but the problem is I want the 7 random numbers to be different.
How do I check if an arrayList contains the same number since it is random?
Thanks for reading.
You could try using the contains() method from the ArrayList numbers:
public void drawNumbers()
{
Random random = new Random();
int counter = 0;
int choice;
while (counter < 7) {
choice = random.nextInt(39) + 1;
if (numbers.contains(choice)) {
continue;
}
numbers.add(choice);
counter++;
}
}
From Java Docs:
public boolean contains(Object o): Returns true if this list contains
the specified element.
So, if the ArrayList already contains the choice (randomly generated), it will continue to the next iteration (counter won't be increased) and choose another random number. If it doesn't contains the choice, it will add it to the array and increase counter.
This can also be done by this way (without using continue)
if (!numbers.contains(choice)) {
numbers.add(choice);
counter++;
}
How do I check if an ArrayList contains the same number since it is random?
Like this (example):
public void drawNumbers() {
Random random = new Random ();
int counter = 0;
while (counter < 7) {
int newNumber = random.nextInt(39) + 1;
if (! numbers.contains(newNumber)) {
this.numbers.add(newNumber);
counter++;
}
}
}
You could use contains as as the earlier responses suggest, however contains on an array list in inefficient with O(n) complexity. One of the comments by #TheLostMind suggest using a Set, the best Set implementation to use in this instance is BitSet, note it does not confirm to the java.util.Set interface specification.
public class LotteryNumbers {
private final int[] numbers = new int[7]
public LotteryNumbers() {
this.drawNumbers();
}
public int[] numbers() {
return this.numbers;
}
public void drawNumbers() {
BitSet selected = new BitSet(40);
Random random = new Random ();
int counter = 0;
while (counter < 7) {
int num = random.nextInt(39) + 1;
if(!selected.get(num)) {
selected.flip(num);
numbers[counter++] = num;
}
}
}
This implementation, tho unlikely, does not guarantee that you will always get a result.
You could also put your numbers in a list and use COllections.shuffle and get the first 7 occurences.
You do not need to check if duplicate...
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
....
Collections.shuffle(list);
loop and get your numbers...
int num = Integer.intValue(list.get(i));
I am currently working on a lab and would like to know how to handle the following problem which I have spent at least two hours on:
I am asked to create an ArrayList containing the values 1, 2, 3, 4 and 10. Whilst I usually never have any trouble creating an ArrayList with said values, I am having trouble this time. Should I create the ArrayList outside of the method or inside the method? Whichever way I have attempted it, I have been presented with numerous error messages. How do I add values to this ArrayList parameter? I have attempted to add values to it when calling it from the main method, but this still doesn't work. Here is the method in question.
public static double ScalesFitness(ArrayList<Double> weights){
//code emitted for illustration purposes
}
If anybody could help me it would be greatly appreciated. If any more code is required, then please let me know.
Thank you so much.
Mick.
EDIT: The code for the class in question is as follows:
import java.util.*;
public class ScalesSolution
{
private static String scasol;
//Creates a new scales solution based on a string parameter
//The string parameter is checked to see if it contains all zeros and ones
//Otherwise the random binary string generator is used (n = length of parameter)
public ScalesSolution(String s)
{
boolean ok = true;
int n = s.length();
for(int i=0;i<n;++i)
{
char si = s.charAt(i);
if (si != '0' && si != '1') ok = false;
}
if (ok)
{
scasol = s;
}
else
{
scasol = RandomBinaryString(n);
}
}
private static String RandomBinaryString(int n)
{
String s = new String();
for(int i = 0; i > s.length(); i++){
CS2004.UI(0,1);
if(i == 0){
System.out.println(s + "0");
}
else if(i == 0){
System.out.println(s + "1");
}
}
return(s);
}
public ScalesSolution(int n)
{
scasol = RandomBinaryString(n);
}
//This is the fitness function for the Scales problem
//This function returns -1 if the number of weights is less than
//the size of the current solution
public static double scalesFitness(ArrayList<Double> weights)
{
if (scasol.length() > weights.size()) return(-1);
double lhs = 0.0,rhs = 0.0;
double L = 0;
double R = 0;
for(int i = 0; i < scasol.length(); i++){
if(lhs == 0){
L = L + i;
}
else{
R = R + i;
}
}
int n = scasol.length();
return(Math.abs(lhs-rhs));
}
//Display the string without a new line
public void print()
{
System.out.print(scasol);
}
//Display the string with a new line
public void println()
{
print();
System.out.println();
}
}
The other class file that I am using (Lab7) is:
import java.util.ArrayList;
public class Lab7 {
public static void main(String args[])
{
for(int i = 0 ; i < 10; ++i)
{
double x = CS2004.UI(-1, 1);
System.out.println(x);
}
System.out.println();
ScalesSolution s = new ScalesSolution("10101");
s.println();
}
}
you can these
1) use varargs instead of list
public static double scalesFitness(Double...weights)
so you can call this method with :
scalesFitness(1.0, 2.0, 3.0, 4.0, 10.0);
2) create the list outside your method
ArrayList<Double> weights = new ArrayList<Double>();
weights.add(1.0);
weights.add(2.0);
weights.add(3.0);
weights.add(4.0);
weights.add(10.0);
scalesFitness(weights);
Towards your initial posting, this would work:
scalesFitness (new ArrayList<Double> (Arrays.asList (new Double [] {1.0, 2.0, 4.0, 10.0})));
You may explicitly list the values in Array form, but
you have to use 1.0 instead of 1, to indicate doubles
you have to prefix it with new Double [] to make an Array, and an Array not just of doubles
Arrays.asList() creates a form of List, but not an ArrayList, but
fortunately, ArrayList accepts a Collection as initial parameter in its constructor.
So with nearly no boilerplate, you're done. :)
If you can rewrite scalesFitness that would be of course a bit more easy. List<Double> as parameter is already an improvement.
Should I create the ArrayList outside of the method or inside the method?
The ArrayList is a parameter for the method so it need to be created outside the method, before you invoke the method.
You need to import ArrayList in the file that includes your methods. This is probably solved but that's the issue I was encountering.