Autor
|
Tema: Códigos (Leído 3,724 veces)
|
TickTack
Desconectado
Mensajes: 433
CipherX
|
 |
Códigos
« en: 8 Enero 2021, 20:23 pm » |
|
Hola a todos, se me ocurrió la idea de publicar este tema, en el que quisiera compartir códigos de Java y en el que también te invito a compartir tus útiles códigos fuente de la vida cotidiana. Quiero empezar: Invertir entre mayúsculas y minúsculas cada N caracteres Este método invierte cada N caracteres de una cadena dada su valor de mayúsculas a minúsculas o viceversa. public static String toUpperIntV(final String s, final int intervall) { final var chars = s.toCharArray();
for(int i = intervall - 1; i < chars.length; i += intervall) { chars[i] = Character.isLowerCase(chars[i]) ? Character.toUpperCase(chars[i]) : Character.toLowerCase(chars[i]); }
return String.valueOf(chars); }
System.out.println(toUpperIntV("la casa azul", 1)); // LA CASA AZUL System.out.println(toUpperIntV("la casa azul", 2)); // lA CaSa aZuL System.out.println(toUpperIntV("la casa azul", 3)); // la caSa AzuL System.out.println(toUpperIntV("La Casa Azul", 1)); // lA cASA aZUL System.out.println(toUpperIntV("La Casa Azul", 2)); // LA caSa AZuL System.out.println(toUpperIntV("La Casa Azul", 3)); // La CaSa azuL System.out.println(toUpperIntV("LA CASA AZUL", 1)); // la casa azul System.out.println(toUpperIntV("LA CASA AZUL", 2)); // La cAsA AzUl System.out.println(toUpperIntV("LA CASA AZUL", 3)); // LA CAsA aZUl
Saludos
|
|
|
En línea
|
|
|
|
TickTack
Desconectado
Mensajes: 433
CipherX
|
 |
Re: Códigos
« Respuesta #1 en: 8 Enero 2021, 20:48 pm » |
|
Quizás esto pueda ser útil para algunas personas... La proporción de números en el vector que son mayores, menores o iguales a 0: public static void printStatistics(int... a) { for (NumberValue nv : NumberValue.values()) { System.out.println(nv.name() + " = " + sum(nv.getPredicate(), a)); } }
private static enum NumberValue { GREATER_THAN_0, LESS_THAN_0, EQUAL_TO_0;
private IntPredicate getPredicate() { return this == GREATER_THAN_0 ? i -> i > 0 : this == LESS_THAN_0 ? i -> i < 0 : i -> i == 0; } }
public static double sum(IntPredicate predicate, int... a) { return Arrays.stream(a).filter(predicate).mapToDouble(i -> 1.0 / a.length).sum(); }
public static void main(String[] args) { printStatistics(-5, 5, 4, 3, 2, 1, 0, -1); }
Resultado: GREATER_THAN_0 = 0.625 LESS_THAN_0 = 0.25 EQUAL_TO_0 = 0.125
Saludos
|
|
|
En línea
|
|
|
|
TickTack
Desconectado
Mensajes: 433
CipherX
|
 |
Re: Códigos
« Respuesta #2 en: 8 Enero 2021, 21:03 pm » |
|
Expresiones recursivas lambda: @SuppressWarnings({ "rawtypes", "unchecked" }) public static Function<Integer, Function<Integer, Function>> myPowerTriFunction = x -> y -> f -> y == 0 ? 1 : x * (Integer) ((Function<Integer, Function<Integer, Function>>) f).apply(x).apply(y - 1).apply(f); @SuppressWarnings("unchecked") public static BiFunction<Integer, Integer, Integer> myPowerBiFunction = (x, y) -> (Integer) myPowerTriFunction.apply(x).apply(y).apply(myPowerTriFunction);
public static void main(String[] args) { System.out.println(myPowerBiFunction.apply(3, 5)); // prints 243 System.out.println(myPowerBiFunction.apply(4, 6)); // prints 4096 }
Saludos
|
|
|
En línea
|
|
|
|
TickTack
Desconectado
Mensajes: 433
CipherX
|
 |
Re: Códigos
« Respuesta #3 en: 16 Enero 2021, 00:24 am » |
|
Un hombre tiene un automóvil bastante viejo que vale $ 2000. Vio un automóvil de segunda mano que valía $ 8000. Quiere quedarse con su coche viejo hasta que pueda comprar uno de segunda mano. Él cree que puede ahorrar $ 1000 cada mes, pero los precios de su auto viejo y del nuevo disminuyen en un 1.5 por ciento por mes. Además, este porcentaje de pérdida aumenta en un 0,5% al final de cada dos meses. A nuestro hombre le resulta difícil hacer todos estos cálculos. ¿Puedes ayudarlo? ¿Cuántos meses le llevará ahorrar suficiente dinero para comprar el auto que quiere y cuánto dinero le sobrará? public static int[] nbMonths(double startPriceOld, double startPriceNew, int savingperMonth, double percentLossByMonth){ double total = startPriceOld - startPriceNew; int month=0, savingperMonthAcum = 0; while (total<0) { percentLossByMonth = ++month%2 == 0 ? percentLossByMonth+0.5 : percentLossByMonth; startPriceOld = startPriceOld-(startPriceOld*(percentLossByMonth/100)); startPriceNew = startPriceNew-(startPriceNew*(percentLossByMonth/100)); total = startPriceOld-startPriceNew+savingperMonth+savingperMonthAcum; savingperMonthAcum += savingperMonth; } return new int[] {month, (int)Math.round(total)}; }
System.out.println(Arrays.toString(nbMonths(2000, 8000, 1000, 1.5))); System.out.println(Arrays.toString(nbMonths(12000, 8000, 1000, 1.5))); System.out.print(Arrays.toString(nbMonths(2800 ,4600 ,1000 ,1.2)));
|
|
|
En línea
|
|
|
|
TickTack
Desconectado
Mensajes: 433
CipherX
|
 |
Re: Códigos
« Respuesta #4 en: 16 Enero 2021, 00:37 am » |
|
Método que recibe una cantidad dada de segundos y devuelve un formato legible por un humano. public static String formatoDuracion(int s) { if (s < 0) s = -s; Map<String,Integer> map = new LinkedHashMap<String,Integer>(); map.put("dia",(int)Math.floor(s/86400)); map.put("hora",(int)Math.floor(s/3600) % 24); map.put("minuto",(int)Math.floor(s/60) % 60); map.put("segundo",(int)Math.floor(s/1) % 60); return map.entrySet().stream() .filter(x -> x.getValue() != 0) .collect(Collectors.toMap( e -> e.getValue() > 1 ? e.getKey() + "s" : e.getKey(), Map.Entry::getValue, (v1, v2) -> v1 > v2 ? v1 : v2, LinkedHashMap::new)) .entrySet().stream() .map(e -> e.getValue() + " " + e.getKey()) .collect(Collectors.joining(", ")).replaceAll("\\b, \\b(?!.*\\b, \\b)", " y "); }
System.out.println(formatoDuracion(1)); //1 segundo System.out.println(formatoDuracion(61)); //1 minuto y 1 segundo System.out.println(formatoDuracion(-61)); //1 minuto y 1 segundo System.out.println(formatoDuracion(62)); //1 minuto y 2 segundos System.out.println(formatoDuracion(86400)); //1 dia System.out.println(formatoDuracion(90061)); //1 dia, 1 hora, 1 minuto y 1 segundo System.out.println(formatoDuracion(180122)); //2 dias, 2 horas, 2 minutos y 2 segundos System.out.println(formatoDuracion(1000000)); //11 dias, 13 horas, 46 minutos y 40 segundos System.out.println(formatoDuracion(34325055)); //397 dias, 6 horas, 44 minutos y 15 segundos
|
|
|
En línea
|
|
|
|
|
Mensajes similares |
|
Asunto |
Iniciado por |
Respuestas |
Vistas |
Último mensaje |
|
|
Codigos BBC
PHP
|
Kizar
|
3
|
2,872
|
18 Octubre 2007, 17:01 pm
por <?BRoWLi?>
|
|
|
codigos c#
.NET (C#, VB.NET, ASP)
|
ronnieale
|
3
|
5,009
|
18 Mayo 2009, 08:50 am
por © Shadoweps ツ
|
|
|
codigos c#
.NET (C#, VB.NET, ASP)
|
jackmats
|
0
|
2,449
|
19 Marzo 2010, 20:25 pm
por jackmats
|
|
|
Codigos CSS
Desarrollo Web
|
Ahm_Shere
|
1
|
2,536
|
24 Mayo 2010, 20:32 pm
por Shell Root
|
|
|
Librería de códigos C# (Compartan aquí sus códigos)
« 1 2 3 »
.NET (C#, VB.NET, ASP)
|
DarK_FirefoX
|
24
|
37,606
|
12 Diciembre 2018, 02:47 am
por z3nth10n
|
|