Nested For Loops Dynamic Depth Java - java

Hello I'm new to programming and registered to this forum :)
So I created a little program with nested for loops that prints out all combinations of five numbers which can have a value from 0 to 5. With nested for-loops this works fine. But isn't there a cleaner solution? I tried it with calling the for loop itself, but my brain doesn't get the solution.. :(
//my ugly solution
int store1, store2, store3, store4, store5;
for (int count = 0; count <= 5; count++) {
store1 = count;
for (int count2 = 0; count2 <= 5; count2++) {
store2 = count2;
for (int count3 = 0; count3 <= 5; count3++) {
store3 = count3;
for (int count4 = 0; count4 <= 5; count4++) {
store4 = count4;
System.out
.println(store1 + " " + store2 + " " + store4);
}
//I'm trying around with something like this
void method1() {
for (int count = 0; count <= 5; count++) {
list.get(0).value = count;
count++;
method2();
}
}
void method2() {
for (int count = 0; count <= 5; count++) {
list.get(1).value = count;
count++;
method1();
}
}

Usually when people try to use recursion or functional, using a loop is simpler or faster. However, in this case recursion is the simpler option in combination with a loop.
public static void method(List<Integer> list, int n, int m) {
if (n < 0) {
process(list);
} else {
for(int i = 0; i < m; i++) {
list.set(n, i);
method(list, n-1, m);
}
}
}

I know that you are trying combinations but this might help.
Permutation with repetitions
When you have n things to choose from ... you have n choices each time!
When choosing r of them, the permutations are:
n × n × ... (r times) = n^r
//when n and r are known statically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i = 0, j = 0;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
System.out.println(values[j] + " " + values[i]);
}
}
}
}
//when n and r are known only dynamically
class Permutation
{
public static void main(String[] args)
{
char[] values = {'a', 'b', 'c', 'd'};
int n = values.length;
int r = 2;
int i[] = new int[r];
int rc = 0;
for(int j=0; j<Math.pow(n,r); j++)
{
rc=0;
while(rc<r)
{
System.out.print(values[i[rc]] + " ");
rc++;
}
System.out.println();
rc = 0;
while(rc<r)
{
if(i[rc]<n-1)
{
i[rc]++;
break;
}
else
{
i[rc]=0;
}
rc++;
}
}
}
}

Something like this?
// Print all sequences of len(list)+n numbers that start w/ the sequence in list
void method( list, n ) {
if ( list.length == n )
// print list
else for ( int c=0; c<=5; c++ ) {
// add c to end of list
method( list, n );
// remove c from end of list
}
}
Initial call would be method( list, 5 ) where list is initially empty.

here another interative but less elegant version
while (store1 < 6) {
store5++;
if (store5 == 6) {
store5 = 0;
store4++;
}
if (store4 == 6) {
store4 = 0;
store3++;
}
if (store3 == 6) {
store3 = 0;
store2++;
}
if (store2 == 6) {
store2 = 0;
store1++;
}
System.out.println(store1 + " " + store2 + " " + store3 + " " + store4 + " " + store5 + " ");
}

The simplest code I can think of would tackle the problem with an entirely different approach:
public class TestA {
public static void main(String[] argv) {
for (int i=0; i<(6 * 6 * 6 * 6 * 6); ++i) {
String permutation = Integer.toString(i, 6);
System.out.println("00000".substring(permutation.length()) + permutation);
}
}
}
From your text (not your code) I gather you have 5 places and 6 symbols, which suggests there are 6 to the 5th power combinations. So the code just counts through those numbers and translates the number to the output combination.
Since this can also be viewed as a number system with base 6, it makes use of Integer.toString which already has formatting code (except the leading zeros) for this. Leading zeros are added where missing.

Related

Perfect Numbers in an ArrayList

This is an exercise.
A perfect number is a number whose sum of divisors without itself is equal to that number
6 is a perfect number because its divisors are: 1,2,3,6 and 1 + 2 + 3 = 6
28 is a perfect number because its divisors are: 1,2,4,7,28 and 1 + 2 + 4 + 7 = 28
Task: write the body of findNPerfectNumbers, which will find n prime perfect numbers and return them as a list
I must use this program:
import java.util.ArrayList;
public class Exercise {
public static ArrayList<Integer> findNPerfectNumbers(int n)
{
return new ArrayList<>();
}
public static void main(String[] args)
{
System.out.println(findNPerfectNumbers(4));
}
}
I create this code to resolve this problem, but I have a problem to return an ArrayList. I don't know how. It should look like this example: 6 = 1,2,3,6 ///// 28 = 1, 2, 4, 7
My idea:
import java.util.ArrayList;
public class Main
{
public static ArrayList<Integer> findNPerfectNumbers(int n)
{
int sum = 0;
ArrayList<Integer> perfectList = new ArrayList<>();
ArrayList<Integer> factorList = new ArrayList<>();
for (int i = 6; i < n; i++)
{
factorList.clear();
for (int j = 1; j <= i / 2; j++)
{
if (i % j == 0)
{
factorList.add(j);
}
}
sum = 0;
for (int h = 0; h < factorList.size(); h++)
{
sum = sum + factorList.get(h);
}
if (sum == i)
{
perfectList.add(i);
}
}
return perfectList;
}
public static void main(String[] args)
{
System.out.println(findNPerfectNumbers(28));
}
}
Anyone have an idea?
The question is as simple as to have the findNPerfectNumbers function return the first N perfect numbers.
The main part for the exercise is probably to do this as efficiently as possible. For example limiting divider check by half like you do in for (int j = 1; j <= i / 2; j++) is one of many options.
The reason your function doesn't return anything though is because your outer for loop is incorrect with the given input of 4 what you'r doing is for (int i = 6; i < 4; i++) which doesn't do any loops because 4 is smaller than 6.
what you probably intended to do issomething like for (int i = 6; perfectList.size() < n; i++) which would loop aslong as you have fewer than N perfect numbers.
example working code:
import java.util.ArrayList;
public class Exercise {
public static ArrayList<Integer> findNPerfectNumbers(int n) {
int sum = 0;
ArrayList<Integer> perfectList = new ArrayList<>();
for (int i = 6; perfectList.size() < n; i++) {
ArrayList<Integer> factorList = new ArrayList<>();
for (int j = 1; j <= i / 2; j++) {
if (i % j == 0) {
factorList.add(j);
}
}
sum = 0;
for (Integer factor : factorList) {
sum += factor;
}
if (sum == i) {
System.out.println("Found perfect number " + i + " with factors " + factorList);
perfectList.add(i);
}
}
return perfectList;
}
public static void main(String[] args) {
System.out.println(findNPerfectNumbers(4));
}
}
If number is less than 10^1500 you can use Euclid's method
public static List<Long> findPerfect(int n){
List<Long> perfectList=new ArrayList<>();
int x=0;
long sum=0;
long last;
while(perfectList.size()!=n){
last= (long) Math.pow(2,x);
sum+=last;
if(isPrime(sum))
perfectList.add(sum*last);
x++;
}
return perfectList;
}
public static boolean isPrime(long x){
if(x==1)
return false;
for (int i = 2; i <= Math.sqrt(x); i++) {
if(x%i==0)
return false;
}
return true;
}

UCF HSPT 2016 - Chomp Chomp

I am having a lot of trouble finding an efficient solution to Problem #9 in the UCF HSPT programming competition. The whole pdf can we viewed here, and the problem is called "Chomp Chomp!".
Essentially the problem involves taking 2 "chomps" out of an array, where each chomp is a continuous chain of elements from the array and the 2 chomps have to have at least element between them that's not "chomped." Once the two "chomps" are determined, the sum of all the elements in both "chomps" has to be a multiple of the number given in the input. My solution essentially is a brute-force that goes through every possible "chomp" and I tried to improve the speed of it by storing previously calculated sums of chomps.
My code:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class chomp {
static long[] arr;
public static long sum(int start, int end) {
long ret = 0;
for(int i = start; i < end; i++) {
ret+=arr[i];
}
return ret;
}
public static int sumArray(int[] arr) {
int sum = 0;
for(int i = 0; i < arr.length; i++) {
sum+=arr[i];
}
return sum;
}
public static long numChomps(long[] arr, long divide) {
HashMap<String, Long> map = new HashMap<>();
int k = 1;
long numchomps = 0;
while(true) {
if (k > arr.length-2) break;
for (int i = 0; i < arr.length -2; i++) {
if ((i+k)>arr.length-2) break;
String one = i + "";
String two = (i+k) + "";
String key1 = one + " " + two;
long first = 0;
if(map.containsKey(key1)) {
//System.out.println("Key 1 found!");
first = map.get(key1).longValue();
} else {
first = sum(i, i+k);
map.put(key1, new Long(first));
}
int kk = 1;
while(true){
if (kk > arr.length-2) break;
for (int j = i+k+1; j < arr.length; j++) {
if((j+kk) > arr.length) break;
String o = j + "";
String t = (j+kk) + "";
String key2 = o + " " + t;
long last = 0;
if(map.containsKey(key2)) {
//System.out.println("Key 2 found!");
last = map.get(key2).longValue();
} else {
last = sum(j, j+kk);
map.put(key2, new Long(last));
}
if (((first+last) % divide) == 0) {
numchomps++;
}
}
kk++;
}
}
k++;
}
return numchomps;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
for(int i = 1; i <= n; i++) {
int length = in.nextInt();
long divide = in.nextLong();
in.nextLine();
arr = new long[length];
for(int j = 0; j < length; j++) {
arr[j] = (in.nextLong());
}
//System.out.println(arr);
in.nextLine();
long blah = numChomps(arr, divide);
System.out.println("Plate #"+i + ": " + blah);
}
}
}
My code gets the right answer, but seems to take too long, especially for large inputs when the size of the array is 1000 or greater. I tried to improve the speed of my algorithm my storing previous sums calculated in a HashMap, but that didn't improve the speed of my program considerably. What can I do to improve the speed so it runs under 10 seconds?
The first source of inefficiency is constant recalculation of sums. You should make an auxiliary array of partial sums long [n] partial;, then instead of calling sum(i, i + k) you may simply do partial[i + k] - partial[i].
Now the problem reduces to finding indices i<j<k<m such that
(partial[j] - partial[i] + partial[m] - partial[k]) % divide == 0
or, rearranging terms,
(partial[j] + partial[m]) % divide == (partial[i] + partial[k]) % divide
To find them you may consider an array of triples (s, i, j) where s = (partial[j] - partial[i]) % divide, stable sort it by s, and inspect equal ranges for non-overlapping "chomps".
This approach improves performance from O(n4) to O(n2 log n). Now you shall be able to improve it to O(n log n).

drawing Diamond of numbers with 2D array in java

So I need to make a diamond_look of numbers using 2D array in Java. I got my results but with null before the diamond. For drawNumDiamond(9) I have to get a diamond look that goes until 5 and back. I know I can make it without using array, but I want to learn more about 2D arrays :this is how it should look like and what are my results
public class Example1{
private static void drawNumDiamond(int h) {
if(h%2 != 0) {
int size = h/2 +1;
int count = 1;
int loop = 1;
String[][] dijamant = new String[h][];
for(int row = 0; row < dijamant.length; row++) {
dijamant[row] = new String[row+1];
for(int kolona=0; kolona<=row; kolona++) {
dijamant[0][0] = "1";
for(int i=0; i< loop;i++) {
dijamant[row][kolona]+= count;
}
}
count++;
loop+=2;
}
for (int k = 0; k < size; k++) {
System.out.printf("%" + h + "s", dijamant[k]);
h++;
System.out.println();
}
h--;
for (int q = size - 2; q>=0; q--) {
h--;
System.out.printf("%" + h + "s", dijamant[q]);
System.out.println();
}
}
}
public static void main(String[] args) {
drawNumDiamond(9);
}
}
The issue is in this line :
dijamant[row][kolona] += count;
if dijamant[row][kolona] is null and count is 2, the result of the string concatenation will be "null2". Try adding the following if statement before to initialize with an empty string :
if (dijamant[row][kolona] == null) {
dijamant[row][kolona] = "";
}
This will get your code working, but there are still things to think about. E.g. you keep setting dijamant[0][0] = "1"; in the loop.

Sum odd numbers from a given range[a,b]?

I was practicing with some exercises from UVA Online Judge, I tried to do the Odd sum which basically is given a range[a,b], calcule the sum of all odd numbers from a to b.
I wrote the code but for some reason I don't understand I'm getting 891896832 as result when the range is [1,2] and based on the algorithm it should be 1, isn't it?
import java.util.Scanner;
public class OddSum
{
static Scanner teclado = new Scanner(System.in);
public static void main(String[] args)
{
int T = teclado.nextInt();
int[] array = new int[T];
for(int i = 0; i < array.length; i++)
{
System.out.println("Case "+(i+1)+": "+sum());
}
}
public static int sum()
{
int a=teclado.nextInt();
int b = teclado.nextInt();
int array[] = new int[1000000];
for (int i = 0; i < array.length; i++)
{
if(a%2!=0)
{
array[i]=a;
if(array[i]==(b))
{
break;
}
}
a++;
}
int res=0;
for (int i = 0; i < array.length; i++)
{
if(array[i]==1 && array[2]==0)
{
return 1;
}
else
{
res = res + array[i];
}
}
return res;
}
}
Your stopping condition is only ever checked when your interval's high end is odd.
Move
if (array[i] == (b)) {
break;
}
out of the if(a % 2 != 0) clause.
In general, I don't think you need an array, just sum the odd values in your loop instead of adding them to the array.
Keep it as simple as possible by simply keeping track of the sum along the way, as opposed to storing anything in an array. Use a for-loop and add the index to the sum if the index is an odd number:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter minimum range value: ");
int min = keyboard.nextInt();
System.out.println("Enter maximum range value: ");
int max = keyboard.nextInt();
int sum = 0;
for(int i = min; i < max; i++) {
if(i % 2 != 0) {
sum += i;
}
}
System.out.println("The sum of the odd numbers from " + min + " to " + max + " are " + sum);
}
I don't have Java installed right now, however a simple C# equivalent is as follows: (assign any values in a and b)
int a = 0;
int b = 10;
int result = 0;
for (int counter = a; counter <= b; counter++)
{
if ((counter % 2) != 0) // is odd
{
result += counter;
}
}
System.out.println("Sum: " + result);
No major dramas, simple n clean.

Print a pattern sequence of numbers in Java

I need to write a method called printOnLines() that takes two arguments an integer n and an integer inLine and prints the n integer, every inLine on a line.
for n = 10, inLine = 3:
1, 2, 3
4, 5, 6
7, 8, 9
10
My call is (10,3). Here's my code:
public static void printOnLines(int n, int s) {
for(int i=1; i<=s; i++) {
for(int j=1; j<=n-1; j++) {
System.out.print(j + ", ");
}
System.out.println();
}
}
}
I believe that there are two mistakes:
I need to remove the last comma appearing in the output.
I need to place 3 of the numbers of each line until I reach the
number 10.
Use this:
public static void printOnLines(int n, int s){
StringBuilder builder = new StringBuilder();
for(int i = 1; i <= n; i++){
builder.append(i);
if(i % s == 0)builder.append("\n");
else builder.append(", ");
}
System.out.println(builder.toString().substring(0,builder.toString().length() - 2));
}
I assume you've already had to submit your homework, so here's how I'd do it:
class printonlines {
public static void main(String[] args) {
printOnLines(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
public static void printOnLines(int n, int s) {
for(int i=1; i<=n; i++) { // do this loop n times
if ( (i != 1) && (i-1)%s == 0 ) { // if i is exactly divisible by s, but not the first time
System.out.println(); // print a new line
}
System.out.print(i);
if (i != n) { // don't print the comma on the last one
System.out.print(", ");
}
}
}
}
Oh, you don't want to use any if statements. All you really learn from doing "tricks" like what you are asked to do is a single trick, not how to write easily comprehensible (even by yourself when you have to debug later) code.
Anyway, here's my less comprehensible but more tricky code that doesn't use if as per the suggestions from the answer from #DavidWallace. I'm sure someone can do it neater but this is the best I could do in 15 minutes...
class printonlineswithnoifs {
public static void main(String[] args) {
printOnLines(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
// i 012012012
// j 000333666
// i+j 012345678
public static void printOnLines(int n, int s) {
int i = 0;
int j = 1;
for (; j <= n; j+=s) {
for (; i < (s-1) && (j+i)<n; i++) {
System.out.print((i+j) + ", ");
}
System.out.println(i+j);
i=0;
}
}
}
I'm not going to post a complete solution, since this is clearly homework. But here is what I would do, if I weren't allowed to use if statements or ternary operators.
Make the index of the outer loop start at 0 and increase by s on every iteration, instead of by 1 (So it goes 0, 3, 6, 9 in your example).
Print the sum of the two loop indexes on each iteration.
Print the last number on each line outside of the inner loop, without a comma.
Edit
OK, on #localhost's request, here is my solution.
public static void printOnLines(int n, int s) {
for (int i = 0; i < n; i += s) {
int j;
for (j = 1; j < s && i + j < n; j++) {
System.out.print(i + j + ", ");
}
System.out.println(i + j);
}
}
Here is the code sample you wanted..
public static void printOnLines(int n, int s) {
for (int i = 1; i < n; i++) {
System.out.print(i + ",\t");
if (i % 3 == 0) System.out.println();
}
System.out.println(n);
}

Categories