JSL 프로그래밍 챌린지: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 그 반대로 변환안녕하세요 JSL 프로그래머 여러분,
더 큰 응용 프로그램의 일부로 약간의 문제가 있었고 이를 여러분과 공유하고 더 나은/더 매끄러운 방법이 있는지 알아보고 싶습니다.
기본적으로 Y와 N의 문자열(예: "YYNNY")로 변환해야 하는 1과 0(예: [1, 1, 0, 0, 1])의 벡터가 있습니다.그런 다음 반대 작업을 수행해야 합니다. 즉, Y와 N의 문자열을 다시 1과 0의 벡터로 변환해야 합니다.
여기 내 빠르고 더러운 기능이 있습니다. 내 미약한 두뇌 능력을 넘어서는 뭔가를 생각해낼 수 있는지 봅시다!
// Convert a vector of 1s and 0s to a string with no separators
matrix_10_to_yn = function({matrix_10}, {default local},
yn_txt = "";
if (nrows(matrix_10) > 0,
// Strip out square brackets and commas
yn_txt = substitute(char(matrix_10), "[", "", "]", "", ", ", "");
// Now convert 1s to Y and 0s to N
yn_txt = substitute(yn_txt, "1", "Y", "0", "N");
);
yn_txt;
);
// Convert a YN string with no separators to a vector of 1s and 0s
yn_to_matrix_10 = function({yn_txt}, {default local},
n = length(yn_txt);
matrix_10 = j(n, 1, 0);
for (i = 1, i <= n, i++,
if (substr(yn_txt, i, 1) == "Y",
matrix_10[i] = 1;
);
);
matrix_10;
);
<BR />// Test thing out
a = yn_to_matrix_10("YYYNNNN"); show(a);
b = matrix_10_to_yn(a); show(b);
c = yn_to_matrix_10(""); show(c);
d = matrix_10_to_yn(c); show(d);Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.정말 멋진 솔루션입니다.나는 비교적 간단한 이 문제를 해결하기 위해 사용된 다양한 접근법을 믿을 수 없습니다.다시 한번 감사드립니다.
Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.이것들은 모두 매우 멋진 솔루션입니다. PMROZ는 secanrio가 목록으로 시작한다고 잘못 읽었다고 지적했습니다. 그는 내 수정된 솔루션을 요청했습니다.아래에서는 YN의 목록이나 문자열을 10의 벡터로 변환하고 10의 벡터를 YN의 문자열로 변환합니다.
이전 게시물과 일관성을 유지하기 위해 빈 문자열 구분 기호를 사용하여 word() 함수를 사용하여 문자열을 목록으로 변환했습니다.
exmat = J(25,1, RandomInteger(0,1));
exlst = Insert({}, {"Y", "N"}[2-exmat]);
exstr = ConcatItems(Insert({}, {"Y", "N"}[2-exmat]), "");
convert_yn = Function({usr}, {rslt=empty(), ynList ={"Y","N"} },
if(IsMatrix(usr),
rslt = ConcatItems(insert({},ynList[2-usr]),"")
, //else
IsList(usr),
rslt = J(nitems(usr),1, 1);
rslt[loc(usr,"N")]=0
, //else
IsString(usr),
rslt = J(length(Trim(usr)),1,1);
rslt[loc(words(usr,""),"N")]=0
); //end if
rslt
); //end Function
show(exmat, convert_yn(exmat), exlst, convert_yn(exlst), exstr, convert_yn(exstr) );Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.나는 대부분의 프로젝트에서 일반적인 'mapply' 함수를 사용하므로 일반적으로 마지막 두 줄만 필요합니다:
Names Default to here(1);
// Utility function to make for loops, combo 'map' and 'apply'
// this is a 'fake' map/apply function because it allows side
// effects (like apply) and it also returns a value (like map)
mapply = function( {x, foo, arg1 = "__missing", arg2 = "__missing"}, { i, r = {}, x, foo, arg1, arg2, arg1missing, arg2missing },
if( N Items( x ) < 1,
return({}), //empty list supplied, return an empty list
for( i = 1, i <= N Items(x), i++,
arg1missing = 0; arg2missing = 0;
If( type(arg1) == "String", If( arg1 == "__missing", arg1missing = 1 ) );
If( type(arg2) == "String", If( arg2 == "__missing", arg2missing = 1 ) );
if(
arg1missing == 1,
r = Insert( r, foo( x[i] ) ),
arg2missing == 1,
r = Insert( r, foo( x[i], arg1 ) ),
r = Insert( r, foo( x[i], arg1, arg2 ) )
)
)
);
return(r);
);
// Solution:
str = "YYYNNNNYYNY";
(numbers = mapply( words(str,""), function( {x}, if( x=="Y", 1, 0) ) ) )
mapply( as list(numbers), function( {x}, if( x==1,"Y", "N") ) )Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.@pmroz ,
이에 대한 나의 취지/시도는 다음과 같습니다. 이런 흥미로운 도전을 제안해주셔서 감사합니다. 나는 루프를 사용하고 있다는 것을 알고 있는데, 그것이 큰 행렬에 걸쳐 잘 확장될지는 모르겠지만 커뮤니티의 일부 다른 사람들이 더 빠른 방법을 생각해 낼 수 있다고 생각했습니다.
Clear Log(); Clear Globals();
ex = Associative Array({1,0} ,{"Y", "N"});
Test = [1,0, 1, 1, 1, 0, 0, 1, 0, 1];
Res = {};
for(i = 1, i <= N Rows(Test), i++,
Insert Into(Res, ex << Get Value(Test[i]));
);
Show(Res);
Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.이제 design() 함수를 공부해야 해요!
Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.와 이거 정말 놀랍네요.모두 감사합니다!
Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.이런, Craig의 답변을 보지 못했습니다. 내 생각에는 그의 버전이 더 나은 것 같습니다.
Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.Char to Blob 및 Blob to Matrix를 사용하여 한 줄에서 문자열을 행렬로 변환할 수 있습니다. 내 기여:
names default to here(1);
a=[1,0, 1, 1, 1, 0, 0, 1, 0, 1];
b="YNYYYNNYNY";
f_YNString_to_IndicatorVector=Function({s},
blob to matrix(char to blob(d),"int", 1, "little", 1)==89;
);
f_IndicatorVector_to_YNString=Function({v},{vv},
vv=As List(v);
vv[loc(v)]="Y";
vv[loc(!v)]="N";
concat items(vv,"");
);
show(a);
show(b);
Show(f_YNString_to_IndicatorVector(b));
Show(f_IndicatorVector_to_YNString(a));
Show(f_IndicatorVector_to_YNString(f_YNString_to_IndicatorVector(b)));
Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.
추가 노력 없이는 세 가지 값이나 누락/오류 값으로 확장되지 않습니다. string--blob--matrix를 변환하고 행렬의 ASCII 문자 수를 사용하여 Y 및 N 감지를 수행합니다. BlobToMatrix 및 MatrixToBlob 함수는 1바이트 리틀 엔디안 정수를 사용하도록 지시됩니다. 엔디안은 1바이트 숫자의 경우 중요하지 않으며 큰 작업도 마찬가지입니다. 이는 1바이트 표현을 갖는 문자에 따라 다릅니다.
source = "YYNNYQ";
// if you are uncomfortable with hard coded constants...
Yvalue = Blob To Matrix( Char To Blob( "Y" ), "int", 1, "little" )[1]; // 89
Nvalue = Blob To Matrix( Char To Blob( "N" ), "int", 1, "little" )[1]; // 78
// forward
numbers = Blob To Matrix( Char To Blob( source ), "int", 1, "little" ) == Yvalue;
// reverse
string = Blob To Char( Matrix To Blob( Nvalue + numbers * (Yvalue - Nvalue), "int", 1, "little" ) );
// display
Show( source, numbers, string );
출처 = "YYNNYQ";
숫자 = [1, 1, 0, 0, 1, 0];
문자열 = "YYNNYN";
Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.또 다른!!
Names Default to here(1);
yto1 = function({str},
{DEFAULT LOCAL},
list = words(str, "");
design(list, {"Y"});
);
oneToY = function({mat},
list = substitute(as list(mat), 1, "Y", 0, "N");
Concat items(list, "");
);
str = "YYYNNNNYYNY";
nums = yto1(str);
show(nums);
str2 = oneToY(nums);
show(str2, str2==str);Re: JSL 프로그래밍 과제: Y와 N 문자열을 1과 0의 행렬로 변환하고 다시 다시 변환합니다.무엇이든지 작동합니다!여기에 한 가지 대안이 있습니다.
exmat = J(25,1, RandomInteger(0,1));
exlst = Insert({}, {"Y", "N"}[2-exmat]);
convert_yn = Function({usr}, {rslt, ynList ={"Y","N"} },
if(IsMatrix(usr),
rslt = insert({},ynList[2-usr])
, //else
rslt = J(nitems(usr),1, 1);
rslt[loc(usr,"N")]=0
); //end if
rslt
); //end Function
show(exmat, convert_yn(exmat), exlst, convert_yn(exlst));