logo
Tags down

shadow

Execution Time optimization of Java Algorithm logic


By : Bill Chapman
Date : August 01 2020, 06:00 AM
I think the issue was by ths following , Try this bro,it took 0.1s in my computer to test data set of 1 Lakh numbers. its just a testing logic,if it goes properly,you can have some optimization on it.
code :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

public class a4_test {
    public static void main(String[] args) {
        // sampleTest1
        int[] freq_standard = new int[]{1, 2};
        int[] freq_signals = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        // sampleTest2
        freq_standard = new int[]{7, 1, 12, 9, 15};
        freq_signals = new int[]{2, 9, 2000, 13, 4};

//         randomArray For Testing
        freq_standard = randomArray((int) Math.pow(10,5),(int) Math.pow(10,9));
        freq_signals = randomArray((int) Math.pow(10,5),(int) Math.pow(10,9));
        System.out.println("standard:" + Arrays.toString(freq_standard));
        System.out.println("signals" + Arrays.toString(freq_signals));

        long start = System.currentTimeMillis();
        int[] classify = classifySignals(freq_standard, freq_signals);
        long end = System.currentTimeMillis();
        System.out.println("time cost:" + (end - start));
        System.out.println("classifyArray:" + Arrays.toString(classify));
    }

    // mainMethod
    public static int[] classifySignals(int[] freq_standard, int[] freq_signals) {
        Map<Integer, Integer> map = freq_sort(freq_standard);

        Arrays.sort(freq_standard); // there are better sort algorithms for a lower time complexity,fix me~

        // a caching classifyArray,should be construct with 'n'
        ArrayList<Integer> list = new ArrayList<>((int) Math.pow(10, 5));
        for (int freq_signal : freq_signals) {
            int index = findTarget(freq_standard, freq_signal);
            list.add(map.get(freq_standard[index]));    // get original index in original freq_standard[]
        }

        // truly classifyArray,the problem asked a int[] to return
        int[] classifyArray = new int[list.size()];
        for (int i = 0; i < classifyArray.length; i++) {
            classifyArray[i] = list.get(i);
        }
        return classifyArray;
    }

    // record the original index of freq_standard
    public static Map<Integer, Integer> freq_sort(int[] freq_standard) {
        Map<Integer, Integer> map = new TreeMap<>();
        for (int i = 0; i < freq_standard.length; i++) {
            map.put(freq_standard[i], i + 1);   // ok,the problem defined 1 is the begin of array index
        }
        return map;
    }

    // find targetIndex
    private static int findTarget(int[] array, int targetNum) {
        // boundaryCheck
        if (targetNum <= array[0]) {
            return 0;
        } else if (targetNum >= array[array.length - 1]) {
            return array.length - 1;
        }
        // binary search
        int left = 0, right = array.length - 1;
        for (; right - left > 1; ) {
            int pivot = (right + left) / 2;
            int middle = array[pivot];
            if (targetNum == middle) {
                return pivot;
            }
            if (targetNum > middle) {
                left = pivot + 1;
            } else {
                right = pivot - 1;
            }
        }
        int index = targetNum < ((array[right] + array[left]) * 1.0 / 2) ?
                left : right;
//        System.out.println("target:" + targetNum + ",leftV:" + array[left] + ",rightV:" + array[right] + ",indexV:" + array[index]);
        return index;
    }

    // generate random array to test
    public static int[] randomArray(int maxMember, int maxValue) {
        int[] randomArray = new int[maxMember];
        for (int i = 0; i < maxMember; i++) {
            randomArray[i] = (int) (Math.random() * maxValue);
        }
        return randomArray;
    }
}



Share : facebook icon twitter icon

Code optimization by compiler in Java- Time taken for execution of "if" condition is Zero


By : Ben
Date : March 29 2020, 07:55 AM
wish helps you The actual reason
The output varies and is sometimes 0, sometimes not as you already noticed. The likeliest issue is that System.nanoTime:
code :
 62    1       3       java.lang.String::hashCode (55 bytes)
 62    3       3       java.lang.String::indexOf (70 bytes)
 63    2       3       java.lang.String::charAt (29 bytes)
 65    4       3       java.lang.AbstractStringBuilder::ensureCapacityInternal (16 bytes)
 65    5       3       java.lang.Object::<init> (1 bytes)
 65    8     n 0       java.lang.System::arraycopy (native)   (static)
 65    6       3       java.lang.CharacterData::of (120 bytes)
 66    7       3       java.lang.CharacterDataLatin1::getProperties (11 bytes)
 66    9       3       java.lang.Character::toLowerCase (9 bytes)
 66   10       3       java.lang.CharacterDataLatin1::toLowerCase (39 bytes)
 66   11       3       java.lang.String::length (6 bytes)
 66   12       3       java.lang.AbstractStringBuilder::append (29 bytes)
 66   13       3       java.lang.StringBuilder::append (8 bytes)
 67   14       3       java.io.WinNTFileSystem::isSlash (18 bytes)
 67   15  s    3       java.lang.StringBuffer::append (13 bytes)
 67   16       3       java.lang.String::<init> (62 bytes)
 68   17       3       java.lang.String::equals (81 bytes)
 68   18       1       java.lang.Object::<init> (1 bytes)
 68    5       3       java.lang.Object::<init> (1 bytes)   made not entrant
 68   19       3       java.lang.String::getChars (62 bytes)
 74   20       3       java.lang.Math::min (11 bytes)
 74   21       3       java.io.BufferedInputStream::getBufIfOpen (21 bytes)
 74   22       3       java.util.Arrays::copyOfRange (63 bytes)
 75   24       3       java.io.DataInputStream::readUTF (501 bytes)
 76   29       3       java.io.DataInputStream::readFully (63 bytes)
 77   26  s    3       java.io.BufferedInputStream::read (113 bytes)
 77   23  s    3       java.io.BufferedInputStream::read (49 bytes)
 77   30       3       java.io.DataInputStream::readShort (40 bytes)
 78   25       3       java.io.DataInputStream::readUTF (5 bytes)
 78   27       3       java.io.BufferedInputStream::read1 (108 bytes)
 78   28       3       java.io.DataInputStream::readUnsignedShort (39 bytes)
 78   31       3       java.util.HashMap::hash (20 bytes)
 79   32  s    3       java.io.ByteArrayInputStream::read (36 bytes)
 79   33       3       java.io.DataInputStream::readByte (23 bytes)
 79   34       3       sun.util.calendar.ZoneInfoFile::indexOf (32 bytes)
 80   35       3       java.util.zip.CRC32::update (16 bytes)
 81   36     n 0       java.util.zip.CRC32::updateBytes (native)   (static)
 81   37       3       sun.util.calendar.ZoneInfoFile$Checksum::update (39 bytes)
 83   39       3       java.util.HashMap::putVal (300 bytes)
 84   41       4       java.lang.String::equals (81 bytes)
 84   38       3       java.util.HashMap::put (13 bytes)
 84   42   !   3       java.io.BufferedReader::readLine (304 bytes)
 86   43       3       java.util.LinkedList::indexOf (73 bytes)
 86   44       3       java.util.HashMap::getNode (148 bytes)
 86   46       3       java.util.HashMap::get (23 bytes)
 87   47       3       sun.misc.JarIndex::addToList (59 bytes)
 87   17       3       java.lang.String::equals (81 bytes)   made not entrant
 87   45       3       java.util.HashMap$Node::<init> (26 bytes)
 87   40       3       java.util.HashMap::newNode (13 bytes)
 88   48       4       java.lang.String::charAt (29 bytes)
 88    2       3       java.lang.String::charAt (29 bytes)   made not entrant
 92   49       3       java.lang.AbstractStringBuilder::append (50 bytes)
 92   50       3       java.lang.System::getSecurityManager (4 bytes)
 93   51       3       java.lang.Math::max (11 bytes)
 93   52       3       java.lang.String::endsWith (17 bytes)
 96   53       3       java.lang.StringBuilder::append (8 bytes)
equal
189546
equal
17232
367
0

 97   54       1       java.nio.Buffer::position (5 bytes)

Query optimization to reduce execution time


By : saman norozi
Date : March 29 2020, 07:55 AM
hope this fix your issue A few observations:you group by a.id ,isnt a.id a primary key?in that case GROUP BY is unnecessary. Rearrange your WHERE conditions with the most restrictive conditions first,leave theINconditions last.Just for one value you don't need IN use =. If the values areINT`,you don't need quotes,mysql knows they are numbers but using quotes will give a slight overhead.
code :
WHERE  a.is_filterable = 1 AND a.type <> "textarea" 
AND c2.rgt = (c2.lft + 1) 
AND c4.id =190 AND p2.status = 1
AND c3.id IN (843, 848, 849, 853, 856, 858) 
AND c.category_id IN (843, 848, 849, 853, 856, 858) 
ALTER TABLE `label` add KEY (is_filterable,type)
ALTER TABLE `label` add KEY (sort_order)
ALTER TABLE `category` add KEY (rgt)
ALTER TABLE `category` add KEY (lft)
ALTER TABLE `category` add KEY (lft,rgt)
ALTER TABLE `product` add KEY (status)
ALTER TABLE `user` add KEY (id,is_active)

Optimization in a time based algorithm


By : user3834498
Date : March 29 2020, 07:55 AM
I hope this helps . One thing you can do is binary search for the answer.
Suppose the answer is X minutes. Then you know how many stones each child will take during that time. If the total number of stones taken turns out to be less than expected, X needs to be higher. Otherwise, search in the lower half.
code :
children_rate = [3, 3, 5, 7, 10]
bucket = 100

lo, hi = 0, bucket * max (children_rate)
while lo < hi:
    me = (lo + hi) // 2
    if sum (me // i for i in children_rate) < bucket:
        lo = me + 1
    else:
        hi = me

print (lo)

Is it bad practice to place algorithm execution logic in Mainwindow class?


By : Julian Veisdal
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further You should definitely look for MVVM Pattern, for start you may want not to realize it as hard as MS Prism does, but simply create MainWindowVieModel and bind your View to it.

Algorithm's Running Time Optimization


By : Romsies
Date : March 29 2020, 07:55 AM
wish helps you You can start sorting the array O(nlogn) (if not), then for each element in the array you can check if there are two elements that the sum is equals to the number in O(n²).
The code is in C#:
code :
public static bool Solve(int[] arr)
{
    Array.Sort(arr);    //If not already sorted

    foreach (var num in arr)
        if (!FindTwoThatSumN(arr, num))
            return false;

    return true;
}

public static bool FindTwoThatSumN(int[] arr, int num)
{
    int min = 0;
    int max = arr.Length - 1;

    while (true)
    {
        if (min == max) break;

        int sum = arr[min] + arr[max];

        if (sum < num) min++;
        if (sum > num) max--;
        if (sum == num) return true;
    }

    return false;
}
Related Posts Related Posts :
  • Split XML stream by XML documents
  • How can I look at the SQL query really used by myBatis?
  • Java setter does not change the value of an integer
  • Vaadin-14: checking if client is a mobile device
  • Exception occurred at Bank bank = new Bank(bankNaam);
  • List<Long> is not serialised to String in Java
  • Getting jackson cast exception while trying to start gemfire pulse with spring boot 2
  • Can I use JDK for commercial use?
  • What is wrong about this code using Transaction Management in Spring
  • Semicolon expected in java method
  • Spring Boot Security OAuth2 custom exception message
  • Transpose 2D Matrix in Java - Time & Space Complexity?
  • How to select grand-grand child (Like 5th OR 6th grand child) element using xpath which has class name only
  • cucumber throwing java.lang.NoClassDefFoundError: io/cucumber/core/gherkin/FeatureParser
  • Days 30/360 calendar calculator implementation
  • Why does comparison of objects return false in my snake game
  • System.currentTimeMillis() vs Timestamp.valueOf(LocalDateTime.now(UTC)).getTime()
  • How to select all text in AutoCompleteTextView Android
  • Why is the computational complexity O(n^4)?
  • Does the JVM use system calls to seek OS functionalities?
  • Can't use float value from dimen file by databinding
  • How can I implement a "promise like" thread-synchronization system in Java 7?
  • Is there any way to access a sub-type method without casting using generic
  • How to detect device name in Safari on iOS 13 using apache WebSession in Java?
  • Migrating Java 8 project to Java 11
  • Use return of a method for string compare in a main if statement
  • How to resolved OnClick method click issue , it is not working
  • How can I know an undecorated JFrame has been fully painted on the screen?
  • how to solve java.sql.SQLException: No suitable driver found for jdbc:derby:
  • Multiline lambda
  • How can I display custom view same as when long pressed on search icon on below image?
  • How to enclose the brackets around a percentage?
  • Java. Collections. Partition by page limit
  • Import error in android studio design and v7 - Android Studio -
  • How to run bat file with arguments from a java program? (Trying to automate using a Command Line Tool )
  • Spring-boot swagger throws java.lang.ClassNotFoundException on io.swagger.models.parameters.Parameter
  • Mockito: mocking a method call of a generic typed class
  • Would it be okay for me to assign variables then reference them right after?
  • Adding a number into a LinkedList, inside an ArrayList
  • How to parse incoming stream where one piece determines another's interpretation in Java?
  • calling particluar function after delay in java
  • Difference between newObject[]{...parameters..} and PreparedStatementSetter Interface implementation in Spring JDBC?
  • How to create an array of integers in char type?
  • Split function returning whitespace character at the begining
  • Where to put validation in java to check whether a product name already exists in the Database or not? Service Layer or
  • Java Math.min Math.max Errors
  • Java Char Array prints ASCII
  • How to parse JSR-310 date to Instant?
  • Vaadin Spring Boot: "Cannot access state in VaadinSession or UI without locking the session" when multiple use
  • How to convert christian year to thai year in Java?
  • Why I/o exceptions must be handled with Buffered Reader , while it is not mandatory with Scanner?
  • File Write in resource folder in jar
  • Is it good practice that creating a new branch for unit testing in Git?
  • Authenticate javax.naming.NamingException: LDAP
  • Change Youtube Data API PublishAt Date Format
  • Eclipse or spring boot doesn't allow calling any of delete API
  • Best way to read data from a file and store them
  • JPA-Repository save: Proceed saving after insert Constraint violation
  • Java List with Object from different classes
  • Find the most common word in a text
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org