if it's in ascending order I need to print "Ascending".
And if otherwise, print "Otherwise".
int [] a = new int[args.length];
for (int i = 0; i < args.length; i++)
{
a[i] = Integer.parseInt(args[i]);
}
if (a[0] <= args.length || a[0] == a[0])
{
System.out.println("Ascending");
}
else
{
System.out.println("Otherwise");
}
You seem to be having a lot more trouble with this exercise than you should. So I'll only give a hint, since this looks like homework: You should make n-1 comparisons in order to determine the order. Do that using a for loop.
To clarify: the code you presented does not contain a for loop that compares numbers, and does some comparisons that have nothing to do with verifying order of the numbers.
Hints:
The following two comparisons don't do anything useful: a[0] <= args.length and a[0] == a[0].
You need to use a loop.
For one, the expression a[0] == a[0] will always evaluate to true, meaning that your current code will always enter the first condition and print "Ascending".
For another, you can't establish that a list of n elements is in ascending order without some kind of iteration. You need to use a loop or recursion to check your array's elements against each other.
Try this code
public class Ascending
{
public static void main(String[] args)
{
int [] a = new int[args.length];
boolean otherwise = false;
for (int i = 0; i < args.length; i++)
{
a[i] = Integer.parseInt(args[i]);
}
for(int i=1;i<a.length;i++){
if(a[i-1]>a[i]){
otherwise = true;
}
}
if (!otherwise)
{
System.out.println("Ascending");
}
else
{
System.out.println("Otherwise");
}
}
}
Related
I'm given an array of doubles, all numbers are equal except for one. My task is to find that unique number. My code returns the correct output and now I'm wondering how will I further optimize it.
This is my code:
public static double findUnique(double array[]) {
double unique = 0;
double common = 0;
for(int i=0; i<array.length; i++) {
for(int j=i+1; j<array.length; j++) {
if(array[i]==array[j]) {
common = array[i];
}
}
if(common!=array[i]) {
unique = array[i];
}
}
return unique;
}
The only thing I could think of is storing the length of the array first, but after some testing it actually took longer. Thanks.
public static double findUnique(double array[]) {
if(array.length < 3) {
throw new IllegalArgumentException("wrong array");
}
double common;
if(array[0] == array[1]) {
common = array[0];
} else {
return array[0] != array[2]? array[0]: array[1];
}
for(int i=2; i<array.length; i++) {
if(common != array[i]) {
return array[i];
}
}
throw new IllegalArgumentException("wrong array");
}
I belive that it is uneccesary to grab two new numbers in everey iteration.
Instead we could just start by grabbing the two first numbers of the array and then if those numbers are the same, we may compare the rest of the numbers to their value. So we define our common above the for loops, that way we will avoid the for loop and if statement containing: common= array[i] in every iteration. I belive this should make a difference in speed, at least if the array is crazy big.^^
Also, put the return inside the for loops so that you don't iterate the entire list even though you really found that piece of gold :):). (returning something always breaks the entire method.)
Hope I din't missunderstand anything :). Here's some code for you aswell. :)
public static double findUnique(double array[]) {
double common = 0;
if(array.length<3){
throw new IllegalArgumentException("Only two numbers exsists");
}
// Set up the common number seperately here.
if(array[0] == array[1]){
common = array[0];
}
else if(array[1] == array[2]){
return array[0];
}else{
return array[1];
}
// Now we iterate with return inside the for loop.
for(int i=2; i<array.length; i++) {
if(common!=array[i]) {
return array[i];
}
}
throw new IllegalArgumentException("All numbers are identical");
}
What if you sort the entire array first. Then just look at the first two and one last elements of the array.
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.
Let's say I have an array in the length of n, and the only values that can appear in it are 0-9. I want to create a recursive function that returns the number of different values in the array.
For example, for the following array: int[] arr = {0,1,1,2,1,0,1} --> the function will return 3 because the only values appearing in this array are 0, 1 and 2.
The function receives an int array and returns int
something like this:
int numOfValues(int[] arr)
If you are using Java 8, you can do this with a simple one-liner:
private static int numOfValues(int[] arr) {
return (int) Arrays.stream(arr).distinct().count();
}
Arrays.stream(array) returns an IntStream consisting of the elements of the array. Then, distinct() returns an IntStream containing only the distinct elements of this stream. Finally, count() returns the number of elements in this stream.
Note that count() returns a long so we need to cast it to an int in your case.
If you really want a recursive solution, you may consider the following algorithm:
If the input array is of length 1 then the element is distinct so the answer is 1.
Otherwise, let's drop the first element and calculate the number of distinct elements on this new array (by a recursive call). Then, if the first element is contained in this new array, we do not count it again, otherwise we do and we add 1.
This should give you enough insight to implement this in code.
Try like this:
public int myFunc(int[] array) {
Set<Integer> set = new HashSet<Integer>(array.length);
for (int i : array) {
set.add(i);
}
return set.size();
}
i.e, add the elements of array inside Set and then you can return the size of Set.
public int f(int[] array) {
int[] counts = new int[10];
int distinct = 0;
for(int i = 0; i< array.length; i++) counts[array[i]]++;
for(int i = 0; i< counts.length; i++) if(counts[array[i]]!=0) distinct++;
return distinct;
}
You can even change the code to get the occurrences of each value.
You can try following code snippet,
Integer[] arr = {0,1,1,2,1,0,1};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
Output: [0, 1, 2]
As you asked for a recursive implementation, this is one bad way to do that. I say bad because recursion is not the best way to solve this problem. There are other easier way. You usually use recursion when you want to evaluate the next item based on the previously generated items from that function. Like Fibonacci series.
Ofcourse you will have to clone the array before you use this function otherwise your original array would be changed (call it using countDistinct(arr.clone(), 0);)
public static int countDistinct(int[] arr, final int index) {
boolean contains = false;
if (arr == null || index == arr.length) {
return 0;
} else if (arr.length == 1) {
return 1;
} else if (arr[index] != -1) {
contains = true;
for (int i = index + 1; i < arr.length; i++) {
if (arr[index] == arr[i]) {
arr[i] = -1;
}
}
}
return countDistinct(arr, index + 1) + (contains ? 1 : 0);
}
int numOfValues(int[] arr) {
boolean[] c = new boolean[10];
int count = 0;
for(int i =0; i < arr.length; i++) {
if(!c[arr[i]]) {
c[arr[i]] = true;
count++;
}
}
return count;
}
Looking at the code below, doesnt the first iteration mean that i = 0 and j = 0 - 1? Why isnt there an error? I thought insertion sort was suppose to start from the end of the array/right side. How is this code accomplishing that?
class stevee {
public static void main(String[] args) {
int A[] = {2,1,9,8,12};
new stevee().sort(A);
System.out.println(Arrays.toString(A));
}
public void sort(int[] data) {
for (int i=0; i<data.length; i++) { //access each element one by one
int current = data[i]; //
int j = i-1;
while (j >= 0 && data[j] > current) {
data[j+1] = data[j];
j--;
}
data[j+1] = current;
}
}
}
Insertion sort works from the end in most examples. But why couldn't it work from the other side? 'Right' and 'Left' are only helping terms. Insertion sort is often explained with set of cards in your hand. Does it matter from which side you start putting them?
And there is no error cause while works also as if, j < 0 -> condition not met -> block not executed. In while condition you have && so both expressions must bu true, if first isn't, there is no sense to execute evaluation of second
There's a condition for that case: while (j >= 0
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