Zadanie 3 - CRC - wersja innym inputem #31

Closed
s426271 wants to merge 14 commits from s426271/DALGLI0:Zadanie-3 into master
22 changed files with 883 additions and 0 deletions

Binary file not shown.

View File

@ -0,0 +1,5 @@
public class DivisionErrorException extends Throwable {
public DivisionErrorException() {
System.out.println("Division error!");
}
}

View File

@ -0,0 +1,19 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) throws DivisionErrorException, MultiplierNotFoundException {
//ex input in run console : 2 "1 1 1 0 1" "0 1 1"
int n = Integer.parseInt(args[0]);
List<Integer> firstPolynomial = new ArrayList<>();
args[1] = args[1].substring(1, args[1].length()-1);
args[2] = args[2].substring(1, args[2].length()-1);
Arrays.asList(args[1].split( ",\\s*" )).forEach(factor -> firstPolynomial.add(Integer.valueOf(factor)));
List<Integer> secondPolynomial = new ArrayList<>();
Arrays.asList(args[2].split(",\\s*" )).forEach(factor -> secondPolynomial.add(Integer.valueOf(factor)));
PolynomialTask polynomialTask = new PolynomialTask(n, firstPolynomial, secondPolynomial);
polynomialTask.printAllValuesToStandardOutput();
}
}

View File

@ -0,0 +1,5 @@
public class MultiplierNotFoundException extends Throwable {
public MultiplierNotFoundException() {
System.out.println("DivisionError");
}
}

View File

@ -0,0 +1,134 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class PolynomialTask {
private int n;
private List<Integer> firstPolynomial;
private List<Integer> secondPolynomial;
public PolynomialTask(int n, List<Integer> firstPoly, List<Integer> secondPoly) {
this.n = n;
this.firstPolynomial = firstPoly;
this.secondPolynomial = secondPoly;
}
public Integer[] multiplyPolynomials(List<Integer> firstPolynomial, List<Integer> secondPolynomial) {
int[] multiplied = new int[firstPolynomial.size() + secondPolynomial.size() - 1];
int sizeOfFirstPoly = firstPolynomial.size();
int sizeOfSecondPoly = secondPolynomial.size();
for (int i = 0; i < sizeOfFirstPoly; i++) {
for (int j = 0; j < sizeOfSecondPoly; j++)
multiplied[i + j] = (multiplied[i + j] + (firstPolynomial.get(i) * secondPolynomial.get(j))) % n;
}
return Arrays.stream(multiplied).boxed().toArray(Integer[]::new);
}
public int[] moduloDividePolynomialsReturnQuotient(List<Integer> firstPoly, List<Integer> secondPoly) throws MultiplierNotFoundException, DivisionErrorException {
int[] quotient = new int[firstPoly.size() + secondPoly.size()];
int firstPolyDegree = firstPoly.size() - 1;
int secondPolyDegree = secondPoly.size() - 1;
List<Integer> polynomialAfterSubtract = firstPoly;
while (firstPolyDegree >= secondPolyDegree) {
polynomialAfterSubtract = calcQuotient(polynomialAfterSubtract, secondPoly, quotient);
firstPolyDegree = polynomialAfterSubtract.size() - 1;
}
int[] remainder = new int[polynomialAfterSubtract.size()];
for (int i = 0; i < polynomialAfterSubtract.size(); i++) {
remainder[i] = polynomialAfterSubtract.get(i);
}
return remainder;
}
private List<Integer> calcQuotient(List<Integer> firstPoly, List<Integer> secondPoly, int[] quotient) throws MultiplierNotFoundException, DivisionErrorException {
int firstPolyDegree = firstPoly.size() - 1;
int secondPolyDegree = secondPoly.size() - 1;
if (firstPolyDegree < secondPolyDegree) {
throw new DivisionErrorException();
}
int quotientCoefficient;
if ((((float) firstPoly.get(firstPolyDegree) / (float) secondPoly.get(secondPolyDegree))) == Math.round(firstPoly.get(firstPolyDegree) / secondPoly.get(secondPolyDegree))) {
quotientCoefficient = firstPoly.get(firstPolyDegree) / secondPoly.get(secondPolyDegree);
} else {
quotientCoefficient = invElem(firstPoly.get(firstPolyDegree), secondPoly.get(secondPolyDegree));
}
quotient[firstPolyDegree - secondPolyDegree] += quotientCoefficient;
List<Integer> newPoly = generatePolyFromIndexAndValue(firstPolyDegree - secondPolyDegree, quotientCoefficient);
Integer[] multipliedPolynomials = multiplyPolynomials(newPoly, secondPoly);
List<Integer> polynomialAfterFirstDivide = new ArrayList<>(Arrays.asList(multipliedPolynomials));
return removeUnnecessaryZeros(subtractTwoPolynomials(firstPoly, polynomialAfterFirstDivide));
}
private List<Integer> removeUnnecessaryZeros(List<Integer> polynomialAfterSubtract) {
int amountOfZeros = 0;
for (int i = polynomialAfterSubtract.size() - 1; i >= 0; i--) {
if (polynomialAfterSubtract.get(i) == 0) {
amountOfZeros++;
} else {
break;
}
}
polynomialAfterSubtract = polynomialAfterSubtract.subList(0, polynomialAfterSubtract.size() - amountOfZeros);
return polynomialAfterSubtract;
}
private List<Integer> subtractTwoPolynomials(List<Integer> firstPoly, List<Integer> secondPoly) {
List<Integer> subtractedPolynomial = new ArrayList<>(Collections.nCopies(firstPoly.size() + secondPoly.size(), 0));
for (int index = firstPoly.size(); index >= 0; index--) {
if (index < secondPoly.size()) {
subtractedPolynomial.set(index, firstPoly.get(index) - secondPoly.get(index));
parseNegativeElement(subtractedPolynomial, index);
}
}
return subtractedPolynomial;
}
private void parseNegativeElement(List<Integer> subtractedPolynomial, int index) {
while (subtractedPolynomial.get(index) < 0)
subtractedPolynomial.set(index, (subtractedPolynomial.get(index) * subtractedPolynomial.get(index)) % n);
}
private List<Integer> generatePolyFromIndexAndValue(int size, int quotientCoefficient) {
List<Integer> poly = new ArrayList<>(Collections.nCopies(size + 1, 0));
poly.set(size, quotientCoefficient);
return poly;
}
private int invElem(int a, int b) throws MultiplierNotFoundException {
for (int i = 0; i < n; i++) {
if (a == (b * i) % n) {
return i;
}
}
throw new MultiplierNotFoundException();
}
public void printAllValuesToStandardOutput() throws DivisionErrorException, MultiplierNotFoundException {
List<List<Integer>> values = new ArrayList<>();
values.add(Arrays.asList(multiplyPolynomials(firstPolynomial, secondPolynomial)));
values.add(Arrays.stream(moduloDividePolynomialsReturnQuotient(firstPolynomial, secondPolynomial)).boxed().collect(Collectors.toList()));
try {
values.add(gcd(firstPolynomial, secondPolynomial));
} catch (MultiplierNotFoundException e) {
}
System.out.println(values);
}
private List<Integer> gcd(List<Integer> polyOne, List<Integer> polyTwo) throws MultiplierNotFoundException, DivisionErrorException {
if (polyTwo.isEmpty()) return polyOne;
List<Integer> poly = Arrays.stream(moduloDividePolynomialsReturnQuotient(polyOne, polyTwo)).boxed().collect(Collectors.toList());
return gcd(polyTwo, poly);
}
}

View File

@ -0,0 +1,8 @@
<component name="ArtifactManager">
<artifact type="jar" name="Zadanie-03:jar">
<output-path>$PROJECT_DIR$/out/artifacts/Zadanie_03_jar</output-path>
<root id="archive" name="Zadanie-03.jar">
<element id="module-output" name="Zadanie-03" />
</root>
</artifact>
</component>

View File

@ -0,0 +1 @@
<html>Simple <b>Java</b> application that includes a class with <code>main()</code> method</html>

12
Zadanie-03/.idea/misc.xml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="ProjectKey">
<option name="state" value="project://e2804f05-5315-4fc6-a121-c522a6c26470" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Zadanie-03.iml" filepath="$PROJECT_DIR$/Zadanie-03.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,3 @@
<template>
<input-field default="com.company">IJ_BASE_PACKAGE</input-field>
</template>

View File

@ -0,0 +1,423 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="5f8a3521-157f-4adb-a0ab-dc99bbf14aa0" name="Default" comment="">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/com/tylkowski/crc/Main.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/com/tylkowski/crc/Main.java" afterDir="false" />
</list>
<ignored path="$PROJECT_DIR$/out/" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file leaf-file-name="Main.java" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/Main.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="255">
<caret line="15" column="9" lean-forward="true" selection-start-line="15" selection-start-column="9" selection-end-line="15" selection-end-column="9" />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="CrcTask.java" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="178">
<caret line="44" column="9" lean-forward="true" selection-start-line="44" selection-start-column="9" selection-end-line="44" selection-end-column="9" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Class" />
</list>
</option>
</component>
<component name="FindInProjectRecents">
<findStrings>
<find>System.out.println</find>
<find>for</find>
<find />
<find>System</find>
<find>ch</find>
<find>shot</find>
<find>gen_deg</find>
<find>char</find>
<find>swa</find>
<find>chunk</find>
<find>toBin</find>
<find>toBinaryStr</find>
<find>swap</find>
<find>letter</find>
<find>lol</find>
</findStrings>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/.." />
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/src/com/tylkowski/crc/Main.java" />
<option value="$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java" />
</list>
</option>
</component>
<component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsGulpfileManager">
<detection-done>true</detection-done>
<sorting>DEFINITION_ORDER</sorting>
</component>
<component name="ProjectFrameBounds" extendedState="6">
<option name="x" value="676" />
<option name="width" value="697" />
<option name="height" value="735" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectView">
<navigator proportions="" version="1">
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="PackagesPane" />
<pane id="AndroidView" />
<pane id="ProjectPane">
<subPane>
<expand>
<path>
<item name="Zadanie-03" type="b2602c69:ProjectViewProjectNode" />
<item name="Zadanie-03" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="Zadanie-03" type="b2602c69:ProjectViewProjectNode" />
<item name="Zadanie-03" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="Zadanie-03" type="b2602c69:ProjectViewProjectNode" />
<item name="Zadanie-03" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
<item name="crc" type="462c0819:PsiDirectoryNode" />
</path>
</expand>
<select />
</subPane>
</pane>
<pane id="Scope" />
</panes>
</component>
<component name="PropertiesComponent">
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="aspect.path.notification.shown" value="true" />
<property name="extract.method.default.visibility" value="private" />
</component>
<component name="RunDashboard">
<option name="ruleStates">
<list>
<RuleState>
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
</RuleState>
<RuleState>
<option name="name" value="StatusDashboardGroupingRule" />
</RuleState>
</list>
</option>
</component>
<component name="RunManager">
<configuration name="Main" type="Application" factoryName="Application" temporary="true">
<option name="MAIN_CLASS_NAME" value="com.tylkowski.crc.Main" />
<module name="Zadanie-03" />
<option name="PROGRAM_PARAMETERS" value="&quot;2&quot; &quot;b­&quot;" />
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
<RunnerSettings RunnerId="Run" />
<ConfigurationWrapper RunnerId="Run" />
</configuration>
<configuration default="true" type="Application" factoryName="Application">
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
<option name="MAIN_CLASS_NAME" />
<option name="VM_PARAMETERS" />
<option name="PROGRAM_PARAMETERS" />
<option name="WORKING_DIRECTORY" />
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="ENABLE_SWING_INSPECTOR" value="false" />
<option name="ENV_VARIABLES" />
<option name="PASS_PARENT_ENVS" value="true" />
<module name="" />
<envs />
<method />
</configuration>
<recent_temporary>
<list>
<item itemvalue="Application.Main" />
</list>
</recent_temporary>
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="5f8a3521-157f-4adb-a0ab-dc99bbf14aa0" name="Default" comment="" />
<created>1528990184795</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1528990184795</updated>
<workItem from="1528990186268" duration="4202000" />
<workItem from="1529055268255" duration="3475000" />
<workItem from="1529355696900" duration="6551000" />
<workItem from="1529407679397" duration="19000" />
<workItem from="1529409635196" duration="1437000" />
<workItem from="1529428699866" duration="20522000" />
<workItem from="1529482084631" duration="5831000" />
<workItem from="1529497353540" duration="2850000" />
</task>
<task id="LOCAL-00001" summary="project started">
<created>1529359475020</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1529359475021</updated>
</task>
<task id="LOCAL-00002" summary="poly generating &amp; swapping">
<created>1529361951813</created>
<option name="number" value="00002" />
<option name="presentableId" value="LOCAL-00002" />
<option name="project" value="LOCAL" />
<updated>1529361951813</updated>
</task>
<task id="LOCAL-00003" summary="encode added!">
<created>1529447421427</created>
<option name="number" value="00003" />
<option name="presentableId" value="LOCAL-00003" />
<option name="project" value="LOCAL" />
<updated>1529447421427</updated>
</task>
<task id="LOCAL-00004" summary="decode added!">
<created>1529449567531</created>
<option name="number" value="00004" />
<option name="presentableId" value="LOCAL-00004" />
<option name="project" value="LOCAL" />
<updated>1529449567531</updated>
</task>
<task id="LOCAL-00005" summary="small code refactor">
<created>1529450003665</created>
<option name="number" value="00005" />
<option name="presentableId" value="LOCAL-00005" />
<option name="project" value="LOCAL" />
<updated>1529450003665</updated>
</task>
<task id="LOCAL-00006" summary="charset update">
<created>1529487959831</created>
<option name="number" value="00006" />
<option name="presentableId" value="LOCAL-00006" />
<option name="project" value="LOCAL" />
<updated>1529487959831</updated>
</task>
<option name="localTasksCounter" value="7" />
<servers />
</component>
<component name="TimeTrackingManager">
<option name="totallyTimeSpent" value="44887000" />
</component>
<component name="ToolWindowManager">
<frame x="-8" y="-8" width="1382" height="744" extended-state="6" />
<editor active="true" />
<layout>
<window_info anchor="right" id="Palette" order="3" />
<window_info anchor="bottom" id="TODO" order="6" />
<window_info anchor="bottom" id="Messages" order="7" weight="0.32838285" />
<window_info anchor="right" id="Palette&#9;" order="3" />
<window_info id="Image Layers" order="2" />
<window_info anchor="right" id="Capture Analysis" order="3" />
<window_info anchor="bottom" id="Event Log" order="7" side_tool="true" />
<window_info anchor="right" id="Maven Projects" order="3" />
<window_info anchor="bottom" id="Database Changes" order="7" show_stripe_button="false" />
<window_info anchor="bottom" id="Version Control" order="7" />
<window_info anchor="bottom" id="Run" order="2" weight="0.38118812" />
<window_info anchor="bottom" id="Terminal" order="7" />
<window_info id="Capture Tool" order="2" />
<window_info id="Designer" order="2" />
<window_info content_ui="combo" id="Project" order="0" visible="true" weight="0.16641453" />
<window_info anchor="right" id="Database" order="3" />
<window_info id="Structure" order="1" side_tool="true" weight="0.25" />
<window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
<window_info id="UI Designer" order="2" />
<window_info anchor="right" id="Theme Preview" order="3" />
<window_info id="Favorites" order="2" side_tool="true" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.39933994" />
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
<window_info anchor="right" id="Commander" order="0" weight="0.4" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
<window_info anchor="bottom" id="Find" order="1" />
</layout>
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="1" />
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="project started" />
<MESSAGE value="poly generating &amp; swapping" />
<MESSAGE value="encode added!" />
<MESSAGE value="decode added!" />
<MESSAGE value="small code refactor" />
<MESSAGE value="charset update" />
<option name="LAST_COMMIT_MESSAGE" value="charset update" />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/Main.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="374">
<caret line="22" lean-forward="true" selection-start-line="22" selection-end-line="22" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="2856">
<caret line="170" selection-start-line="170" selection-end-line="170" selection-end-column="50" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/Main.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="204">
<caret line="12" lean-forward="true" selection-start-line="12" selection-end-line="12" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="663">
<caret line="39" column="9" lean-forward="true" selection-start-line="39" selection-start-column="9" selection-end-line="39" selection-end-column="9" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/Main.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="85">
<caret line="5" column="44" selection-start-line="5" selection-start-column="44" selection-end-line="5" selection-end-column="44" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="663">
<caret line="39" lean-forward="true" selection-start-line="39" selection-end-line="39" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/Main.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="68">
<caret line="5" column="44" selection-start-line="5" selection-start-column="44" selection-end-line="5" selection-end-column="44" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="561">
<caret line="33" column="16" selection-start-line="33" selection-start-column="16" selection-end-line="33" selection-end-column="16" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/Main.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="85">
<caret line="5" column="44" selection-start-line="5" selection-start-column="44" selection-end-line="5" selection-end-column="44" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="561">
<caret line="33" column="16" selection-start-line="33" selection-start-column="16" selection-end-line="33" selection-end-column="16" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/Main.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="442">
<caret line="26" lean-forward="true" selection-start-line="26" selection-end-line="26" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="221">
<caret line="13" column="9" lean-forward="true" selection-start-line="13" selection-start-column="9" selection-end-line="13" selection-end-column="9" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/Main.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="272">
<caret line="16" column="69" selection-start-line="16" selection-start-column="69" selection-end-line="16" selection-end-column="69" />
</state>
</provider>
</entry>
<entry file="jar://C:/Program Files/Java/jdk1.8.0_77/src.zip!/java/lang/Integer.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="186">
<caret line="329" column="16" selection-start-line="329" selection-start-column="16" selection-end-line="329" selection-end-column="33" />
</state>
</provider>
</entry>
<entry file="jar://C:/Program Files/Java/jdk1.8.0_77/src.zip!/java/lang/System.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="329">
<caret line="494" column="24" selection-start-line="494" selection-start-column="24" selection-end-line="494" selection-end-column="24" />
</state>
</provider>
</entry>
<entry file="jar://C:/Program Files/Java/jdk1.8.0_77/src.zip!/java/util/Arrays.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="278">
<caret line="3556" column="19" selection-start-line="3556" selection-start-column="19" selection-end-line="3556" selection-end-column="19" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/CrcTask.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="178">
<caret line="44" column="9" lean-forward="true" selection-start-line="44" selection-start-column="9" selection-end-line="44" selection-end-column="9" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/com/tylkowski/crc/Main.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="255">
<caret line="15" column="9" lean-forward="true" selection-start-line="15" selection-start-column="9" selection-end-line="15" selection-end-column="9" />
</state>
</provider>
</entry>
</component>
</project>

12
Zadanie-03/Zadanie-03.iml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

Binary file not shown.

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Main-Class: com.tylkowski.crc.Main

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Main-Class: com.tylkowski.crc.Main

View File

@ -0,0 +1,225 @@
package com.tylkowski.crc;
import java.util.Arrays;
class CrcTask {
private String message;
private short[] messageAsShortArray;
private short[] polyGenerator;
private String rawMessage;
CrcTask(String message) {
this.rawMessage = message;
this.message = formatMessage(toBinaryString(message)) + "0000000000000000";
createGeneratingPolynomial();
}
private String formatMessage(String message) {
int firstNonZeroVal = 0;
boolean found = false;
StringBuilder validString = new StringBuilder();
while (!found && firstNonZeroVal < message.length()) {
if (message.charAt(firstNonZeroVal) == 48) {
firstNonZeroVal++;
} else {
found = true;
}
}
for (int i = firstNonZeroVal; i < message.length(); i++) {
if (message.charAt(i) == 48) {
validString.append(0);
} else {
validString.append(1);
}
}
StringBuilder msg = new StringBuilder(validString.toString());
while (msg.length() % 8 != 0) {
msg.insert(0, "0");
}
return msg.toString();
}
private String generateFCS() {
while (true) {
if (messageAsShortArray[0] == 0) {
messageAsShortArray = Arrays.copyOfRange(messageAsShortArray, 1, messageAsShortArray.length);
} else {
short[] piece = Arrays.copyOfRange(messageAsShortArray, 0, Math.min(polyGenerator.length, messageAsShortArray.length));
if (piece.length < polyGenerator.length) {
fillPolynomial(piece);
return createTwoCharsOfFCS(piece);
}
short[] remainder = calcXOR(piece, polyGenerator);
remainder = removeUnecessaryZeros(remainder);
messageAsShortArray = createMessageFromRemainderAndPartFromOldMessage(remainder, messageAsShortArray);
}
}
}
private String createTwoCharsOfFCS(short[] piece) {
short[] firstPiece = Arrays.copyOfRange(piece, 0, 8);
short[] secondPiece = Arrays.copyOfRange(piece, piece.length - 8, piece.length);
short[] mergedPieces = new short[firstPiece.length + secondPiece.length];
for (int i = 0; i < firstPiece.length; i++) {
mergedPieces[i] = firstPiece[i];
mergedPieces[i + 8] = secondPiece[i];
}
return "0x" + Integer.toHexString(Integer.parseInt(shortArrayToBinaryString(mergedPieces), 2));
}
private short[] createMessageFromRemainderAndPartFromOldMessage(short[] remainder, short[] msg) {
short[] tempArr = new short[remainder.length + msg.length - polyGenerator.length];
System.arraycopy(remainder, 0, tempArr, 0, remainder.length);
int diff = polyGenerator.length - remainder.length;
System.arraycopy(msg, remainder.length + diff, tempArr, remainder.length, msg.length - diff - remainder.length);
msg = tempArr;
return msg;
}
private short[] removeUnecessaryZeros(short[] remainder) {
int firstNonZeroVal = 0;
boolean found = false;
while (!found && firstNonZeroVal < remainder.length) {
if (remainder[firstNonZeroVal] == 0) {
firstNonZeroVal++;
} else {
found = true;
}
}
return Arrays.copyOfRange(remainder, firstNonZeroVal, remainder.length);
}
private short[] calcXOR(short[] piece, short[] polyGenerator) {
int a = Integer.parseInt(shortArrayToBinaryString(piece), 2);
int b = Integer.parseInt(shortArrayToBinaryString(polyGenerator), 2);
String binaryString = Integer.toBinaryString(a ^ b);
return convertBinaryStringToShortArray(binaryString);
}
private String shortArrayToBinaryString(short[] value) {
StringBuilder binaryString = new StringBuilder();
for (Short a : value) {
binaryString.append(a);
}
return binaryString.toString();
}
private void fillPolynomial(short[] piece) {
while (piece.length % 8 != 0) {
piece = addZeroAtBeginningOfArray(piece);
}
}
private short[] addZeroAtBeginningOfArray(short[] piece) {
short[] tempArray = new short[piece.length + 1];
tempArray[0] = 0;
System.arraycopy(piece, 0, tempArray, 1, piece.length);
return tempArray;
}
private short[] convertBinaryStringToShortArray(String binaryString) {
short[] shortArray = new short[binaryString.length()];
for (int i = 0; i < binaryString.length(); i++) {
if (binaryString.charAt(i) == 48) {
shortArray[i] = 0;
} else {
shortArray[i] = 1;
}
}
return shortArray;
}
private void createGeneratingPolynomial() {
polyGenerator = new short[17];
for (int i = 0; i < 17; i++) {
polyGenerator[i] = 0;
}
polyGenerator[0] = 1;
polyGenerator[4] = 1;
polyGenerator[11] = 1;
polyGenerator[16] = 1;
}
private short[] swapPolynomialValues(short[] poly) {
for (int i = 0; i < polyGenerator.length - 1; i++) {
poly[i] = (short) ((poly[i] + 1) % 2);
}
return poly;
}
String encode() {
messageAsShortArray = convertBinaryStringToShortArray(message);
messageAsShortArray = swapPolynomialValues(messageAsShortArray);
return rawMessage + generateFCS();
}
private String letterToBinaryString(char letter) {
short a = (short) letter;
StringBuilder binaryString = new StringBuilder(Integer.toBinaryString(a));
while (binaryString.length() % 8 != 0) {
binaryString.insert(0, "0");
}
return binaryString.toString();
}
boolean decode(String encodedString) {
String fcs = encodedString.substring(encodedString.indexOf("0x"), encodedString.length());
encodedString = encodedString.replace(fcs, "");
encodedString = toBinaryString(encodedString);
encodedString = encodedString + toBinaryStringFromHexValue(fcs);
encodedString = fillPoly(encodedString);
short[] encodedShortArray = convertBinaryStringToShortArray(encodedString);
encodedShortArray = swapPolynomialValues(encodedShortArray);
while (true) {
if (!shortArrayContains(encodedShortArray, 1)) {
return true;
}
if (encodedShortArray[0] == 0) {
encodedShortArray = Arrays.copyOfRange(encodedShortArray, 1, encodedShortArray.length);
} else {
short[] piece = Arrays.copyOfRange(encodedShortArray, 0, Math.min(polyGenerator.length, encodedShortArray.length));
if (piece.length < polyGenerator.length) {
return false;
}
short[] remainder = calcXOR(piece, polyGenerator);
remainder = removeUnecessaryZeros(remainder);
encodedShortArray = createMessageFromRemainderAndPartFromOldMessage(remainder, encodedShortArray);
}
}
}
private String toBinaryStringFromHexValue(String hexString) {
hexString = hexString.substring(2, hexString.length());
return String.valueOf(Integer.toBinaryString(Integer.parseInt(hexString, 16)));
}
private String toBinaryString(String encodedString) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < encodedString.length(); i++) {
stringBuilder.append(letterToBinaryString(encodedString.charAt(i)));
}
return stringBuilder.toString();
}
private boolean shortArrayContains(short[] encodedShortArray, int value) {
for (short item : encodedShortArray) {
if (item == value) {
return true;
}
}
return false;
}
private String fillPoly(String encodedString) {
StringBuilder stringBuilder = new StringBuilder(encodedString);
while (stringBuilder.length() % 8 != 0) {
stringBuilder.insert(0, "0");
}
return stringBuilder.toString();
}
}

View File

@ -0,0 +1,22 @@
package com.tylkowski.crc;
public class Main {
public static void main(String[] args) {
// in command line type "1" for mode and "b" for message
// example "1" "b" -> this will encode string "b" and return FCS
// example "2" "bX" -> this will decode string "bX" and return true if it is valid or false if not
// X - FCS
CrcTask crcTask = new CrcTask(args[1]);
if (args[0].equals("1")) {
//create FCS
System.out.println(crcTask.encode());
} else if (args[0].equals("2")) {
// check fcs
if (args[1].length() >= 3) System.out.println(crcTask.decode(args[1]));
}
}
}