Java for loop where values jump - java

If I have three variables and I want a value in a for loop to jump from one to the next, how would I do that? You can assume the first variable is the smallest and the third is the biggest, and that the variables are not equal to one another(although if there is a way to do it where they are equal that would be good).
I have an example for if it was only two values.
int val1 = 5;
int val2 = 9;
for(int i = val1; i <= val2; i=i+(val2-val1) {
}
In this case i would first be 5, and then 9. Also, is there any way to do it with a different amount of variables?

I'm not 100% certain I understand your question, but you could do
for(int i = val1; i <= val2; i = (i == val1) ? val2 : val2+1) {
// ...
}
If you need more values, I would put them in an array and use a for-each loop over that
int[] vals = {5,9,17};
for (int i : vals) {
// ...
}

you can place those in an array and access to it by index
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[] myArray = {4, 6 , 9};
for(int x : myArray)
{
System.out.println(x);
}
//or....
for(int x =0; x<3; x++)
{
System.out.println(myArray[x]);
}
}
}

As #Gonen I said, you can handle this using stream. If you want '...the first variable is the smallest and the third is the biggest...' you should use stream.sorted() to get sorted values.
x corresponds to each one element of the vals list while traversing. So you can do whatever you want in the forEach block with using x
List<Integer> vals = Arrays.asList(5,9,17);
vals.stream().sorted().forEach(x -> {
System.out.println(x);
});

If we are already being a bit silly, this will do the trick for as many values as you want, and inside a for loop. But I would never actually write code like this because its completely unreadable:
package package1;
public class SillySkip {
public static void main(String[] args) {
for( int data[] = {5,10,-4}, i, j=0; j < data.length && (i = data[j]) % 1 == 0 ; ++j )
{
System.out.println(i);
}
}
}
From Java 8 and up you can use Stream.of to iterate arbitrary values like this:
package package1;
import java.util.stream.Stream;
public class IterateSomeValues {
public static void main(String[] args) {
Stream.of(5,10,-4).forEach(e->System.out.println(e));
}
}

Related

Finding the occurrence of values within an array

My question is how do I find the frequency of the numbers "8" and "88" in this array, using a method. It seems as what I put in the assessor method does not appear to work. For example, if "8" occurs three times in the array the output would be "3" and the same for "88".
If I am wrong please point me to the right direction. Any help with my question is greatly appreciate.
import java.util.Random;
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
public void printArray() {
for (int i = 0; i < MAX_ARRAY_SIZE; ++i)
System.out.println(arr[i]);
}
public int countFrequency(int value) {
for (int i: MAX_VALUE) {
if (i == 8)
i++;
}
public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();
System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");
System.out.println("The frequency of 8 is: " + ap.countFrequency(8));
System.out.println("The frequency of 88 is: " + ap.countFrequency(88));
}
}
}
You need to iterate over arr and increment a variable when an element matches value.
public int countFrequency(int value) {
int count = 0;
for (int num : arr) {
if (num == value) {
count++;
}
}
return count;
}
You have a hard-coded seed, so your random values won't be random on different runs. You are also hard-coding your frequency count against 8 (instead of value). But honestly, I suggest you revisit this code with lambdas (as of Java 8), they make it possible to write the array generation, the print and the count routines in much less code. Like,
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// randomly fill array with numbers
Random rand = new Random();
arr = IntStream.generate(() -> rand.nextInt(MAX_VALUE) + 1)
.limit(MAX_ARRAY_SIZE).toArray();
}
public void printArray() {
IntStream.of(arr).forEachOrdered(System.out::println);
}
public int countFrequency(int value) {
return (int) IntStream.of(arr).filter(i -> i == value).count();
}
}
You need to iterate over the array and increment a counter variable when an element matches i
what you are doing is increment i instead of a counter:
if (i == 8)
i++;
} // if i is 8 then i becomes 9
A working example:
public int countFrequency(int i) {
int count = 0;
for (int num : arr) {
if (num == i) {
count++;
}
}
return count;
}
Solution:
public int countFrequency(int value) {
int counter = 0; // here you will store counter of occurences of value passed as argument
for (int i : arr) { // for each int from arr (here was one of your errors)
if (i == value) // check if currently iterated int is equal to value passed as argument
counter++; // if it is equal, increment the counter value
}
return counter; // return the result value stored in counter
}
Explanation:
Main problem in your code was countFrequency() method, there are few bugs that you need to change if you want to make it work correctly:
You passed value as argument and you didn't even use it in the body of method.
for (int i : MAX_VALUE ) - you meant to iterate over elements of arr array, (You can read it then as: For each int from arr array do the following: {...}.
if (i == 8) i++ - here you said something like this: Check if the current element from array (assuming that you meant MAX_VALUE is an array) is equal to 8, and if it is - increment this value by 1 (so if it were 8, now it's 9). Your intention here was to increment counter that counts occurences of 8.
You might want to consider making these improvements to countFrequency() method, to make it work properly.

What is the best way to check if ALL values in a range exist in an array? (java)

I have the task of determining whether each value from 1, 2, 3... n is in an unordered int array. I'm not sure if this is the most efficient way to go about this, but I created an int[] called range that just has all the numbers from 1-n in order at range[i] (range[0]=1, range[1]=2, ect). Then I tried to use the containsAll method to check if my array of given numbers contains all of the numbers in the range array. However, when I test this it returns false. What's wrong with my code, and what would be a more efficient way to solve this problem?
public static boolean hasRange(int [] givenNums, int[] range) {
boolean result = true;
int n = range.length;
for (int i = 1; i <= n; i++) {
if (Arrays.asList(givenNums).containsAll(Arrays.asList(range)) == false) {
result = false;
}
}
return result;
}
(I'm pretty sure I'm supposed to do this manually rather than using the containsAll method, so if anyone knows how to solve it that way it would be especially helpful!)
Here's where this method is implicated for anyone who is curious:
public static void checkMatrix(int[][] intMatrix) {
File numberFile = new File("valid3x3") ;
intMatrix= readMatrix(numberFile);
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
int[] range = new int[nSquared];
int valCount = 0;
for (int i = 0; i<sideLength; i++) {
for (int j=0; j<sideLength; j++) {
values[valCount] = intMatrix[i][j];
valCount++;
}
}
for (int i=0; i<range.length; i++) {
range[i] = i+1;
}
Boolean valuesThere = hasRange(values, range);
valuesThere is false when printed.
First style:
if (condition == false) // Works, but at the end you have if (true == false) or such
if (!condition) // Better: not condition
// Do proper usage, if you have a parameter, do not read it in the method.
File numberFile = new File("valid3x3") ;
intMatrix = readMatrix(numberFile);
checkMatrix(intMatrix);
public static void checkMatrix(int[][] intMatrix) {
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
Then the problem. It is laudable to see that a List or even better a Set approach is the exact abstraction level: going into detail not sensible. Here however just that is wanted.
To know whether every element in a range [1, ..., n] is present.
You could walk through the given numbers,
and for every number look whether it new in the range, mark it as no longer new,
and if n new numbers are reached: return true.
int newRangeNumbers = 0;
boolean[] foundRangeNumbers = new boolean[n]; // Automatically false
Think of better names.
You say you have a one dimensional array right?
Good. Then I think you are thinking to complicated.
I try to explain you another way to check if all numbers in an array are in number order.
For instance you have the array with following values:
int[] array = {9,4,6,7,8,1,2,3,5,8};
First of all you can order the Array simpel with
Arrays.sort(array);
After you've done this you can loop through the array and compare with the index like (in a method):
for(int i = array[0];i < array.length; i++){
if(array[i] != i) return false;
One way to solve this is to first sort the unsorted int array like you said then run a binary search to look for all values from 1...n. Sorry I'm not familiar with Java so I wrote in pseudocode. Instead of a linear search which takes O(N), binary search runs in O(logN) so is much quicker. But precondition is the array you are searching through must be sorted.
//pseudocode
int range[N] = {1...n};
cnt = 0;
while(i<-inputStream)
int unsortedArray[cnt]=i
cnt++;
sort(unsortedArray);
for(i from 0 to N-1)
{
bool res = binarySearch(unsortedArray, range[i]);
if(!res)
return false;
}
return true;
What I comprehended from your description is that the array is not necessarily sorted (in order). So, we can try using linear search method.
public static void main(String[] args){
boolean result = true;
int[] range <- Contains all the numbers
int[] givenNums <- Contains the numbers to check
for(int i=0; i<givenNums.length; i++){
if(!has(range, givenNums[i])){
result = false;
break;
}
}
System.out.println(result==false?"All elements do not exist":"All elements exist");
}
private static boolean has(int[] range, int n){
//we do linear search here
for(int i:range){
if(i == n)
return true;
}
return false;
}
This code displays whether all the elements in array givenNums exist in the array range.
Arrays.asList(givenNums).
This does not do what you think. It returns a List<int[]> with a single element, it does not box the values in givenNums to Integer and return a List<Integer>. This explains why your approach does not work.
Using Java 8 streams, assuming you don't want to permanently sort givens. Eliminate the copyOf() if you don't care:
int[] sorted = Arrays.copyOf(givens,givens.length);
Arrays.sort(sorted);
boolean result = Arrays.stream(range).allMatch(t -> Arrays.binarySearch(sorted, t) >= 0);
public static boolean hasRange(int [] givenNums, int[] range) {
Set result = new HashSet();
for (int givenNum : givenNums) {
result.add(givenNum);
}
for (int num : range) {
result.add(num);
}
return result.size() == givenNums.length;
}
The problem with your code is that the function hasRange takes two primitive int array and when you pass primitive int array to Arrays.asList it will return a List containing a single element of type int[]. In this containsAll will not check actual elements rather it will compare primitive array object references.
Solution is either you create an Integer[] and then use Arrays.asList or if that's not possible then convert the int[] to Integer[].
public static boolean hasRange(Integer[] givenNums, Integer[] range) {
return Arrays.asList(givenNums).containsAll(Arrays.asList(range));
}
Check here for sample code and output.
If you are using ApacheCommonsLang library you can directly convert int[] to Integer[].
Integer[] newRangeArray = ArrayUtils.toObject(range);
A mathematical approach: if you know the max value (or search the max value) check the sum. Because the sum for the numbers 1,2,3,...,n is always equal to n*(n+1)/2. So if the sum is equal to that expression all values are in your array and if not some values are missing. Example
public class NewClass12 {
static int [] arr = {1,5,2,3,4,7,9,8};
public static void main(String [] args){
System.out.println(containsAllValues(arr, highestValue(arr)));
}
public static boolean containsAllValues(int[] arr, int n){
int sum = 0;
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == n*(n+1)/2);
}
public static int highestValue(int[]arr){
int highest = arr[0];
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
return highest;
}
}
according to this your method could look like this
public static boolen hasRange (int [] arr){
int highest = arr[0];
int sum = 0;
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == highest *(highest +1)/2);
}

Chose amount of parameters to call in a method?

While I was attempting to make a method that runs calculations and returns the binary value for a small project I'm working on; I was trying to have the method parameters include all of the values to add together, but when doing so I realized I don't know how to do so without using an array of some sort.
Is it possible to have the parameters in the following method addBinary change based on the amount I wish to add?
public int addBinary() // I want these parameters to have all integers I wish to add
{
// Calculations go here //
}
Essentially, if I wish to run the program and add 5 values the first time and 25 the next; how would I get all of the values into the method without creating an array?
You can use variable number of arguments in the method definiton(using ellipses i.e ... ) like this:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static int add(int ...arr)
{
int sum=0;
for(int i=0;i<arr.length;i++)
sum+=arr[i];
return sum;
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(add(1, 2, 3, 4));
System.out.println(add(1, 2, 3));
}
}
Output:
10
6
https://ideone.com/PHL8Lb
I don't know why you are not thinking of using arrays here. Just pass an array as a parameter and do the calculations you want to do.
public int addBinary(int a[])
{
for(int i=0;i<a.length;i++)
sum+=a[i];
return sum;
}
Or by using an arraylist
public int addBinary(ArrayList m)
{
int sum = 0;
for(i = 1; i < m.size(); i++)
sum += m.get(i);
return sum;
}
Link for the code Ideone
You can use varargs for this
void testapp(String ...studentsName){
for (int i = 0; i < studentsName.length; i++) {
System.out.println(studentsName[i]);
}
}

Java: array methods

This code supposedly checks an array of integers for 9's and returns it's frequency but the method is not being recognized. Any help please to make this code work.
public static int arrayCount9(int[] nums) {
int count = 0;
for (int i=0; i<nums.length; i++) {
if (nums[i] == 9) {
count++;
}
}
return count;
};
public static void main(String[]args){
System.out.println(arrayCount9({1,2,9}));
}
Change your method call to the following:
System.out.println(arrayCount9(new int[]{1,2,9}));
Alternatively:
int[] a = {1,2,9};
System.out.println(arrayCount9(a));
The shortcut syntax {1,2,9} can only be used when initializing an array type. If you pass this notation to a method, it will not be interpreted it as an array by the compiler.

Java formula for if using

I have a code and I know that it isn't right. My task is "print all two-digit numbers which don't have two equal numbers". That means - program need to print numbers like 10, 12, 13 etc. Program didnt need to print 11 because there are 2 equal numbers. Hope that my program at least some is correct. (And sorry for my english).
public class k_darbs1 {
public static void main(String[] args) {
int a,b;
boolean notequal;
for(a = 10; a < 100; a++)
{
notequal = true;
for(b = 100; b < a; b++)
{
if(a != b)
{
notequal = false;
}
}
if(notequal == true)
{
System.out.println(a);
}
}
}
}
so why making things to much complex!?!!?!!!??
public static void main(String[] args) {
for(a = 10; a < 100; a++)
{
if(a%11==0){continue;}
System.out.println(a);
}
}
I think your making this slightly more complicated than it has to be. If n is a 2-digit number, then the leading digit is n/10 (integer division by 10) and the trailing digit is n%10 (modulo 10). You can just test if those two are unequal and print n as appropriate, there's no need for another for-loop.
For instance:
int n = 42;
System.out.println(n/10);
System.out.println(n%10);
4
2
Convert it to a string and check the characters.
for (int a = 10; a < 100; a++) {
String value = String.valueOf(a);
if (value.charAt(0) != value.charAt(1)) {
System.out.println(value);
}
}
You can parse Integer to String. Then compare the numbers with substring. For this process,
you need to know
Integer.toString(i);.
string.substring();
methods. This is not a very efficent way but it is a solution.

Categories

Resources