Generate even numbers in an int array? - java

For my program I need to make a 10 element array and the goal is to print out the even numbers from 2 to 20. I have to do this by adding 2 to the beginning element. This is what I have so far. I think I should use a loop as shown but I don't know how to go about adding 2 and printing that out. Thanks!
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
}

if you want program print even number between 2 & 20
for(int i=2;i<=20;i++)
{
if(i%2 == 0)
print(i)
}

Start at 2 and increment by 2 to get the even numbers:
int[] array = new int[10]
for(int counter=2; counter <= 20; counter += 2) {
array[counter/2 - 1] = counter
}
or
int[] array = new int[10]
for(int i=0; i <= 10; i++) {
array[i] = i*2 + 2
}

this is also an option
int i, value;
int nums[] = new int[10];
for (i = 0, value = 2; i < nums.length; value = value + 2, i = i + 1) {
nums[i] = value;
}
for (i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}

int[] array = new int[10];
for (int i = 0, j = 1; i < array.length && j <= 20; j++) {
if (j % 2 == 0) {
array[i] = j;
i++;
}
}
System.out.println(Arrays.toString(array));

Java 8: int[] array = IntStream.range(1, 11).map(x -> x * 2).toArray();
Or, to just print: IntStream.range(1, 11).map(x -> x * 2).forEach(System.out::println);

From java-9 you can use IntStream.iterate to create int array
int[] arr= IntStream.iterate(2, i->i<=20, i->i+2).toArray();
for Integer array you can use Stream.iterate
Integer[] ary = Stream.iterate(2, i->i<=20, i->i+2).toArray(Integer[]::new);

Dear Alexis,
Below is an example using do-while.
you can simply define a range of expected even numbers using minVal and maxVal.
Program will execute and return list of ordered even numbers for given range. Assuming input values are correct even numbers. You can improve to apply validations.
public class EvenNumberGenerator {
static int minVal=2; //enter valid min value even number
static int maxVal = 20; //enter valid max value even number
public static void main(String[] args) {
List<Integer> evenNumbers = new ArrayList();
do {
if(minVal % 2 == 0) {
evenNumbers.add(minVal);
}
minVal++;
} while (!evenNumbers.contains(maxVal));
System.out.println(evenNumbers);
// evenNumbers.toArray(); in case you need an array
}
}
OUTPUT
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Hope it helps!

Using your code as a start, this will work:
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
array[counter] = (counter + 1) * 2;
}
System.out.println(Arrays.toString(array));
The following will also work with Eclipse Collections:
int[] array = IntInterval.evensFromTo(2, 20).toArray();
System.out.println(Arrays.toString(array));
Note: I am a committer for Eclipse Collections

Related

Return indices of the two numbers such that they add up to a specific target

I have the below question I am trying to solve:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
I have the below array as input - [2, 7, 11, 15] with target = 9.
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
This is my code -
import java.util.Random;
public class TwoSum {
static int[] numbers = new int[] {2, 7, 11, 15};
int[] indices = new int[numbers.length];
public static int[] returnIndices(int target, int[] inputArr) {
int[] indices = new int[2];
int randomOne = new Random().nextInt(inputArr.length);
int randomTwo = new Random().nextInt(inputArr.length);
while(true) {
if(target == inputArr[randomOne] + inputArr[randomTwo]) {
indices[0] = randomOne;
indices[1] = randomTwo;
break;
}
}
System.out.println("done");
return indices;
}
public static void main(String[] args) {
int[] output = returnIndices(9, numbers);
}
}
Is this the right way to approach my problem?
You can use a hashmap to store the first array in the following manner:
key value(index in array)
2 - 0
7 - 1
11 - 2
15 - 3
Next get the target element which is 9, and start traversing your given array from index 0.
Element at index 0 is 2 --> calculate (9-2) = 7 --> check if 7 is a key in the hashmap
Additional Note: You need to take care of the following case:
arr = [3, 2, 1, 1] target = 6 (no answer exists in this case, but by the above method, when you calculate 6-3 = 3 you get index 0 as the answer.)
But this can easily be taken care of by checking whether (target-arr[i] == arr[i]) returns true or not. If it returns true and if the hashmap has two indices stored at the key arr[i], then return it as an answer, else proceed to the next element.
There are various ways to solve this question:
Hashmap way - #mettleap answer has covered that one.
Sort-Array way - I am going to explain its pseudo code to you.
Let us take an example to see it in action first. We are given arr = [5, 2, 1, 9, 7] elements in an array, and we are to find the indices of two elements if we can make 8.
If you look closely, then you will know if we sum 3rd + last element in an array, we will get 8, which means 2 and 4 would be our answer. So How would be land there? Let us go step by step
Maintain a separate array of the same size, it will hold the indices of arr in its initial setup.
[5, 2, 1, 9, 7] = arr
[0, 1, 2, 3, 4] = index_arr
Now sort arr in increasing order, and also sort the index_arr such that index of elements in arr in their initial setup is still in place.
[1, 2, 5, 7, 9] = arr
[2, 1, 0, 4, 3] = index_arr
Use the below pseudo code:
low = 0
high = length of arr - 1
while (low < high) {
sum = arr[low] + arr[high]
if (sum == number) {}
print "index_arr[low]" and "index_arr[high]"
break the loop and exit
} else if ( sum < number ) {
low = low + 1
} else {
high = high - 1
}
}
Let us see psuedo code in action:
[1, 2, 5, 7, 9] = arr
[2, 1, 0, 4, 3] = index_arr
Iteration # 01
low = 0 and high = 4
sum = arr[0] + arr[4] = 1 + 9 = 10
10 > 8 , means 'else' will be executed high = high - 1 = 4 - 1 = 3
Iteration # 02
low = 0 and high = 3
sum = arr[0] + arr[3] = 1 + 7 = 8
8 == 8 , means first 'if' condiion will execute, and will indices and exit the loop
Time Complexity - O(n)
Space Complexity - O(n)
I have tried it in c#, It may help..
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
int[] nums = { 2, 7, 11, 15 };
int target = 9;
int[] result= TwoSumNumbers(nums, target);
}
public static int[] TwoSumNumbers(int[] nums, int target)
{
Dictionary<int, int> numsDict = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
int num = nums[i];
if (numsDict.TryGetValue(target - num, out int index))
{
return new[] { index, i };
}
numsDict[num] = i;
}
return null;
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int [] answer = new int[2];
Map<Integer,Integer> values = new HashMap<Integer,Integer>();
for ( int i=0; i < nums.length; i++){
values.put(nums[i],i);
}
for ( int i=0; i < nums.length; i++){
int val = target - nums[i];
Integer secondIndex = values.get(val);
if ( secondIndex != null && secondIndex != i){
answer[0] = i;
answer[1] = secondIndex;
return answer;
}
}
return answer;
}
}
C# Version
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace MyBasics
{
class ArrayIndexForTarget
{
public static void Main()
{
ArrayIndexForTarget find = new ArrayIndexForTarget();
int[] arr = new int[] { 9, 2, 3, 9, 10 };
int target = 11;
var result = find.IndexFinder(arr, target);
Console.ReadKey();
}
public int[] IndexFinder(int[]myArray,int target)
{
int[] arr = new int[2];
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int p=0; p < myArray.Length; p++)
{
int numberToFind = target - myArray[p];
if (dict.ContainsValue(numberToFind))
{
arr[0] = dict.FirstOrDefault(x => x.Value == numberToFind).Key;
arr[1] = p;
return arr;
}
else
{
dict.Add(p,myArray[p]);
}
}
return arr;
}
}
}
class Solution {
function twoSum($nums, $target) {
$lenght = count($nums);
$indices = array();
for($i = 0; $i<$lenght-1; $i++){
for($j=$i+1; $j<$lenght; $j++){
if(($nums[$i]+$nums[$j]) == $target){
$indices[] = $i;
$indices[] = $j;
return $indices;
}
}
}
} }
private static int[] findNumbersToAdd(int target, int[] array) {
int[] answer = {-1, -1};
int length = array.length;
for (int i = 0; i < length; i++) {
int var1 = array[i];
for (int j = i + 1; j < length; j++) {
int var2 = array[j];
if (var1 + var2 == target) {
answer[0] = i;
answer[1] = j;
break;
}
}
}
return answer;
}
Given you aren't focused on performance I would think a brute force approach would be fine. Here is a solution using streams and records.
record IndexPair(int index1, int index2) { };
IntStream.range(0, arr.length).boxed()
.flatMap(i1 -> IntStream.range(i1, arr.length)
.filter(i2 -> arr[i1] + arr[i2] == target)
.mapToObj(i2 -> new IndexPair(i1, i2))
.forEach(ip -> ...);
If you only want one solution then you could use findAny instead of forEach.
I tried this question and implement it using HashMap in Java and it works completely fine.
public class Solution {
public int[] twoSum(final int[] A, int B) {
HashMap<Integer,Integer> hm=new HashMap<>();
int index1=Integer.MAX_VALUE;
int index2=Integer.MAX_VALUE;
int diff=0;
for(int i=0;i<A.length;i++){
diff=B-A[i];
if(hm.containsKey(diff)){
index2=i;
index1=hm.get(diff);
return new int[] {index1+1,index2+1};
}else{
if(!hm.containsKey(A[i])){
hm.put(A[i],i);
}
}
}
// If Arrays doesnt have such pairs
if(index2 == (Integer.MAX_VALUE) || index1 == (Integer.MAX_VALUE)){
return new int[] {};
}
return new int[] {index1+1,index2+1};
}
}
here is a simple solution with 2 running loops,
assuming the following
you only need 2 numbers to get to the target.
the solution exists (therefor no need to validate).
public int[] TwoSum(int[] nums, int target) {
for (int i=0; i< nums.Length; i++){
for (int j=i+1; j< nums.Length; j++){
if (nums[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return null;
}
public int[] sumofTwo(int[] numbers, int target)
{
int[] answer = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0 ; i < numbers.length ; i++)
{
if(map.containsKey(target - numbers[i]))
{
answer[0] = map.get(target - numbers[i]);
answer[1] = i;
return answer;
}
else
{
map.put(numbers[i],i);
}
}
return null;
}
}
public class Main {
public static void main(String[] args) {
int [] arr = {4,7,1,-3,2};
for(int i=0; i<arr.length-1; i++)
{
for(int j=0; j<=arr.length-2; j++)
{
if((arr[i]+arr[j+1])==6)
{
System.out.println("indices = "+"["+i +","+(j+1)+"]");
}
}
}
}
}

Sorting from one array into another, Java

My goal is to move the elements in the ar[] array into the sorted[] array and sort them from least to greatest. I'm having trouble with that part though because my loop is supposed to find the smallest element in the array and then replace the element with a large number. I think I have most of the code down but when I run the program, every element in the sorted[] array is 2. What am I doing wrong here?
public class Lab1
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[ar.length];
int smallest = ar[0];
int smallestindex = 0;
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n];
smallestindex = n;
}
}
sorted[i] = smallest;
ar[i] = 1000000;
}
// print sorted array:
for (int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
What about something like this?
Short and sweet:
import java.util.Arrays;
public class Lab1
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = ar.clone();
Arrays.sort(sorted);
System.out.println("Original array: " + Arrays.toString(ar));
System.out.println("Sorted array: " + Arrays.toString(sorted));
}
}
Output:
Original array: [7, 5, 2, 8, 4, 9, 6]
Sorted array: [2, 4, 5, 6, 7, 8, 9]
I don't have my pc now but I think the problem is that once you set the variable smallest with 2 the first time, it remains 2 forever and there is no other number smaller. So I think you are executing the internal if just once and the value is always 2.
Edit. I think that moving the smallest inizialization below the fist for should work.
You didn't do any action when this condition is not true.
if (ar[n] < smallest)
So just smallest element can pass this check and goes on new array.
Also you can sort your array in better shape like this
List<Integer> ar = Arrays.as list ( *your numbers here*);
Collections.sort(ar):
oops, there is a problem inside your loop,
which copy the smallest in ar[] into sorted[], which is 2,
so you are getting 2 in every element inside sorted[].
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n]; <----YOU ALWAYS GET 2 HERE
smallestindex = n;
}
}
sorted[i] = smallest; <---- AND SET 2 TO YOUR sorted[] HERE
ar[i] = 1000000;
}
I don't know if you want a solution or solve it yourself since your question is asking what's wrong, but here it is
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n];
smallestindex = n;
ar[n] = 1000000; <----CHANGE THE SMALLEST ITEM HERE RATHER THAN OUTSIDE
}
}
sorted[i] = smallest;
}
btw, to make a sorted copy in a easier way:
Firsy make a copy:
int[] sorted = ar.clone();
Then, sort it using Java Util:
Arrays.sort(sorted);
Just 2 lines you get what you want.
I just can't understand, why do we require this, like sorting into another array. You can sort within the array using Arrays.sort() method, or if you want to sort in a different array, you can take following steps:
Copy the array to new array.
Sort the new array and then sort.
If you still want to go with your implementation, then I have refactored your code. Now your code works fine and looks like:
public class Prog1 {
public static void main(String[] args) {
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[ar.length];
int smallest = ar[0];
int smallestindex = 0;
for (int i = 0; i < ar.length; i++) {
for (int n = 0; n < ar.length; n++) {
if (ar[n] < smallest) {
smallest = ar[n];
smallestindex = n;
}
}
sorted[i] = smallest;
//Your mistake was here.
ar[smallestindex] = 1000000;
smallest=ar[0];
smallestindex=0;
}
// print sorted array:
for (int i = 0; i < sorted.length; i++) {
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
Your mistake was that you were not reassigning 'smallest' variable. As it was pointing to the smallest element of array so it doesn't get updated in next run because no element in array is less than this variable. Hope you get it. If any questions, you still have, please ask.
Because each time you crush old value (big value) and you don't save it for shifting
smallest = ar[n]; smallestindex = n; You need to add another variable to change values between cells ,or use arraylist for easy way.
int ar[] = {7, 5, 2, 8, 4, 9, 6};
int sorted[] = new int[ar.length];
int smallest = ar[0];
for (int i = 0; i < ar.length ; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) {
smallest = ar[j]; //save small value
ar[j] = ar[i];//transaction between two comparables cells
ar[i] = smallest;//set small value as first
}
sorted[i]=ar[i]; //set first small value
}
}
// print sorted array:
for (int i = 0; i < sorted.length; i++) {
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
It seems you want to sort by using an algorithm called 'Selection Sort', but your code is a poorly implement.
You can learn from this brother's question and check the answers below that:
Selection Sort Example

return an Array which contains only odd integers

Ok, so I have this problem where when given an Array arr, return an Array which contains only odd integers in the original order from arr.
My code:
public int [] youMakeMeOdd(int [] arr)
{
int[] odds;
odds = new int[arr.length];
for(int i = 0; i < arr.length; i++)
{
if(arr[i] % 2 != 0)
{
odds[i] = arr[i];
}
}
return odds;
}
Few Testers:
Expected...........................................................Run:
youMakeMeOdd({1,2,3}) → {1, 3}.....................{1, 0, 3}
youMakeMeOdd({2,1,3,5,7}) → {1, 3, 5, 7}.......{0, 1, 3, 5, 7}
youMakeMeOdd({2,4,6,8}) → {}........................{0, 0, 0, 0}
.
I can't seem to figure out how to put a blank space there instead of 0's. Help appreciated, thanks :)
The output array is being initialized to the size of the input array. I guess this being java code, the array elements are initialized to zero by default. So whenever the if condition does skips the ith position the default value (zero) is being shown.
public int[] youMakeMeOdd(int [] arr) {
List<Integer> odds = new ArrayList<Integer>();
for(int i = 0; i < arr.length; i++)
{
if(arr[i] % 2 != 0)
{
odds.add(arr[i]);
}
}
return convertIntegers(odds);
}
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
You could have a pre-computation loop where you just increment a counter and then allocate odds:
int counter = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 != 0)
{
counter ++;
}
}
odds = new int[counter];
I would use an ArrayList. Your problems seems to be the fact that arrays are immutable, so you it automatically fills your array with a bunch of unneeded 0s. ArrayLists can change dimensions, so you don't have to have the 0s.
You can have a look at them here: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Make sure you import the util package.
import java.util.*;
public ArrayList<Integer> youMakeMeOdd(int [] arr)
{
You need to specify the type that you want to hold in the angle braces. Because int is a primitive, you need to use the Integer class
ArrayList<Integer> odds;
odds = new ArrayList<>();
for(int i = 0; i < arr.length; i++)
{
if(arr[i] % 2 != 0)
{
The add method adds an integer to the end
odds.add(new Integer(arr[i]));
}
}
return odds;
}
var result = input.Select(a=>a % 2 != 0 ? a : 0).ToArray()
You can use linq easily, basically you use the original array and then use the Select to select either the value itself of the array or 0 if it's even, and then convert to an array using ToArray method.

How can I move all even numbers to front in an array?

Following is the problem-
Given an array of integers as input, return an array that contains the same numbers as that in the input array, but rearranged so that all the even numbers are in front and the odds numbers are at the back. Note that the order of the even numbers and odd numbers should be maintained i.e. if an even number n1 that appears before an even number n2 in the input, then in the output array n1 should appear before n2. The same is true for odd numbers. Also note that in this problem you should not create any new array.
What is done so far is as follows but I am unable to get the expected output.
public class MoveEvenToFront {
static int[] testcase1 = {3, 5, 4, 6, 8, 9, 7, 10};
public static void main(String[] args) {
MoveEvenToFront testInstance = new MoveEvenToFront();
int[] result = testInstance.moveEvenToFront(testcase1);
System.out.print("{");
for (int i = 0; i < result.length; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(result[i]);
}
System.out.print("}");
}
public int[] moveEvenToFront(int[] arr) {
int temp = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i - 1] % 2 != 0) {
temp = arr[i - 1];
arr[i - 1] = arr[i];
arr[i] = temp;
}
}
return arr;
}
}
The expected output for testcase {1,2,3,4,5,6,7,8,10,12} is {2,4,6,8,10,12,1,3,5,7}.
Your algorithm is wrong. You are checking if arr[i-1] is not even and swapping it with arr[i]. If arr[i] is also odd, then you are not checking for it, and it moves to the front even when it is odd.
What you could do is
find the first even number in the array and swap it with first index and increment the index.
then find the second even number and swap it with second index, continue until end of array.
change the method as shown below:
public int[] moveEvenToFront(int[] arr){
int temp=0;
int a=0;
for(int i=0;i<arr.length;i++){
if(arr[i]%2==0){
for (int j=i;j>a;j--){
temp=arr[j-1];
arr[j-1]=arr[j];
arr[j]=temp;
}
a++;
}
}
return arr;
}
Try it straight forward:
public static Integer[] NUMBERS = {3,5,4,6,8,9,7,10};
public static void main(String[] args) {
ArrayList<Integer> ints = new ArrayList<>(Arrays.asList(NUMBERS));
int nextIdx = 0;
for (int idx = 0; idx < ints.size(); idx++) {
if (ints.get(idx) % 2 == 0) ints.add(nextIdx++, ints.remove(idx));
}
System.out.println(ints);
}
OUTPUT:
[4, 6, 8, 10, 3, 5, 9, 7]
public void moveEvenToFront(){
int temp=0;
for(int i=0;i<values.length;i++){
for(int j=i;j<values.length;j++){
if(values[j]%2==0){
temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
after creating values[], the key point of solving this is identifying where there is an even number and switching with values[0]. and increase by 1 so that the even numbers don't disappear. Hope this helps.

Algorithm to find the largest integer in array

I am trying to create a method which returns an int - the value of the largest integer in the sent array.
The way I want this method to work, is to check the first and the last element of the array in a for-loop, and work their way to the middle. So i = first integer, k = last integer. When i = 0, k = n-1 (indexes), when i = 1, k = n-2 if you catch my drift. In every loop it needs to check if a[i]>a[k]. Then they switch places. Then I know that the largest number is in the leading half of the array, and then I want it to check that half, so ultimately the largest int is at index 0.
I tried like this:
public static int maxOfArray(int[] a)
{
int length = a.length;
if(length<1)
throw new NoSuchElementException("Not at least one integer in array");
while (length > 1)
{
int k = length;
for(int i = 0; i < length/2; i++)
{
k--;
if(a[i]<a[k])
{
int j = a[i];
a[i] = a[k];
a[k] = j;
}
}
length /=2;
}
return a[0];
}
..but I don't really get it.. I'm having a hard time "picturing" what's happening here.. But it's not always working.. (though sometimes).
EDIT
Also: The array {6,15,2,5,8,14,10,16,11,17,13,7,1,18,3,4,9,12}; will spit out 17 as the largest number. I realize I have to fix the odd-length bug, but I would like to solve this even-length array first..
A bug is when encountering length is odd.
In these cases, you "miss" the middle element.
Example: for input int[] arr = { 8, 1, 5, 4, 9, 4, 3, 7, 2 }; - the element 9 will be compared and checked against itself, but then you reduce the size of length, you exclude 9 from the array you are going to iterate next.
I believe it can be solved by reducing the problem to ceil(length/2) instead of length/2 (and handling special case of length==1)
The other issue as was mentioned in comments is: you need to iterate up to length/2 rather then up to length, otherwise you are overriding yourself.
Lastly - the sign is wrong.
if(a[i]>a[k])
should be
if(a[i]<a[k])
Remember - you are trying to swap the elements if the first is smaller the the second in order to push the larger elements to the head of your array.
but I don't really get it.. I'm having a hard time "picturing" what's happening here.. But it's not always working.. (though sometimes).
In that case you should use a debugger to step through the code to get a picture of what each line of code does.
What I would do is:
public static int maxOfArray(int[] a) {
int max = a[0];
for (int i : a)
if (max < i)
max = i;
return max;
}
public static int findMaxTheHardWay(int[] array) {
for (int length = array.length; length > 1; length = (length + 1) / 2) {
for (int i = 0; i < length / 2; i++) {
if (array[i] < array[length - i - 1])
array[i] = array[length - i - 1]; // don't need to swap.
}
}
return array[0];
}
public static void main(String... args) {
Random rand = new Random(1);
for (int i = 1; i <= 1000; i++) {
int[] a = new int[i];
for (int j = 0; j < i; j++) a[j] = rand.nextInt();
int max = maxOfArray(a);
int max2 = findMaxTheHardWay(a);
if (max != max2)
throw new AssertionError(i + ": " + max + " != " + max2);
}
}
This is rather a crazy way to solve the problem, but I'll play along.
The problem is in the inner loop.
You start out with i = 0 and k = length - 1.
If a[i] > a[k] you swap them.
...
You end up with k = 0 and i = length - 1
If a[i] > a[k] you swap them.
If you look at that carefully you will notice that if we swapped the elements in the first swap, we will also swap them in the last swap; i.e. we will UNDO the effects of the first swap. And the same applies pair-wise through the entire array slice.
See?
What you need to do is to stop the inner loop half way ... and then take account of the case where length is odd.
By the way, the reason I called this "rather crazy", because the obvious and simple way is much faster: O(N) versus O(NlogN)
int a[] = {1,7,3};
List<Integer> list = Arrays.asList(a);
Integer largest = Collections.max(list);
This will give you Largest number in Array.
Here is a solution that fits the specifications that you want (unlike many other here, humm, humm):
final Integer[] input = {1, 2, 6, 32, 4, 44 ,12, 42, 3, 7, 17, 22, 57, 23, 102, 103 };
int half = (input.length / 2);
int mod = input.length % 2;
while (half >= 0) {
for (int i = 0, j = (half * 2) + mod - 1; i <= half && j >= half; i++, j--) {
if (input[i] < input[j]) {
final int tmp = input[i];
input[i] = input[j];
input[j] = tmp;
}
}
if (half == 0) break;
half = half / 2;
mod = half % 2;
}
//Here, input[0] = the biggest number in the original input.
Edit: Added mod, so it works if the last element is the largest..
I think your code is working, you just have to ceil the length / 2 in case of odd array but my tests return proper result:
package org.devince.largestinteger;
import java.util.NoSuchElementException;
public class LargestInteger {
final static int[] input = {1, 2, 6, 32, 4, 44 ,12, 42, 3, 7, 17, 22, 57, 23, 102, 103 };
// final static int[] input = { 8, 1, 5, 4, 9, 4, 3, 7, 2 };
// final static int[] input = {1,3,7};
/**
* #param args
*/
public static void main(String[] args) {
System.out.println(String.valueOf(maxOfArray(input)));
}
public static int maxOfArray(int[] a)
{
int length = a.length;
if(length<1)
throw new NoSuchElementException("Not at least one integer in array");
while (length > 1)
{
int k = length;
for(int i = 0; i < length; i++)
{
k--;
if(a[i]>a[k])
{
int j = a[i];
a[i] = a[k];
a[k] = j;
}
}
length = (int) Math.ceil(length / 2f);
}
return a[0];
}
}
Why not just store the first value of the array to a variable max.
After that just loop through the array starting from second position till the last ,
in the loop just check if the current value is greater than max or not.If it is greater just assign max that value.
Return max and you have the largest number.
public int FindLargest()
{
int[] num = { 1, 2, 5, 12, 13, 56, 16, 4 };
int max = num[0];
for (int i = 1; i <num.length; i++)
{
if (num[i] > max)
{
max = num[i];
}
}
return max;
}
As the same u can approach like also,
int length = a.length;
while (length > 1)
{
int k = length;
for(int i = 0; i < length; i++)
{
for(int y = k-1; y >= i; y--)
{
if(a[i]<a[y])
{
int j = a[i];
a[i] = a[y];
a[y] = j;
}
}
}
length /=2;
}
final int validSampleRates[] = new int[]{
5644800, 2822400, 352800, 192000, 176400, 96000,
88200, 50400, 50000, 4800,47250, 44100, 44056, 37800, 32000, 22050, 16000, 11025, 4800, 8000};
ArrayList <Integer> YourArray = new ArrayList <Integer> ():
for (int smaple : validSampleRates){
YourArray.add(smaple);
}
Integer largest = Collections.max(YourArray);
System.out.println("Largest " + String.valueOf(largest));
The best way is to use Array that extends List Collection as ArrayList

Categories