해결책
for (...) 또는 while (...) 또는 이국적인 변형 중 하나를 사용하십시오.
그만큼
...에 대한 루프는 일부 문장을 반복하는 가장 일반적인 방법입니다.
Cars = {"Ford", "Chevy", "Tesla"}; // a list
nCars = N Items( Cars );
// notice loop starts at one and <= counts to the end
For( iCar = 1, iCar <= nCars, iCar += 1,
car = Cars[iCar]; // JSL lists are 1-based
Write( "\!n", car, " has four wheels." );
);
포드는 4 개의 바퀴를 가지고있다.
시보레에는 4 개의 바퀴가 있습니다.
테슬라에는 4 개의 바퀴가 있습니다.
실수에 대한 for 루프는 예상 한대로 작동하지 않을 수도 있습니다. 0.1과 같은 숫자는 64 비트 배정도 숫자로 잘릴 때 약간 작거나 너무 큰 바이너리 분수를 반복합니다. 이 예제에서 3.0에 매우 근접한 최종 값은 실제로 약간 크다.
for(i=2, i<= 3, i+=.1, print(i);); // 2, 2.1, ... 2.9 (but not 3.0)
write("\!nFinally ",i-3); // 8.88178419700125e-16
2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 마지막으로 8.88178419700125e-16
정수 단계가 필요할 경우 for 문에 정수를 사용하고 부동 소수점 값을 계산하십시오.
for(i=0,i<=10,i++,
write(" ", 2 + i/10);
// 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3
);
2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3
그만큼
동안 루프는 간단하지만 for 루프보다 덜 일반적 일 수 있습니다. 이 예제는
...에 대한 고리; 그만큼
다음 것 예를 사용하면
동안 .
authors = {"Margaret Mitchell", "J.D. Salinger", "Emily Brontë"};
iAuthor = 1;
While( iAuthor <= N Items( authors ),
Write( "\!n", authors[iAuthor], " wrote one novel" );
iAuthor += 1;
);
Margaret Mitchell은 하나의 소설을 썼다. JD 샐린저가 한 소설을 썼다. Emily Brontë는 하나의 소설을 썼다.
그만큼 동안 루프는 목록이 비어있을 때까지 요소를 제거하여 목록과 함께 작업 할 수 있습니다.
animals = {"octopus", "spider", "scorpion"};
While( N Items( animals ) > 0,
// RemoveFrom modifies the animals list
// and returns a list of (in this example)
// one item
animal = Remove From( animals, 1 );
// subscript the list to get just the animal
// name, without the curly braces for the list
Write( "\!n", animal[1], " has eight legs" );
);
문어는 8 개의 다리를 가지고있다.
거미는 8 개의 다리를 가지고있다.
전갈에는 8 개의 다리가있다.
에 대한 과
동안 루프는
단절 () 문을 사용하여 루프를 일찍 종료하고
잇다 () 문을 사용하여 나머지 명령문을 건너 뛰고 맨 위에서 계속하십시오. Continue ()는 맨 위에 증가분이있는 for 루프에서 가장 잘 작동합니다.
For( i = 1, i <= 10, i++,
If( i == 3, Continue() );
If( i == 7, Break() );
Write( " ", i ); // 1 2 4 5 6
);
1 2 4 5 6
ForEachRow 데이터 테이블과 함께 작동하며 다른 방법으로 수행 할 수있는 바로 가기입니다. ForEachRow의 주요 문제점은 현재 데이터 테이블과 함께 작동한다는 것입니다. 이 때문에 하나 이상의 테이블이 열려있는 경우 사용하지 않는 것이 좋습니다. 내부 루프와 외부 루프가 현재 행에 대해 서로를 혼동하므로 ForEachRow 루프를 중첩시키지 않는 것이 좋습니다.
dt = Open( "$sample_data/big class.jmp" );
For Each Row(
If( Starts With( dt:name, "A" ),
Write( " ", dt:name ); // ALICE ALFRED AMY
)
);
ALICE ALFRED AMY
그만큼 수식 열 루프는 JMP에서 내부적으로 수행됩니다. 데이터 테이블에 수식 열을 만들면 JMP는 각 행의 수식을 계산합니다. 나중에 수식이 의존하는 다른 열의 값을 변경하면 JMP는 변경된 값에 의존하는 행을 다시 계산합니다. JMP는 유휴 시간 동안 이러한 평가를 수행합니다. JMP가 더 빨리 더 빨리 처리하도록하려면 데이터 테이블에 << RunFormulas 메시지를 보냅니다.
dt = Open( "$sample_data/big class.jmp" );
hw = dt << New Column( "HW_Ratio", formula( height / weight ) );
dt << RunFormulas; // all 40 values are computed
dt << Sort(by (HW_Ratio), replaceTable); // tall enough for my weight?
Table with formula columnTable with formula columnTable with formula column수식 열이있는 표
많은 함수들이 매트릭스 인수를 선택하고 모든 요소에 함수를 적용하십시오. 결과 행렬이 리턴됩니다.
s = Round(Sqrt( [1, 2, 3, 4, 5, 6, 7, 8, 9] ), 2);
write(s); // [1, 1.41, 1.73, 2, 2.24, 2.45, 2.65, 2.83, 3]
행렬 함수
Loc 행렬을 반복하며 Loc이 식별하는 요소의 위치를 반환합니다. for 루프보다 훨씬 빠릅니다.
s = Round(Sqrt( [1, 2, 3, 4, 5, 6, 7, 8, 9] ), 2);
write(Loc(s > 2)); // [5, 6, 7, 8, 9] (element 4 is equal)
사용
행렬 첨자 for 루프보다 훨씬 빠르게 매트릭스를 재구성 할 수 있습니다.
s = Round( Sqrt( [1, 2, 3, 4, 5, 6, 7, 8, 9] ), 2 );
s[Loc( s > 2 )] = -1;
Write( s ); // [1, 1.41, 1.73, 2, -1, -1, -1, -1, -1]
이 시점을 넘어서는 모든 것이 별난 당신이 정말로 좋은 이유가 없다면 피해야하는 사용 패턴. 나중에 다른 사람이 유지하기가 어려울 것입니다.
그만큼
J 함수 행렬을 만들고 값으로 초기화합니다. 이 값이 표현식이면 모든 요소에 대해 평가됩니다. 이 예에서 J ()의 세 번째 인수는 괄호 안에있는 명령문 쌍입니다. 첫 번째 명령문은 카운터를 증가시키고 두 번째 명령문은 값을 계산합니다. 마지막으로 계산 된 값은 여러 문장으로 이루어진 표현식의 값입니다.
idx = 0; // not a recommended pattern!
mat = J( 2, 3, (idx += 1 ; Sqrt( idx )) );
Write( Round( mat, 1 ) ); // [1 1.4 1.7, 2 2.2 2.4]
그만큼
병렬 할당 기능 배열을 채우기 위해 여러 스레드를 사용합니다. J 함수의 세 번째 인수와 달리 계산할 요소의 특정 순서에 의존 할 수 없습니다. 병렬 할당은 서로 격리 된 스레드를 유지하려고 시도하지만 실제로 표현식이 전역 데이터에 액세스하는 것을 원하지 않습니다.
bigMat = J( 500, 500, . );
// these are global x and y values that are only copied into each thread, below.
x = 2;
yy = 3;
// x=x and y=yy is copying global values to local values of the same/similar name.
// bigMat[rr, cc] determines the array that is being filled in and the
// row and column names you'll use in the expression after the =.
// the if statement is an example expression, not terribly interesting but
// typical of the kind of thing parallel assign does well.
rc = Parallel Assign( {x = x, y = yy}, bigMat[rr, cc] = If( x == 2, rr * cc, y ) );
// Max dose NOT return an array, it returns the maximum value in the array.
// dividing by max scales the values from 0 to 1
bigMat = bigMat / Max( bigMat );
// new image expects values from 0 to 1
New Window( "demo", New Image( "rgb", {bigMat, 1 - bigMat, bigMat} ) );
250,000 if statements evaluated250,000 if statements evaluated250,000 if statements evaluated if 문의 계산 된 250,000 개 그만큼
패턴 일치 자 문자열을 반복 할 수 있고 일치가 진행될 때 JSL을 실행할 수 있습니다.
text = // use the \[ and ]\ to escape the quotes in this text
"\[John Bartlett, who ran the University Book Store in Cambridge,
Massachusetts, was frequently asked for information on quotations and
he began a commonplace book of them for reference. In 1855, he
privately printed his compilation as A Collection of Familiar Quotations.
This first edition contained 258 pages of quotations by 169 authors,
chiefly the Bible, William Shakespeare, and the great English poets.
Bartlett wrote in the fourth edition that "it is not easy to determine in
all cases the degree of familiarity that may belong to phrases and
sentences which present themselves for admission; for what is familiar
to one class of readers may be quite new to another." - Wikipedia]\";
words = [=> 0]; // an associative array that defaults unknown keys to a value of 0
// this match repeats a pair of alternatives: a run of a-z or a run of NOT a-z.
// the runs of a-z are stored in an associative array
rc = Pat Match(
text,
Pat Repeat( // the loop starts here
(Pat Regex( "[a-zA-Z]+" ) >> word
+Pat Test( // insert word into words assoc array
words[Lowercase( word )] += 1; // this JSL is evaluated for each word
1; // the test must succeed for the pattern to continue
)) | Pat Regex( "[^a-zA-Z]+" ) // skip non-words
)
);
// make a table, load it from the words assoc array keys and values
dt = New Table( "word count",
New Column( "word", character, Set Values( words << getkeys ) ),
New Column( "count", Set Values( words << getvalues ) )
);
// sort by the count column
dt << sort( by( count ), order( descending ), replaceTable );
Table of word countsTable of word countsTable of word counts단어 수 표
그만큼
스케줄러 몇 초마다 코드를 반복해서 실행할 수 있습니다.
n = 0; // counter, just for this demo
dowork = Function( {},
Print( "hi", n );
n += 1;
If( n < 10,
Schedule( .5, dowork() );// half second from now, run me again
, // else
Schedule( 0, 0 ) << close; // no delay, no code
);
);
dowork(); // start the loop
재귀 나무를 걸을 수 있습니다.
// this tree walker looks for button boxes in a display
// box tree and prints the button name
treeWalker = Function( {box}, // parameter
{child = box << child}, // local variables
While( !Is Empty( child ),
If( child << classname == "ButtonBox",
Show( child << Get Button Name )
);
treeWalker( child ); // you could also use recurse(child)
child = child << sib;
)
);
x = V List Box(
H List Box( Button Box( "x" ), Button Box( "z" ) ),
Border Box( Button Box( "w" ) )
);
treeWalker( x ); // shows x, z, and w
for 루프를 사용하면 그렇게 할 수 있습니다. 문제에 따라 배열 첨자를 더 빠르고 쉽게 찾을 수 있습니다. 배열이나 데이터 테이블에는 다음과 같은 트리플을 첨자로 붙일 수 있습니다.
x[ start::stop::step ]
x의 조각을 반환합니다. 아니면 당신은 사용할 수 있습니다
for( i = start, i <= stop, i+= step,
...statements separated by semicolons...
)
if you want to move the window, put an outer loop around it to adjust the start and stop values.