java – Odd/even sums competitive programming

I am stuck on a competitive programming problem. There are N < 1000 numbers each with values from 1-100. These numbers can be separated into groups such that the first group’s sum is even, the second group’s sum is odd, the third group’s sum is even, etc in this alternating fashion. I have written some code, but this code ends up returning the wrong answer sometimes, but not all the time. I’m guessing this has something to do with my casework but I am just stuck.

Example input:

7

1 3 5 7 9 11 13

Output:

3

Explanation:
You can place 1 and 3 in first group, 5 7 9 in second group, and 11 13 as last group.

import java.util.Scanner;


public class Average {
    public static void main(String() args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int odd = 0;
        int even = 0;
        int ans = 0;
        int x;
        for (int i = 0; i < n; i++) {
            x = sc.nextInt();
            if (x % 2 == 0) {
                even++;
            } else {
                odd++;
            }
        }

        ans = Math.min(even, odd) * 2;
        even -= ans;
        odd -= ans;

        if (even > odd) {
            ans++;
        } else {

            if (odd % 3 == 0) {
                ans += (odd / 3) * 2;
            } else if(odd%3 == 1){
                ans += (odd / 3) * 2 - 1;
            } else {
                ans += (odd/3) * 2 + 1;
            }

        }

        System.out.println(ans);
    }
}
```

algorithm – Substring search in Java

I am trying to make an algorithm that will find the index of a given substring (which I have labeled pattern) in a given String (which I have labeled text). This method can be compared to String.indexOf(String str). In addition to general feedback, I’m curious what the time complexity of my method is, and would appreciate if someone can help me figure it out.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

public class SubstringSearch {
    public static void main(String() args) {
        String text = "This is a test String";
        String pattern = "is a";
        int index = search(pattern, text);
        System.out.println(index);
    }

    private static int search(String pattern, String text) {
        int patternLength = pattern.length();
        int textLength = text.length();

        Set<Integer> set = new HashSet<>(textLength);
        List<Integer> addList = new ArrayList<>(textLength);

        for (int i = 0; i < textLength; i++) {
            set.add(0);

            for (Integer index : set) {
                if (pattern.charAt(index) == text.charAt(i)) {
                    addList.add(index + 1);
                }
            }

            set.clear();
            set.addAll(addList);

            if (set.contains(patternLength)) {
                return i - patternLength + 1;
            }
        }

        throw new NoSuchElementException();
    }
}

how to ADD a NEW entity/item/effect to Minecraft Java

In Minecraft Java, I am creating many resource packs by myself (no studio or external resource) so, I want to ADD a new file/entity/element/items/etc. to the game to not replace an old item because EVERY item/effect/entity has SOME use in the game. In conclusion: how I can ADD (not replace) a file in the game and give it custom physical and mental properties?

java – Cyclic Permutations Problem **Fixed**

I have come across a problem on cyclic permutations. It is about swapping numbers around.

It starts out with input N < 100,000 which makes the first N natural numbers as orders: 1 2 3 … N-1 N

Then we get the next input K < 200,000 as the period

Next N input lines are the swaps:

For example, the input is

5 4
1 3
1 2
2 3
2 4

There are 5 numbers and the swap period is 4. The first swap switches number at position 1 with position 3. The second swap is between position 1 and position 2. The third swap is between position 2 and position 3. The fourth swap is between 2 and 4. K+1th swap is same as first. K+2th swap is same as second. Etc.

The simulation for this is:

1 2 3 4 5
3 2 1 4 5 
2 3 1 4 5 
2 1 3 4 5 
2 4 3 1 5 
3 4 2 1 5 
4 3 2 1 5 
4 2 3 1 5 
4 1 3 2 5 
3 1 4 2 5 
1 3 4 2 5 
1 4 3 2 5 
1 2 3 4 5

We can see that the original number at position 3 can go to positions 1, 2, and 3. The original number at position 1 can go to positions 1, 2, 3, 4. The original number at position 2 can go to positions 1, 2, 3, 4. The original number at position 4 can go to positions 1, 2, 3, 4. The original number at position 5 can go to positions 5.

Position 1 goes to 4 positions. Position 2 goes to 4 positions. Position 3 goes to 3 positions. Position 4 goes to 4 positions. Position 5 goes to 1 position.

Given that each output line is represented by y, the output is the number of totals positions the yth original position goes to. Output for this example is:

4
4
3
4
1

The memory limit is 256MB and the time limit is 2 seconds for noninterpreted languages such as C++ and 4 seconds for interpreted languages such as Java.


z, d = map(int, input().split())

S = ()

pos = {}


for i in range(1, z+1):
  pos(i) = (i,)

permute = list(range(1, z+1))
for i in range(d):
  S.append(list(map(int, input().split())))


Flag = True

while Flag:
  Flag = False
  for i in S:
    if i(0) not in pos(permute(i(1)-1)):
      Flag = True
      pos(permute(i(1)-1)).append(i(0))
    if i(1) not in pos(permute(i(0)-1)):
      Flag = True
      pos(permute(i(0)-1)).append(i(1))
    permute(i(0)-1), permute(i(1)-1) = permute(i(1)-1), permute(i(0)-1)


for i in pos:
  print(len(pos(i)))

My solution takes too much space/time. Can you help me fix this?

java – Applying functions to decorated objects

I have an interface Animal with a class that implements it, Cat.

public interface Animal {
    public int price();
    public Breed.BreedType breedType();
}

public class Cat implements Animal {

    private int price;
    private Breed.BreedType breedType;

    public Cat(int price) {
        this.price = price;
    }

    public Cat(int price, Breed.BreedType breedType) {
        this.price = price;
        this.breedType = breedType;
    }

    @Override
    public int price() {
        return price;
    }

    @Override
    public Breed.BreedType breedType() {
        return breedType;
    }
}

I have decorated the Animal class with the following interface, Breed.

import java.util.List;

public interface Breed {
    public enum BreedType {
        RARE,
        EXOTIC
    }

    public int calculatePrice(List<Animal> animals);
}

The concrete decorator class looks as follows:

import java.util.List;

public class Exotic implements Breed {

    @Override
    public int calculatePrice(List<Animal> animals) {
        return animals.stream()
                .mapToInt(Animal::price)
                .map(i -> i * 2)
                .sum();
    }
}

Finally I iterate over a collection of animals and apply the decorator to them to work out their total cost of special breed animals.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String() args) {
        Cat cat1 = new Cat(100);
        Cat cat2 = new Cat(100, Breed.BreedType.EXOTIC);
        Cat cat3 = new Cat(100, Breed.BreedType.EXOTIC);

        Map<Breed.BreedType, List<Animal>> map = Stream.of(cat1, cat2, cat3)
                .filter(animal -> animal.breedType() != null)
                .collect(Collectors.groupingBy(Animal::breedType, Collectors.toList()));

        int total = 0;
        for(Breed.BreedType breedType : map.keySet()) {
            if(breedType.equals(Breed.BreedType.EXOTIC)) {
                total += new Exotic().calculatePrice(map.get(breedType));
            }
        }
        System.out.println(total);
    }
}

This does not seem particularly flexible as I will end up with a giant if statement as more breeds are added. Is there a better way to do this? My enum and the corresponding method for the Exotic breed seem a bit disconnected.

java – how to stop a thread running in JavaFX if it is running?

how to check if a Thread is running and stop in javaFX ?

 Runnable UpdateRunnableYellow = () -> {
                Platform.runLater(new Runnable() {
                    public void run() {
                        labelExecuteResult.setText("cartes avec code erronés :");
                        ResultList.getChildren().setAll(yellow);
                    }
                });

            };
            updateyellow = new Thread(UpdateRunnableYellow);
            updateyellow.start();

datetime – Java – General purpose String to LocalDateTime parser

I have a couple of general purpose LocalDateTime parser methods I wrote to handle Dates flowing between a number of legacy XML based processing pipelines over to a modern Spring Boot, Mongo applications. Because both the legacy and modern applications are set in stone, I’m stuck with a narrow conversion of legacy String dates to LocalDateTime. That said I wanted to present it for review and perhaps improve the code. The various legacy String Dates we have are :

    // 200701     - 6  yyyyMM
    // 032007     - 6  MMyyyy
    // 2007-01    - 7  yyyy-MM
    // 03-2007    - 7  MM-yyyy
    // 03012007   - 8  MMddyyyy
    // 20070301   - 8  yyyyMMdd
    // 03-01-2007 - 10 MM-dd-yyyy
    // 2007-03-01 - 10 MM-dd-yyyy

And the methods I came up with are : The primary method is parseDate(), I just pass in the legacy String Date and basically have it figure out the length and then try and convert it to LocalDateTime. It works and all the JUnit tests pass.

public LocalDateTime    parseDate(String dateString) {
    checkArgument(!Strings.isNullOrEmpty(dateString), "Date (" + dateString + ") is empty of NULL!");
    LOG.debug("parseDate.................................Date ({})", dateString);
    LocalDateTime   ldateResults = null;
    dateString = dateString.replace("/","-");

    switch (dateString.length()) 
    {
        case 6:
            try { ldateResults = getLocalDateTimeFromString ( dateString, "MMyyyy" ); }
            catch ( Exception ltwoXcp ) {
                LOG.warn("Date ({}) failed with format (MMyyyy), trying another", dateString);
                try { ldateResults = getLocalDateTimeFromString ( dateString, "yyyyMM" ); }
                catch ( Exception loneXcp ) {
                    LOG.warn("Date ({}) failed with format (yyyyMM), trying another", dateString);
                }
            }
            break;
        case 7:
            if ( dateString.indexOf("-") > 3 ) {
                try { ldateResults = getLocalDateTimeFromString ( dateString, "yyyy-MM" ); }
                catch ( Exception loneXcp ) {
                    LOG.warn("Date ({}) failed with format (yyyy-MM), trying another", dateString);
                }
                try { ldateResults = getLocalDateTimeFromString ( dateString, "MM-yyyy" ); }
                catch ( Exception ltwoXcp ) {
                    LOG.warn("Date ({}) failed with format (MM-yyyy), trying another", dateString);
                }
            }
            break;
        case 8:
            try { ldateResults = getLocalDateTimeFromString ( dateString, "MMddyyyy" ); }
            catch ( Exception loneXcp ) {
                LOG.warn("Date ({}) failed with format (MMddyyyy), trying another", dateString);
                try { ldateResults = getLocalDateTimeFromString ( dateString, "yyyyMMdd" ); }
                catch ( Exception ltwoXcp ) {
                    LOG.warn("Date ({}) failed with format (yyyyMMdd), trying another", dateString);
                }
            }
            break;
        case 10:
            try { ldateResults = getLocalDateTimeFromString ( dateString, "MM-dd-yyyy" ); }
            catch ( Exception loneXcp ) {
                LOG.warn("Date ({}) failed with format (MM-dd-yyyy), trying another", dateString);
                try { ldateResults = getLocalDateTimeFromString ( dateString, "yyyy-MM-dd" ); }
                catch ( Exception ltwoXcp ) {
                    LOG.warn("Date ({}) failed with format (yyyy-MM-dd), trying another", dateString);
                }
            }
            break;
    }
    
    return ldateResults;
    
}
public LocalDateTime getLocalDateTimeFromString(String dateString, String dateFormat) {
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(dateFormat);
    if ( dateFormat.length() == 6 ) {
        LocalDate localDate = YearMonth.parse(dateString, dateFormatter).atDay(1);
        return localDate.atStartOfDay();
    }
    return LocalDate.parse(dateString, dateFormatter).atStartOfDay();
}
public String getStringFromLocalDateTime(LocalDateTime date, String dateFormat) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
    return formatter.format(date);
}

Here are some JUnit tests that run :

@Test
public void parseDateReturnsCorrectyyyyMM() {
    String dateString="200703";
    LocalDateTime ldtValue = null;
    try {
        ldtValue = dateUtils.parseDate(dateString);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    if ( ldtValue != null ) {
        dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
    }
    
    assertEquals("03/01/2007", dateString);
}

@Test
public void parseDateReturnsCorrectMMyyyy() {
    String dateString="032007";
    LocalDateTime ldtValue = null;
    try {
        ldtValue = dateUtils.parseDate(dateString);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    if ( ldtValue != null ) {
        dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
    }
    
    assertEquals("03/01/2007", dateString);
}

@Test
public void parseDateReturnsCorrectyyyyMMdd() {
    String dateString="20070301";
    LocalDateTime ldtValue = null;
    try {
        ldtValue = dateUtils.parseDate(dateString);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    if ( ldtValue != null ) {
        dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
    }
    
    assertEquals("03/01/2007", dateString);
}

@Test
public void parseDateReturnsCorrectMMddyyyy() {
    String dateString="03012007";
    LocalDateTime ldtValue = null;
    try {
        ldtValue = dateUtils.parseDate(dateString);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    if ( ldtValue != null ) {
        dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
    }
    
    assertEquals("03/01/2007", dateString);
}

@Test
public void parseDateReturnsCorrectMM_dd_yyyy() {
    String dateString="03-01-2007";
    LocalDateTime ldtValue = null;
    try {
        ldtValue = dateUtils.parseDate(dateString);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    if ( ldtValue != null ) {
        dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
    }
    
    assertEquals("03/01/2007", dateString);
}

@Test
public void parseDateReturnsCorrectyyyy_MM_dd() {
    String dateString="2007-03-01";
    LocalDateTime ldtValue = null;
    try {
        ldtValue = dateUtils.parseDate(dateString);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    if ( ldtValue != null ) {
        dateString = dateUtils.getStringFromLocalDateTime(ldtValue,"MM/dd/yyyy");
    }
    
    assertEquals("03/01/2007", dateString);
}

Tia adym

java – Comparar dos horas Android

**Quisiera saber como puedo comparar dos horas de manera correcta en Android.
He estado leyendo, y pues econtré una posible solución.

Método:

private boolean horas(){
    //para la hora actual
    Calendar actual = Calendar.getInstance();
    actual.get(Calendar.HOUR);
    actual.get(Calendar.MINUTE);

    //para la hora final
    Calendar fin = Calendar.getInstance();
    fin.set(Calendar.HOUR, 12);
    fin.set(Calendar.MINUTE, 39);

    if(actual.equals(fin) || actual.after(fin)){
        carga.setEnabled(false);
        return true;
    }else{
        carga.setEnabled(true);
        return false;
    }
}

onCreate:

    if(horas() == true){
        Toast.makeText(ListaPreciosActivity.this, "Lo sentimos, las cargas y modificaciones de precio solo se pueden realizar hasta las 20:00 hs.", Toast.LENGTH_SHORT).show();
    }else{
        carga.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cargarPrecio();
            }
        });
    }

La idea es que luego de la hora indicada, se inhabilite el botón pero no me ha funcionado. ¿Qué estoy haciendo mal?

java swing – desarrollar tablero de ajedrez mediante bucles

quiero programar un tablero de ajedrez pero solo lo consigo casilla a casilla
hay alguna forma de hacerlo mediante bucles?
con JLabels por ejemplo lo hago en modo de diseño pero casilla a casilla y temgo que repetir el codigo 64 veces y eso es mucho codigo

java – Why wont this .jar file run when I try to start it on C#?

Hey Im very new to the coding space and was wondering if someone could help me start a .jar file. BTW This is using C# my issue is this wont run the file. I got it to work with .txt files tho so Im just a bit confused.

private void button1_Click(object sender, EventArgs e)
    {
        Process.Start("java" , "server.jar");
    }