Bonjour tout le monde
je souhaite écrire un programme java me permettant de générer une matrice de binaire à partir d'une String donnée
et par la même occasion ajouter un bit a la fin de chaque ligne et colonne.
J'ai du mal a le faire :bug:
Merci
Version imprimable
Bonjour tout le monde
je souhaite écrire un programme java me permettant de générer une matrice de binaire à partir d'une String donnée
et par la même occasion ajouter un bit a la fin de chaque ligne et colonne.
J'ai du mal a le faire :bug:
Merci
Salut
Ce serait bien si tu pouvais donner un début de code et expliquer exactement ou tu bloques s'il te plait
voici ce que j'ai essayé de faire:
à partir de ce code je voudrais générer une matrice a partir d'une String donnée par la suite ajouter un bit a la fin de chaque ligne et chaque colonneCode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 public class MAT { public static String toBinary(char c) { String s = Integer.toBinaryString(c); int n = Integer.bitCount(c); if (n % 2 == 0) { return s + '0'; } else { return s + '1'; } } public static char[] tochar(String str) { char []tab; tab=new char[str.length()]; for(int i=0;i<str.length();i++) { tab[i]=str.charAt(i); } return tab; } public static void main(String[] args) { String maChaine = "HELLOWORLD"; char [] tab; char [][]mat; for (int i = 0; i < maChaine.length(); i++) { String s = Integer.toBinaryString(maChaine.charAt(i)); s = toBinary(maChaine.charAt(i)); tab=new char [s.length()]; tab=tochar(s); mat=new char[s.length()][8]; for(int j=0;j<8;j++) { mat[i]=tab; } System.out.println(mat[i]); }
Merci a vous tout en espérant été clair
Slt.
Tu pourrais commencer d'abord par convertir ton String en un tableau de int [], chaque case du tableau correspondra a la valeur d'un caractère de la chaine. En suite faire des et logiques pour obtenir la valeur de chacune des bit de l'octect :Pour le test bit par bit :Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 public static byte[] toByteArray (char[] array) {//Conversion char [] en byte [] return toByteArray(array, Charset.defaultCharset()); }//toByteArray /** * * @param array * @param charset * @return */ public static byte[] toByteArray (char[] array, Charset c){//toByteArray CharBuffer cbuf = CharBuffer.wrap(array); ByteBuffer bbuf = charset.encode(cbuf); return bbuf.array(); }//toByteArray
Pour la conversion byte->int, une simple affectation suffira (il va y avoir un cast).Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 String s = "Java"; int [] tab = arrayByteToArrayInt (toByteArray (s.toCharArray ()))); tab [0] = tab [0] & 0x01; if (tab [0] > 0) System.out.println ("1"); else System.out.println ("0"); tab [0] = tab [0] & 0x02; if (tab [0] > 0) System.out.println ("1"); else System.out.println ("0"); ... ... ...
Bon courage :ccool:
Si ceci est le résultat que tu veux obtenir:
Voici ton code que j'ai quelque peu modifiéCode:
1
2
3
4
5
6
7
8
9
10 H: [1, 0, 0, 1, 0, 0, 0, 0] E: [1, 0, 0, 0, 1, 0, 1, 1] L: [1, 0, 0, 1, 1, 0, 0, 1] L: [1, 0, 0, 1, 1, 0, 0, 1] O: [1, 0, 0, 1, 1, 1, 1, 1] W: [1, 0, 1, 0, 1, 1, 1, 1] O: [1, 0, 0, 1, 1, 1, 1, 1] R: [1, 0, 1, 0, 0, 1, 0, 1] L: [1, 0, 0, 1, 1, 0, 0, 1] D: [1, 0, 0, 0, 1, 0, 0, 0]
Pas besoin d'utiliser ta méthode "tochar", il y'a déjà une fonction pour ça: machaine.toCharArray().Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 import java.util.Arrays; public class MAT { public static String toBinary(char c) { String s= Integer.toBinaryString(c); int n= Integer.bitCount(c); if (n % 2 == 0) return s+"0"; else return s+"1"; } public static void main(String[] args) { String maChaine= "HELLOWORLD"; char[][] mat= new char[maChaine.length()][8]; String s; char c; for(int i=0; i<maChaine.length(); i++) { c= maChaine.charAt(i); s= toBinary(c); mat[i]= s.toCharArray(); System.out.println(c+": "+Arrays.toString(mat[i])); } } }
Sinon les autres modifications sont des modifications d'affectations.
Oui bien sûr, ce code pourrait t'aider:Citation:
mais est ce qu'il est possible d'ignorer les caractères spéciaux
Cette fonction permet de tester si un caractère est une lettre inclue entre a et z, en majscule et minuscule.Code:
1
2
3 public boolean isLetter(char ch) { return Character.toString(ch).matches("[a-zA-Z]"); }
Et si tu veux inclure les accents aussi, utilise:
Dans ce cas la taille de ton tableau mat ne sera plus la taille de ta chaîne String, tu peux laisser ton code ainsi ce n'est pas vraiment un problème ou tu peux utiliser une ArrayList pour mat. Mais ce n'est pas obligatoire.Code:Character.isLetter(char);
Y'a pas de quoi ;)
De rien :ccool:Citation:
Envoyé par proc02
Bonjour
L'opération que j'ai eu à faire sur les lignes j'aimerais faire la même chose pour les colonnes vous avez une idée :idea:
Voici :
MerciCode:
1
2
3
4
5
6
7
8
9
10 public static String toBinary(char c) { String s= Integer.toBinaryString(c); int n= Integer.bitCount(c); if (n % 2 == 0) return s+"0"; else return s+"1"; }
Explique moi, ce que tu veux faire c'est à partir de la matrice que tu as obtenu:Citation:
L'opération que j'ai eu à faire sur les lignes j'aimerais faire la même chose pour les colonnes
Récupérer chaque colonne puis rajouter un 1 ou 0 selon le contenu de la colonne ?Code:
1
2
3
4
5
6
7
8
9
10 H: [1, 0, 0, 1, 0, 0, 0, 0] E: [1, 0, 0, 0, 1, 0, 1, 1] L: [1, 0, 0, 1, 1, 0, 0, 1] L: [1, 0, 0, 1, 1, 0, 0, 1] O: [1, 0, 0, 1, 1, 1, 1, 1] W: [1, 0, 1, 0, 1, 1, 1, 1] O: [1, 0, 0, 1, 1, 1, 1, 1] R: [1, 0, 1, 0, 0, 1, 0, 1] L: [1, 0, 0, 1, 1, 0, 0, 1] D: [1, 0, 0, 0, 1, 0, 0, 0]
Si c'est bien ce que tu veux, je t'ai concocter un code qui donne ça
Le voiciCode:
1
2
3
4
5
6
7
8
9
10
11 H: [1, 0, 0, 1, 0, 0, 0, 0] E: [1, 0, 0, 0, 1, 0, 1, 1] L: [1, 0, 0, 1, 1, 0, 0, 1] L: [1, 0, 0, 1, 1, 0, 0, 1] O: [1, 0, 0, 1, 1, 1, 1, 1] W: [1, 0, 1, 0, 1, 1, 1, 1] O: [1, 0, 0, 1, 1, 1, 1, 1] R: [1, 0, 1, 0, 0, 1, 0, 1] L: [1, 0, 0, 1, 1, 0, 0, 1] D: [1, 0, 0, 0, 1, 0, 0, 0] +: [0, 0, 0, 0, 0, 0, 0, 0]
Il est commenté. J'espère que ça te conviendraCode:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 import java.util.Arrays; import javax.naming.BinaryRefAddr; public class MAT { public static String toBinaryRow(char c) { String s= Integer.toBinaryString(c); int n= Integer.bitCount(c); if (n % 2 == 0) return s+"0"; else return s+"1"; } public static char toBinaryCol(String s) { int a= Integer.parseInt(s, 2); //convertir la chaine de binaire en entier int n= Integer.bitCount(a); // compter le nombre de 1 contenu dans le binaire de l'entier if (n % 2 == 0) return '0'; else return '1'; } public static void main(String[] args) { String maChaine= "HELLOWORLD"; int nbRow= maChaine.length() + 1; int nbCol= 8; char[][] mat= new char[nbRow][nbCol]; String s; char c; for(int i=0; i<nbRow-1; i++) { //traiter chaque caractère de la chaine maChaine c= maChaine.charAt(i); s= toBinaryRow(c); mat[i]= s.toCharArray(); } StringBuilder binary; for(int j=0; j<nbCol; j++) { //traiter chaque colonne de mat binary= new StringBuilder(); for(int i=0; i<nbRow-1; i++) binary.append(mat[i][j]); //concaténation des cases pour la colonne traitée String str= ""+binary; mat[nbRow-1][j]= toBinaryCol(str); } for(int i=0; i<nbRow-1; i++) System.out.println(maChaine.charAt(i)+": "+Arrays.toString(mat[i])); System.out.println("+: "+Arrays.toString(mat[nbRow-1])); } }
Le voici
Il est commenté. J'espère que ça te conviendra[/QUOTE]Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 import java.util.Arrays; import javax.naming.BinaryRefAddr; public class MAT { public static String toBinaryRow(char c) { String s= Integer.toBinaryString(c); int n= Integer.bitCount(c); if (n % 2 == 0) return s+"0"; else return s+"1"; } public static char toBinaryCol(String s) { int a= Integer.parseInt(s, 2); //convertir la chaine de binaire en entier int n= Integer.bitCount(a); // compter le nombre de 1 contenu dans le binaire de l'entier if (n % 2 == 0) return '0'; else return '1'; } public static void main(String[] args) { String maChaine= "HELLOWORLD"; int nbRow= maChaine.length() + 1; int nbCol= 8; char[][] mat= new char[nbRow][nbCol]; String s; char c; for(int i=0; i<nbRow-1; i++) { //traiter chaque caractère de la chaine maChaine c= maChaine.charAt(i); s= toBinaryRow(c); mat[i]= s.toCharArray(); } StringBuilder binary; for(int j=0; j<nbCol; j++) { //traiter chaque colonne de mat binary= new StringBuilder(); for(int i=0; i<nbRow-1; i++) binary.append(mat[i][j]); //concaténation des cases pour la colonne traitée String str= ""+binary; mat[nbRow-1][j]= toBinaryCol(str); } for(int i=0; i<nbRow-1; i++) System.out.println(maChaine.charAt(i)+": "+Arrays.toString(mat[i])); System.out.println("+: "+Arrays.toString(mat[nbRow-1])); } }
you know:ccool::ccool: Merci infiniment :ange:
De rien :) avec plaisir
Bonsoir
étant donné que les lettres de ta chaine constituent les lignes de ta matrices, que tu as besoin de remplir toute les lignes de ta matrice avant de traiter la dernière ligne, personnellement je ne vois pas une autre façon de faire je suis désolée.
:)
Slt, encore une fois, c'est encore moi :).
Je ne sais pas ce que vous y pensez, mais je trouve quelle n'est pas si longue que ça ma méthode, tu devrais juste éviter la conversion char [] -> byte [], et faire une conversion directe char [] -> int [], une simple affectation pour chaque élément du tableau suffira (int coder sur 4 octect, char sur 2 octet).
Donc :Ici, a partir d'un int (32 bits = 4 octects), on fait a chaque fois un et logique, on met 1 a la position du bit quand veut tester, et un zéro ailleurs. Si la valeur obtenue est > 0, le bit a cette position est a 1, sinon, il est a zéro.Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 String s = "Java"; char [] tab = s.toCharArray (); int i = tab [0]; if ((i & 0x00000001) > 0) System.out.println ("1"); else System.out.println ("0"); if ((i & 0x00000002) > 0) System.out.println ("1"); else System.out.println ("0"); if ((i & 0x00000004) > 0) System.out.println ("1"); else System.out.println ("0"); ...
0x00000004 : en hexadécimal.
PS : je m'excuse pour la dernière fois, j’étais impeut pressé, je l'ais fait a la va vite, j'ai fais du n'importe quoi :ccool:
Bon courage ;)
... Ca reste bien plus long qu'un simple Integer.toBinaryString() ...
A la limite il y aurait :
qui est passablement plus court.Code:
1
2
3
4
5
6
7 for(int bit = 0; bit < 8; bit++) { if(((i >> bit) & 1) != 0) { System.out.println ("1"); } else { System.out.println ("0"); } }
Je m’excuse pour le retard :oops:, j’étais occupé.
En terme de code (code source, exécutable généré), oui c'est long, mais en terme de temps d’exécution, c'est plus rapide.
Ici tu utilise une boucle avec un compteur, incrémentation et test a chaque fois->traitement en plus.Citation:
Envoyé par thelvin
mais vu :Je pense que tu as raison.Citation:
Envoyé par proc02
En tous cas, bon courage :ccool:
Non, car il y a un appel à System.out.println() pour chaque caractère.
Chacun de ces appels prend infiniment plus de temps que ce qu'on gagne en évitant un compteur. Cette micro-optimisation ne se justifie donc pas.
(Et si ce n'était pas un println(), ce serait une affectation dans un char[], ce qui est plus rapide, mais reste infiniment supérieur au temps gagné par la micro-optimisation. D'ailleurs le compteur avec incrémentation deviendrait inévitable.)
De manière générale, il est très rare qu'on puisse réellement optimiser quelque chose avec un code plus compliqué. La JVM est trop maline pour ça.
Bonsoir
Dis moi tu veux faire ça pour chaque mot de la phrase, ou une seule matrice pour la phrase en entier ?
Ceci te permet de récupérer chaque mot de ta phrase dans un tableau
après tu n'a plus qu'a appliquer la procédure sur chaque mot comme ceciCode:
1
2 String phrase= "je suis une phrase toute jolie"; String[] decoupe= phrase.split(" ");
pour l'autre possibilité, j'y réfléchis là je voulais d'abord te répondre pour la première :)Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 import java.util.ArrayList; import java.util.Arrays; public class MAT { public static String toBinaryRow(char c) { String s= Integer.toBinaryString(c); int n= Integer.bitCount(c); if (n % 2 == 0) return s+"0"; else return s+"1"; } public static char toBinaryCol(String s) { int a= Integer.parseInt(s, 2); //convertir la chaine de binaire en entier int n= Integer.bitCount(a); // compter le nombre de 1 contenu dans le binaire de l'entier if (n % 2 == 0) return '0'; else return '1'; } public static char[][] traitement(String maChaine) { int nbRow= maChaine.length() + 1; int nbCol= 8; char[][] mat= new char[nbRow][nbCol]; String s; char c; for(int i=0; i<nbRow-1; i++) { //traiter chaque caractère de la chaine maChaine c= maChaine.charAt(i); s= toBinaryRow(c); mat[i]= s.toCharArray(); } StringBuilder binary; for(int j=0; j<nbCol; j++) { //traiter chaque colonne de mat binary= new StringBuilder(); for(int i=0; i<nbRow-1; i++) binary.append(mat[i][j]); //concaténation des cases pour la colonne traitée String str= ""+binary; mat[nbRow-1][j]= toBinaryCol(str); } for(int i=0; i<nbRow-1; i++) System.out.println(maChaine.charAt(i)+": "+Arrays.toString(mat[i])); System.out.println("+: "+Arrays.toString(mat[nbRow-1])); return mat; } public static void main(String[] args) { String phrase= "je suis une phrase toute jolie"; String[] decoupe= phrase.split(" "); ArrayList<char[][]> listMat= new ArrayList<char[][]>(); for(String maChaine: decoupe) listMat.add(traitement(maChaine)); } }
Dans le cas d'une seule matrice pour toute la phrase, quel traitement tu veux faire pour les espaces ?
tu veux t'en débarasser ? Mettre des 0 par défaut ? ou les convertir ?
Bein alors c'est déja fait car ceci
est la liste des matrices de tes mots et sans aucun espace à laquelle tu accède comme ça par exempleCode:ArrayList<char[][]> listMat= new ArrayList<char[][]>();
a moins que tu ne préfères une autre structure ?Code:char t= listMat.get(0)[4][4];