This is my code:
int[] primes = new int[25];
for (int i = 2; i <= 100; i++)
{
for (int j = i; j > 0; j--)
{
int prime = i%j;
if (prime == 0)
{
if ((j == i) || (j == 1))
{
isPrime = true;
}
else
{
isPrime = false;
break;
}
}
}
if (isPrime == true){
primes[index] = i;
index++;
}
}
As you can see, I'm writing prime numbers into array. I counted all the prime numbers that are within range 2-100, so I set array size to 25.
But let's say that I wouldn't know there are 25 prime numbers. Is there a way to create an array (any type of array) without defining the size? I tried this:
int[] primes = new int[0];
But it crashed.
You can use List for unknown size of data (probably ArrayList will be the best solution for you).
No; an array's size must be declared ahead of time. Try taking a look at the different implementations of List or Vector.
If in the end you absolutely need an array, you may create an array from your List.
Lists are best for situations, when you don't know exact size of array. For example, you can use ArrayList.
You have to use List instead of an Array.
Compiler needs to know the size of an Array. When you define an Array like this.
int[] primes = new int[0];
It creates space for only 1 integer. So, when you write to primes[1], it creates segmentation fault signal and your program crashes.
As mentioned by others, you can use an ArrayList, and if you still need the output as an array, you can convert the ArrayList to array at the end (once you know the size of the array).
Arrays are meant for the situation when we know about the size and number of elements we are going to put inside.If we are not sure about the size then in that case Collection API of Java can help you out.
for example
List Interface implemented by ArrayList and Vector
ArrayList can extends its size 50% at runtime so this will solve your problem.Or else you can use Vector if your application dealing with thread safety.but avoid using Vector because It increases its size to double at runtime.
This code may help you.
public static void main(String[] args) {
boolean isPrime;
List<Integer> list = new ArrayList<Integer>();
for (int i = 2; i <= 100; i++)
{
isPrime = true;
for (int j = 2; j < i/2; j++)
{
int prime = i % j;
if (prime == 0)
{
isPrime = false;
break;
}
}
if (isPrime == true){
list.add(i);
}
}
// all the prime numbers
for(Iterator<Integer> iterator = list.iterator(); iterator.hasNext();){
System.out.print(iterator.next()+" ");
}
}
Related
static int[] evenFactorsOfNum(int num) {
int[] result = {}; // need help in this line
int index = 0;
for (int i = 2; i <= num / 2; i = i + 2) {
if (i % 2 == 0) {
result[index] = i;
index++;
}
}
return result;
}
In this code snippet, I needed to store the even factors of given numbers in an array and return it. But it is not known how many factors will be possible of that number so we can't specify the size of array during array declaration. How do we handle it without storing the even factors in ArrayList (Collections in Java)? One restricted condition is we cannot initialize array size explicitly.
How do we achieve this dynamic behaviour of array without Arraylist?
An array in Java must be initialized with a fixed size. It can't be re-sized later.
You may create an array with some random size, and once it will be filled and you stil during your loop - create a new one with a larger size (let's say - double of the current array size) and copy all of the elements you poplutaed so far.
You calculate the maximum number of even factors the number can have and use that as the array size. After the loop is complete, index is the number of even factors; you can use Arrays.copyOfRange (or a loop) to create an array with the correct size.
static int[] evenFactorsOfNum(int num) {
int[] result = new int[num / 2];
int index = 0;
for (int i = 2; i <= num; i += 2) {
if(num % i == 0) result[index++] = i;
}
return Arrays.copyOfRange(result, 0, index);
}
IntStream.iterate can also be used to avoid an explicit array creation.
static int[] evenFactorsOfNum(int num) {
return IntStream.iterate(2, i -> i + 2).limit(num / 2)
.filter(i -> num % i == 0).toArray();
}
I would like to use list.negativeNumbers(); to call out the part of a code, which counts how many negative numbers are in a list.
public void negativeNumbers(){
int negative = 0;
for (int i = 0; i <= size; i++){
if (i < 0) {
negative = negative + 1;
}
System.out.println("There are "+ negative +" negative elements in the list!");
}
}
Can you help me in creating a method, that could count negative numbers in the list the correct way?
public void negativeNumbers(){
int negative = 0;
for (int i = 0; i <= size; i++){
if (i < 0) {
negative = negative + 1;
}
System.out.println("There are "+ negative +" negative elements in the list!");
}
}
You will learn better by working out the solution for yourself.
Your code as presented is a good start but lacks:
a defined list of values to test.
a definition of the size of the list (use list.size()).
proper indexing of the list to access values to test (use list.get(i) or list[i]).
a test of each element in the list to determine its negativity. Your code tests whether the list increment variable is < 0.
negative = negative + 1 is ok, but simpler to write ++negative.
Here's a simple example:
import java.util.ArrayList;
public class negnum {
public static void main(String [] args) {
ArrayList<Integer> nums = new ArrayList();
nums.add(0);
nums.add(10);
nums.add(-10);
nums.add(20);
nums.add(-20);
nums.add(30);
nums.add(-30);
nums.add(40);
nums.add(-40);
nums.add(50);
int negs = 0;
for (int i = 0; i < nums.size(); i++){
int n = nums.get(i);
if (n < 0) {
++negs;
System.out.println(n);
}
}
System.out.println(negs +" negatives");
}
}
c:\dev>java negnum
-10
-20
-30
-40
4 negatives
If it is a list of integers you should not be doing "i < 0" but rather the number at index of i. If you were to do that, you would also want to do "< size" rather than "<= size" or else you would run into an IndexArrayOutOfBounds.
It depends on how your double linked list is implemented, but if it extends the normal List<Integer> interface it would look like:
final Integer ZERO = Integer.valueOf(0);
int countNegativeElements() {
return stream().filter(MyList::isNegative).count();
}
static boolean isNegative(Integer i) {
return i.compareTo(ZERO) < 0;
}
with streams. More traditionally with an collection for-each (or an iterator for-each):
int countNegativeElements() {
int count = 0;
for(Integer i : this) { // or iterator()
if (isNegative(i)) count++;
}
return count;
}
This does not expect concurrent modifications and is optimized for collections where iterating is the fastest access. If you have a simple type list then you can replace isNegative with a simple < 0.
This article here talks about different ways to iterate a collection.
In my code I assumed you will add the method directly to your list implementation class. Replace this or this.iterator() or this.stream() with your actual list instance if it is external.
Update:
I just saw your link to the actual linked list you are using, this would look like this (hand made iteration):
int countNegativeElements() {
Node n = start;
int count = 0;
while(n != null) {
if (n.getData() < 0) count++;
n = n.getLinkNext();
}
return count;
}
Using null since there is no hasLinkNext() which would be typical for homework :)
I don't think it is a particular good idea to work with implementations which do not fit in the Collections framework, but maybe it is required to keep the lessons simple.
I'm trying to create a list of 20 integers between 0 and 26 (so in the 1-25 range) that does not repeat as a part of an assignment. I thought I had it figured out, but the program keeps looping over and over without ever ending. Can anyone help me out?
import java.util.Random;
public class prog433a
{
public static void main(String args[])
{
Random r = new Random();
int[] list = new int[20];
for (int k = 0; k < list.length; k++)
{
boolean notADupe = false;
while (notADupe == false)
{
list[k] = r.nextInt(25) + 1;
for (int j = 0; j < list.length; j++)
{
if (list[j] == list [k] && j != k)
{
notADupe = true;
}
else
{
notADupe = false;
break;
}
}
System.out.println(list[k]);
}
}
}
}
EDIT: This is different from the other question because I am trying to figure out how to check for uniqueness using the methods that I am allowed to use in my assignment (essentially, the ones I'm already using in the code).
I think you've reversed the condition out there. Inside if, you should set notADup to false, rather than true. However, I would make the variable isDup instead, and change the while loop accordingly.
One more suggestion: instead of while (notADupe == false), you should just use while (!notADupe). Never compare boolean variables like that. It might surprise you at times.
So to solve your issue, just change your if-else block to:
if (list[j] == list [k] && j != k) {
notADupe = false;
break;
} else {
notADupe = true;
}
BTW, your solution is a bit complex. For every element, you are iterating over whole array to find duplicate. Rather I would suggest you to maintain a Set<Integer> storing the already seen numbers, and check in that every randomly generated number. If present, skip it and re-generate.
Pseudo code would look something like this:
arr = [] // Your list array, initialize to size 20
seen = [] // A Set
for i from 1 -> arr.length
num = rand.nextInt(25) + 1
while seen contains num
num = rand.nextInt(25) + 1
seen.add(num)
arr[i] = num
I am given a problem in which I have to store a list of N numbers in an array and then sort it ,
and then I have to add the numbers at alternative positions and output the sum.
The problem is the constraint of N i.e 0 <= N <= 1011 so I have to declare the N as double type variable here is my code :
ArrayList<Double> myList = new ArrayList<Double>();
myList.add(number);
.....
Collections.sort(myList);
String tempNo = "";
for(double i = 0 ; i < myList.size() ; i=i+2){
tempNo = myStringWayToAdd(tempNo , myList(i)+""); // Since the sum will exceed the limit of double I have to add the numbers by help of Strings
}
But the problem is that the get(int) method takes an int not double. Is there any other way I can solve the problem? , and Is it even allowed to store number of elements that exceed int range?
Any help will be highly appreciated. Thank you in Advance.
Edit 1 :
I can use Strings instead of double in ArrayList and then add up the numbers but my problem is that i need to store N elements which can exceed the range of Integers
You could use LinkedList because it does not have a size limit (although odd things may begin to happen up there). You should also be able to use BigInteger for your numbers if the numbers themselves could get huge (you don't seem to state).
// LinkedList can hold more than Integer.MAX_VALUE elements,
List<BigInteger> myList = new LinkedList<>();
// Fill it with a few numbers.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
myList.add(BigInteger.probablePrime(10, r));
}
// Sort it - not sure if Collections.sort can handle > Integer.MAX_VALUE elements but worth a try.
Collections.sort(myList);
// Start at 0.
BigInteger sum = BigInteger.ZERO;
// Add every other one.
boolean addIt = false;
for (BigInteger b : myList) {
if (addIt) {
sum = sum.add(b);
}
addIt = !addIt;
}
I am not sure if Collections.sort can handle a list of numbers that big, let alone whether it will succeed in sorting within the age of the universe.
You may prefer to consider a database but again you might even have probelms there with this many numbers.
Ah, I misunderstood the question. So we have to store something that is significantly larger than the capacity of int.
Well, we can do this by dividing and conquering the problem. Assuming this is theoretical and we have unlimited memory, we can create a SuperArrayList.
'Scuse my bad generics, no compiler.
public class SuperArrayList<E>() {
private ArrayList<ArrayList<E>> myList;
private int squareRoot;
private double capacity;
public SuperArrayList(double capacity) {
this.capacity = capacity;
squareRoot = Math.ceil(Math.sqrt(capacity)); //we create a 2d array that stores the capacity
myList = new ArrayList<ArrayList<E>>();
for(int i = 0; i < squareRoot; i++) {
myList.add(new ArrayList<E>());
}
}
public E get(double index) {
if(index >= capacity || index < 0) {
//throw an error
}
else {
return myList.get((int) capacity / squareRoot).get(capacity % squareRoot);
}
}
}
As an alternative to squareRoot, we can do maxValue and add additional arraylists of length maxvalue instead.
boolean add = true;
for (Double doubleNum : myList) {
if (add) {
tempNo = myStringWayToAdd(tempNo , doubleNum+"");
}
add = !add;
}
Using this way, you won't have to use index.
I've been working on code to sort integer in an array list, but my code is only returning only 2 numbers can anybody help me understand what I'm doing wrong here. How do I get all the numbers to be displayed? The numbers in my array
ArrayList testNumbers = new ArrayList();
testNumbers.add(48);
testNumbers.add(3);
testNumbers.add(23);
testNumbers.add(99);
[48,3,23,99]. Any help would be greatly appreciated.
public ArrayList<Integer> listSort(ArrayList<Integer> numbers) {
// create variable to store max number
int maxNumber = 0;
// creates an array that will store the sorted numbers
ArrayList<Integer> sortedIntArray = new ArrayList<Integer>();
// loops through each number in the numbers arraylist
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) > maxNumber) {
// set the number to the new max number
maxNumber = numbers.get(i);
// add current max number to sorted array
sortedIntArray.add(maxNumber);
// remove the max number from numbers array
numbers.remove(numbers.get(i));
}
}
return sortedIntArray;
}
//the sortedIntArray returns
[48,99]
Use java.util.Collections.sort(List<T> list). Or are you required to implement your own sorting algorithm?
If you take a careful look at your code, it doesn't do anything if the number you are currently looking at is not bigger than maxNumber.
It adds in 48 because 48 > 0. Then it discards 3 and 23 because they are less than 48. then it adds 99 because it is greater than 48.
I believe you want to archive a classical Selection Sort.
Maybe try good old wikipedia: http://en.wikipedia.org/wiki/Selection_sort
public ArrayList<Integer> listSort(ArrayList<Integer> numbers) {
// create variable to store max number
int maxNumber = 0;
// creates an array that will store the sorted numbers
ArrayList<Integer> sortedIntArray = new ArrayList<Integer>();
// loops through each number in the numbers arraylist
for (int i = numbers.size(); i > 0; i--) {
maxNumber = numbers.get(0);
for(int j = 0; j < numbers.size(); j++) {
if (numbers.get(j) > maxNumber) {
// set the number to the new max number
maxNumber = numbers.get(i);
}
}
// add current max number to sorted array
sortedIntArray.add(maxNumber);
// remove the max number from numbers array
numbers.remove(numbers.get(i));
// add current max number to sorted array
sortedIntArray.add(maxNumber);
}
return sortedIntArray;
}
Basically you're only adding numbers that are greater than the max number you've seen. You also need to account for numbers that are smaller, and store them appropriately.
You are only adding to sortedIntArray when the array element you're looking at is bigger than the biggest found so far. 48 gets added because you haven't found any so far. Then 99 gets added because it's larger than 48.
You need to pass through the array more than once. As it stands, what you're doing is finding every number larger than all the previous numbers in the array. If you're really just looking for a selection sort (not a great idea, it's pretty slow) you want:
int size = numbers.size();
for (int i = 0; i < size; i++)
{
int maxNumber = 0;
for (int j = 0; j < numbers.size(); j++)
{
if (numbers.get(j) > numbers.get(maxNumber))
maxNumber = j;
}
SortedIntArray.add(numbers.get(maxNumber));
numbers.remove(maxNumber);
}
This also returns your array from largest to smallest, which isn't necessarily what you want. Also, by removing from numbers, you're changing the array so it won't be available to you once you're done (unless you pass a clone). In general, you need to rethink your set-up.
you mixed several sorting strats
public ArrayList<Integer> listSort(ArrayList<Integer> numbers) {
// create variable to store max number
int maxNumber = 0;
// creates an array that will store the sorted numbers
ArrayList<Integer> sortedIntArray = new ArrayList<Integer>();
// loops through each number in the numbers arraylist
while (!numbers.isEmpty()) {
int i;
for(i=0;i<number.size();i++){//double loop to get the current max numbers
if (numbers.get(i) > maxNumber) {
// set the number to the new max number
maxNumber = numbers.get(i);
}
}
// add current max number to sorted array
sortedIntArray.add(maxNumber);
// remove the max number from numbers array
number.listIterator(i).remove();
maxNumber=0;//reset maxNumber
}
}
return sortedIntArray;
}
I'm guessing you are asking this for a homework assignment. If you aren't just use any managed languages built in sort method as it will be faster than anything you write.
You are removing entries as you process them.
This means the size is shrinking when you insert entries.
After you add two entries, you have removed two entries leaving two entries so the loop stops.
try this algorithm it works with classes.. you can plug a list of class' into it as well
package drawFramePackage;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class QuicksortAlgorithm {
ArrayList<AffineTransform> affs;
ListIterator<AffineTransform> li;
Integer count, count2;
/**
* #param args
*/
public static void main(String[] args) {
new QuicksortAlgorithm();
}
public QuicksortAlgorithm(){
count = new Integer(0);
count2 = new Integer(1);
affs = new ArrayList<AffineTransform>();
for (int i = 0; i <= 128; i++){
affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0));
}
affs = arrangeNumbers(affs);
printNumbers();
}
public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){
while (list.size() > 1 && count != list.size() - 1){
if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){
list.add(count, list.get(count2));
list.remove(count2 + 1);
}
if (count2 == list.size() - 1){
count++;
count2 = count + 1;
}
else{
count2++;
}
}
return list;
}
public void printNumbers(){
li = affs.listIterator();
while (li.hasNext()){
System.out.println(li.next());
}
}
}