神戸プログラミングアカデミーのブログ

「未経験から」「スキルアップ」「起業を目指す」無料で学べる神戸のプログラミング学校&学習コミュニティ

与えられた配列の中身が全てその値かどうかを判定する関数を作成せよ

与えられた配列の中身が全てその値かどうかを判定する関数 isFilledArray(arr, val)を作成せよ

// この関数を実装
function isFilledArray(arr, val){
}

console.log(isFilledArray([1,1,1], 1))
console.log(isFilledArray([1,1,1], 0))
console.log(isFilledArray([1,1,0], 1))
true
false
false

デイリー問題集

Array.filter()関数を自作してみよう

値が指定された範囲内にあるかどうかを判定する関数を作成せよ

Array.find()を自作せよ

重複した値を省いて返すメソッド unique(array)を作成せよ

除算演算子/を使わずに整数を返す割り算関数を作成し、またその関数を使い剰余演算子%を使わずに剰余を求める関数を作成せよ

フィボナッチ数列を20個表示せよ

正方形を回転させて表示させよ

配列から最小の数を取得する関数を作成せよ(Math.min()を使わずに)

最高気温が30度を越えた連続日数を表示せよ

出現回数を数えて出力せよ

表の合計を計算する

数値検査

データを棒グラフで表現せよ

最小値・最大値に丸める関数を作成せよ

覆面算を解くプログラム

配列を受け取りコールバックで指定された条件のもの省いて返す関数を作成せよ

指定されたインデックスが先頭になるようにして返す関数を作成せよ

String.splitを自作せよ

西暦を和暦に変換する関数を作成せよ

String.trimを自作せよ

配列とオブジェクトを操る

Userデータを集計する

入力された文字列をチェーンケース・スネークケース・アッパーキャメルケース・ローワーキャメルケースに変換する関数を作成せよ

小数を切り捨て、切り上げ、四捨五入する関数を作成せよ

与えられた数値を2進数に変換するメソッドを作成せよ

文字列を比較する関数strcmp()を作成せよ

文字列の長さを返す関数strlen()を作成せよ

与えられた2次元配列の縦・横・斜めが与えられた値で揃っているかを返す関数を作成せよ

与えられた配列の中身が全てその値かどうかを判定する関数を作成せよ

Excelの列キーを生成する関数を作る

 

Excelの列キーを生成する関数を作る

Excelの列はA, B, C...と続き、Z, AA, AB, AC..., AZ, BA, BB, BC..., ZZ, AAA, AABと表現されます。

この文字列を返す以下の仕様の関数 indexToExcelColumnKey() を生成せよ。

const ALPHABET_NUM = 26
// この関数を実装する
function indexToExcelColumnKey(num) {
}
// コマンドライン引数の数だけ表示する
for (let i = 0; i < Number(process.argv[2]); i++) {
    console.log(indexToExcelColumnKey(i))
}

#

node excel.js 3
A
B
C

#

node excel.js 30
.
.
.
W
X
Y
Z
AA
AB
AC
AD

#

node main.js 704

出力結果

.
.
.
ZX
ZY
ZZ
AAA
AAB

#

node excel.js 18280
.
.
.
ZZX
ZZY
ZZZ
AAAA
AAAB

475256, 12356632

ヒント

↓この関数を使います

String.fromCharCode
String.charCodeAt

解答例

const ALPHABET_NUM = 26

function indexToExcelColumnKey(num) {
    let ret = ""
    if (num >= ALPHABET_NUM) {
        ret = indexToExcelColumnKey(num / ALPHABET_NUM - 1)
    }
    ret += String.fromCharCode("A".charCodeAt(0) + num % ALPHABET_NUM)
    return ret
}
for (let i = 0; i < Number(process.argv[2]); i++) {
    console.log(indexToExcelColumnKey(Number(i)))
}

Vue.jsの練習

この記事がよくまとまっている

qiita.com

Vuetifyでやりましょう

vuetifyjs.com

.vueの基本

<template>
  <div></div>
</template>

<script>
export default {
  data: function() {
    return {};
  },
  methods: {},
  computed: {}
};
</script>

dataの練習

script 内の dataで宣言した変数をtemplateで表示せよ f:id:prog-ac:20210520115716p:plain

<template>
  <div></div>
</template>
<script>
export default {
  data: function() {
    return {
      message: "Hello Vue!"
    };
  },
  methods: {},
  computed: {}
};
</script>

解答例

<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      message: "Hello Vue!"
    };
  },
  methods: {},
  computed: {}
};
</script>

methodの練習

templateにボタンを配置し、クリックされたらmethods: onClickButton()を呼び、カウント変数をインクリメントせよ f:id:prog-ac:20210520121026g:plain

<template>
  <div></div>
</template>
<script>
export default {
  data: function() {
    return {
      count: 0
    };
  },
  methods: {
    onClickButton(){
    }
  },
  computed: {}
};
</script>

解答例

<template>
  <div>
    <v-btn @click="onClickButton">クリック</v-btn>
    <p>{{ count }}</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      count: 0
    };
  },
  methods: {
    onClickButton() {
      this.count++;
    }
  },
  computed: {}
};
</script>

v-modelの練習

templateにテキストフィールドを配置し、入力された内容をテキストフィールド外に配置したpタグ内に表示せよ f:id:prog-ac:20210520121240g:plain

解答例

<template>
  <div>
    <v-text-field v-model="text"></v-text-field>
    <p>{{text}}</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      text: ""
    };
  },
  methods: {},
  computed: {}
};
</script>

computedの練習

templateにテキストフィールドを配置し、入力された内容をテキストフィールド外に配置したpタグ内に全て大文字に変換して表示せよ f:id:prog-ac:20210520121142g:plain

解答例

<template>
  <div>
    <v-text-field v-model="text"></v-text-field>
    <p>{{upperText}}</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      text: ""
    };
  },
  methods: {},
  computed: {
    upperText() {
      return this.text.toUpperCase();
    }
  }
};
</script>

classバインドの練習

templateにボタン「大」「中」「小」、pを配置し、それぞれのボタンが押下されたらpタグ内の文字サイズを変更せよ f:id:prog-ac:20210520121020g:plain

解答例

<template>
  <div>
    <v-btn @click="onClickButton('text-h1')">大</v-btn>
    <v-btn @click="onClickButton('text-h4')">中</v-btn>
    <v-btn @click="onClickButton('text-caption')">小</v-btn>
    <p :class="className">神戸プログラミングアカデミー</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      className: ""
    };
  },
  methods: {
    onClickButton(c) {
      this.className = c;
    }
  },
  computed: {}
};
</script>

v-forの練習

scriptにオブジェクトの配列を定義し、v-forを使ってテーブルに表示せよ

準備
curl https://raw.githubusercontent.com/prog-ac/sortable-table/master/assets/users.json > users.json

f:id:prog-ac:20210520121336p:plain

解答例

<template>
  <div>
    <v-simple-table>
      <thead>
        <tr>
          <th>名前</th>
          <th>出身地</th>
          <th>誕生日</th>
          <th>点数</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(user, index) in users" :key="index">
          <td>{{user.name}}</td>
          <td>{{user.pref}}</td>
          <td>{{user.birthday}}</td>
          <td>{{user.score}}</td>
        </tr>
      </tbody>
    </v-simple-table>
    <p>{{users}}</p>
  </div>
</template>

<script>
const users = require("~/users.json");
export default {
  data: function() {
    return {
      users: users
    };
  },
  methods: {},
  computed: {}
};
</script>

アプリケーションを作ってみよう

prog-ac.hatenablog.com

componentの練習(v-model)

上記components/OkCancelDialog.vue にボタンOK/Cancelを配置し、@onOk、@onCancelでemitを実装し、ボタン押下時にダイアログを閉じよ

解答例

OkCancel.vue

<template>
  <v-dialog v-model="dialog" persistent max-width="290">
    <v-card>
      <v-card-title>{{title}}</v-card-title>
      <v-card-text>{{message}}</v-card-text>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn @click="onCancel">キャンセル</v-btn>
        <v-btn @click="onOk">OK</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script>
export default {
  props: {
    title: "",
    message: "",
    value: false
  },
  data: function() {
    return {};
  },
  methods: {
    onOk() {
      this.$emit("onOk", this.title, this.message);
    },
    onCancel() {
      this.$emit("onCancel", this.title, this.message);
    }
  },
  computed: {
    dialog: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    }
  }
};
</script>

index.vue

<template>
  <div>
    <v-btn @click="openDialog('ダイアログ1','神戸')">ダイアログ1</v-btn>
    <v-btn @click="openDialog('ダイアログ2','プロアカ')">ダイアログ2</v-btn>
    <ok-cancel-dialog
      @onOk="onOk"
      @onCancel="onCancel"
      v-model="dialog"
      :title="dialogTitle"
      :message="dialogMessage"
    ></ok-cancel-dialog>
  </div>
</template>

<script>
import OkCancelDialog from "~/components/OkCancelDialog";
export default {
  components: {
    OkCancelDialog
  },
  data: function() {
    return {
      dialog: false,
      dialogTitle: "",
      dialogMessage: ""
    };
  },
  methods: {
    openDialog(title, message) {
      this.dialogTitle = title;
      this.dialogMessage = message;
      this.dialog = true;
    },
    onOk(title, message) {
      this.dialog = false;
      console.log("onOk(): ", title, message);
    },
    onCancel(title, message) {
      this.dialog = false;
      console.log("onCancel(): ", title, message);
    }
  },
  computed: {}
};
</script>

◯×ゲームを作ろう

プロジェクト作成

yarn create nuxt-app marubatsu
項目 選択肢
Project name そのまま
Programming language JavaScript
パッケージマネージャー yarn
UI Framework Vuetify
Nuxt.js modules チェックなし
Linting tools なし
Testing framework None
Rendering mode Single Page App
Deployment target Static
Development tool jsconfig.json (Recommended for VS Code)
cd marubatsu
yarn dev

実装手順

設計を考える

マーク 数値
1
× -1
なし 0
  • v-forを使って3x3のマスを書く

  • マスがクリックされたらコールされるメソッドを作る(引数に場所を渡す)

  • ◯のターンor×のターンを表示し、マスがクリックされるたびに切り替える

  • クリックしたマス(配列)に◯or×を設定する

  • マスを指定したら文字(◯or×or空白)を返す関数を作り、各マスに文字を表示する

  • 既にマークが置かれているところには置けないようにする

  • 3つ揃ったら勝敗判定をしダイアログを表示

  • 全てのマスが揃って勝敗が決まっていなかったら引き分け判定をしダイアログを表示

  • ダイアログを閉じたらリセットし、始めから

回答例

<template>
  <v-container>
    <h2>{{`${numToChar(turn)}のターンです`}}</h2>
    <div class="row" v-for="y of LINE_NUM" :key="y">
      <div class="cell" v-for="x of LINE_NUM" :key="x" @click="onCellClick(x-1,y-1)">
        <div>{{getCellChar(x-1,y-1)}}</div>
      </div>
    </div>
    <v-dialog v-model="dialog" @click:outside="reset" max-width="290">
      <v-card>
        <v-card-title>
          <h2>{{dialogMessage}}</h2>
        </v-card-title>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script>
export default {
  data: function() {
    return {
      turn: -1,
      cells: Array(9),
      LINE_NUM: 3,
      dialog: false,
      dialogMessage: ""
    };
  },
  mounted() {
    this.reset();
  },
  methods: {
    reset() {
      this.turn = -1;
      this.dialog = false;
      this.dialogMessage = "";
      this.cells.fill(0);
    },
    onCellClick(x, y) {
      if (0 === this.getCellNum(x, y)) {
        this.cells[y * this.LINE_NUM + x] = this.turn;
        if (this.checkLines()) {
          this.dialogMessage = `${this.numToChar(this.turn)}の勝ちです`;
          this.dialog = true;
        } else {
          this.turn *= -1;
          if (this.isFullArray()) {
            this.dialogMessage = `引き分けです`;
            this.dialog = true;
          }
        }
      }
    },
    getCellNum(x, y) {
      return this.cells[y * this.LINE_NUM + x];
    },
    numToChar(num) {
      switch (num) {
        case 0:
          return " ";
          break;
        case 1:
          return "◯";
          break;
        case -1:
          return "×";
      }
      return " ";
    },
    getCellChar(x, y) {
      return this.numToChar(this.getCellNum(x, y));
    },
    isFullArray() {
      let ret = true;
      for (let i = 0; i < this.cells.length; i++) {
        if (this.cells[i] === 0) {
          ret = false;
          break;
        }
      }
      return ret;
    },
    isCompleteArray(arr) {
      let ret = true;
      for (let i = 0; i < arr.length; i++) {
        if (arr[0] !== arr[i]) {
          ret = false;
          break;
        }
      }
      return ret && arr[0] !== 0;
    },
    checkLines() {
      let completed = false;
      // 横
      for (let y = 0; y < this.LINE_NUM; y++) {
        const line = [];
        for (let x = 0; x < this.LINE_NUM; x++) {
          line.push(this.getCellNum(x, y));
        }
        if (this.isCompleteArray(line)) {
          completed = true;
        }
      }
      // 縦
      for (let x = 0; x < this.LINE_NUM; x++) {
        const line = [];
        for (let y = 0; y < this.LINE_NUM; y++) {
          line.push(this.getCellNum(x, y));
        }
        if (this.isCompleteArray(line)) {
          completed = true;
        }
      }
      // 斜め
      {
        const line = [];
        for (let x = 0; x < this.LINE_NUM; x++) {
          line.push(this.getCellNum(x, x));
        }
        if (this.isCompleteArray(line)) {
          completed = true;
        }
      }
      // 斜め
      {
        const line = [];
        for (let x = 0; x < this.LINE_NUM; x++) {
          line.push(this.getCellNum(x, this.LINE_NUM - x - 1));
        }
        if (this.isCompleteArray(line)) {
          completed = true;
        }
      }
      return completed;
    }
  },
  computed: {}
};
</script>
<style scoped>
.cell {
  border: 1px solid;
  text-align: center;
  font-size: 2rem;
  width: 4em;
  height: 4em;
  line-height: 4em;
}
</style>

Vue.js / Nuxt.js 入門

Vue.jsとは

jp.vuejs.org

現在のバージョンはVue 2

2020年8月頃にVue 3がリリースされるらしい。

github.com

いまから勉強する内容は、おそらく1年後古くなっているけど、恨まないでね。(というか、WebのJavaScript界隈のスピード感はそんな感じ)

競合

React, Angularがある。日本ではVue, Reactが人気。周りを見るとVue多い。

Vueが簡単だから、Vueでやる。

Nuxt.jsとは

Nuxt.jsは「Vue.js トッピング全部入り」みたいな感じ。

Vueでアプリケーションを作っていくためには、いろんな部品(Vuex, Vue Routerとか)を組み合わせて作っていく必要があるが、Nuxt.jsはそんなVue.jsに必要な設定が最初から入っている。

プロアカで使っていくNuxt.jsの構成について

項目 選択肢 プロアカ 理由
言語 JavaScript, TypeScript JavaScript 情報の多さ
パッケージマネージャー npm, yarn yarn 速さ重視
UI Framework いっぱいある None or Vuetify まぁお好きなのを
Nuxt.js modules 必要に応じて
Linting tools ESLint, Prettier, Lint staged files, StyleLint ESLint, Prettier
Testing framework None,Jest,AVA,WebdriverIO Jest Jest以外知らない
Rendering mode Universal, Single Page App Single Page App SSRは現状使わないかな
Deployment target Server (Node.js hosting),Static (Static/JAMStack hosting) Static Staticでいい
Development tool jsconfig.json (Recommended for VS Code) jsconfig.json (Recommended for VS Code)

qiita.com

yarnのインストール

classic.yarnpkg.com

yarn create nuxt-app [プロジェクト名]

配列とオブジェクトを操る

オブジェクトにオブジェクトを追加する & そのオブジェクトに要素を追加する。

※一行づつ書く

出力結果

{ '兵庫': { '神戸': 'A', '明石': 'B', '西宮': 'C' } }

解答例

const obj = {}
obj["兵庫"] = {} // ←これがないとobj["兵庫"]がundefinedになるから以下が動かない
obj["兵庫"]["神戸"] = "A"
obj["兵庫"]["明石"] = "B"
obj["兵庫"]["西宮"] = "C"
console.log(obj)

オブジェクトに配列を追加する & 追加した配列に要素を追加する

※一行づつ書く

{ cities: [ '神戸', '明石', '西宮' ] }

解答例

const obj = {}
obj["cities"] = []
obj["cities"].push("神戸")
obj["cities"].push("明石")
obj["cities"].push("西宮")
console.log(obj)

配列にオブジェクトを追加する & 追加したオブジェクトに要素を追加する

※一行づつ書く

[
  { pref: '兵庫', city: '神戸' },
  { pref: '兵庫', city: '明石' },
  { pref: '兵庫', city: '西宮' }
]

解答例

const cities = []
cities.push({})
cities[cities.length - 1]["pref"] = "兵庫"
cities[cities.length - 1]["city"] = "神戸"
cities.push({})
cities[cities.length - 1]["pref"] = "兵庫"
cities[cities.length - 1]["city"] = "明石"
cities.push({})
cities[cities.length - 1]["pref"] = "兵庫"
cities[cities.length - 1]["city"] = "西宮"
console.log(cities)

配列に配列を追加する & 追加した配列に要素を追加する

※一行づつ書く

[
  [
    1, 2, 3, 4, 5,
    6, 7, 8, 9
  ],
  [
     2,  4,  6,  8, 10,
    12, 14, 16, 18
  ],
  [
     3,  6,  9, 12, 15,
    18, 21, 24, 27
  ],
  [
     4,  8, 12, 16, 20,
    24, 28, 32, 36
  ],
  [
     5, 10, 15, 20, 25,
    30, 35, 40, 45
  ],
  [
     6, 12, 18, 24, 30,
    36, 42, 48, 54
  ],
  [
     7, 14, 21, 28, 35,
    42, 49, 56, 63
  ],
  [
     8, 16, 24, 32, 40,
    48, 56, 64, 72
  ],
  [
     9, 18, 27, 36, 45,
    54, 63, 72, 81
  ]
]

解答例

const result = []
for (let i = 1; i <= 9; i++) {
  const ans = []
  for (let j = 1; j <= 9; j++) {
    ans.push(i * j)
  }
  result.push(ans)
}
console.log(result)