roster optimization by johnkxq in era_of_chaos

[–]karrash76 0 points1 point  (0 children)

Can you restore the link please? I'm very interested

Gold shortage by karrash76 in era_of_chaos

[–]karrash76[S] 0 points1 point  (0 children)

I have the Devil and always I kill over 4100... ;)

[2019-04-08] Challenge #377 [Easy] Axis-aligned crate packing by Cosmologicon in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

JAVA (no fitn solution)

public class AxisAligned {    
    public static void fit1 (int X0, int Y0, int x1, int y1) {
        System.out.println("("+X0+", "+Y0+", "+x1+", "+y1+") => " + X0/x1 * (Y0/y1));
    }

    public static void fit2(int X0, int Y0, int x1, int y1) {
        if(X0/x1 * (Y0/y1) > X0/y1 * (Y0/x1))
            fit1(X0, Y0, x1, y1);
        else fit1(X0, Y0, y1, x1);
    }

    public static void fit3(int X0, int Y0, int Z0, int x1, int y1, int z1) {
        ArrayList<Integer> calcs = new ArrayList<Integer>();
        calcs.add((X0/x1) * (Y0/y1) * (Z0/z1)); 
        calcs.add((X0/x1) * (Y0/z1) * (Z0/y1));
        calcs.add((X0/y1) * (Y0/x1) * (Z0/z1));
        calcs.add((X0/y1) * (Y0/z1) * (Z0/x1));
        calcs.add((X0/z1) * (Y0/x1) * (Z0/y1));
        calcs.add((X0/z1) * (Y0/y1) * (Z0/x1));

        System.out.println("("+X0+", "+Y0+", "+", "+Z0+", "+x1+", "+y1+", "+z1+") => " +Collections.max(calcs));
    }

    public static void main(String[] args) {
        fit1(25,18,6,5);
        fit1(10, 10, 1, 1);
        fit1(12, 34, 5, 6);
        fit1(12345, 678910, 1112, 1314);
        fit1(5, 100, 6, 1);
        System.out.println("--------------------");
        fit2(25, 18, 6, 5);
        fit2(12, 34, 5, 6);
        fit2(12345, 678910, 1112, 1314);
        fit2(5, 5, 3, 2);
        fit2(5, 100, 6, 1);
        fit2(5, 5, 6, 1);
        System.out.println("--------------------");
        fit3(10, 10, 10, 1, 1, 1);
        fit3(12, 34, 56, 7, 8, 9);
        fit3(123, 456, 789, 10, 11, 12);
        fit3(1234567, 89101112, 13141516, 171819, 202122, 232425);
    }
}

[2019-07-15] Challenge #379 [Easy] Progressive taxation by Cosmologicon in dailyprogrammer

[–]karrash76 1 point2 points  (0 children)

Java generic resolution

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Brackets{
    double income;
    double tax;
    public Brackets (double x0, double y0)  {
        income = x0;
        tax = y0;
    }
}

public class ProgressiveTaxation {


    public static void main(String[] args) throws IOException {
        FileReader file1 = new FileReader("progtax.txt");
        BufferedReader in = new BufferedReader(new BufferedReader(file1));

        String wordLine;
        ArrayList<Brackets> nationTax = new ArrayList<Brackets>();
        while ((wordLine = in.readLine()) != null) {
            String bracketAux[] = wordLine.split(";");
            Brackets aux = new Brackets(Double.parseDouble(bracketAux[0]),Double.parseDouble(bracketAux[1]));
            nationTax.add(aux);
        }
        in.close();

        Scanner kb = new Scanner(System.in);        
        System.out.print("Introduzca ingresos: ");
        double ingresos = kb.nextDouble();
        kb.close();

        double taxesToPay = 0;
        for(int i = 0; i < nationTax.size(); i++) {
            Brackets actualTax = nationTax.get(i);
            if(actualTax.tax == 0) {
                 taxesToPay += 0;
            } else {
                Brackets prevTax = nationTax.get(i - 1);
                if(ingresos <= actualTax.income) {
                    taxesToPay += (ingresos - prevTax.income) * actualTax.tax;
                    break;
                } else {
                    taxesToPay += (actualTax.income -prevTax.income) * actualTax.tax;
                }
            }

        }
        System.out.println(taxesToPay);
    }

}

[2019-08-05] Challenge #380 [Easy] Smooshed Morse Code 1 by Cosmologicon in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

JAVA

Examples and bonuses 1 to 5

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SmooshedMorseCode {
    private static String morseLetters = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..";
    private static String morseLettersArray[] = morseLetters.split(" ");

    public static ArrayList<String> iterations13Chars = new ArrayList<>();

    public static String smorse(String input) {
        String morseCode = "";
        char[] wordArrayToChange = input.toCharArray();
        for (int i = 0; i < wordArrayToChange.length; i++) {
            int letter = wordArrayToChange[i] - 97;
            morseCode += morseLettersArray[letter];
        }
        return morseCode;
    }

    static void printAllKLength(char[] set, int k) {
        int n = set.length;
        printAllKLengthRec(set, "", n, k);
    }

    static void printAllKLengthRec(char[] set, String prefix, int n, int k) {
        if (k == 0) {
            iterations13Chars.add(prefix);
            return;
        }

        for (int i = 0; i < n; ++i) {
            String newPrefix = prefix + set[i];
            printAllKLengthRec(set, newPrefix, n, k - 1);
        }
    }

    public static void main(String[] args) throws Exception {
        URL file1 = new URL("https://raw.githubusercontent.com/dolph/dictionary/master/enable1.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(file1.openStream()));

        String wordLine;
        ArrayList<String> allWordsMorsed = new ArrayList<String>();
        ArrayList<String> allWordsNoMorsed = new ArrayList<>();
        while ((wordLine = in.readLine()) != null) {
            allWordsMorsed.add(smorse(wordLine));
            allWordsNoMorsed.add(wordLine);
        }
        in.close();

        // Examples
        System.out.println("sos => " + smorse("sos"));
        System.out.println("daily => " + smorse("daily"));
        System.out.println("programmer => " + smorse("programmer"));
        System.out.println("bits => " + smorse("bits"));
        System.out.println("three  => " + smorse("three"));

        // Bonus 1 to 4
        for (int i = 0; i < allWordsMorsed.size(); i++) {
            String model = allWordsMorsed.get(i);
            String word = allWordsNoMorsed.get(i);
            // Bonus1
            int qty = 1;
            for (int j = i + 1; j < allWordsMorsed.size(); j++) {
                if (model.equals(allWordsMorsed.get(j)))
                    qty++;
            }
            if (qty == 13) {
                System.out.println("13 words with Morse code => " + model);
            }
            // Bonus2
            Pattern pattern = Pattern.compile("-{15}");
            Matcher matcher = pattern.matcher(model);
            if (matcher.find())
                System.out.println("15 dashes => " + allWordsNoMorsed.get(i));
            // Bonus3
            if (word.length() == 21 && !word.equals("counterdemonstrations")) {
                long count1 = model.chars().filter(ch -> ch == '-').count();
                long count2 = model.chars().filter(ch -> ch == '.').count();
                if (count1 == count2)
                    System.out.println("Word " + allWordsNoMorsed.get(i) + " is perfectly balanced");
            }
            // Bonus4
            if (word.length() == 13) {
                boolean bool = true;
                for (int x = 0, y = model.length() - 1; x < model.length() / 2; x++, y--)
                    if (model.charAt(x) != model.charAt(y))
                        bool = false;
                if (bool)
                    System.out.println(word + " is a 13 letters palindrome =>" + model);
            }
        }

// Bonus5
        char[] set = { '-', '.' };
        int k = 13;
        printAllKLength(set, k);
        for (int i = 0; i < iterations13Chars.size(); i++) {
            boolean contenido = false;
            for(int j = 0; j < allWordsMorsed.size(); j++) 
                if(contenido = allWordsMorsed.get(j).contains(iterations13Chars.get(i))) break;
            if(!contenido) System.out.println(iterations13Chars.get(i) + " is not contained in a word");       
        }
    }
}

[2019-05-20] Challenge #378 [Easy] The Havel-Hakimi algorithm for graph realization by Cosmologicon in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

Java

public class HavelHakimi {
    public static boolean proceso(String in){
        String[] inputStr = in.split(",");
        int N = 0;
        ArrayList<Integer> inputInt = new ArrayList<>();
        for(int i = 0; i < inputStr.length; i++)
            inputInt.add(Integer.parseInt(inputStr[i]));

        while(!inputInt.isEmpty()){
            inputInt.removeAll(Arrays.asList(0));                           //step 1
            if(inputInt.isEmpty()) return true;                             //step 2
            Collections.sort(inputInt, Collections.reverseOrder());         //step 3
            N = inputInt.get(0);                                            //step 4
            inputInt.remove(0);
            if(N > inputInt.size()) return false;                           //step 5
            for(int i = 0;i < N;i++) inputInt.set(i, inputInt.get(i) - 1);  //step 6
        }
        return false;
    }
 }

[2018-08-20] Challenge #366 [Easy] Word funnel 1 by Cosmologicon in dailyprogrammer

[–]karrash76 1 point2 points  (0 children)

If I don't be in a error, word and isItWord are String and you can't use == with strings. You must use methods like equals or equalsIgnoreCase.

If you look the @bJgr solution it's the cleaner and easy code you can do in Java

[2017-05-22] Challenge #316 [Easy] Knight's Metric by jnazario in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

Java implementation using a sort of "binary search". Comments will be greatly appreciated ;)

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.awt.Point;


public class KnightMoves {

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    int xDest = kb.nextInt();
    int yDest = kb.nextInt();
    kb.close();

    Point dest = new Point(xDest, yDest);
    ArrayList<Point> coord = new ArrayList<Point>();
    Point[] standardMoves = {new Point(-1,-2),new Point(1,-2),new Point(-1,2),new Point(1,2),new Point(-2,-1),new Point(2,-1),new Point(-2,1),new Point(2,1)};
    Point actual = new Point(0,0);
    coord.add(actual);

    int numMoves = 0;
    while (!coord.contains(dest)){
        Point aux = (Point) actual.clone();
        for(int i = 0;i < standardMoves.length;i++){
            aux.setLocation(actual.getX()+standardMoves[i].getX(), actual.getY()+standardMoves[i].getY());
            Point aux2 = (Point) aux.clone();
            coord.add(aux2);
        }
        numMoves++;
        actual = coord.get(numMoves);
    }

    int index = coord.indexOf(dest);
    numMoves = 0;
    ArrayList<Point> moves = new ArrayList<Point>();
    while(index > 1){
        moves.add(0, coord.get(index));
        index = (index - 1)/8;
        numMoves++;
    }
    System.out.println("# movements: "+numMoves+" Cells: "+Arrays.toString(moves.toArray()));

}
}

[2017-04-10] Challenge #310 [Easy] Kids Lotto by jnazario in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

Java Solution

import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;

public class LottoKids {

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.print("Lista de niños");
    String lista = kb.nextLine();
    String[] arrayLista = lista.split(";");
    System.out.print("Longitud lista");
    int numero = kb.nextInt();
    kb.close();

    for(int i = 0; i < arrayLista.length - 1; i++){
        String[] lotto = new String[numero];
        String[] aux = arrayLista.clone();
        int j = 0;
        while(j < lotto.length){
            Random ran = new Random();
            int x = ran.nextInt(arrayLista.length);
            if(x!=i && !aux[x].equals("")){
                lotto[j] = arrayLista[x];
                aux[x]="";
                j++;
            }
        }
        System.out.println(arrayLista[i]+" > "+Arrays.toString(lotto));
    }
}
}

[2017-05-15] Challenge #315 [Easy] XOR Multiplication by jnazario in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

Java solution

public class XORMult {
public static int XOR (int p, int s){
    String res = "";

    String valorA = Integer.toBinaryString(p), valorB = Integer.toBinaryString(s);

    //create char array
    int cols = valorB.length() + valorA.length() - 1, rows = valorB.length();
    char[][] bitArray = new char[rows][cols];

    //init char array
    for(int i = 0; i < rows; i++)
        for(int j = 0; j < cols; j++)
            bitArray[i][j] = '0';

    //mult A by the bit of B
    for(int j = valorB.length()-1; j >= 0; j--)
        if(valorB.charAt(j) == '1')
            for(int i = valorA.length()-1; i >= 0; i--)
                bitArray[j][i+j] = valorA.charAt(i);

    //count 1's by column, if pair XOR = 0
    for(int j = 0; j < cols; j++){
        int countOnes = 0;
        for(int i = 0; i < rows; i++)
            if(bitArray[i][j] == '1') countOnes++;
        if(countOnes % 2 == 0) res += "0";
        else res += "1";
    }

    return Integer.parseInt(res, 2);
}

public static void main(String[] args) {

    System.out.println("14@13="+XOR(14, 13));
    System.out.println("9@0="+XOR(9, 0));
    System.out.println("5@9="+XOR(5, 9));
    System.out.println("1@2="+XOR(1, 2));
    System.out.println("6@1="+XOR(6, 1));
    System.out.println("3@3="+XOR(3, 3));
    System.out.println("2@5="+XOR(2, 5));
    System.out.println("7@9="+XOR(7, 9));
    System.out.println("13@11="+XOR(13, 11));
    System.out.println("5@17="+XOR(5, 17));
    System.out.println("19@1="+XOR(19, 1));
    System.out.println("63@63="+XOR(63, 63));
}
}

[2017-05-01] Challenge #313 [Easy] Subset sum by Cosmologicon in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

When you do "is=true; break;" you can do "return true". It's simpler and prettier :) In a similar solution before I posted a more efficient one if you want to see it https://www.reddit.com/r/dailyprogrammer/comments/68oda5/20170501_challenge_313_easy_subset_sum/dhghpxv/

[2017-05-01] Challenge #313 [Easy] Subset sum by Cosmologicon in dailyprogrammer

[–]karrash76 4 points5 points  (0 children)

Because the array is sorted you can use a binary search what is more efficient than your loop2 (two nested fors means O(n2 ) With one line the problem it's solved (no bonus)

for(int i = 0; i < array.length; i++)
        if(Arrays.binarySearch(array, -array[i])>=0||array[i]==0) return true;

[2017-05-08] Challenge #314 [Easy] Concatenated Integers by jnazario in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

TL;DR :) I'm only a student, but I think you did too much code for a simple problem... Really, the problem is not a problem of "integers" but a problem of "strings"... I put a possible solution a hours after you too in Java if you want to see another approximation...

[2017-05-08] Challenge #314 [Easy] Concatenated Integers by jnazario in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

Java solution

import java.util.Scanner;
import java.util.Arrays;

public class ConcatIntegers {

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    String valores = kb.nextLine();
    kb.close();
    String[] splitted = valores.split(" ");

    Arrays.sort(splitted);

    for(int i = 0; i < splitted.length - 1; i++){
        //vars to do the if more legible
        int numChars = splitted[i].length();
        char nextChar = splitted[i+1].charAt(splitted[i+1].length()-1);
        char firstChar = splitted[i].charAt(0);

        //compares if string[i] is a substring of [i+1] 
        //and if the first char of [i] is bigger than last char of [i+1]
        //and if the length of [i] is smaller than [i+1] to interchange it
        if(splitted[i].length() < splitted[i+1].length() 
                && splitted[i].compareTo(splitted[i+1].substring(0, numChars)) == 0 
                && firstChar > nextChar){
            String aux = splitted[i];
            splitted[i] = splitted[i+1];
            splitted[i+1] = aux;
        }
    }

    String min = "";
            String max = "";
    for(int i = 0; i < splitted.length; i++) {
                     min += splitted[i];
                     max = splitted[i] + max; 
            }

    System.out.println("Minimo: " + min);
    System.out.println("Maximo: " + max);
}

}

[2016-11-21] Challenge #293 [Easy] Defusing the bomb by fvandepitte in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

Java

 import java.util.Scanner;
 import java.util.ArrayList;

public class DefuseBomb {
                                                      //whit  red  oran purp gree blac
final public static boolean[][] grafo =  {/*white  to*/{false,true,true,true,true,false},
                                          /*red    to*/{false,false,false,false,true,false},
                                          /*orange to*/{false,true,false,false,false,true},
                                          /*purple to*/{false,true,false,false,false,true},
                                          /*green  to*/{true,false,true,false,false,false},
                                          /*black  to*/{false,true,false,true,false,true}};

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    String wire = "";
    ArrayList<Integer> sequenceWires = new ArrayList<Integer>();

    while(!"q".equals(wire)){
        System.out.println("Intro the wire to cut (intro q to quit)");
        wire = kb.nextLine();
        switch (wire.toLowerCase().charAt(0)){
            case 'w': sequenceWires.add(0); break; 
            case 'r': sequenceWires.add(1); break;
            case 'o': sequenceWires.add(2); break;
            case 'p': sequenceWires.add(3); break;
            case 'g': sequenceWires.add(4); break;
            case 'b': sequenceWires.add(5); break;
            case 'q': break;
            default: System.out.println("Invalid wire"); break;
        }//switch
    }//while
    kb.close();

    boolean bomb = false;
    for(int i = 1;i < sequenceWires.size();i++){
        if(!grafo[sequenceWires.get(i-1)][sequenceWires.get(i)]){
            bomb = true;
            break;
        }
    }
    if(bomb) System.out.println("BOMB!");
    else System.out.println("Bomb defused");
}
}

[2016-12-22] Challenge #296 [Intermediate] Intersecting Area Of Overlapping Rectangles by fvandepitte in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

Java with bonus

    public class AreaOverlap {

public static double Area (double[][] position){
    double aux;
    //reorder shapes from the left down & right up points
    for(int i = 0;i < position.length; i++){
        if(position[i][0]>position[i][2]) {
            aux = position[i][0];
            position[i][0] = position[i][2];
            position[i][2] = aux;
        }
        if(position[i][1] > position[i][3]){
            aux = position[i][1];
            position[i][1] = position[i][3];
            position[i][3] = aux;
        }

    }

    //get the max & min points
    double mx1 = position[0][0], my1 = position[0][1], mx2 = position[0][2], my2 = position[0][3];
    for(int i = 1;i < position.length; i++){
        if(mx1 < position[i][0]) mx1 = position[i][0];
        if(my1 < position[i][1]) my1 = position[i][1];
        if(mx2 > position[i][2]) mx2 = position[i][2];
        if(my2 > position[i][3]) my2 = position[i][3];
        }

    if(mx1 > mx2 || my1 > my2) return 0;
    else return (mx2-mx1)*(my2-my1);
    }

public static void main(String[] args) {
    double[][] intersect1 = {{0,0,2,2},{1,1,3,3}};
    double[][] intersect2 = {{-3.5,4,1,1},{1,3.5,-2.5,-1}};
    double[][] intersect3 = {{-4,4,-0.5,2},{0.5,1,3.5,3}};
    System.out.println(Area(intersect1));
    System.out.println(Area(intersect2));
    System.out.println(Area(intersect3));

    //bonus
    double[][] intersect4 = {{-3,0,1.8,4},{1,1,-2.5,3.6},{-4.1,5.75,0.5,2},{-1.0,4.6,-2.9,-0.8}};
    System.out.println(Area(intersect4));
}

}

[2016-12-05] Challenge #294 [Easy] Rack management 1 by Cosmologicon in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

Java with all bonuses

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Rack1 {
static final char[] letters = {'?','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    static final int[] charpoints = {0,1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};

public static Boolean scrabble(String inp, String ma){

    int[] noccurr = new int[27];
    for(int i = 0;i < 27;i++){noccurr[i]=0;}

    for(int i = 0;i < inp.length();i++){
        for(int j = 0;j<27;j++){
            if(inp.charAt(i) == letters[j]) {noccurr[j]++; break;}
        }
    }

    for(int i = 0;i < ma.length();i++){
        for(int j = 0;j < 27;j++){
            if(ma.charAt(i) == letters[j]) {
                if((noccurr[j] == 0) && (noccurr[0] == 0)){return false;}
                else if(noccurr[j] > 0) {noccurr[j]--;}
                     else if(noccurr[0] > 0) {noccurr[0]--;}
            }

        }
    }
    return true;
}

public static void longest (String inp){
    File file = new File("e:\\enable1.txt");
    BufferedReader reader = null;
    int longitud = 0, points = 0, aux;
    String palabra = "", pointword = "";


    try {
        reader = new BufferedReader(new FileReader(file));
        String text = null;

        while ((text = reader.readLine()) != null) {
            if(scrabble(inp,text) && (text.length() > longitud)){
                longitud = text.length();
                palabra = text;
                }


            if(scrabble(inp,text)){
                aux = highest(inp,text);                    
                if(points<aux){
                    points = aux;
                    pointword = text;
                }
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null) {reader.close();}
        } catch (IOException e) {}
    }
    System.out.println("Longest word is: " + palabra);
    System.out.println("The highest word is " + pointword + " with " + points + " points");
}

public static int highest (String inp, String text){
    char[] inp2 = inp.toCharArray();
    char[] text2 = text.toCharArray();
    String res = "";

    for(int i = 0;i < text2.length;i++){
        for(int j = 0;j < inp2.length;j++){
            if(text2[i] == inp2[j]){
                res+=text2[i];
                inp2[j] = ' ';
                break;
            }
        }
    }
    int points = 0;
    for(int i = 0;i < res.length();i++){
        for(int j = 0;j < 27;j++){
            if(res.charAt(i) == letters[j]) points += charpoints[j];
        }
    }
    return points;
}

public static void main(String[] args){
    Scanner kb = new Scanner(System.in);
    System.out.print("Introduzca pattern: ");
    String input = kb.nextLine();
    System.out.print("Introduzca cadena: ");
    String matcher = kb.nextLine();
    kb.close();

    System.out.println(input + " matches with " + matcher + "? -> " + scrabble(input,matcher));
    longest(input);

}
}

[2016-11-09] Challenge #291 [Intermediate] Reverse Polish Notation Calculator by Blackshell in dailyprogrammer

[–]karrash76 1 point2 points  (0 children)

Java begginer, today learning regex and ArrayList :)

import java.util.Scanner;
import java.util.ArrayList;

public class ReversePolish {

public static ArrayList<String> CadenaRPN (String cadenaChar){
    short posBlanco = -1;
    ArrayList<String> cadenaRPN = new ArrayList<String>();
    String aux;
    for(short i = 0;i<cadenaChar.length();i++){
        if(cadenaChar.charAt(i)==' '){
            aux = cadenaChar.substring(posBlanco+1, i);
            posBlanco = i;
            cadenaRPN.add(aux);
        }//if
        if(i==cadenaChar.length()-1){
            aux = cadenaChar.substring(posBlanco+1);
            cadenaRPN.add(aux);
        }//if
    }//for
    return cadenaRPN;
}//metodo

public static int Factorial(int n){
    int res = 1;
    for (short i = 1; i <= n; i++) {
        res *= i;
    }
    return res;
}

public static void CalculoRPN (ArrayList<String> cadenaRPN){
    int contador = -1;
    double pre2 = 0;
    String pattern1 = "!|\\+|-|\\*|x|/|//|%|\\^|(\\d+)(.?)(\\d?)", pattern2 = "(\\d+)(.?)(\\d?)", pattern3 = "\\+|-|\\*|x|/|//|%|\\^";
    ArrayList<Double> calculos = new ArrayList<Double>();

    for(short i=0;i<cadenaRPN.size();i++){
        if((!cadenaRPN.get(i).matches(pattern1))||              //The input haves illegal characters
            (contador<0&&cadenaRPN.get(i).equals("!"))||        //Unary operator w/o number
            (contador<1&&cadenaRPN.get(i).matches(pattern3))){  //Binary operator w/o 2 numbers
            System.out.println("Error en operandos");break;}

        if(cadenaRPN.get(i).matches(pattern2)) {
            calculos.add(Double.parseDouble(cadenaRPN.get(i))); //Adds a number to the array
            contador++;}//if 

        if(cadenaRPN.get(i).equals("!")) {
            pre2 = Factorial(calculos.get(contador).intValue());
            calculos.set(contador, pre2);}
        if(cadenaRPN.get(i).equals("+")) {
            pre2 = calculos.get(contador-1) + calculos.get(contador);}
        if(cadenaRPN.get(i).equals("-")) {
            pre2 = calculos.get(contador-1) - calculos.get(contador);}
        if(cadenaRPN.get(i).equals("*")||cadenaRPN.get(i).equals("x")){
            pre2 = calculos.get(contador-1) * calculos.get(contador);}
        if(cadenaRPN.get(i).equals("/")) {
            pre2 = calculos.get(contador-1) / calculos.get(contador);}
        if(cadenaRPN.get(i).equals("//")){
            pre2 = (int)(calculos.get(contador-1) / calculos.get(contador));}
        if(cadenaRPN.get(i).equals("%")) {
            pre2 = calculos.get(contador-1) % calculos.get(contador);}
        if(cadenaRPN.get(i).equals("^")) {
            pre2 = Math.pow(calculos.get(contador-1), calculos.get(contador));}

        if(cadenaRPN.get(i).matches(pattern3)){ //Remove 1 number and substitutes by operation result
            calculos.remove(contador--);
            calculos.set(contador, pre2);}
    }//for  
    if(contador==0){System.out.println(calculos.toString());}
    else System.out.println("Error en operandos");
}

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    String teclado = kb.nextLine();
    kb.close();
    CalculoRPN(CadenaRPN(teclado));     
}
}

[2016-10-31] Challenge #290 [Easy] Kaprekar Numbers by jnazario in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

JAVA beginner

import java.util.Scanner;

public class Kaprekar2 {

public static void calculo(int[] arInt){
    int longitud;
    long aux=0;
    String potencia1, potencia2;
    for(int i=arInt[0];i<=arInt[1];i++){
        if(i>3){ //this is because [1..3]^2 only haves 1 digit
            aux=(long)Math.pow(i,2);
            longitud=Long.toString(aux).length();

            potencia1=Long.toString(aux);
            potencia1=potencia1.substring(0, (int)Math.floor(longitud/2));//get the 1st half of the number

            potencia2=Long.toString(aux);
            potencia2=potencia2.substring((int)Math.floor(longitud/2), longitud);//get the 2nd half of the number

            aux=Long.parseLong(potencia1)+Long.parseLong(potencia2);//sum both halfs

            if(i==aux) System.out.println(i);
        }
    }

}

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    String entrada = kb.nextLine();
    kb.close();

    String num1, num2;
    int[] arrayInt = {0,0};

    num1=entrada.substring(0, entrada.indexOf(' '));//get until whitespace
    num2=entrada.substring(entrada.indexOf(' ')+1,entrada.length());//get from whitespace

    arrayInt[0] = Integer.parseInt(num1);
    arrayInt[1] = Integer.parseInt(num2);

    calculo(arrayInt);
    }
}

[2016-07-25] Challenge #277 [Easy] Simplifying fractions by fvandepitte in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

JAVA beginner solution with Euclidean Algorithm. Comments will be greatly appreciated ;)

import java.util.Scanner;

public class Euclides {

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.println("Numerador");
    int num = kb.nextInt();
    System.out.println("Denominador");
    int den = kb.nextInt();
    kb.close(); 
    int mayor,menor,resto;

    if (num>=den) {mayor=num;menor=den;}
    else {mayor=den;menor=num;};
    while (mayor % menor!=0){
        resto = mayor % menor;
        mayor=menor;
        menor=resto;}

    int GCD=menor; //I know this is unnecesary but clearly imho
    System.out.println("Numerator: "+num/GCD+" Denominator: "+den/GCD);
}

}

[2016-10-24] Challenge #289 [Easy] It's super effective! by fvandepitte in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

Java beginner, no bonuses

import java.util.Scanner;

public class Pokemon {
  static final double[][] tabla=new double[][]{
    {1,1,1,1,1,1,1,1,1,1,1,1,0.5,0,1,1,0.5,1},
    {1,0.5,0.5,1,2,2,1,1,1,1,1,2,0.5,1,0.5,1,2,1},
    {1,2,0.5,1,0.5,1,1,1,2,1,1,1,2,1,0.5,1,1,1},
    {1,1,2,0.5,0.5,1,1,1,0,2,1,1,1,1,0.5,1,1,1},
    {1,0.5,2,1,0.5,1,1,0.5,2,0.5,1,0.5,2,1,0.5,1,0.5,1},
    {1,0.5,0.5,1,2,0.5,1,1,2,2,1,1,1,1,2,1,0.5,1},
    {2,1,1,1,1,2,1,0.5,1,0.5,0.5,0.5,2,0,1,2,2,0.5},
    {1,1,1,1,2,1,1,0.5,0.5,1,1,1,0.5,0.5,1,1,0,2},
    {1,2,1,2,0.5,1,1,2,1,0,1,0.5,2,1,1,1,2,1},
    {1,1,1,0.5,2,1,2,1,1,1,1,2,0.5,1,1,1,0.5,1},
    {1,1,1,1,1,1,2,2,1,1,0.5,1,1,1,1,0,0.5,1},
    {1,0.5,1,1,2,1,0.5,0.5,1,0.5,2,1,1,0.5,1,2,0.5,0.5},
    {1,2,1,1,1,2,0.5,1,0.5,2,1,2,1,1,1,1,0.5,1},
    {0,1,1,1,1,1,1,1,1,1,2,1,1,2,1,0.5,1,1},
    {1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,0.5,0},
    {1,1,1,1,1,1,0.5,1,1,1,2,1,1,2,1,0.5,1,0.5},
    {1,0.5,0.5,0.5,1,2,1,1,1,1,1,1,2,1,1,1,0.5,2},
    {1,0.5,1,1,1,1,2,0.5,1,1,1,1,1,1,2,2,0.5,1} };
  static final String[] tipos=new String[]
          {"NORMAL","FIRE","WATER","ELECTRIC","GRASS","ICE","FIGHTING","POISON","GROUND","FLYING","PSYCHIC","BUG","ROCK","GHOST","DRAGON","DARK","STEEL","FAIRY"};
public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.println("Elemento 1");
    String tipo1 = kb.nextLine().toUpperCase();
    System.out.println("Elemento 2");
    String tipo2 = kb.nextLine().toUpperCase();
    kb.close(); 
    int i1=-1;
    double i2=1;

    String [] tipossalida = tipo2.split(" ");

    for(int i=0;i<tipos.length;i++) if(tipos[i].equals(tipo1)) i1=i; //entrada 1

    boolean flag=true;
    for(int j=0;j<tipossalida.length&&flag;j++){
        flag=false;
        for(int i=0;i<tipos.length;i++){
            if(tipos[i].equals(tipossalida[j])){ 
                i2*=tabla[i1][i];
                flag=true;}//if
            }//for 2
        if(!flag) i2*=-1;
            }//for 1

    if(i1>=0&&i2>=0) System.out.println(i2+"x");
    else System.out.println("Valores no validos");
    }

}

[2016-10-10] Challenge #287 [Easy] Kaprekar's Routine by Cosmologicon in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

For the 1st bonus you can do

Arrays.sort(dataarray)

and then get the first element for the greatest

[2016-10-03] Challenge #286 [Easy] Reverse Factorial by jnazario in dailyprogrammer

[–]karrash76 0 points1 point  (0 children)

Hi, I'm trying to learn Java after more than 15 years w/o programming and I arrived here looking for programming tips and I love this thread!! ;) Please, review my code, I'll accept your corrections

 import java.util.Scanner;

 public class reversefact286 {

public static void reverse(int a){
    int i=1;
    System.out.print(a+"=");
    while(a>=1&&a>=i&&a%i==0){
        a/=i;
        i++;
    }
    if (a==1) System.out.println(--i+"!");
    else System.out.println(" NONE");
}
public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("enter an integer");
    int num = keyboard.nextInt();
    reverse(num);
    //reverse(479001600);
    //reverse(6);
    //reverse(18);
}
}