김보안의 블로깅
  • 🏠 Home
  • 📚 Project
    • Blockchain
      • 🎦 PickMe
      • 🎦 IoTC
      • 🎦 Blackchain
      • 📃 Gemology
      • 🎦 PickMe
      • 🎦 PickMe
    • AI
      • 👋 A.I. Dream Reader
      • 🎦 A.I. Dream Reader
    • Security
      • 🎦 SNAC
    • Education
      • 🎦 Smart Lecture
  • 🤸‍♂ Hobby
    • Music
      • Violin
      • Guitar
      • Piano
      • Drum
    • Flower
      • Flower Certificate
    • Sport
      • Ski
      • Skateboard
      • Golf
      • Boxing

2018년 8월 26일 일요일

Javascript 배열의 모든 것 1탄 ( 선언, 정렬, 2차원배열, 멀티 소팅, 순열, 조합 )

 SecureKim     오전 2:09     2차원 배열, 배열, 복사, 순열, 자바스크립트, 정렬, 조합, Array, combination, copy, Javascript, Node.js, permutation, sort     No comments   


ㆍ배열의 선언

// 5개 짜리 배열 선언
var origin = new Array (5);

// 5개 짜리 배열을 선언 할 때 0으로 초기화 하기
var origin =  Array.apply(null, new Array(5)).map(Number.prototype.valueOf,0);

// 5개 짜리 배열을 선언 할 때 "securekim" 으로 초기화 하기
var origin = Array.apply(null, new Array(5)).map(String.prototype.valueOf,"securekim");

// 배열의 복사 (Deep copy)
// for 문 돌면서 직접 대입하는것이 가장 빠르지만, 이것이 그 다음으로 빠르다. 코드가 간결하다는 장점이 있다.
var copy = origin.slice(0);
//참고로 map 이 가장 느리다. (https://jsperf.com/cloning-arrays/3)
var copy = origin.map(x=>(x));

// 배열의 간단 정렬 - 내부 알고리즘은 Merge sort. 브라우저별로 다를 수 있음.
origin.sort(function(a, b) {
    return a - b;
});


ㆍ2차원 배열

2차원 배열이라는게 따로 있는건 아니고 배열 안에 배열을 선언하는 것.

// x,y (4,2) 짜리 배열 선언
// ? ? ? ?
// ? ? ? ?
var origin  = new Array( new Array(4), new Array(4) );

// 이런 이상한 모양의 배열도 만들 수 있음.
// ? ? ? ?
// ? ?
// ? ? ? ?
var origin  = new Array( new Array(4), new Array(2), new Array(4) );

// 배열의 복사 (Deep copy)
// 방법 1.
var copy = new Array(origin.length);
for(var i in origin){
    copy[i] = origin[i].slice(0);
}
// 방법 2.
var copy = origin.map(x => x.map( y=>(y) ));

// 배열 복사(Deep copy) 하면서 0으로 초기화 하기
// 방법 1.
var copy = new Array(origin.length);
for(var i in origin){
 copy[i] = Array.apply(null, new Array(origin[i].length)).map(Number.prototype.valueOf,0);
}
// 방법 2.
var copy = origin.map(x => x.map( y=>(0) ));

ㆍ배열의 정렬 (멀티 소팅)
툰 아저씨가  만들어 놓은 것을 사용하자.

https://github.com/Teun/thenBy.js/blob/master/thenBy.js

/***
Copyright 2013 Teun Duynstee
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var firstBy = (function() {
function identity(v){return v;}
function ignoreCase(v){return typeof(v)==="string" ? v.toLowerCase() : v;}
function makeCompareFunction(f, opt){
opt = typeof(opt)==="number" ? {direction:opt} : opt||{};
if(typeof(f)!="function"){
var prop = f;
// make unary function
f = function(v1){return !!v1[prop] ? v1[prop] : "";}
}
if(f.length === 1) {
// f is a unary function mapping a single item to its sort score
var uf = f;
var preprocess = opt.ignoreCase?ignoreCase:identity;
var cmp = opt.cmp || function(v1,v2) {return v1 < v2 ? -1 : v1 > v2 ? 1 : 0;}
f = function(v1,v2) {return cmp(preprocess(uf(v1)), preprocess(uf(v2)));}
}
if(opt.direction === -1) return function(v1,v2){return -f(v1,v2)};
return f;
}
/* adds a secondary compare function to the target function (`this` context)
which is applied in case the first one returns 0 (equal)
returns a new compare function, which has a `thenBy` method as well */
function tb(func, opt) {
/* should get value false for the first call. This can be done by calling the
exported function, or the firstBy property on it (for es6 module compatibility)
*/
var x = (typeof(this) == "function" && !this.firstBy) ? this : false;
var y = makeCompareFunction(func, opt);
var f = x ? function(a, b) {
return x(a,b) || y(a,b);
}
: y;
f.thenBy = tb;
return f;
}
tb.firstBy = tb;
return tb;
})();

// 이름은 사전순
// 이름이 같으면 키는 오름차순
// 키도 같으면 몸무게는 내림차순으로 정렬

var people = [
{weight:70, height:170, name:"BRABO" },
{weight:70, height:170, name:"CHARLIE" },
{weight:70, height:170, name:"ALPHA" },
{weight:70, height:175, name:"BRABO" },
{weight:70, height:175, name:"CHARLIE" },
{weight:70, height:175, name:"ALPHA" },
{weight:75, height:170, name:"BRABO" },
{weight:75, height:170, name:"CHARLIE" },
{weight:75, height:170, name:"ALPHA" },
{weight:90, height:170, name:"BRABO" },
{weight:75, height:190, name:"CHARLIE" },
{weight:75, height:190, name:"ALPHA" },
]

people.sort(
    firstBy(function (v1, v2) { return v1.name < v2.name ? -1 : v1.name > v2.name ? 1: 0; })
    .thenBy(function (v1, v2) { return v1.height- v2.height; })
    .thenBy(function (v1, v2) { return v2.weight - v1.weight; })
);
// 2차원 배열인 경우.
people.sort(
    firstBy(function (v1, v2) { return v1[2] < v2[2] ? -1 : v1[2] > v2[2] ? 1: 0; })
    .thenBy(function (v1, v2) { return v1[1] - v2[1]; })
    .thenBy(function (v1, v2) { return v2[0] - v1[0]; })
);


ㆍ배열의 순열과 조합

function combi(chars) {
var result = [];
var f = (prefix, chars) => {
for (var i = 0; i < chars.length; i++) {
result.push(prefix + chars[i]);
f(prefix + chars[i], chars.slice(i + 1));
}
}
f('', chars);
return result;
}


function permute(permutation) {
var length = permutation.length,
result = [permutation.slice()],
c = new Array(length).fill(0),
i = 1, k, p;
while (i < length) {
if (c[i] < i) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
result.push(permutation.slice());
} else {
c[i] = 0;
++i;
}
}
return result;
}


  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
이메일로 전송BlogThis!X에 공유Facebook에서 공유
최근 게시물 이전 게시물 홈

0 개의 댓글:

댓글 쓰기

페이지

  • 홈
  • Hobby

Categories

  • AI
  • AWS
  • Blockchain
  • Hardware
  • Javascript
  • Node.js
  • Plasma
  • Security
  • Study
  • Video
  • android
  • mysql
  • review
  • windows

Popular Posts

  • 블랙보드 강의 녹화 영상 다운로드 가능한 방법 (노설치)
    별도의 설치도 필요 없고 아주 쉽습니다. 구글 크롬브라우저 에서 블랙보드 녹화 영상에  다운로드 가능한 메뉴가 나오게 하는 코드입니다.  먼저 블랙보드 강의자료에 입장하고, 재생 버튼을 클릭 하지 않은 상태로 F12 를 입력합니다. 재생을 클릭하지 마...
  • 다빈치리졸브로 영상의 음성 보정 (잡음 노이즈 없애기)
      잡음 없애는 방법 1. 음악 쪽 들어가서 음악에서 소스 우클릭 - Normalize Audio Levels 2. 우측의 Mixer에서 Dynamics 더블클릭, Effects아래 +누르고 Metering에 Meter 그럼 아래처럼 나오는데  Gat...
  • 회사 프록시와 인증서에 고통받는 그대를 위한 글 (Bash, Gradle, Python, wget, nodejs(npm), apt-get, cURL, git, yarn, androidStudio)
    대기업에 입사하면 장단점이 있는데, 단점 중에 하나가 회사에서 프록시를 사용하여 트래픽 감시를 하므로 프록시 설정을 해주어야 한다는 점 입니다. 특히, 회사에서는 https 트래픽도 감시를 하므로 인증서도 설정해 주어야 합니다. 그런데 문...

Blog Archive

  • ►  2024 (2)
    • ►  11월 (2)
  • ►  2023 (2)
    • ►  10월 (1)
    • ►  1월 (1)
  • ►  2022 (10)
    • ►  12월 (1)
    • ►  11월 (3)
    • ►  9월 (1)
    • ►  8월 (1)
    • ►  6월 (2)
    • ►  3월 (2)
  • ►  2021 (9)
    • ►  12월 (3)
    • ►  11월 (1)
    • ►  6월 (1)
    • ►  5월 (2)
    • ►  4월 (2)
  • ►  2020 (12)
    • ►  10월 (1)
    • ►  9월 (2)
    • ►  7월 (1)
    • ►  6월 (1)
    • ►  5월 (5)
    • ►  4월 (1)
    • ►  2월 (1)
  • ►  2019 (14)
    • ►  10월 (2)
    • ►  7월 (1)
    • ►  3월 (4)
    • ►  2월 (2)
    • ►  1월 (5)
  • ▼  2018 (14)
    • ►  12월 (2)
    • ►  11월 (4)
    • ►  10월 (1)
    • ▼  8월 (2)
      • Javascript 배열의 모든것 2 ( filter, some, every, reduce )
      • Javascript 배열의 모든 것 1탄 ( 선언, 정렬, 2차원배열, 멀티 소팅, 순열,...
    • ►  5월 (4)
    • ►  1월 (1)
  • ►  2017 (12)
    • ►  10월 (2)
    • ►  9월 (9)
    • ►  5월 (1)
  • ►  2016 (8)
    • ►  10월 (2)
    • ►  8월 (1)
    • ►  6월 (1)
    • ►  1월 (4)
  • ►  2015 (6)
    • ►  12월 (3)
    • ►  10월 (1)
    • ►  6월 (1)
    • ►  5월 (1)
  • ►  2014 (10)
    • ►  11월 (1)
    • ►  9월 (1)
    • ►  7월 (1)
    • ►  6월 (1)
    • ►  5월 (3)
    • ►  4월 (1)
    • ►  3월 (2)
  • ►  2013 (28)
    • ►  12월 (3)
    • ►  11월 (6)
    • ►  10월 (6)
    • ►  9월 (6)
    • ►  8월 (1)
    • ►  7월 (3)
    • ►  6월 (3)

구독

글
Atom
글
댓글
Atom
댓글

로드 중입니다...

각오

직접 해보지 않은 것은 포스팅 하지 않겠습니다.

Copyright © 김보안의 블로깅 | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com | Distributed By Gooyaabi Templates